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
23643042cfe0f0c7b6d3a886c8fe753713c470a6
6,398
rs
Rust
day04/src/lib.rs
vescoc/AdventOfCode2020
7999970344a2612f3fffeb039c22d50aa52b0e76
[ "MIT" ]
4
2021-12-05T20:20:07.000Z
2021-12-17T23:07:42.000Z
day04/src/lib.rs
vescoc/AdventOfCode2020
7999970344a2612f3fffeb039c22d50aa52b0e76
[ "MIT" ]
null
null
null
day04/src/lib.rs
vescoc/AdventOfCode2020
7999970344a2612f3fffeb039c22d50aa52b0e76
[ "MIT" ]
null
null
null
#![feature(test)] extern crate test; #[macro_use] extern crate lazy_static; use regex::Regex; use std::collections::HashSet; lazy_static! { static ref INPUT: Vec<&'static str> = include_str!("../input").split("\n\n").collect(); static ref BYR_RE: Regex = Regex::new(r"^(\d{4})$").unwrap(); static ref IYR_RE: Regex = Regex::new(r"^(\d{4})$").unwrap(); static ref EYR_RE: Regex = Regex::new(r"^(\d{4})$").unwrap(); static ref HGT_RE: Regex = Regex::new(r"^(\d+)((?:in)|(?:cm))$").unwrap(); static ref HCL_RE: Regex = Regex::new(r"^#[\da-f]{6}$").unwrap(); static ref ECL_RE: Regex = Regex::new(r"^(amb)|(blu)|(brn)|(gry)|(grn)|(hzl)|(oth)$").unwrap(); static ref PID_RE: Regex = Regex::new(r"^\d{9}$").unwrap(); } fn solve<F: Fn(&str, Option<&str>) -> Option<bool>>(input: &[&str], check: F) -> usize { input .iter() .map(|line| line.split_ascii_whitespace()) .filter_map(|pp| { pp.filter_map(|p| { let mut i = p.split(':'); let k = i.next().unwrap(); let v = i.next(); match (k, check(k, v)) { ("cid", _) => None, (_, Some(true)) => Some((k, true)), (_, Some(false)) => Some((k, false)), (_, None) => unimplemented!(), } }) .try_fold(HashSet::new(), |mut s, (k, v)| { if s.contains(k) || !v { Err(false) } else { Ok({ s.insert(k); s }) } }) .and_then(|s| if s.len() == 7 { Ok(1) } else { Err(false) }) .ok() }) .count() } fn solve_1(input: &[&str]) -> usize { solve(input, |_, _| Some(true)) } fn solve_2(input: &[&str]) -> usize { solve(input, |k, v| match k { "byr" => v .map(|v| { BYR_RE .captures(v) .map(|cap| { cap[1] .parse::<u32>() .map(|v| (1920..=2002).contains(&v)) .unwrap_or(false) }) .unwrap_or(false) }) .or(Some(false)), "iyr" => v .map(|v| { IYR_RE .captures(v) .map(|cap| { cap[1] .parse::<u32>() .map(|v| (2010..=2020).contains(&v)) .unwrap_or(false) }) .unwrap_or(false) }) .or(Some(false)), "eyr" => v .map(|v| { EYR_RE .captures(v) .map(|cap| { cap[1] .parse::<u32>() .map(|v| (2020..=2030).contains(&v)) .unwrap_or(false) }) .unwrap_or(false) }) .or(Some(false)), "hgt" => v .map(|v| { HGT_RE .captures(v) .map(|cap| match (cap[1].parse::<u32>(), &cap[2]) { (Ok(v), "in") => (59..=76).contains(&v), (Ok(v), "cm") => (150..=193).contains(&v), _ => false, }) .unwrap_or(false) }) .or(Some(false)), "hcl" => v.map(|v| HCL_RE.is_match(v)).or(Some(false)), "ecl" => v.map(|v| ECL_RE.is_match(v)).or(Some(false)), "pid" => v.map(|v| PID_RE.is_match(v)).or(Some(false)), _ => None, }) } pub fn part_1() -> usize { solve_1(&INPUT) } pub fn part_2() -> usize { solve_2(&INPUT) } #[cfg(test)] mod tests { use super::*; use test::Bencher; lazy_static! { static ref INPUT: Vec<&'static str> = r#"ecl:gry pid:860033327 eyr:2020 hcl:#fffffd byr:1937 iyr:2017 cid:147 hgt:183cm iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 hcl:#cfa07d byr:1929 hcl:#ae17e1 iyr:2013 eyr:2024 ecl:brn pid:760753108 byr:1931 hgt:179cm hcl:#cfa07d eyr:2025 pid:166559648 iyr:2011 ecl:brn hgt:59in"# .split("\n\n") .collect(); } #[test] fn same_results_1() { assert_eq!(solve_1(&INPUT), 2); } #[test] fn same_results_2_1() { let input: Vec<&str> = r"eyr:1972 cid:100 hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926 iyr:2019 hcl:#602927 eyr:1967 hgt:170cm ecl:grn pid:012533040 byr:1946 hcl:dab227 iyr:2012 ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277 hgt:59cm ecl:zzz eyr:2038 hcl:74454a iyr:2023 pid:3556412378 byr:2007" .split("\n\n") .collect(); assert_eq!(solve_2(&input), 0); } #[test] fn same_results_2_2() { let input: Vec<&str> = r"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f eyr:2029 ecl:blu cid:129 byr:1989 iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm hcl:#888785 hgt:164cm byr:2001 iyr:2015 cid:88 pid:545766238 ecl:hzl eyr:2022 iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719" .split("\n\n") .collect(); assert_eq!(solve_2(&input), 4); } #[test] fn valid_passport() { let input: Vec<&str> = r"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f" .split("\n\n") .collect(); assert_eq!(solve_2(&input), 1); } #[test] fn invalid_passport() { let input: Vec<&str> = r"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f hcl:#623a2" .split("\n\n") .collect(); assert_eq!(solve_2(&input), 0); } #[test] fn invalid_passport_2() { let input: Vec<&str> = r"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980 hcl:#623a2f hcl:#623a2f" .split("\n\n") .collect(); assert_eq!(solve_2(&input), 0); } #[bench] fn bench_part_1(b: &mut Bencher) { b.iter(part_1); } #[bench] fn bench_part_2(b: &mut Bencher) { b.iter(part_2); } }
27.34188
99
0.450922
65cd72e63cc37c00c58c9249577574495ad5ab7c
2,367
rs
Rust
examples/gpio_generic.rs
c-rustacean/lpc8xx-hal
cee8a0047ff38ec909c87b30b7435a225e3a29a1
[ "0BSD" ]
15
2019-06-10T14:13:41.000Z
2022-01-31T10:11:31.000Z
examples/gpio_generic.rs
c-rustacean/lpc8xx-hal
cee8a0047ff38ec909c87b30b7435a225e3a29a1
[ "0BSD" ]
135
2019-03-29T16:48:02.000Z
2022-01-15T18:56:06.000Z
examples/gpio_generic.rs
c-rustacean/lpc8xx-hal
cee8a0047ff38ec909c87b30b7435a225e3a29a1
[ "0BSD" ]
5
2019-07-01T19:01:54.000Z
2021-01-16T10:05:28.000Z
#![no_main] #![no_std] extern crate panic_rtt_target; use lpc8xx_hal::{ cortex_m_rt::entry, delay::Delay, gpio::{direction::Dynamic, GpioPin, Level}, pins::{DynamicPinDirection, GenericPin}, prelude::*, CorePeripherals, Peripherals, }; #[entry] fn main() -> ! { rtt_target::rtt_init_print!(); // Get access to the device's peripherals. Since only one instance of this // struct can exist, the call to `take` returns an `Option<Peripherals>`. // If we tried to call the method a second time, it would return `None`, but // we're only calling it the one time here, so we can safely `unwrap` the // `Option` without causing a panic. let cp = CorePeripherals::take().unwrap(); let p = Peripherals::take().unwrap(); // Initialize the APIs of the peripherals we need. let mut delay = Delay::new(cp.SYST); let mut syscon = p.SYSCON.split(); let gpio = p.GPIO.enable(&mut syscon.handle); // Select pins for all three LEDs let (green_led, green_led_token) = (p.pins.pio1_0, gpio.tokens.pio1_0); let (blue_led, blue_led_token) = (p.pins.pio1_1, gpio.tokens.pio1_1); let (red_led, red_led_token) = (p.pins.pio1_2, gpio.tokens.pio1_2); // Generate Generic Dynamic Pins from `Token` + `Pin`s and gather them for further batch // processing. let mut leds: [GpioPin<GenericPin, Dynamic>; 3] = [ green_led.into_generic_dynamic_pin( green_led_token, Level::High, // led is off initially DynamicPinDirection::Output, ), blue_led.into_generic_dynamic_pin( blue_led_token, Level::High, // led is off initially DynamicPinDirection::Output, ), red_led.into_generic_dynamic_pin( red_led_token, Level::High, // led is off initially DynamicPinDirection::Output, ), ]; loop { // Blink all LED colors by looping through the array that holds them // This should make the on-board LED blink like this: // 🟢 🔵 🔴 🟢 🔵 🔴 🟢 🔵 🔴 ... for led in leds.iter_mut() { blink_led(led, &mut delay); } } } /// Turn `led` on for 1000 ms fn blink_led(led: &mut GpioPin<GenericPin, Dynamic>, delay: &mut Delay) { led.set_low(); delay.delay_ms(1_000_u16); led.set_high(); }
31.986486
92
0.621039
9bda2cb01e6f0acac8df53a761c446910d507251
3,561
js
JavaScript
app.js
ubern00bie/Team-Builder
bb9f78827408924f3163ecd312e3bec5ff4dea7b
[ "Unlicense" ]
null
null
null
app.js
ubern00bie/Team-Builder
bb9f78827408924f3163ecd312e3bec5ff4dea7b
[ "Unlicense" ]
null
null
null
app.js
ubern00bie/Team-Builder
bb9f78827408924f3163ecd312e3bec5ff4dea7b
[ "Unlicense" ]
null
null
null
const inquirer = require("inquirer"); const fs = require("fs"); const path = require("path"); const Manager = require("./lib/Manager"); const Engineer = require("./lib/Engineer"); const Intern = require("./lib/Intern"); const { type } = require("os"); // const Employee = require("./lib/Employee"); const OUTPUT_DIR = path.resolve(__dirname, "output"); const outputPath = path.join(OUTPUT_DIR, "team.html"); //write my returned html text using fs, save file using outputPath for output directory const render = require("./lib/htmlRenderer"); let teamComplete = false; const team = []; const questions = [ { name:"name", type:"input", message:"Enter employee name:" }, { name:"id", type:"input", message:"Enter employee id:" }, { name:"email", type:"input", message:"Enter employee E-mail:" }, { name:"role", type:"list", message:"What role does this employee hold?", choices:["Manager","Engineer","Intern"] } ] function getMemberInfo (){ return inquirer.prompt(questions); } async function addMembers(){ try{ return inquirer.prompt({//seperate this question and call it like the function above, then it should work name:"addMember", type:"list", message:"Would you like to add another team member?", choices:['Yes','No'] }) }catch(err){ console.log(err); } } //loop for amount of team members async function buildMember() { // for await (index of numMembers){ try { var roleInfo; const teamInfo = await getMemberInfo(); switch (teamInfo.role){ case "Manager": roleInfo = await inquirer.prompt([ { name:"officeNumber", type:"input", message:"Enter Manager's office number: " } ]) team.push(new Manager(teamInfo.name,teamInfo.id,teamInfo.email,roleInfo.officeNumber)) break; case "Engineer": roleInfo = await inquirer.prompt([ { name:"github", type:"input", message:"Enter Engineer's GitHub username: " } ]) team.push(new Engineer(teamInfo.name,teamInfo.id,teamInfo.email,roleInfo.github)) break; case "Intern": roleInfo = await inquirer.prompt([ { name:"school", type:"input", message:"Enter intern's school: " } ]) team.push(new Intern(teamInfo.name,teamInfo.id,teamInfo.email,roleInfo.school)) break; } } catch(err) { console.log(err); } }//end async function async function run(){ try{ while(teamComplete != true){ await buildMember(); const cont = await addMembers(); if(cont.addMember === 'Yes'){ }else{ teamComplete = true; var htmlFile = render(team); fs.writeFileSync(outputPath,htmlFile); } //send my html to output } }catch(err){ console.log(err); } } run();
28.95122
142
0.495647
b2c0fe0d284c1df72e6a811ac09a5b401ed7fb9b
509
py
Python
tests/schema_mapping/expected/generated_example3.py
loyada/typed-py
8f946ed0cddb38bf7fd463a4c8111a592ccae31a
[ "MIT" ]
14
2018-02-14T13:28:47.000Z
2022-02-12T08:03:21.000Z
tests/schema_mapping/expected/generated_example3.py
loyada/typed-py
8f946ed0cddb38bf7fd463a4c8111a592ccae31a
[ "MIT" ]
142
2017-11-22T14:02:33.000Z
2022-03-23T21:26:29.000Z
tests/schema_mapping/expected/generated_example3.py
loyada/typed-py
8f946ed0cddb38bf7fd463a4c8111a592ccae31a
[ "MIT" ]
4
2017-12-14T16:46:45.000Z
2021-12-15T16:33:31.000Z
from typedpy import * class Person(Structure): first_name = String() last_name = String() age = Integer(minimum=1) _required = ['first_name', 'last_name'] class Groups(Structure): groups = Array(items=Person) _required = ['groups'] # ******************** class Example1(Structure): people = Array(items=Person) id = Integer() i = Integer() s = String() m = Map(items=[String(), Person]) groups = Groups _required = ['groups', 'id', 'm', 'people']
17.551724
47
0.581532
83eba35beb82cd28e9e1752e536b1d9e6b689fd9
1,212
lua
Lua
tidepool1.lua
sjtower/Super-Twiggle-World
79d7e601dfa87df20bef34173b1b08c0073678a1
[ "Apache-2.0" ]
null
null
null
tidepool1.lua
sjtower/Super-Twiggle-World
79d7e601dfa87df20bef34173b1b08c0073678a1
[ "Apache-2.0" ]
null
null
null
tidepool1.lua
sjtower/Super-Twiggle-World
79d7e601dfa87df20bef34173b1b08c0073678a1
[ "Apache-2.0" ]
null
null
null
local checkpoints = require("Checkpoints/checkpoints") local tidepool1 = { identifier = "tidepool1", title = "Tidepool 1: Octolus Rift", theme = THEME.TIDE_POOL, width = 4, height = 4, file_name = "tide-1.lvl", world = 4, level = 1, } local level_state = { loaded = false, callbacks = {}, } tidepool1.load_level = function() if level_state.loaded then return end level_state.loaded = true checkpoints.activate() define_tile_code("spike_shoes") level_state.callbacks[#level_state.callbacks+1] = set_pre_tile_code_callback(function(x, y, layer) local shoes = spawn_entity(ENT_TYPE.ITEM_PICKUP_SPIKESHOES, x, y, layer, 0, 0) shoes = get_entity(shoes) return true end, "spike_shoes") if not checkpoints.get_saved_checkpoint() then toast(tidepool1.title) end end tidepool1.unload_level = function() if not level_state.loaded then return end checkpoints.deactivate() local callbacks_to_clear = level_state.callbacks level_state.loaded = false level_state.callbacks = {} for _,callback in ipairs(callbacks_to_clear) do clear_callback(callback) end end return tidepool1
23.764706
102
0.685644
86e7c3b92a87fb47f458240d315df54da606de02
119
rs
Rust
src/lib/executor/mod.rs
myyrakle/rrdb
ccc0ee95732bdf100f1c3d6f0a69a20a2cb845fe
[ "MIT" ]
null
null
null
src/lib/executor/mod.rs
myyrakle/rrdb
ccc0ee95732bdf100f1c3d6f0a69a20a2cb845fe
[ "MIT" ]
null
null
null
src/lib/executor/mod.rs
myyrakle/rrdb
ccc0ee95732bdf100f1c3d6f0a69a20a2cb845fe
[ "MIT" ]
null
null
null
pub mod executor; pub use executor::*; pub mod config; pub use config::*; pub mod implements; pub use implements::*;
13.222222
22
0.705882
7f2bc3700b5322df21604116597712c8c7f0d092
771
go
Go
controller/charts/getpnl.go
zhs007/tradingwebserv
f27ba9eae03965df995eb73f60960f8f4732127b
[ "Apache-2.0" ]
null
null
null
controller/charts/getpnl.go
zhs007/tradingwebserv
f27ba9eae03965df995eb73f60960f8f4732127b
[ "Apache-2.0" ]
null
null
null
controller/charts/getpnl.go
zhs007/tradingwebserv
f27ba9eae03965df995eb73f60960f8f4732127b
[ "Apache-2.0" ]
null
null
null
package charts import ( "net/http" "time" "github.com/gin-gonic/gin" "github.com/zhs007/tradingwebserv/model/trading" ) // GetPNL - func GetPNL() gin.HandlerFunc { return func(c *gin.Context) { name := c.Request.FormValue("name") timezone := c.Request.FormValue("timezone") loc, err := time.LoadLocation(timezone) if err != nil { c.String(http.StatusOK, err.Error()) return } rtd, err := trading.GetTradingData(c.Request.Context(), name) if err != nil { c.String(http.StatusOK, err.Error()) return } lsttime, lstval := trading.FormatTradingData2PNLChart(loc, rtd) if err != nil { c.String(http.StatusOK, err.Error()) } else { c.HTML(http.StatusOK, "getpnl.html", gin.H{"lsttime": lsttime, "lstval": lstval}) } } }
19.275
84
0.656291
6e20a5c637f539e60084ff35a4f07769ebdde64f
12,838
xhtml
HTML
src/epub/text/chapter-2-14.xhtml
standardebooks/benjamin-disraeli_sybil
abbe306fd6cda07f6ed591e571d523c0079f551e
[ "CC0-1.0" ]
null
null
null
src/epub/text/chapter-2-14.xhtml
standardebooks/benjamin-disraeli_sybil
abbe306fd6cda07f6ed591e571d523c0079f551e
[ "CC0-1.0" ]
1
2018-12-10T21:42:43.000Z
2018-12-10T21:42:43.000Z
src/epub/text/chapter-2-14.xhtml
standardebooks/benjamin-disraeli_sybil
abbe306fd6cda07f6ed591e571d523c0079f551e
[ "CC0-1.0" ]
1
2021-02-05T05:51:28.000Z
2021-02-05T05:51:28.000Z
<?xml version="1.0" encoding="utf-8"?> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" epub:prefix="z3998: http://www.daisy.org/z3998/2012/vocab/structure/, se: https://standardebooks.org/vocab/1.0" xml:lang="en-GB"> <head> <title>XIV</title> <link href="../css/core.css" rel="stylesheet" type="text/css"/> <link href="../css/local.css" rel="stylesheet" type="text/css"/> </head> <body epub:type="bodymatter z3998:fiction"> <section id="book-2" epub:type="part"> <section id="chapter-2-14" epub:type="chapter"> <h3 epub:type="ordinal z3998:roman">XIV</h3> <p>“Your wife is ill?” said Sybil.</p> <p>“Very!” replied Warner’s wife. “Our daughter has behaved infamously to us. She has quitted us without saying by your leave or with your leave. And her wages were almost the only thing left to us; for Philip is not like Walter Gerard you see: he cannot earn two pounds a-week, though why he cannot I never could understand.”</p> <p>“Hush, hush, wife!” said Warner. “I speak I apprehend to Gerard’s daughter?”</p> <p>“Just so.”</p> <p>“Ah! this is good and kind; this is like old times, for Walter Gerard was my friend, when I was not exactly as I am now.”</p> <p>“He tells me so: he sent a messenger to me last night to visit you this morning. Your letter reached him only yesterday.”</p> <p>“Harriet was to give it to Caroline,” said the wife. “That’s the girl who has done all the mischief and inveigled her away. And she has left Trafford’s works, has she? Then I will be bound she and Harriet are keeping house together.”</p> <p>“You suffer?” said Sybil, moving to the bedside of the woman; “give me your hand,” she added in a soft sweet tone. “ ’Tis hot.”</p> <p>“I feel very cold,” said the woman. “Warner would have the window open, till the rain came in.”</p> <p>“And you, I fear, are wet,” said Warner, addressing Sybil, and interrupting his wife.</p> <p>“Very slightly. And you have no fire. Ah! I have brought some things for you, but not fuel.”</p> <p>“If he would only ask the person downstairs,” said his wife, “for a block of coal; I tell him, neighbours could hardly refuse; but he never will do anything; he says he has asked too often.”</p> <p>“I will ask,” said Sybil. “But first, I have a companion without,” she added, “who bears a basket for you. Come in, Harold.”</p> <p>The baby began to cry the moment a large dog entered the room; a young bloodhound of the ancient breed, such as are now found but in a few old halls and granges in the north of England. Sybil untied the basket, and gave a piece of sugar to the screaming infant. Her glance was sweeter even than her remedy; the infant stared at her with his large blue eyes; for an instant astonished, and then he smiled.</p> <p>“Oh! beautiful child!” exclaimed Sybil; and she took the babe up from the mattress and embraced it.</p> <p>“You are an angel from heaven,” exclaimed the mother, “and you may well say beautiful. And only to think of that infamous girl, Harriet, to desert us all in this way.”</p> <p>Sybil drew forth the contents of the convent basket, and called Warner’s attention to them. “Now,” she said, “arrange all this as I tell you, and I will go downstairs and speak to them below as you wish. Harold, rest there;” and the dog laid himself down in the remotest corner.</p> <p>“And is that Gerard’s daughter?” said the weaver’s wife. “Only think what it is to gain two pounds a-week, and bring up your daughters in that way⁠—instead of such shameless hussies as our Harriet! But with such wages one can do anything. What have you there, Warner? Is that tea? Oh! I should like some tea. I do think tea would do me some good. I have quite a longing for it. Run down, Warner, and ask them to let us have a kettle of hot water. It is better than all the fire in the world. Amelia, my dear, do you see what they have sent us. Plenty to eat. Tell Maria all about it. You are good girls; you will never be like that infamous Harriet. When you earn wages you will give them to your poor mother and baby, won’t you?”</p> <p>“Yes, mother,” said Amelia.</p> <p>“And father, too,” said Maria.</p> <p>“And father, too,” said the wife. “He has been a very good father to you all; and I never can understand why one who works so hard should earn so little; but I believe it is the fault of those machines. The police ought to put them down, and then everybody would be comfortable.”</p> <p>Sybil and Warner re-entered; the fire was lit, the tea made, the meal partaken. An air of comfort, even of enjoyment, was diffused over this chamber, but a few minutes back so desolate and unhappy.</p> <p>“Well,” said the wife, raising herself a little up in her bed, “I feel as if that dish of tea had saved my life. Amelia, have you had any tea? And Maria? You see what it is to be good girls; the Lord will never desert you. The day is fast coming when that Harriet will know what the want of a dish of tea is, with all her fine wages. And I am sure,” she added, addressing Sybil, “what we all owe to you is not to be told. Your father well deserves his good fortune, with such a daughter.”</p> <p>“My father’s fortunes are not much better than his neighbours,” said Sybil, “but his wants are few; and who should sympathise with the poor, but the poor? Alas! none else can. Besides, it is the Superior of our convent that has sent you this meal. What my father can do for you, I have told your husband. ’Tis little; but with the favour of heaven, it may avail. When the people support the people, the divine blessing will not be wanting.”</p> <p>“I am sure the divine blessing will never be wanting to you,” said Warner in a voice of great emotion.</p> <p>There was silence; the querulous spirit of the wife was subdued by the tone of Sybil; she revolved in her mind the present and the past; the children pursued their ungrudged and unusual meal; the daughter of Gerard, that she might not interfere with their occupation, walked to the window and surveyed the chink of troubled sky, which was visible in the court. The wind blew in gusts; the rain beat against the glass. Soon after this, there was another knock at the door. Harold started from his repose, and growled. Warner rose, and saying, “they have come for the rent. Thank God, I am ready,” advanced and opened the door. Two men offered with courtesy to enter.</p> <p>“We are strangers,” said he who took the lead, “but would not be such. I speak to Warner?”</p> <p>“My name.”</p> <p>“And I am your spiritual pastor, if to be the vicar of Mowbray entitles me to that description.”</p> <p>“<abbr>Mr.</abbr> <abbr>St.</abbr> Lys.”</p> <p>“The same. One of the most valued of my flock, and the most influential person in this district, has been speaking much of you to me this morning. You are working for him. He did not hear of you on Saturday night; he feared you were ill. <abbr>Mr.</abbr> Barber spoke to me of your distress, as well as of your good character. I came to express to you my respect and my sympathy, and to offer you my assistance.”</p> <p>“You are most good, sir, and <abbr>Mr.</abbr> Barber too, and indeed, an hour ago, we were in as great straits⁠—”</p> <p>“And are now, sir,” exclaimed his wife interrupting him. “I have been in this bed a-week, and may never rise from it again; the children have no clothes; they are pawned; everything is pawned; this morning we had neither fuel, nor food. And we thought you had come for the rent which we cannot pay. If it had not been for a dish of tea which was charitably given me this morning by a person almost as poor as ourselves that is to say, they live by labour, though their wages are much higher, as high as two pounds a-week, though how that can be I never shall understand, when my husband is working twelve hours a day, and gaining only a penny an hour⁠—if it had not been for this I should have been a corpse; and yet he says we were in straits, merely because Walter Gerard’s daughter, who I willingly grant is an angel from heaven for all the good she has done us, has stepped into our aid. But the poor supporting the poor, as she well says, what good can come from that!”</p> <p>During this ebullition, <abbr>Mr.</abbr> <abbr>St.</abbr> Lys had surveyed the apartment and recognised Sybil.</p> <p>“Sister,” he said when the wife of Warner had ceased, “this is not the first time we have met under the roof of sorrow.”</p> <p>Sybil bent in silence, and moved as if she were about to retire: the wind and rain came dashing against the window. The companion of <abbr>Mr.</abbr> <abbr>St.</abbr> Lys, who was clad in a rough great coat, and was shaking the wet off an oilskin hat known by the name of a ‘southwester,’ advanced and said to her, “It is but a squall, but a very severe one; I would recommend you to stay for a few minutes.”</p> <p>She received this remark with courtesy but did not reply.</p> <p>“I think,” continued the companion of <abbr>Mr.</abbr> <abbr>St.</abbr> Lys, “that this is not the first time also that we have met?”</p> <p>“I cannot recall our meeting before,” said Sybil.</p> <p>“And yet it was not many days past; though the sky was so very different, that it would almost make one believe it was in another land and another clime.”</p> <p>Sybil looked at him as if for explanation.</p> <p>“It was at Marney Abbey,” said the companion of <abbr>Mr.</abbr> <abbr>St.</abbr> Lys.</p> <p>“I was there; and I remember, when about to rejoin my companions, they were not alone.”</p> <p>“And you disappeared; very suddenly I thought: for I left the ruins almost at the same moment as your friends, yet I never saw any of you again.”</p> <p>“We took our course; a very rugged one; you perhaps pursued a more even way.”</p> <p>“Was it your first visit to Marney?”</p> <p>“My first and my last. There was no place I more desired to see; no place of which the vision made me so sad.”</p> <p>“The glory has departed,” said Egremont mournfully.</p> <p>“It is not that,” said Sybil: “I was prepared for decay, but not for such absolute desecration. The Abbey seems a quarry for materials to repair farmhouses; and the nave a cattle gate. What people they must be⁠—that family of sacrilege who hold these lands!”</p> <p>“Hem!” said Egremont. “They certainly do not appear to have much feeling for ecclesiastical art.”</p> <p>“And for little else, as we were told,” said Sybil. “There was a fire at the Abbey farm the day we were there, and from all that reached us, it would appear the people were as little tendered as the Abbey walls.”</p> <p>“They have some difficulty perhaps in employing their population in those parts.”</p> <p>“You know the country?”</p> <p>“Not at all: I was travelling in the neighbourhood, and made a diversion for the sake of seeing an abbey of which I had heard so much.”</p> <p>“Yes; it was the greatest of the Northern Houses. But they told me the people were most wretched round the Abbey; nor do I think there is any other cause for their misery, than the hard hearts of the family that have got the lands.”</p> <p>“You feel deeply for the people!” said Egremont looking at her earnestly.</p> <p>Sybil returned him a glance expressive of some astonishment, and then said, “And do not you? Your presence here assures me of it.”</p> <p>“I humbly follow one who would comfort the unhappy.”</p> <p>“The charity of <abbr>Mr.</abbr> <abbr>St.</abbr> Lys is known to all.”</p> <p>“And you⁠—you too are a ministering angel.”</p> <p>“There is no merit in my conduct, for there is no sacrifice. When I remember what this English people once was; the truest, the freest, and the bravest, the best-natured and the best-looking, the happiest and most religious race upon the surface of this globe; and think of them now, with all their crimes and all their slavish sufferings, their soured spirits and their stunted forms; their lives without enjoyment and their deaths without hope; I may well feel for them, even if I were not the daughter of their blood.”</p> <p>And that blood mantled to her cheek as she ceased to speak, and her dark eye gleamed with emotion, and an expression of pride and courage hovered on her brow. Egremont caught her glance and withdrew his own; his heart was troubled.</p> <p><abbr>St.</abbr> <abbr>Lys.</abbr> who had been in conference with the weaver, left him and went to the bedside of his wife. Warner advanced to Sybil, and expressed his feelings for her father, his sense of her goodness. She, observing that the squall seemed to have ceased, bade him farewell, and calling Harold, quitted the chamber.</p> </section> </section> </body> </html>
162.506329
985
0.72449
74458c253933e264df2976e54a884130e991c0a5
8,209
h
C
aws-cpp-sdk-amplify/include/aws/amplify/model/CreateDeploymentResult.h
grujicbr/aws-sdk-cpp
bdd43c178042f09c6739645e3f6cd17822a7c35c
[ "Apache-2.0" ]
1
2020-03-11T05:36:20.000Z
2020-03-11T05:36:20.000Z
aws-cpp-sdk-amplify/include/aws/amplify/model/CreateDeploymentResult.h
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
aws-cpp-sdk-amplify/include/aws/amplify/model/CreateDeploymentResult.h
novaquark/aws-sdk-cpp
a0969508545bec9ae2864c9e1e2bb9aff109f90c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/amplify/Amplify_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSMap.h> #include <utility> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Amplify { namespace Model { /** * <p> Result structure for create a new deployment. </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/amplify-2017-07-25/CreateDeploymentResult">AWS * API Reference</a></p> */ class AWS_AMPLIFY_API CreateDeploymentResult { public: CreateDeploymentResult(); CreateDeploymentResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); CreateDeploymentResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p> The jobId for this deployment, will supply to start deployment api. </p> */ inline const Aws::String& GetJobId() const{ return m_jobId; } /** * <p> The jobId for this deployment, will supply to start deployment api. </p> */ inline void SetJobId(const Aws::String& value) { m_jobId = value; } /** * <p> The jobId for this deployment, will supply to start deployment api. </p> */ inline void SetJobId(Aws::String&& value) { m_jobId = std::move(value); } /** * <p> The jobId for this deployment, will supply to start deployment api. </p> */ inline void SetJobId(const char* value) { m_jobId.assign(value); } /** * <p> The jobId for this deployment, will supply to start deployment api. </p> */ inline CreateDeploymentResult& WithJobId(const Aws::String& value) { SetJobId(value); return *this;} /** * <p> The jobId for this deployment, will supply to start deployment api. </p> */ inline CreateDeploymentResult& WithJobId(Aws::String&& value) { SetJobId(std::move(value)); return *this;} /** * <p> The jobId for this deployment, will supply to start deployment api. </p> */ inline CreateDeploymentResult& WithJobId(const char* value) { SetJobId(value); return *this;} /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline const Aws::Map<Aws::String, Aws::String>& GetFileUploadUrls() const{ return m_fileUploadUrls; } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline void SetFileUploadUrls(const Aws::Map<Aws::String, Aws::String>& value) { m_fileUploadUrls = value; } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline void SetFileUploadUrls(Aws::Map<Aws::String, Aws::String>&& value) { m_fileUploadUrls = std::move(value); } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& WithFileUploadUrls(const Aws::Map<Aws::String, Aws::String>& value) { SetFileUploadUrls(value); return *this;} /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& WithFileUploadUrls(Aws::Map<Aws::String, Aws::String>&& value) { SetFileUploadUrls(std::move(value)); return *this;} /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& AddFileUploadUrls(const Aws::String& key, const Aws::String& value) { m_fileUploadUrls.emplace(key, value); return *this; } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& AddFileUploadUrls(Aws::String&& key, const Aws::String& value) { m_fileUploadUrls.emplace(std::move(key), value); return *this; } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& AddFileUploadUrls(const Aws::String& key, Aws::String&& value) { m_fileUploadUrls.emplace(key, std::move(value)); return *this; } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& AddFileUploadUrls(Aws::String&& key, Aws::String&& value) { m_fileUploadUrls.emplace(std::move(key), std::move(value)); return *this; } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& AddFileUploadUrls(const char* key, Aws::String&& value) { m_fileUploadUrls.emplace(key, std::move(value)); return *this; } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& AddFileUploadUrls(Aws::String&& key, const char* value) { m_fileUploadUrls.emplace(std::move(key), value); return *this; } /** * <p> When the fileMap argument is provided in the request, the fileUploadUrls * will contain a map of file names to upload url. </p> */ inline CreateDeploymentResult& AddFileUploadUrls(const char* key, const char* value) { m_fileUploadUrls.emplace(key, value); return *this; } /** * <p> When the fileMap argument is NOT provided. This zipUploadUrl will be * returned. </p> */ inline const Aws::String& GetZipUploadUrl() const{ return m_zipUploadUrl; } /** * <p> When the fileMap argument is NOT provided. This zipUploadUrl will be * returned. </p> */ inline void SetZipUploadUrl(const Aws::String& value) { m_zipUploadUrl = value; } /** * <p> When the fileMap argument is NOT provided. This zipUploadUrl will be * returned. </p> */ inline void SetZipUploadUrl(Aws::String&& value) { m_zipUploadUrl = std::move(value); } /** * <p> When the fileMap argument is NOT provided. This zipUploadUrl will be * returned. </p> */ inline void SetZipUploadUrl(const char* value) { m_zipUploadUrl.assign(value); } /** * <p> When the fileMap argument is NOT provided. This zipUploadUrl will be * returned. </p> */ inline CreateDeploymentResult& WithZipUploadUrl(const Aws::String& value) { SetZipUploadUrl(value); return *this;} /** * <p> When the fileMap argument is NOT provided. This zipUploadUrl will be * returned. </p> */ inline CreateDeploymentResult& WithZipUploadUrl(Aws::String&& value) { SetZipUploadUrl(std::move(value)); return *this;} /** * <p> When the fileMap argument is NOT provided. This zipUploadUrl will be * returned. </p> */ inline CreateDeploymentResult& WithZipUploadUrl(const char* value) { SetZipUploadUrl(value); return *this;} private: Aws::String m_jobId; Aws::Map<Aws::String, Aws::String> m_fileUploadUrls; Aws::String m_zipUploadUrl; }; } // namespace Model } // namespace Amplify } // namespace Aws
38.359813
170
0.678645
e8ed68a76b6810bfc7416102a15fd740faaea0ec
4,699
py
Python
program.py
jaesik817/programmable-agents_tensorflow
b64d1774803c585e87aa9769beadde31e18f8ea4
[ "MIT" ]
39
2017-09-25T02:01:18.000Z
2019-06-18T15:17:53.000Z
program.py
jsikyoon/programmable-agents_tensorflow
b64d1774803c585e87aa9769beadde31e18f8ea4
[ "MIT" ]
5
2017-09-22T00:40:09.000Z
2018-05-07T15:11:11.000Z
program.py
jsikyoon/programmable-agents_tensorflow
b64d1774803c585e87aa9769beadde31e18f8ea4
[ "MIT" ]
10
2017-09-25T06:49:12.000Z
2019-06-18T10:17:03.000Z
import tensorflow as tf import numpy as np import math # Parameter order_num=2; class Program: def __init__(self,sess,state_dim,obj_num,fea_size,Theta,program_order,postfix): self.sess = sess; self.state_dim = state_dim; self.fea_size=fea_size; self.obj_num=obj_num; self.order_num=order_num; self.Theta=Theta; self.program_order=program_order; self.postfix=postfix; self.p = self.compile_order(); def compile_order(self): self.Theta=tf.reshape(self.Theta,[-1,self.obj_num,6]); self.Theta=tf.transpose(self.Theta,perm=[0,2,1]); self.Theta=tf.unstack(self.Theta,6,1); # temporary ordering p_1=tf.multiply(self.Theta[0],self.Theta[3]); p_1=p_1+self.Theta[5]; p_2=tf.multiply(self.Theta[1],self.Theta[3]); p_2=p_2+self.Theta[5]; p_3=tf.multiply(self.Theta[0],self.Theta[4]); p_3=p_3+self.Theta[5]; p_4=tf.multiply(self.Theta[1],self.Theta[4]); p_4=p_4+self.Theta[5]; program_order2=tf.unstack(self.program_order,(self.obj_num-1),1); p=tf.multiply(tf.stack([program_order2[0]]*(self.obj_num),1),p_1)+tf.multiply(tf.stack([program_order2[1]]*(self.obj_num),1),p_2)+tf.multiply(tf.stack([program_order2[2]]*(self.obj_num),1),p_3)+tf.multiply(tf.stack([program_order2[3]]*(self.obj_num),1),p_4); # Currently tf.cond makes problems """ program_order2=tf.unstack(self.program_order,self.order_num,1); for i in range(self.order_num): program_order2[i]=tf.unstack(program_order2[i],3,1); for i in range(self.order_num): for k in range(9): for l in range(k+1,9): # not=1, and=2, or=3 p=tf.cond(tf.equal(program_order2[i][0],1)&tf.equal(program_order2[i][1],k),lambda:1-self.Theta[k],lambda:p); p=tf.cond(tf.equal(program_order2[i][0],1)&tf.equal(program_order2[i][1],-1),lambda:1-p,lambda:p); p=tf.cond(tf.equal(program_order2[i][0],2)&tf.equal(program_order2[i][1],k)&tf.equal(program_order2[i][2],l),lambda:tf.multiply(self.Theta[k],self.Theta[l]),lambda:p); p=tf.cond(tf.equal(program_order2[i][0],2)&tf.equal(program_order2[i][1],k)&tf.equal(program_order2[i][2],-1),lambda:tf.multiply(self.Theta[k],p),lambda:p); p=tf.cond(tf.equal(program_order2[i][0],3)&tf.equal(program_order2[i][1],k)&tf.equal(program_order2[i][2],l),lambda:self.Theta[k]+self.Theta[l]-tf.multiply(self.Theta[k],self.Theta[l]),lambda:p); p=tf.cond(tf.equal(program_order2[i][0],3)&tf.equal(program_order2[i][1],k)&tf.equal(program_order2[i][2],l),lambda:self.Theta[k]+p-tf.multiply(self.Theta[k],p),lambda:p); """ return p; def run_target_nets(self,Theta,program_order): Theta=tf.reshape(Theta,[-1,self.obj_num,6]); Theta=tf.transpose(Theta,perm=[0,2,1]); Theta=tf.unstack(Theta,6,1); # temporary ordering p_1=tf.multiply(Theta[0],Theta[3]); p_1=p_1+Theta[5]; p_2=tf.multiply(Theta[1],Theta[3]); p_2=p_2+Theta[5]; p_3=tf.multiply(Theta[0],Theta[4]); p_3=p_3+Theta[5]; p_4=tf.multiply(Theta[1],Theta[4]); p_4=p_4+Theta[5]; program_order2=tf.unstack(program_order,(self.obj_num-1),1); p=tf.multiply(tf.stack([program_order2[0]]*(self.obj_num),1),p_1)+tf.multiply(tf.stack([program_order2[1]]*(self.obj_num),1),p_2)+tf.multiply(tf.stack([program_order2[2]]*(self.obj_num),1),p_3)+tf.multiply(tf.stack([program_order2[3]]*(self.obj_num),1),p_4); # Currently tf.cond makes problems """ # Currently tf.cond makes problems program_order2=tf.unstack(program_order,self.order_num,1); for i in range(self.order_num): program_order2[i]=tf.unstack(program_order2[i],3,1); for i in range(self.order_num): for k in range(9): for l in range(k+1,9): # not=1, and=2, or=3 p=tf.cond(tf.equal(program_order2[i][0],1)&tf.equal(program_order2[i][1],k),lambda:1-Theta[k],lambda:p); p=tf.cond(tf.equal(program_order2[i][0],1)&tf.equal(program_order2[i][1],-1),lambda:1-p,lambda:p); p=tf.cond(tf.equal(program_order2[i][0],2)&tf.equal(program_order2[i][1],k)&tf.equal(program_order2[i][2],l),lambda:tf.multiply(Theta[k],Theta[l]),lambda:p); p=tf.cond(tf.equal(program_order2[i][0],2)&tf.equal(program_order2[i][1],k)&tf.equal(program_order2[i][2],-1),lambda:tf.multiply(Theta[k],p),lambda:p); p=tf.cond(tf.equal(program_order2[i][0],3)&tf.equal(program_order2[i][1],k)&tf.equal(program_order2[i][2],l),lambda:Theta[k]+Theta[l]-tf.multiply(Theta[k],Theta[l]),lambda:p); p=tf.cond(tf.equal(program_order2[i][0],3)&tf.equal(program_order2[i][1],k)&tf.equal(program_order2[i][2],l),lambda:Theta[k]+p-tf.multiply(Theta[k],p),lambda:p); """ return p;
53.397727
262
0.668227
9c425790b4e45ba7bd6bbea00feacbde8dc5585b
1,569
js
JavaScript
ProtoPixel/scripts/webapp/remote/libs/widgets/v2/toggle.js
ImanolGo/IngoLightAndBuilding
23bfce0633ad056b2db5eb62822dc30c331ba800
[ "MIT", "Unlicense" ]
null
null
null
ProtoPixel/scripts/webapp/remote/libs/widgets/v2/toggle.js
ImanolGo/IngoLightAndBuilding
23bfce0633ad056b2db5eb62822dc30c331ba800
[ "MIT", "Unlicense" ]
null
null
null
ProtoPixel/scripts/webapp/remote/libs/widgets/v2/toggle.js
ImanolGo/IngoLightAndBuilding
23bfce0633ad056b2db5eb62822dc30c331ba800
[ "MIT", "Unlicense" ]
null
null
null
"use strict" newImports("widgets/cssvars.js") registerCustomElem("toggle", () => { const elem = newElem("label") setStyle(elem, { position: "relative", display: "inline-block", width: "2em", height: "1em", cursor: "pointer", }) const checkbox = append(elem, newINPUT("checkbox")) checkbox.checked = true hideElem(checkbox) const slider = append(elem, newDIV(), { position: "absolute", top: 0, left: 0, right: 0, bottom: 0, transition: ".4s", boxShadow: "0 0 1px 0 rgba(0, 0, 0, 0.5)", borderRadius: "0.6em", cursor: "pointer", }) slider.classList.add("switch") slider.classList.add("switchA") newCSSRule("input:checked + .switch", "background:var(--highlight)") newCSS(`.switch:before { position: absolute; content: ""; transition: .4s; box-shadow: 0 0 1px 0 rgba(0, 0, 0, 0.5); border-radius: 0.6em; }`) // switch A newCSS(`.switchA { background-color: rgba(120,120,120,0.5); }`) newCSS(`.switchA:before { width: 50%; height: 100%; left: 0px; bottom: 0px; background-color: var(--textColorBold); }`) newCSS(`input:checked + .switchA:before { transform: translateX(100%); }`) return { elem, checkbox } }) function newToggle(_elem = null) { const elem = _elem || newCustomElem("toggle") const cb = useAPIElem("checkbox", elem) elem.onclick = e => { e.stopPropagation() e.preventDefault() cb.checked = !cb.checked o.onchange(cb.checked) } const o = { elem: elem, onchange: noop, get value() { return cb.checked }, set value(v) { cb.checked = v } } return o }
19.134146
69
0.635437
4a4efcdd7924a5c21c7e0f1e332ee155ca95b166
1,521
js
JavaScript
frontend/src/components/thingInformation/Properties.test.js
cadivus/KIT-PSE_Sensordatenbankmanagementsystem
f493f14063142cdbb43d39a560fe353403808a79
[ "MIT" ]
1
2021-11-26T10:14:59.000Z
2021-11-26T10:14:59.000Z
frontend/src/components/thingInformation/Properties.test.js
cadivus/KIT-PSE_Sensordatenbankmanagementsystem
f493f14063142cdbb43d39a560fe353403808a79
[ "MIT" ]
null
null
null
frontend/src/components/thingInformation/Properties.test.js
cadivus/KIT-PSE_Sensordatenbankmanagementsystem
f493f14063142cdbb43d39a560fe353403808a79
[ "MIT" ]
null
null
null
import React from 'react' import {mount} from 'enzyme' import {getJson, getText, postJsonGetText} from '../../store/communication/restClient' import { getJson as getJsonMock, getText as getTextMock, postJsonGetText as postJsonGetTextMock, } from '../../../test/mock/store/communication/restClientMock' import Properties from './Properties' import ThingStore from '../../store/ThingStore' import {thing1, thing1Id} from '../../../test/mock/store/communication/mockData/backend/getJson' import DatastreamStore from '../../store/DatastreamStore' jest.mock('../../store/communication/restClient') beforeEach(() => { getJson.mockImplementation(getJsonMock) getText.mockImplementation(getTextMock) postJsonGetText.mockImplementation(postJsonGetTextMock) }) test('check for sensors', async () => { const thingStore = new ThingStore(new DatastreamStore()) const thing = await thingStore.getThing(thing1Id) const wrapper = mount(<Properties thing={thing} />) expect(wrapper.html().includes(thing1.description)).toBe(true) expect(wrapper.html().includes('Description: ')).toBe(true) expect(wrapper.html().includes('Location: ')).toBe(true) expect(wrapper.html().includes('shortname: ')).toBe(true) expect(wrapper.html().includes('hardware.id: ')).toBe(true) expect(wrapper.html().includes('operator.domain: ')).toBe(true) expect(wrapper.html().includes('Street:')).toBe(true) expect(wrapper.html().includes('City:')).toBe(true) expect(wrapper.html().includes('Coordinates:')).toBe(true) })
40.026316
96
0.737015
133c3f7ad60793003d0d04455f2d7c7a96eeb481
6,243
h
C
io_engine/include/ps.h
kefanchen/rctcp
806838cfc578678fc9eaf612f5dcf8df9f928984
[ "BSD-3-Clause" ]
1
2017-07-13T14:45:54.000Z
2017-07-13T14:45:54.000Z
io_engine/include/ps.h
shakuniji/mtcp
a3c73c8be22f5be3833b947c0b8be8af98151cb5
[ "BSD-3-Clause" ]
1
2018-01-11T00:11:41.000Z
2018-01-11T17:21:47.000Z
io_engine/include/ps.h
shakuniji/mtcp
a3c73c8be22f5be3833b947c0b8be8af98151cb5
[ "BSD-3-Clause" ]
2
2021-09-03T10:18:52.000Z
2021-09-18T21:23:40.000Z
#ifndef _PS_H_ #define _PS_H_ #define MAX_DEVICES 16 #define MAX_RINGS 64 /* IN: option for ps_wait(); */ #define PS_CTL_IN 0x1 /* The associated queue is available to read */ #define PS_CTL_OUT 0x2 /* The associated queue is available to write */ /* The associated queue is available to write or read */ #define PS_CTL_INOUT (PS_CTL_IN | PS_CTL_OUT) /* OUT: return values for ps_wait() */ #define PS_SEND_AVAILABLE 0x1 /* The associated queue is available to read */ #define PS_RECEIVE_AVAILABLE 0x2 /* The associated queue is available to write */ /* The associated queue is available to read and write */ #define PS_ALL_AVAILABLE (PS_SEND_AVAILABLE | PS_RECEIVE_AVAILABLE) #define PS_SEND_MIN 256 #ifdef __KERNEL__ #define PS_MAJOR 1010 #define PS_NAME "packet_shader" #define MAX_BUFS (12*4) struct ____cacheline_aligned ps_context { struct semaphore sem; wait_queue_head_t wq; int num_attached; struct ixgbe_ring *rx_rings[MAX_RINGS]; int next_ring; struct ps_pkt_info *info; /* char *buf; */ int num_bufs; int buf_refcnt[MAX_BUFS]; char *kbufs[MAX_BUFS]; char __user *ubufs[MAX_BUFS]; }; #else /* __KERNEL__ */ #include <string.h> #include <stdint.h> #include <pthread.h> #include <linux/types.h> #define __user #ifndef IFNAMSIZ #define IFNAMSIZ 16 #endif #ifndef ETH_ALEN #define ETH_ALEN 6 #endif #define ALIGN(x,a) __ALIGN_MASK(x,(typeof(x))(a)-1) #define __ALIGN_MASK(x,mask) (((x)+(mask))&~(mask)) static inline __sum16 ip_fast_csum(const void *iph, unsigned int ihl) { unsigned int sum; asm(" movl (%1), %0\n" " subl $4, %2\n" " jbe 2f\n" " addl 4(%1), %0\n" " adcl 8(%1), %0\n" " adcl 12(%1), %0\n" "1: adcl 16(%1), %0\n" " lea 4(%1), %1\n" " decl %2\n" " jne 1b\n" " adcl $0, %0\n" " movl %0, %2\n" " shrl $16, %0\n" " addw %w2, %w0\n" " adcl $0, %0\n" " notl %0\n" "2:" /* Since the input registers which are loaded with iph and ih are modified, we must also specify them as outputs, or gcc will assume they contain their original values. */ : "=r" (sum), "=r" (iph), "=r" (ihl) : "1" (iph), "2" (ihl) : "memory"); return (__sum16)sum; } #endif /* __KERNEL__ */ struct ps_device { char name[IFNAMSIZ]; char dev_addr[ETH_ALEN]; uint32_t ip_addr; /* network order */ /* NOTE: this is different from kernel's internal index */ int ifindex; /* This is kernel's ifindex. */ int kifindex; int num_rx_queues; int num_tx_queues; }; struct ps_queue { int ifindex; int qidx; }; #define MAX_PACKET_SIZE 2048 #define MAX_CHUNK_SIZE 4096 #define ENTRY_CNT 4096 #define PS_CHECKSUM_RX_UNKNOWN 0 #define PS_CHECKSUM_RX_GOOD 1 #define PS_CHECKSUM_RX_BAD 2 struct ps_pkt_info { uint32_t offset; uint16_t len; uint8_t checksum_rx; }; struct ps_chunk { /* number of packets to send/recv */ int cnt; int recv_blocking; /* for RX: output (where did these packets come from?) for TX: input (which interface do you want to xmit?) */ struct ps_queue queue; struct ps_pkt_info __user *info; char __user *buf; }; struct ps_chunk_buf { uint16_t cnt; uint16_t next_to_use; uint16_t next_to_send; uint32_t next_offset; struct ps_queue queue; void __user *lock; struct ps_pkt_info __user *info; char __user *buf; }; struct ps_packet { int ifindex; int len; char __user *buf; }; #define NID_ZERO(isp) (isp = 0) #define NID_SET(id, isp) (isp |= 1 << id) #define NID_CLR(id, isp) (isp &= ~(1 << id)) #define NID_ISSET(id, isp) (isp & (1 << id)) // maximum number of interface descriptor is 16 typedef uint16_t nids_set; struct ps_event { long timeout; int qidx; nids_set rx_nids; nids_set tx_nids; }; static inline void prefetcht0(void *p) { asm volatile("prefetcht0 (%0)\n\t" : : "r" (p) ); } static inline void prefetchnta(void *p) { asm volatile("prefetchnta (%0)\n\t" : : "r" (p) ); } static inline void memcpy_aligned(void *to, const void *from, size_t len) { if (len <= 64) { memcpy(to, from, 64); } else if (len <= 128) { memcpy(to, from, 64); memcpy((uint8_t *)to + 64, (uint8_t *)from + 64, 64); } else { size_t offset; for (offset = 0; offset < len; offset += 64) memcpy((uint8_t *)to + offset, (uint8_t *)from + offset, 64); } } #define PS_IOC_LIST_DEVICES 0 #define PS_IOC_ATTACH_RX_DEVICE 1 #define PS_IOC_DETACH_RX_DEVICE 2 #define PS_IOC_RECV_CHUNK 3 #define PS_IOC_SEND_CHUNK 4 #define PS_IOC_SLOWPATH_PACKET 5 #define PS_IOC_RECV_CHUNK_IFIDX 6 #define PS_IOC_SEND_CHUNK_BUF 7 #define PS_IOC_GET_TXENTRY 8 #define PS_IOC_SELECT 9 #ifndef __KERNEL__ struct ps_handle { int fd; uint64_t rx_chunks[MAX_DEVICES]; uint64_t rx_packets[MAX_DEVICES]; uint64_t rx_bytes[MAX_DEVICES]; uint64_t tx_chunks[MAX_DEVICES]; uint64_t tx_packets[MAX_DEVICES]; uint64_t tx_bytes[MAX_DEVICES]; void *priv; }; int ps_list_devices(struct ps_device *devices); int ps_init_handle(struct ps_handle *handle); void ps_close_handle(struct ps_handle *handle); int ps_attach_rx_device(struct ps_handle *handle, struct ps_queue *queue); int ps_detach_rx_device(struct ps_handle *handle, struct ps_queue *queue); int ps_alloc_chunk(struct ps_handle *handle, struct ps_chunk *chunk); void ps_free_chunk(struct ps_chunk *chunk); int ps_alloc_chunk_buf(struct ps_handle *handle, int ifidx, int qidx, struct ps_chunk_buf *c_buf); void ps_free_chunk_buf(struct ps_chunk_buf *c_buf); char* ps_assign_chunk_buf(struct ps_chunk_buf *c_buf, int len); int ps_recv_chunk(struct ps_handle *handle, struct ps_chunk *chunk); int ps_recv_chunk_ifidx(struct ps_handle *handle, struct ps_chunk *chunk, int ifidx); int ps_send_chunk(struct ps_handle *handle, struct ps_chunk *chunk); int ps_send_chunk_buf(struct ps_handle *handle, struct ps_chunk_buf *chunk); int ps_select(struct ps_handle *handle, struct ps_event * event); int ps_get_txentry(struct ps_handle *handle, struct ps_queue * queue); int ps_slowpath_packet(struct ps_handle *handle, struct ps_packet *packet); void dump_packet(char *buf, int len); void dump_chunk(struct ps_chunk *chunk); int get_num_cpus(); int bind_cpu(int cpu); uint64_t rdtsc(); #endif #endif /* _PS_H_ */
23.122222
85
0.700465
92a733618f388dcfcbb5f28fcdb4d07f61e49701
154
sql
SQL
keyCars.sql
Amnesia80/esx_carkeys
04b30dc60fc5b6e93bbaa4c981ec6b89cf9c7f9c
[ "Apache-2.0" ]
1
2019-11-19T04:05:05.000Z
2019-11-19T04:05:05.000Z
keyCars.sql
Amnesia80/esx_carkeys
04b30dc60fc5b6e93bbaa4c981ec6b89cf9c7f9c
[ "Apache-2.0" ]
1
2019-12-13T21:54:38.000Z
2019-12-13T21:54:38.000Z
keyCars.sql
Amnesia80/esx_carkeys
04b30dc60fc5b6e93bbaa4c981ec6b89cf9c7f9c
[ "Apache-2.0" ]
null
null
null
CREATE TABLE `owned_keys` ( `id` int NOT NULL AUTO_INCREMENT, `plate` VARCHAR(50) NOT NULL, `owner` VARCHAR(22) NOT NULL, PRIMARY KEY (`id`) );
22
35
0.655844
b4a94db46489d9e02fd3d3d9b0c66164ac17e938
933
lua
Lua
prototypes/item.lua
Baedel/Quarry-fix
782600f8eaeed4afb20700f85734133d719598a1
[ "MIT" ]
null
null
null
prototypes/item.lua
Baedel/Quarry-fix
782600f8eaeed4afb20700f85734133d719598a1
[ "MIT" ]
null
null
null
prototypes/item.lua
Baedel/Quarry-fix
782600f8eaeed4afb20700f85734133d719598a1
[ "MIT" ]
null
null
null
data:extend({ { type = "item", name = "quarry", icon = "__Quarry-fix__/graphics/quarry/quarry-icon.png", icon_size = 32, flags = {"goes-to-quickbar"}, subgroup = "extraction-machine", order = "a[items]-m[quarry]", place_result = "quarry", stack_size = 20 }, { type = "item", name = "quarry-mk2", icon = "__Quarry-fix__/graphics/quarry-mk2/quarry-icon.png", icon_size = 32, flags = {"goes-to-quickbar"}, subgroup = "extraction-machine", order = "a[items]-n[quarry-mk2]", place_result = "quarry-mk2", stack_size = 20 }, { type = "item", name = "quarry-mk3", icon = "__Quarry-fix__/graphics/quarry-mk3/quarry-icon.png", icon_size = 32, flags = {"goes-to-quickbar"}, subgroup = "extraction-machine", order = "a[items]-o[quarry-mk3]", place_result = "quarry-mk3", stack_size = 20 } })
26.657143
65
0.566988
46b978207334e620243aa38c30bb3cc21ee07b35
4,672
css
CSS
style.css
easthermutheumwengei/Anitas-Kitchen
a0722b0e17bf65d754140ad780398f72f39a9edb
[ "MIT" ]
null
null
null
style.css
easthermutheumwengei/Anitas-Kitchen
a0722b0e17bf65d754140ad780398f72f39a9edb
[ "MIT" ]
null
null
null
style.css
easthermutheumwengei/Anitas-Kitchen
a0722b0e17bf65d754140ad780398f72f39a9edb
[ "MIT" ]
null
null
null
*body{ margin: 2%,2%,0,2%; padding: 0; box-sizing: border-box; } .container{ background-image: url("./assets-20210424T204913Z-001/assets/backgrounds/landing.jpg"); height: 900px; } .logo{ text-align: center; } .text{ text-align: center; color: white; } .list2{ display: flex; height: 20vh; } #items{ display: flex; flex-direction: column; align-items: center; width: 24%; /* height: 10vh; padding-bottom: 100px; */ } #item1{ font-size: 20px; /* border-bottom: 1px solid black; */ height: 10vh; align-items: center; font-style: italic; } #item2{ display: flex; justify-content: center; align-items: center; /* color: white; */ font-style: italic; height: 10vh; width: 97%; font-size: 20px; background-color: #F15A29; padding: 10px; } #two{ background-image:url(./assets-20210424T204913Z-001/assets/foodtop/breakfast.jpg); background-size: cover; display: flex; justify-content: center; align-items: center; color: white; font-style: italic; height: 140px; width: 30%; font-size: 20px; text-align: center; } #there{ background-image: url(./assets-20210424T204913Z-001/assets/foodtop/lunch.jpg); background-size: cover; display: flex; justify-content: center; font-style: italic; color: white; height:140px ; width: 26%; font-size: 20px; text-align: center; align-items: center; } #four{ background-image: url(./assets-20210424T204913Z-001/assets/foodtop/dinner.jpg); background-size: cover; display: flex; justify-content: center; font-style: italic; color: white; height: 140px; width: 26%; font-size: 20px; text-align: center; align-items: center; } .breakfast{ /* background-image: url("./assets-20210424T204913Z-001/assets/foodtop/breakfast.jpg"); */ background-size: cover; display: flex; justify-content: center; align-items: center; color: white; font-style: italic; height: 20vh; width: 20%; font-size: 20px; text-align: center; } .fastfoods{ display: flex; padding-top: 60px; } .fastimg{ display: flex; flex-direction: column; } .fastfood1{ text-align: center; padding-left: 40px; } .g1{ border: solid red; padding: 10px 0; border-width: 1px; } .drinks{ display: flex; } .main{ display: flex; padding-top: 60px; flex-direction: ; } .main2{ text-align: left; } #navigation{ background-image: url("./assets-20210424T204913Z-001/assets/backgrounds/foodsBg.jpg"); display: flex; justify-content: center; align-items: center; height: 600px; padding-top: 60px; } #burger{ margin: 0 auto; width: 80%; padding: 10px; background: white; } #fd2{ display: flex; justify-content: space-evenly; font-size: 22px; background-color: grey; color: white; text-decoration: none; } .container3{ display: flex; justify-content: space-around; align-items: center; } .fd2{ display: flex; justify-content: space-around; color: white; } nav h4 { background-color: white; padding-top: 60px; } .customers{ display: flex; text-align: left; /* margin-right: 50%; */ /* border: 2px solid grey; padding: 1%; width: 40%; align-items: center; margin-left: 10%; */ } .name{ color: #F15A29; } .hc{ text-align: center; color: #F15A29; } .cst{ display: flex; justify-content: space-evenly; } .para{ color:black; } #border{ border-left: 1px solid black; box-sizing: border-box; border-bottom-left-radius: 30px; color: grey; text-align: left; } .get{ background-image: url("./assets-20210424T204913Z-001/assets/backgrounds/subscribe.jpg"); height: 600px; text-align: center; color: white; padding-bottom: 30px; } .email{ background-color: white; padding: 10px 20px; } .button{ background-color: #F15A29; padding: 10px 20px; } .all{ padding-bottom: 200px; } .menu{ text-align: right; margin-left: 50%; width: 40%; padding: 1%; border: 2px solid grey; } .about h3{ color: #F15A29; } } .menu1{ display: flex; flex-direction: right; justify-content: center; background-color: #F15A29; height: 300px; color: white; text-align: center; padding-top: 20px; } .menu2{ background-color: #F15A29; padding-bottom: 20px; text-align: center; } h6{ display: flex; justify-content: center; background-color: #F15A29; } .icons3{ display: flex; justify-content: space-evenly; }
18.83871
94
0.622432
be3ed71979521413c5cf68717a2006a9c81f7a82
3,573
rs
Rust
bc/mav/src/kits.rs
scryinfo/cashbox
667b89c4b3107b9229c3758bf9f8266316dac08f
[ "Apache-2.0" ]
51
2020-06-29T02:03:29.000Z
2021-05-24T08:14:07.000Z
bc/mav/src/kits.rs
scryinfo/cashbox
667b89c4b3107b9229c3758bf9f8266316dac08f
[ "Apache-2.0" ]
48
2020-07-06T08:04:46.000Z
2021-07-17T07:22:31.000Z
bc/mav/src/kits.rs
scryinfo/cashbox
667b89c4b3107b9229c3758bf9f8266316dac08f
[ "Apache-2.0" ]
8
2020-08-05T09:40:46.000Z
2021-11-26T12:45:46.000Z
use std::{fmt, fs, io, path}; use std::ops::Add; use rbatis::rbatis::{Rbatis, RbatisOption}; use uuid::Uuid; use rbatis::plugin::log::{RbatisLogPlugin, LogPlugin}; use std::sync::Arc; #[derive(Debug, PartialEq, Clone, Default)] pub struct Error { pub err: String, } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Db Error: {}", self.err) } } impl From<rbatis_core::Error> for Error { fn from(e: rbatis_core::Error) -> Self { Error::from(e.to_string().as_str()) } } impl From<&str> for Error { fn from(e: &str) -> Self { Self { err: e.to_owned() } } } impl From<io::Error> for Error { fn from(err: io::Error) -> Self { Error::from(err.to_string().as_str()) } } pub fn uuid() -> String { Uuid::new_v4().to_string() } pub fn now_ts_seconds() -> i64 { chrono::offset::Utc::now().timestamp() } /// 如果数据库文件不存在,则创建它 /// 如果连接出错直接panic pub async fn make_rbatis(db_file_name: &str) -> Result<Rbatis, Error> { if fs::metadata(db_file_name).is_err() { let file = path::Path::new(db_file_name); let dir = file.parent(); if dir.is_none() { return Err(Error::from(db_file_name)); } let dir = dir.unwrap(); fs::create_dir_all(dir)?; fs::File::create(db_file_name)?; } let rb = Rbatis::new(); let url = "sqlite://".to_owned().add(db_file_name); rb.link(url.as_str()).await?; return Ok(rb); } pub async fn make_memory_rbatis() -> Result<Rbatis, Error> { let rb = { let op = RbatisOption { log_plugin: Arc::new(Box::new(RbatisLogPlugin { level_filter: log::max_level(), }) as Box<dyn LogPlugin>), ..RbatisOption::default() }; Rbatis::new_with_opt(op) }; let url = "sqlite://:memory:".to_owned(); rb.link(&url).await?; return Ok(rb); } #[cfg(test)] pub mod test { use futures::executor::block_on; use rbatis::rbatis::Rbatis; use crate::kits::make_memory_rbatis; use crate::ma::{Db, DbName}; pub fn mock_memory_db() -> Db { let mut db = Db::default(); let re = block_on(db.init_memory_sql(&DbName::new("", ""))); assert_eq!(false, re.is_err(), "{:?}", re.unwrap_err()); db } pub fn mock_files_db() -> Db { let mut db = Db::default(); let re = block_on(db.connect(&DbName::new("test_", "./temp"))); assert_eq!(false, re.is_err(), "{:?}", re); db } pub async fn make_memory_rbatis_test() -> Rbatis { struct SimpleLogger; impl log::Log for SimpleLogger { fn enabled(&self, _: &log::Metadata) -> bool { true } fn log(&self, record: &log::Record) { println!("{} - {}", record.level(), record.args()); } fn flush(&self) {} } let _ = log::set_boxed_logger(Box::new(SimpleLogger)); log::set_max_level(log::LevelFilter::Info); let re = make_memory_rbatis().await; re.unwrap() } } pub fn sql_left_join_get_b(a: &str, a_id: &str, b: &str, b_id: &str) -> String { let sql = { format!("select {}.* from {} left join {} on {}.{} = {}.{}", b, a, b, a, a_id, b, b_id ) }; sql } pub fn sql_left_join_get_a(a: &str, a_id: &str, b: &str, b_id: &str) -> String { let sql = { format!("select {}.* from {} left join {} on {}.{} = {}.{}", a, a, b, a, a_id, b, b_id ) }; sql }
26.664179
82
0.541562
a1b52b1a682458680ea0bbdbb56cb6179097bd3c
121
h
C
FirstInterCommunication/src/TextureAttribute.h
droplet92/FIC
db8bcc2503f7001dc6af5474b59ef9129f995f91
[ "MIT" ]
null
null
null
FirstInterCommunication/src/TextureAttribute.h
droplet92/FIC
db8bcc2503f7001dc6af5474b59ef9129f995f91
[ "MIT" ]
null
null
null
FirstInterCommunication/src/TextureAttribute.h
droplet92/FIC
db8bcc2503f7001dc6af5474b59ef9129f995f91
[ "MIT" ]
null
null
null
#pragma once #include <string> namespace Texture { struct TextureAttribute { int id; std::string pathname; }; }
11
24
0.68595
9eac6ec6b584b87dd0e5f46abbe4c51e8c6c88c0
356
sql
SQL
sql/src/test/resources/insert_jobinput.sql
ykyang/org.allnix.java
a21a611ac785d714cf3f794ed8a5addaf62637e7
[ "Apache-2.0" ]
null
null
null
sql/src/test/resources/insert_jobinput.sql
ykyang/org.allnix.java
a21a611ac785d714cf3f794ed8a5addaf62637e7
[ "Apache-2.0" ]
null
null
null
sql/src/test/resources/insert_jobinput.sql
ykyang/org.allnix.java
a21a611ac785d714cf3f794ed8a5addaf62637e7
[ "Apache-2.0" ]
null
null
null
INSERT OR IGNORE INTO JOBINPUT VALUES ('e5a482e5-ceed-4cdb-b82f-4dcdfc7757cb', '{"method":"simulate"}'); INSERT OR IGNORE INTO JOBINPUT VALUES ('a5b5a598-97fe-45c6-af65-59f09aee24a7', '{"method":"run"}'); INSERT OR IGNORE INTO JOBINPUT VALUES ('a', '{"id":"a", "method":"run"}'); INSERT OR IGNORE INTO JOBINPUT VALUES ('b', '{"id":"b", "method":"run"}');
59.333333
104
0.676966
befb536317d51c660b53b573c5bc7be23164f37d
987
html
HTML
manuscript/page-164/body.html
marvindanig/Sense-and-Sensibility
9ca3dbab123fde9ec42221daf9fc53446efac69f
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
manuscript/page-164/body.html
marvindanig/Sense-and-Sensibility
9ca3dbab123fde9ec42221daf9fc53446efac69f
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
manuscript/page-164/body.html
marvindanig/Sense-and-Sensibility
9ca3dbab123fde9ec42221daf9fc53446efac69f
[ "BlueOak-1.0.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
<div class="leaf "><div class="inner justify"><p class="no-indent ">hope you like your house, Miss Marianne. It is a very large one, I know; and when I come to see you, I hope you will have new-furnished it, for it wanted it very much when I was there six years ago."</p><p>Marianne turned away in great confusion. Mrs. Jennings laughed heartily; and Elinor found that in her resolution to know where they had been, she had actually made her own woman enquire of Mr. Willoughby's groom; and that she had by that method been informed that they had gone to Allenham, and spent a considerable time there in walking about the garden and going all over the house.</p><p>Elinor could hardly believe this to be true, as it seemed very unlikely that Willoughby should propose, or Marianne consent, to enter the house while Mrs. Smith was in it, with whom Marianne had not the smallest acquaintance.</p><p class=" stretch-last-line ">As soon as they left the dining-room, Elinor</p></div> </div>
987
987
0.763931
2f6f8fd432c77d594a6798630e70b3e80e9bc45e
336
sql
SQL
server/midlib/SessionRedis/test_ip_ban.sql
pschlump/Go-FTL
21aa93798aa0fcfd75068cf584a5fe612a494273
[ "MIT" ]
6
2016-06-29T05:38:43.000Z
2019-07-29T03:59:18.000Z
server/midlib/SessionRedis/test_ip_ban.sql
pschlump/Go-FTL
21aa93798aa0fcfd75068cf584a5fe612a494273
[ "MIT" ]
null
null
null
server/midlib/SessionRedis/test_ip_ban.sql
pschlump/Go-FTL
21aa93798aa0fcfd75068cf584a5fe612a494273
[ "MIT" ]
null
null
null
-- CREATE or REPLACE FUNCTION s_ip_ban(p_ip_addr varchar) -- select 'success-019' from dual where exists ( select 'ok' from "t_config" where "customer_id" = '1' and "item_name" = '2fa.required' ); select 'success-100' from dual where s_ip_ban ( '1.1.1.1' ) = false; select 'success-101' from dual where s_ip_ban ( '1.1.1.2' ) = true;
48
138
0.693452
b77999b3c67eef625e08322a3ff5c8019513c95a
859
swift
Swift
Manoj-MVVM-Demo/Network/MovieAPIService.swift
manojgadamsetty/Sample_MVVM
0e5dfb101e282aeb6680435953a8b3a750cc735c
[ "MIT" ]
null
null
null
Manoj-MVVM-Demo/Network/MovieAPIService.swift
manojgadamsetty/Sample_MVVM
0e5dfb101e282aeb6680435953a8b3a750cc735c
[ "MIT" ]
null
null
null
Manoj-MVVM-Demo/Network/MovieAPIService.swift
manojgadamsetty/Sample_MVVM
0e5dfb101e282aeb6680435953a8b3a750cc735c
[ "MIT" ]
null
null
null
// // MovieAPIService.swift // Manoj-MVVM-Demo // // Created by Manoj Gadamsetty on 03/08/20. // Copyright © 2020 Manoj Gadamsetty. All rights reserved. // import UIKit class MovieAPIService: NSObject, Requestable { static let instance = MovieAPIService() public var movies: [Movie]? // Prepare the service func prepare(callback: @escaping([Movie]?,Bool) -> Void) { let filePath = Bundle.main.url(forResource: "movie", withExtension: "json") let originalContents = try? Data(contentsOf: filePath!) let movies = try? JSONDecoder().decode([Movie].self, from: originalContents!) callback(movies!, false) } func fetchMovies(callback: @escaping Handler) { request(method: .get, url: Domain.baseUrl() + APIEndpoint.movies) { (result) in callback(result) } } }
27.709677
87
0.647264
7122fee7a4f1463091408a338473f82b6ddd896a
838
ts
TypeScript
src/state/actionCreators/index.ts
UnumID/acme-demo-client
e9ff656b8aaee2ba33eaefc885c43103acdd4a90
[ "MIT" ]
null
null
null
src/state/actionCreators/index.ts
UnumID/acme-demo-client
e9ff656b8aaee2ba33eaefc885c43103acdd4a90
[ "MIT" ]
null
null
null
src/state/actionCreators/index.ts
UnumID/acme-demo-client
e9ff656b8aaee2ba33eaefc885c43103acdd4a90
[ "MIT" ]
null
null
null
import { Dispatch } from 'redux'; import { resetSessionState } from './session'; import { resetPresentationState } from './presentation'; import { resetPresentationRequestState } from './presentationRequest'; import { resetUserState } from './user'; import { logout } from './auth'; export * from './session'; export * from './presentationRequest'; export * from './presentation'; export * from './user'; export * from './auth'; export const resetState = () => async (dispatch: Dispatch): Promise<void> => { dispatch(resetPresentationState()); dispatch(resetPresentationRequestState()); dispatch(resetSessionState()); dispatch(resetUserState()); await logout()(dispatch); }; export const startOver = () => (dispatch: Dispatch): void => { dispatch(resetPresentationState()); dispatch(resetPresentationRequestState()); };
31.037037
78
0.711217
ab112e972619dfbba243ddb2a7dbed7658d3c4c4
6,685
sql
SQL
database/blog.sql
Sahsanem/Java-MySql-Servlet-Web-Application-Blog-Project
87b9ac63c3afaa1d3df70ad1637d429a3b80205c
[ "MIT" ]
1
2021-10-08T12:14:20.000Z
2021-10-08T12:14:20.000Z
database/blog.sql
Sahsanem/Java-MySql-Servlet-Web-Application-Blog-Project
87b9ac63c3afaa1d3df70ad1637d429a3b80205c
[ "MIT" ]
null
null
null
database/blog.sql
Sahsanem/Java-MySql-Servlet-Web-Application-Blog-Project
87b9ac63c3afaa1d3df70ad1637d429a3b80205c
[ "MIT" ]
null
null
null
-- phpMyAdmin SQL Dump -- version 5.1.1 -- https://www.phpmyadmin.net/ -- -- Anamakine: 127.0.0.1 -- Üretim Zamanı: 13 Ağu 2021, 08:19:55 -- Sunucu sürümü: 10.4.20-MariaDB -- PHP Sürümü: 7.3.29 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 */; -- -- Veritabanı: `blog` -- -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `admin` -- CREATE TABLE `admin` ( `aid` int(11) NOT NULL, `ad` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `password` varchar(32) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Tablo döküm verisi `admin` -- INSERT INTO `admin` (`aid`, `ad`, `email`, `password`) VALUES (1, 'Ali Kar', 'ali@gmail.com', 'e10adc3949ba59abbe56e057f20f883e'), (2, 'Azra Ok', 'azra@mail.com', 'e10adc3949ba59abbe56e057f20f883e'), (3, 'Veli Can', 'veli@mail.com', 'e10adc3949ba59abbe56e057f20f883e'); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `blog` -- CREATE TABLE `blog` ( `bid` int(11) NOT NULL, `title` varchar(255) NOT NULL, `detail` text NOT NULL, `date` datetime NOT NULL, `aid` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Tablo döküm verisi `blog` -- INSERT INTO `blog` (`bid`, `title`, `detail`, `date`, `aid`) VALUES (3, 'What is Lorem Ipsum?', 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.', '2021-08-11 02:41:16', 2), (5, 'Why do we use it?', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using \'Content here, content here\', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for \'lorem ipsum\' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '2021-08-11 02:45:47', 3), (8, 'Büyük Patlama', '1929’da Edwin Hubble’ın uzak galaksilerdeki (galaksilerin ışığındaki) nispi kırmızıya kaymayı keşfinden sonra, bu gözlemi, çok uzak galaksilerin ve galaksi kümelerinin konumumuza oranla bir \"görünür hız\"a sahip olduklarını ortaya koyan bir kanıt olarak ele alındı. Bunlardan en yüksek \"görünür hız\"la hareket edenler en uzak olanlarıdır.[7] Galaksi kümeleri arasındaki uzaklık gitgide artmakta olduğuna göre, bunların hepsinin geçmişte bir arada olmaları gerekmektedir. Big Bang modeline göre, evren genişlemeden önceki bu ilk durumundayken aşırı derecede yoğun ve sıcak bir halde bulunuyordu. Bu ilk hale benzer koşullarda üretilen \"parçacık hızlandırıcı\"larla yapılan deney sonuçları teoriyi doğrulamaktadır. Fakat bu hızlandırıcılar, şimdiye dek yalnızca laboratuvar ortamındaki yüksek enerji sistemlerinde denenebilmiştir. Evrenin genişlemesi olgusu bir yana bırakılırsa, Big Bang teorisinin, ilk genişleme anına ilişkin bir bulgu olmaksızın bu ilk hale herhangi bir kesin açıklama getirmesi mümkün değildir. Kozmozdaki hafif elementlerin günümüzde gözlemlediğimiz bolluğu, Big Bang teorisince kabul edilen ilk nükleosentez[8] sonuçlarına uygun olarak, evrenin ilk hızlı genişleme ve soğuma dakikalarındaki nükleer süreçlerde hafif elementlerin oluşmuş olduğu tahminleriyle örtüşmektedir.(Hidrojen ve helyumun evrendeki oranı, yapılan teorik hesaplamalara göre Big Bang\'den arta kalması gereken hidrojen ve helyum oranıyla uyuşmaktadır. Evrenin bir başlangıcı olmasaydı, evrendeki hidrojenin tümüyle yanarak helyuma dönüşmüş olması gerekirdi.) Bu ilk dakikalarda, soğuyan evren bazı çekirdeklerin oluşmasına imkân sağlamış olmalıydı.(Belirli miktarlarda hidrojen, helyum ve lityum oluşmuştu.)', '2021-08-13 02:48:37', 1), (10, 'AAA', 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of ', '2021-08-13 02:53:31', 1); -- -------------------------------------------------------- -- -- Tablo için tablo yapısı `contact` -- CREATE TABLE `contact` ( `cid` int(11) NOT NULL, `name` varchar(255) NOT NULL, `email` varchar(255) NOT NULL, `message` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Tablo döküm verisi `contact` -- INSERT INTO `contact` (`cid`, `name`, `email`, `message`) VALUES (1, 'Kerem', 'kerem@mail.com', 'Kereeeem'), (2, 'Şahsanem', 'sahsanem@mail.com', 'Güzel'); -- -- Dökümü yapılmış tablolar için indeksler -- -- -- Tablo için indeksler `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`aid`), ADD UNIQUE KEY `email` (`email`); -- -- Tablo için indeksler `blog` -- ALTER TABLE `blog` ADD PRIMARY KEY (`bid`); -- -- Tablo için indeksler `contact` -- ALTER TABLE `contact` ADD PRIMARY KEY (`cid`), ADD UNIQUE KEY `email` (`email`); -- -- Dökümü yapılmış tablolar için AUTO_INCREMENT değeri -- -- -- Tablo için AUTO_INCREMENT değeri `admin` -- ALTER TABLE `admin` MODIFY `aid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4; -- -- Tablo için AUTO_INCREMENT değeri `blog` -- ALTER TABLE `blog` MODIFY `bid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- Tablo için AUTO_INCREMENT değeri `contact` -- ALTER TABLE `contact` MODIFY `cid` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 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 */;
47.411348
1,754
0.734031
0891084281d302e177c3d5873697946dceff8906
5,191
go
Go
jlo.go
dcmn-com/jlo
236f79ebf98cecdb4f5b2820a6dd762ef019e77a
[ "MIT" ]
2
2021-04-26T14:00:47.000Z
2021-09-26T17:51:50.000Z
jlo.go
dcmn-com/jlo
236f79ebf98cecdb4f5b2820a6dd762ef019e77a
[ "MIT" ]
null
null
null
jlo.go
dcmn-com/jlo
236f79ebf98cecdb4f5b2820a6dd762ef019e77a
[ "MIT" ]
1
2021-09-26T18:06:43.000Z
2021-09-26T18:06:43.000Z
// Light-weight json logging package jlo import ( "fmt" "io" "os" "sync" "time" easyjson "github.com/mailru/easyjson" ) //go:generate easyjson -no_std_marshalers $GOFILE const ( // FieldKeyLevel is the log level log field name FieldKeyLevel = "@level" // FieldKeyMsg is the log message log field name FieldKeyMsg = "@message" // FieldKeyTime is the time log field name FieldKeyTime = "@timestamp" // FieldKeyCommit is the commit log field name FieldKeyCommit = "@commit" ) // LogLevel represents a log level used by Logger type type LogLevel int func (lvl LogLevel) MarshalEasyJSON() ([]byte, error) { s := lvl.String() out := make([]byte, len(s)+2) copy(out[1:len(out)-2], s[:]) out[0], out[len(out)-1] = '"', '"' return out, nil } const ( // UnknownLevel means the log level could not be parsed UnknownLevel LogLevel = iota // DebugLevel is the most verbose output and logs messages on all levels DebugLevel // InfoLevel logs messages on all levels except the DebugLevel InfoLevel // WarningLevel logs messages on all levels except DebugLevel and InfoLevel WarningLevel // ErrorLevel logs messages on ErrorLevel and FatalLevel ErrorLevel // FatalLevel logs messages on FatalLevel FatalLevel ) // String returns a string representation of the log level func (l LogLevel) String() string { switch l { case DebugLevel: return "debug" case InfoLevel: return "info" case WarningLevel: return "warning" case ErrorLevel: return "error" default: return "fatal" } } // logLevel is used as initial value upon creation of a new logger var logLevel = InfoLevel // SetLogLevel changes the global log level func SetLogLevel(level LogLevel) { logLevel = level } var Now = func() time.Time { return time.Now().UTC() } //easyjson:json type Entry map[string]interface{} // Logger logs json formatted messages to a certain output destination type Logger struct { FieldKeyMsg string FieldKeyLevel string FieldKeyTime string fields Entry mu sync.RWMutex logLevel LogLevel outMu sync.Mutex out io.Writer } // DefaultLogger returns a new default logger logging to stdout func DefaultLogger() *Logger { return NewLogger(os.Stdout) } // NewLogger creates a new logger which will write to the passed in io.Writer func NewLogger(out io.Writer) *Logger { return &Logger{ FieldKeyMsg: FieldKeyMsg, FieldKeyLevel: FieldKeyLevel, FieldKeyTime: FieldKeyTime, fields: make(Entry), logLevel: logLevel, out: out, } } // Fatalf logs a message on FatalLevel func (l *Logger) Fatalf(format string, args ...interface{}) { l.mu.RLock() defer l.mu.RUnlock() l.log(FatalLevel, format, args...) } // Errorf logs a messages on ErrorLevel func (l *Logger) Errorf(format string, args ...interface{}) { l.mu.RLock() defer l.mu.RUnlock() if l.logLevel <= ErrorLevel { l.log(ErrorLevel, format, args...) } } // Warnf logs a messages on WarningLevel func (l *Logger) Warnf(format string, args ...interface{}) { l.mu.RLock() defer l.mu.RUnlock() if l.logLevel <= WarningLevel { l.log(WarningLevel, format, args...) } } // Infof logs a messages on InfoLevel func (l *Logger) Infof(format string, args ...interface{}) { l.mu.RLock() defer l.mu.RUnlock() if l.logLevel <= InfoLevel { l.log(InfoLevel, format, args...) } } // Debugf logs a messages on DebugLevel func (l *Logger) Debugf(format string, args ...interface{}) { l.mu.RLock() defer l.mu.RUnlock() if l.logLevel <= DebugLevel { l.log(DebugLevel, format, args...) } } // SetLogLevel changes the log level func (l *Logger) SetLogLevel(level LogLevel) { l.mu.Lock() defer l.mu.Unlock() l.logLevel = level } // WithField returns a copy of the logger with a custom field set, which will be // included in all subsequent logs func (l *Logger) WithField(key string, value interface{}) *Logger { l.mu.RLock() defer l.mu.RUnlock() fields := make(Entry, len(l.fields)+1) fields[key] = value for k, v := range l.fields { fields[k] = v } clone := NewLogger(l.out) clone.fields = fields return clone } // log builds the final log data by concatenating the log template array data with // the values for log level, timestamp and log message func (l *Logger) log(level LogLevel, format string, args ...interface{}) { entry := l.generateLogEntry(level, format, args...) // wrap Write() method call in mutex to guarantee atomic writes l.outMu.Lock() defer l.outMu.Unlock() l.out.Write(append(entry, '\n')) } // generateLogEntry generates a log entry by gathering all field data and marshal // everthing to json format func (l *Logger) generateLogEntry(level LogLevel, format string, args ...interface{}) []byte { var msg string if len(args) > 0 { msg = fmt.Sprintf(format, args...) } else { msg = format } data := make(Entry, len(l.fields)+3) data[l.FieldKeyTime] = Now() data[l.FieldKeyLevel] = level.String() data[l.FieldKeyMsg] = msg for k, v := range l.fields { data[k] = v } // Error is ignored intentionally, as no errors are expected because the // data type to be marshaled will never change. entry, _ := easyjson.Marshal(data) return entry }
22.969027
94
0.698324
3d5b3f5e352466204937b904959acd946003d8d1
2,171
rs
Rust
src/time.rs
isaec/greeter
fb3bb9f29dc65fde55034c06982fe314ae9bce49
[ "MIT" ]
null
null
null
src/time.rs
isaec/greeter
fb3bb9f29dc65fde55034c06982fe314ae9bce49
[ "MIT" ]
null
null
null
src/time.rs
isaec/greeter
fb3bb9f29dc65fde55034c06982fe314ae9bce49
[ "MIT" ]
null
null
null
use std::fmt; use std::fs; use chrono::prelude::Local; struct Time<'a> { label: &'a str, value: u64, } impl Time<'_> { fn new(label: &str, value: f64) -> Time { Time { label, value: value as u64, } } } impl fmt::Display for Time<'_> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{value} {label}{plural}", value = self.value, label = self.label, plural = if self.value == 1 { "" } else { "s" } ) } } const HOUR: f64 = 60.0; const DAY: f64 = HOUR * 24.0; const YEAR: f64 = DAY * 365.0; pub fn up() -> String { match fs::read_to_string("/proc/uptime") { Err(_e) => "unknown time".to_string(), Ok(uptime) => { let float_minutes = uptime .split_whitespace() .next() .unwrap_or_default() .parse::<f64>() .unwrap_or_default() / 60.0; let mut time = vec![ Time::new("year", float_minutes / YEAR), Time::new("day", float_minutes % YEAR / DAY), Time::new("hour", float_minutes % DAY / HOUR), Time::new("minute", float_minutes % HOUR), ]; time.retain(|unit| unit.value != 0); let len = time.len() - 1; let mut result = "".to_string(); for (i, unit) in time.iter().enumerate() { result = format!( "{}{}{}", result, unit, if i == len { "" } else if i == len - 1 { " and " } else { ", " } ); } if result.len() > 0 { result } else { "less than a minute".to_string() } } } } pub fn total() -> String { Local::now() .format("at %-I:%M %P on %A, %B %d, %Y") .to_string() .to_lowercase() }
24.954023
62
0.387379
a1a9de322f87fe860b4aa3b74a4b78f30d015ae8
255
h
C
XQPageControllerDemo/TableCellFooterMoreController.h
west-east/XQPageController
7e9d5d0f89cd54bcce8d79f63f56ea4d2bab863c
[ "MIT" ]
322
2017-07-22T16:39:54.000Z
2019-11-15T08:08:48.000Z
XQPageControllerDemo/TableCellFooterMoreController.h
ticsmatic/XQPageController
7e9d5d0f89cd54bcce8d79f63f56ea4d2bab863c
[ "MIT" ]
4
2017-10-25T06:57:01.000Z
2019-07-16T03:21:41.000Z
XQPageControllerDemo/TableCellFooterMoreController.h
ticsmatic/XQPageController
7e9d5d0f89cd54bcce8d79f63f56ea4d2bab863c
[ "MIT" ]
21
2017-07-25T04:56:07.000Z
2019-09-05T05:45:38.000Z
// // TableCellFooterMoreController.h // XQPageControllerDemo // // Created by Ticsmatic on 2017/7/21. // Copyright © 2017年 Ticsmatic. All rights reserved. // #import <UIKit/UIKit.h> @interface TableCellFooterMoreController : UIViewController @end
18.214286
59
0.74902
bf3736c5e3ad05882e7cf298fa785abbf6646312
1,024
sql
SQL
public/dump/websites.sql
daotientu-devops/php_laravel_qc
2d1d406209db16f3165fa99cc0d52bd72ba1f990
[ "MIT" ]
null
null
null
public/dump/websites.sql
daotientu-devops/php_laravel_qc
2d1d406209db16f3165fa99cc0d52bd72ba1f990
[ "MIT" ]
null
null
null
public/dump/websites.sql
daotientu-devops/php_laravel_qc
2d1d406209db16f3165fa99cc0d52bd72ba1f990
[ "MIT" ]
1
2021-08-12T22:49:44.000Z
2021-08-12T22:49:44.000Z
3 4 Sức khỏe cộng đồng Công ty Cổ phần iNews 247 quận Cầu Giấy, Hà Nội info@tintuc.vn http://skcd.com.vn/ 52 247 0 97271 28033 0 94 2015-05-13 13:44:32 2015-05-13 06:44:32 0 5 _ 1 4 5 Tin tức Việt Nam Công ty Cổ phần iNews 247 quận Cầu Giấy, Hà Nội info@tintuc.vn http://tintuc.vn/ 52 247 0 26069623 19002012 0 24 2015-05-28 11:19:54 2015-05-13 06:44:32 0 1 _ 1 5 6 Mobile tin tức Việt Nam 247 Cầu Giấy, quận Cầu Giấy, Hà Nội info@tintuc.vn http://m.tintuc.vn/ 52 247 0 22953079 18474812 0 24 2015-05-12 16:28:23 2014-12-03 06:12:13 0 3 _ 1 6 8 CÔNG TY TNHH THÔNG TIN TRƯỜNG PHÁT Số 179, Lý Chính Thắng, P.7, Q.3. TP.HCM ntthom@tpinfo.vn http://truongphat.com.vn/ 52 247 0 0 0 0 0 2015-01-26 07:57:55 2015-01-26 07:57:55 0 4 _ 1 7 9 MẠNG BÁN LẺ TRỰC TUYẾN GOHAPPY Văn phòng giao dịch: Lô 11-H1 khu đô thị Yên Hòa, quận Cầu Giấy, Hà Nội, Việt Nam sales@gohappy.vn http://gohappy.vn/ gohappy.vn 52 247 0 0 0 0 \N 2015-05-13 13:44:29 2015-05-13 06:44:29 0 2 _ 1
170.666667
242
0.668945
475fbe68192e4e528b6d4a5301e317bdd8644bb0
53
html
HTML
docs/googlea211139c43d4edca.html
estefan3112/docs
5418e5a5ec24b3c4d6035d5bdcb33d29610a750d
[ "MIT" ]
190
2017-02-26T17:35:45.000Z
2022-03-25T20:00:27.000Z
docs/googlea211139c43d4edca.html
Seanpm2001-gaming/docs
d7f80249167bb92815af44082353c22bd03bc8d0
[ "MIT" ]
254
2017-04-30T12:08:01.000Z
2022-03-19T19:16:36.000Z
docs/googlea211139c43d4edca.html
Seanpm2001-gaming/docs
d7f80249167bb92815af44082353c22bd03bc8d0
[ "MIT" ]
321
2017-01-02T20:27:57.000Z
2022-03-31T22:47:42.000Z
google-site-verification: googlea211139c43d4edca.html
53
53
0.90566
7fb37b01b2053bd54ab4de63a5f6ed7ce8b41940
15,849
go
Go
cmd/vic-machine/converter/converter.go
mhazankin/vic
c7036a165aaa90cec10c290b95a40e9e74a3e46b
[ "Apache-2.0" ]
678
2016-04-04T19:47:24.000Z
2022-02-28T21:13:12.000Z
cmd/vic-machine/converter/converter.go
mhazankin/vic
c7036a165aaa90cec10c290b95a40e9e74a3e46b
[ "Apache-2.0" ]
7,047
2016-04-04T20:08:35.000Z
2022-03-09T02:33:36.000Z
cmd/vic-machine/converter/converter.go
mhazankin/vic
c7036a165aaa90cec10c290b95a40e9e74a3e46b
[ "Apache-2.0" ]
239
2016-04-04T20:01:50.000Z
2022-01-17T13:05:58.000Z
// Copyright 2017 VMware, Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package converter import ( "fmt" "net" "net/url" "os" "reflect" "strconv" "strings" "github.com/Sirupsen/logrus" "github.com/vmware/govmomi/vim25/types" "github.com/vmware/vic/cmd/vic-machine/common" "github.com/vmware/vic/lib/config/executor" "github.com/vmware/vic/lib/install/data" "github.com/vmware/vic/pkg/ip" viclog "github.com/vmware/vic/pkg/log" ) const ( cmdTag = "cmd" labelTag = "label" parentTagValue = "parent" optionSeparator = "-" keyAfterValueLabel = "value-key" valueAfterKeyLabel = "key-value" ) var ( kindConverters = make(map[reflect.Kind]converter) typeConverters = make(map[string]converter) labelHandlers = make(map[string]labelConverter) ) var log = &logrus.Logger{ Out: os.Stderr, // We're using our own text formatter to skip the \n and \t escaping logrus // was doing on non TTY Out (we redirect to a file) descriptors. Formatter: viclog.NewTextFormatter(), Hooks: make(logrus.LevelHooks), Level: logrus.InfoLevel, } type converter func(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error type labelConverter func(dest map[string][]string, key string) error func init() { kindConverters[reflect.Struct] = convertStruct kindConverters[reflect.Slice] = convertSlice kindConverters[reflect.Map] = convertMap kindConverters[reflect.String] = convertString kindConverters[reflect.Ptr] = convertPtr kindConverters[reflect.Int] = convertPrimitive kindConverters[reflect.Int8] = convertPrimitive kindConverters[reflect.Int16] = convertPrimitive kindConverters[reflect.Int32] = convertPrimitive kindConverters[reflect.Int64] = convertPrimitive kindConverters[reflect.Bool] = convertPrimitive kindConverters[reflect.Float32] = convertPrimitive kindConverters[reflect.Float64] = convertPrimitive typeConverters["url.URL"] = convertURL typeConverters["net.IPNet"] = convertIPNet typeConverters["net.IP"] = convertIP typeConverters["ip.Range"] = convertIPRange typeConverters["data.NetworkConfig"] = convertNetwork typeConverters["common.ContainerNetworks"] = convertContainerNetworks typeConverters["executor.TrustLevel"] = convertTrustLevel typeConverters["types.SharesInfo"] = convertShares labelHandlers[keyAfterValueLabel] = keyAfterValueLabelHandler labelHandlers[valueAfterKeyLabel] = valueAfterKeyLabelHandler } func EnableLog() { log.Level = logrus.DebugLevel } func DisableLog() { log.Level = logrus.InfoLevel } // DataToOption convert data.Data structure to vic-machine create command options based on tags defined in data.Data structure // Note: need to make sure the tags are consistent with command line option name func DataToOption(data *data.Data) (map[string][]string, error) { result := make(map[string][]string) if data == nil { return result, nil } err := convert(reflect.ValueOf(data), "", "", result) return result, err } func convert(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { t := src.Type().String() if converter, ok := typeConverters[t]; ok { return converter(src, prefix, tags, dest) } if converter, ok := kindConverters[src.Kind()]; ok { return converter(src, prefix, tags, dest) } log.Debugf("Skipping unsupported field, interface: %#v, kind %s", src, src.Kind()) return nil } func convertPtr(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { if src.IsNil() { // no need to attempt anything return nil } return convert(src.Elem(), prefix, tags, dest) } func convertStruct(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertStruct: prefix: %s, src: %s", prefix, src.String()) // iterate through every field in the struct for i := 0; i < src.NumField(); i++ { field := src.Field(i) // get field key, and keep going even if the attribute key is empty, to make sure children attribute is not missing tags := src.Type().Field(i).Tag key := calculateKey(tags, prefix) if err := convert(field, key, tags, dest); err != nil { return err } if field.Kind() == reflect.Map { // label handler is invoked in map converter continue } } return nil } func convertSlice(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertSlice: prefix: %s, src: %s", prefix, src) length := src.Len() if length == 0 { log.Debug("Skipping empty slice") return nil } for i := 0; i < length; i++ { if err := convert(src.Index(i), prefix, tags, dest); err != nil { return err } } return nil } func convertMap(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertMap: prefix: %s, src: %s", prefix, src) // iterate over keys and recurse mkeys := src.MapKeys() length := len(mkeys) if length == 0 { log.Debug("Skipping empty map") return nil } handler, hasHandler := labelHandlers[tags.Get(labelTag)] // use tempMap to avoid duplicate processing for _, pkey := range src.MapKeys() { tempMap := make(map[string][]string) if pkey.Kind() != reflect.String { log.Errorf("Unsupported map key type interface: %s, kind %s", src, src.Kind()) continue } if !hasHandler { if err := convert(src.MapIndex(pkey), prefix, tags, dest); err != nil { return err } continue } if err := convert(src.MapIndex(pkey), prefix, tags, tempMap); err != nil { return err } if err := handler(tempMap, pkey.String()); err != nil { return err } for k, v := range tempMap { addValues(dest, k, v) } } return nil } // keyAfterValueLabelHandler will add the map key as label after the value, // e.g. change from datastore/path to datastore/path:default func keyAfterValueLabelHandler(dest map[string][]string, pkey string) error { log.Debugf("keyAfterValueLabelHandler: map key: %s, map: %#v", pkey, dest) for _, values := range dest { for i := range values { values[i] = fmt.Sprintf("%s:%s", values[i], pkey) } } return nil } // valueAfterKeyLabelHandler will add the map key as label before the value, // e.g. change from 10.10.10.0/24 to management:10.10.10.0/24 func valueAfterKeyLabelHandler(dest map[string][]string, pkey string) error { log.Debugf("valueAfterKeyLabelHandler: map key: %s, map: %#v", pkey, dest) for _, values := range dest { for i := range values { values[i] = fmt.Sprintf("%s:%s", pkey, values[i]) } } return nil } // calculateKey generate key as prefix-tag. if any one is empty, return the other func calculateKey(tags reflect.StructTag, prefix string) string { tag := tags.Get(cmdTag) if tag == "" { return prefix } if tag == parentTagValue && prefix == "" { return "" } if tag == parentTagValue && prefix != "" { // for this tag, use parent name only return prefix } if prefix == "" { return tag } return fmt.Sprintf("%s%s%s", prefix, optionSeparator, tag) } func convertURL(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertURL: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } u, ok := src.Interface().(url.URL) if !ok { panic(fmt.Sprintf(src.Type().String() + " is not URL")) } v := u.String() if u.Scheme == "" { if u.Path == "" { v = u.Host } else if u.Host == "" { v = u.Path } else { v = fmt.Sprintf("%s/%s", u.Host, u.Path) } } log.Debugf("%s=%s", prefix, v) addValue(dest, prefix, v) return nil } func convertIPNet(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertIPNet: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } ipNet, ok := src.Interface().(net.IPNet) if !ok { panic(fmt.Sprintf(src.Type().String() + " is not IPNet")) } if ip.IsUnspecifiedSubnet(&ipNet) { return nil } v := ipNet.String() log.Debugf("%s=%s", prefix, v) addValue(dest, prefix, v) return nil } func convertIP(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertIP: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } ipAddr, ok := src.Interface().(net.IP) if !ok { panic(fmt.Sprintf(src.Type().String() + " is not IP")) } if ip.IsUnspecifiedIP(ipAddr) { return nil } v := ipAddr.String() log.Debugf("%s=%s", prefix, v) addValue(dest, prefix, v) return nil } func convertTrustLevel(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertTrustLevel: prefix: %s, src: %s", prefix, src.String()) trustLevel, ok := src.Interface().(executor.TrustLevel) if !ok { panic(fmt.Sprintf(src.Type().String() + " is not TrustLevel")) } if trustLevel == executor.Unspecified { return nil } v := trustLevel.String() log.Debugf("%s=%s", prefix, v) addValue(dest, prefix, v) return nil } func convertIPRange(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertIPRange: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } ipRange, ok := src.Interface().(ip.Range) if !ok { panic(fmt.Sprintf(src.Type().String() + " is not ip range")) } v := ipRange.String() if v == "" { return nil } log.Debugf("%s=%s", prefix, v) addValue(dest, prefix, v) return nil } func convertString(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertString: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } v := src.String() if v == "" { return nil } log.Debugf("%s=%s", prefix, v) addValue(dest, prefix, v) return nil } func convertPrimitive(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertPrimitive: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } v := "" switch src.Kind() { case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: if src.Int() == 0 { return nil } v = strconv.FormatInt(src.Int(), 10) case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: if src.Uint() == 0 { return nil } v = strconv.FormatUint(src.Uint(), 10) case reflect.Bool: if !src.Bool() { return nil } v = strconv.FormatBool(src.Bool()) case reflect.Float32, reflect.Float64: if src.Float() == 0 { return nil } v = strconv.FormatFloat(src.Float(), 'E', -1, 64) default: panic(fmt.Sprintf("%s is not supported type", src.Kind())) } log.Debugf("%s=%s", prefix, v) addValue(dest, prefix, v) return nil } // convertNetwork will merge destination and gateway to one option with format: 192.168.3.0/16,192.168.128.0/16:192.168.2.1 // after that, convertStruct is called for left conversion func convertNetwork(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertNetwork: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } network, ok := src.Interface().(data.NetworkConfig) if !ok { panic(fmt.Sprintf(src.Type().String() + " is not NetworkConfig")) } if !network.IsSet() { return nil } if len(network.Destinations) > 0 || !ip.Empty(network.Gateway) { destination := "" if len(network.Destinations) > 0 { for _, d := range network.Destinations { destination = fmt.Sprintf("%s,%s", destination, d.String()) } destination = strings.TrimLeft(destination, ",") } gateway := network.Gateway.IP.String() tag := "cmd:\"gateway\"" key := calculateKey(reflect.StructTag(tag), prefix) if destination != "" { addValue(dest, key, fmt.Sprintf("%s:%s", destination, gateway)) } else { addValue(dest, key, gateway) } } return convertStruct(reflect.ValueOf(network), prefix, tags, dest) } func convertShares(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertShares: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } shares, ok := src.Interface().(types.SharesInfo) if !ok { panic(fmt.Sprintf(src.Type().String() + " is not SharesInfo")) } v := "" switch shares.Level { case types.SharesLevelCustom: v = fmt.Sprintf("%v", shares.Shares) case types.SharesLevelNormal: return nil default: v = string(shares.Level) } log.Debugf("%s=%s", prefix, v) addValue(dest, prefix, v) return nil } // convertContainerNetworks will switch the map keys in MappedNetworks using value, and replace all keys with the same value in other structure, // cause option is using vsphere network name as key label, but guestinfo is using alias as key for easy to use in portlayer // after that, convertStruct is called for left conversion func convertContainerNetworks(src reflect.Value, prefix string, tags reflect.StructTag, dest map[string][]string) error { log.Debugf("convertContainerNetworks: prefix: %s, src: %s", prefix, src.String()) if prefix == "" { return nil } if tags.Get(cmdTag) == "" { return nil } networks, ok := src.Interface().(common.ContainerNetworks) if !ok { panic(fmt.Sprintf(src.Type().String() + " is not ContainerNetworks")) } if !networks.IsSet() { return nil } newMappedNetworks := make(map[string]string, len(networks.MappedNetworks)) for k, v := range networks.MappedNetworks { if k == v { newMappedNetworks[v] = k continue } if dns, ok := networks.MappedNetworksDNS[k]; ok { networks.MappedNetworksDNS[v] = dns delete(networks.MappedNetworksDNS, k) } if gateways, ok := networks.MappedNetworksGateways[k]; ok { networks.MappedNetworksGateways[v] = gateways delete(networks.MappedNetworksGateways, k) } if ipRange, ok := networks.MappedNetworksIPRanges[k]; ok { networks.MappedNetworksIPRanges[v] = ipRange delete(networks.MappedNetworksIPRanges, k) } if firewall, ok := networks.MappedNetworksFirewalls[k]; ok { networks.MappedNetworksFirewalls[v] = firewall delete(networks.MappedNetworksFirewalls, k) } newMappedNetworks[v] = k } networks.MappedNetworks = newMappedNetworks return convertStruct(reflect.ValueOf(networks), prefix, tags, dest) } // addValue will append value without duplicates func addValue(dest map[string][]string, key, value string) { slice, _ := dest[key] found := false for _, o := range slice { if o == value { found = true break } } if !found { slice = append(slice, value) } dest[key] = slice } // addValues append new value to existing slice if missing // as this method is called every time the value is appended, the existing slice will be no duplicates func addValues(dest map[string][]string, key string, values []string) { for _, v := range values { addValue(dest, key, v) } }
27.467938
144
0.687867
6010e00447c1e7dfa71d8dd1cf2bc99737199031
836
kt
Kotlin
app/src/main/java/net/pfiers/osmfocus/viewmodel/support/events.kt
yuhuitech/osmfocus
5e1050578690d1267493720506b44528204b9154
[ "Apache-2.0" ]
null
null
null
app/src/main/java/net/pfiers/osmfocus/viewmodel/support/events.kt
yuhuitech/osmfocus
5e1050578690d1267493720506b44528204b9154
[ "Apache-2.0" ]
null
null
null
app/src/main/java/net/pfiers/osmfocus/viewmodel/support/events.kt
yuhuitech/osmfocus
5e1050578690d1267493720506b44528204b9154
[ "Apache-2.0" ]
null
null
null
package net.pfiers.osmfocus.viewmodel.support import android.net.Uri import kotlinx.coroutines.channels.Channel import net.pfiers.osmfocus.service.osm.OsmElement abstract class Event class CancelEvent : Event() class OpenUriEvent(val uri: Uri) : Event() class CopyEvent(val label: String, val text: String) : Event() class SendEmailEvent( val address: String, val subject: String, val body: String, val attachments: Map<String, ByteArray> = emptyMap() ) : Event() class EditBaseMapsEvent : Event() class EditTagboxLongLinesEvent : Event() class ShowAboutEvent : Event() class ShowSettingsEvent : Event() class ShowElementDetailsEvent(val element: OsmElement) : Event() class MoveToCurrentLocationEvent() : Event() class ExceptionEvent(val exception: Throwable) : Event() fun createEventChannel() = Channel<Event>(10)
32.153846
64
0.772727
3d5e7dd0af1213b009b6f61d88f573916cfc40ef
22,135
rs
Rust
src/librustc/dep_graph/dep_node.rs
MOZGIII/rust
e3976fff44e6ce14c2f92252e6a807800b9aa7c0
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
15
2015-12-17T18:20:31.000Z
2019-12-10T20:07:24.000Z
src/librustc/dep_graph/dep_node.rs
netcazean/rust
a24f636e60a5da57ab641d800ac5952bbde98b65
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
8
2017-03-16T17:51:46.000Z
2017-07-18T01:47:29.000Z
src/librustc/dep_graph/dep_node.rs
netcazean/rust
a24f636e60a5da57ab641d800ac5952bbde98b65
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
10
2016-12-13T07:07:21.000Z
2022-03-20T06:08:58.000Z
//! This module defines the `DepNode` type which the compiler uses to represent //! nodes in the dependency graph. A `DepNode` consists of a `DepKind` (which //! specifies the kind of thing it represents, like a piece of HIR, MIR, etc) //! and a `Fingerprint`, a 128 bit hash value the exact meaning of which //! depends on the node's `DepKind`. Together, the kind and the fingerprint //! fully identify a dependency node, even across multiple compilation sessions. //! In other words, the value of the fingerprint does not depend on anything //! that is specific to a given compilation session, like an unpredictable //! interning key (e.g., NodeId, DefId, Symbol) or the numeric value of a //! pointer. The concept behind this could be compared to how git commit hashes //! uniquely identify a given commit and has a few advantages: //! //! * A `DepNode` can simply be serialized to disk and loaded in another session //! without the need to do any "rebasing (like we have to do for Spans and //! NodeIds) or "retracing" like we had to do for `DefId` in earlier //! implementations of the dependency graph. //! * A `Fingerprint` is just a bunch of bits, which allows `DepNode` to //! implement `Copy`, `Sync`, `Send`, `Freeze`, etc. //! * Since we just have a bit pattern, `DepNode` can be mapped from disk into //! memory without any post-processing (e.g., "abomination-style" pointer //! reconstruction). //! * Because a `DepNode` is self-contained, we can instantiate `DepNodes` that //! refer to things that do not exist anymore. In previous implementations //! `DepNode` contained a `DefId`. A `DepNode` referring to something that //! had been removed between the previous and the current compilation session //! could not be instantiated because the current compilation session //! contained no `DefId` for thing that had been removed. //! //! `DepNode` definition happens in the `define_dep_nodes!()` macro. This macro //! defines the `DepKind` enum and a corresponding `DepConstructor` enum. The //! `DepConstructor` enum links a `DepKind` to the parameters that are needed at //! runtime in order to construct a valid `DepNode` fingerprint. //! //! Because the macro sees what parameters a given `DepKind` requires, it can //! "infer" some properties for each kind of `DepNode`: //! //! * Whether a `DepNode` of a given kind has any parameters at all. Some //! `DepNode`s, like `Krate`, represent global concepts with only one value. //! * Whether it is possible, in principle, to reconstruct a query key from a //! given `DepNode`. Many `DepKind`s only require a single `DefId` parameter, //! in which case it is possible to map the node's fingerprint back to the //! `DefId` it was computed from. In other cases, too much information gets //! lost during fingerprint computation. //! //! The `DepConstructor` enum, together with `DepNode::new()` ensures that only //! valid `DepNode` instances can be constructed. For example, the API does not //! allow for constructing parameterless `DepNode`s with anything other //! than a zeroed out fingerprint. More generally speaking, it relieves the //! user of the `DepNode` API of having to know how to compute the expected //! fingerprint for a given set of node parameters. use crate::mir; use crate::mir::interpret::GlobalId; use crate::hir::def_id::{CrateNum, DefId, DefIndex, CRATE_DEF_INDEX}; use crate::hir::map::DefPathHash; use crate::hir::HirId; use crate::ich::{Fingerprint, StableHashingContext}; use rustc_data_structures::stable_hasher::{StableHasher, HashStable}; use std::fmt; use std::hash::Hash; use syntax_pos::symbol::InternedString; use crate::traits; use crate::traits::query::{ CanonicalProjectionGoal, CanonicalTyGoal, CanonicalTypeOpAscribeUserTypeGoal, CanonicalTypeOpEqGoal, CanonicalTypeOpSubtypeGoal, CanonicalPredicateGoal, CanonicalTypeOpProvePredicateGoal, CanonicalTypeOpNormalizeGoal, }; use crate::ty::{self, TyCtxt, ParamEnvAnd, Ty}; use crate::ty::subst::SubstsRef; // erase!() just makes tokens go away. It's used to specify which macro argument // is repeated (i.e., which sub-expression of the macro we are in) but don't need // to actually use any of the arguments. macro_rules! erase { ($x:tt) => ({}) } macro_rules! replace { ($x:tt with $($y:tt)*) => ($($y)*) } macro_rules! is_anon_attr { (anon) => (true); ($attr:ident) => (false); } macro_rules! is_eval_always_attr { (eval_always) => (true); ($attr:ident) => (false); } macro_rules! contains_anon_attr { ($($attr:ident),*) => ({$(is_anon_attr!($attr) | )* false}); } macro_rules! contains_eval_always_attr { ($($attr:ident),*) => ({$(is_eval_always_attr!($attr) | )* false}); } macro_rules! define_dep_nodes { (<$tcx:tt> $( [$($attr:ident),* ] $variant:ident $(( $tuple_arg_ty:ty $(,)? ))* $({ $($struct_arg_name:ident : $struct_arg_ty:ty),* })* ,)* ) => ( #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub enum DepKind { $($variant),* } impl DepKind { #[allow(unreachable_code)] #[inline] pub fn can_reconstruct_query_key<$tcx>(&self) -> bool { match *self { $( DepKind :: $variant => { if contains_anon_attr!($($attr),*) { return false; } // tuple args $({ return <$tuple_arg_ty as DepNodeParams> ::CAN_RECONSTRUCT_QUERY_KEY; })* // struct args $({ return <( $($struct_arg_ty,)* ) as DepNodeParams> ::CAN_RECONSTRUCT_QUERY_KEY; })* true } )* } } pub fn is_anon(&self) -> bool { match *self { $( DepKind :: $variant => { contains_anon_attr!($($attr),*) } )* } } #[inline(always)] pub fn is_eval_always(&self) -> bool { match *self { $( DepKind :: $variant => { contains_eval_always_attr!($($attr), *) } )* } } #[allow(unreachable_code)] pub fn has_params(&self) -> bool { match *self { $( DepKind :: $variant => { // tuple args $({ erase!($tuple_arg_ty); return true; })* // struct args $({ $(erase!($struct_arg_name);)* return true; })* false } )* } } } pub enum DepConstructor<$tcx> { $( $variant $(( $tuple_arg_ty ))* $({ $($struct_arg_name : $struct_arg_ty),* })* ),* } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub struct DepNode { pub kind: DepKind, pub hash: Fingerprint, } impl DepNode { #[allow(unreachable_code, non_snake_case)] #[inline(always)] pub fn new<'tcx>(tcx: TyCtxt<'tcx>, dep: DepConstructor<'tcx>) -> DepNode { match dep { $( DepConstructor :: $variant $(( replace!(($tuple_arg_ty) with arg) ))* $({ $($struct_arg_name),* })* => { // tuple args $({ erase!($tuple_arg_ty); let hash = DepNodeParams::to_fingerprint(&arg, tcx); let dep_node = DepNode { kind: DepKind::$variant, hash }; if cfg!(debug_assertions) && !dep_node.kind.can_reconstruct_query_key() && (tcx.sess.opts.debugging_opts.incremental_info || tcx.sess.opts.debugging_opts.query_dep_graph) { tcx.dep_graph.register_dep_node_debug_str(dep_node, || { arg.to_debug_str(tcx) }); } return dep_node; })* // struct args $({ let tupled_args = ( $($struct_arg_name,)* ); let hash = DepNodeParams::to_fingerprint(&tupled_args, tcx); let dep_node = DepNode { kind: DepKind::$variant, hash }; if cfg!(debug_assertions) && !dep_node.kind.can_reconstruct_query_key() && (tcx.sess.opts.debugging_opts.incremental_info || tcx.sess.opts.debugging_opts.query_dep_graph) { tcx.dep_graph.register_dep_node_debug_str(dep_node, || { tupled_args.to_debug_str(tcx) }); } return dep_node; })* DepNode { kind: DepKind::$variant, hash: Fingerprint::ZERO, } } )* } } /// Construct a DepNode from the given DepKind and DefPathHash. This /// method will assert that the given DepKind actually requires a /// single DefId/DefPathHash parameter. #[inline(always)] pub fn from_def_path_hash(kind: DepKind, def_path_hash: DefPathHash) -> DepNode { debug_assert!(kind.can_reconstruct_query_key() && kind.has_params()); DepNode { kind, hash: def_path_hash.0, } } /// Creates a new, parameterless DepNode. This method will assert /// that the DepNode corresponding to the given DepKind actually /// does not require any parameters. #[inline(always)] pub fn new_no_params(kind: DepKind) -> DepNode { debug_assert!(!kind.has_params()); DepNode { kind, hash: Fingerprint::ZERO, } } /// Extracts the DefId corresponding to this DepNode. This will work /// if two conditions are met: /// /// 1. The Fingerprint of the DepNode actually is a DefPathHash, and /// 2. the item that the DefPath refers to exists in the current tcx. /// /// Condition (1) is determined by the DepKind variant of the /// DepNode. Condition (2) might not be fulfilled if a DepNode /// refers to something from the previous compilation session that /// has been removed. #[inline] pub fn extract_def_id(&self, tcx: TyCtxt<'_>) -> Option<DefId> { if self.kind.can_reconstruct_query_key() { let def_path_hash = DefPathHash(self.hash); tcx.def_path_hash_to_def_id.as_ref()? .get(&def_path_hash).cloned() } else { None } } /// Used in testing pub fn from_label_string(label: &str, def_path_hash: DefPathHash) -> Result<DepNode, ()> { let kind = match label { $( stringify!($variant) => DepKind::$variant, )* _ => return Err(()), }; if !kind.can_reconstruct_query_key() { return Err(()); } if kind.has_params() { Ok(def_path_hash.to_dep_node(kind)) } else { Ok(DepNode::new_no_params(kind)) } } /// Used in testing pub fn has_label_string(label: &str) -> bool { match label { $( stringify!($variant) => true, )* _ => false, } } } /// Contains variant => str representations for constructing /// DepNode groups for tests. #[allow(dead_code, non_upper_case_globals)] pub mod label_strs { $( pub const $variant: &str = stringify!($variant); )* } ); } impl fmt::Debug for DepNode { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.kind)?; if !self.kind.has_params() && !self.kind.is_anon() { return Ok(()); } write!(f, "(")?; crate::ty::tls::with_opt(|opt_tcx| { if let Some(tcx) = opt_tcx { if let Some(def_id) = self.extract_def_id(tcx) { write!(f, "{}", tcx.def_path_debug_str(def_id))?; } else if let Some(ref s) = tcx.dep_graph.dep_node_debug_str(*self) { write!(f, "{}", s)?; } else { write!(f, "{}", self.hash)?; } } else { write!(f, "{}", self.hash)?; } Ok(()) })?; write!(f, ")") } } impl DefPathHash { #[inline(always)] pub fn to_dep_node(self, kind: DepKind) -> DepNode { DepNode::from_def_path_hash(kind, self) } } impl DefId { #[inline(always)] pub fn to_dep_node(self, tcx: TyCtxt<'_>, kind: DepKind) -> DepNode { DepNode::from_def_path_hash(kind, tcx.def_path_hash(self)) } } rustc_dep_node_append!([define_dep_nodes!][ <'tcx> // We use this for most things when incr. comp. is turned off. [] Null, // Represents the `Krate` as a whole (the `hir::Krate` value) (as // distinct from the krate module). This is basically a hash of // the entire krate, so if you read from `Krate` (e.g., by calling // `tcx.hir().krate()`), we will have to assume that any change // means that you need to be recompiled. This is because the // `Krate` value gives you access to all other items. To avoid // this fate, do not call `tcx.hir().krate()`; instead, prefer // wrappers like `tcx.visit_all_items_in_krate()`. If there is no // suitable wrapper, you can use `tcx.dep_graph.ignore()` to gain // access to the krate, but you must remember to add suitable // edges yourself for the individual items that you read. [eval_always] Krate, // Represents the body of a function or method. The def-id is that of the // function/method. [eval_always] HirBody(DefId), // Represents the HIR node with the given node-id [eval_always] Hir(DefId), // Represents metadata from an extern crate. [eval_always] CrateMetadata(CrateNum), [eval_always] AllLocalTraitImpls, [anon] TraitSelect, [] CompileCodegenUnit(InternedString), [eval_always] Analysis(CrateNum), ]); pub trait RecoverKey<'tcx>: Sized { fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self>; } impl RecoverKey<'tcx> for CrateNum { fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> { dep_node.extract_def_id(tcx).map(|id| id.krate) } } impl RecoverKey<'tcx> for DefId { fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> { dep_node.extract_def_id(tcx) } } impl RecoverKey<'tcx> for DefIndex { fn recover(tcx: TyCtxt<'tcx>, dep_node: &DepNode) -> Option<Self> { dep_node.extract_def_id(tcx).map(|id| id.index) } } trait DepNodeParams<'tcx>: fmt::Debug { const CAN_RECONSTRUCT_QUERY_KEY: bool; /// This method turns the parameters of a DepNodeConstructor into an opaque /// Fingerprint to be used in DepNode. /// Not all DepNodeParams support being turned into a Fingerprint (they /// don't need to if the corresponding DepNode is anonymous). fn to_fingerprint(&self, _: TyCtxt<'tcx>) -> Fingerprint { panic!("Not implemented. Accidentally called on anonymous node?") } fn to_debug_str(&self, _: TyCtxt<'tcx>) -> String { format!("{:?}", self) } } impl<'tcx, T> DepNodeParams<'tcx> for T where T: HashStable<StableHashingContext<'tcx>> + fmt::Debug, { default const CAN_RECONSTRUCT_QUERY_KEY: bool = false; default fn to_fingerprint(&self, tcx: TyCtxt<'tcx>) -> Fingerprint { let mut hcx = tcx.create_stable_hashing_context(); let mut hasher = StableHasher::new(); self.hash_stable(&mut hcx, &mut hasher); hasher.finish() } default fn to_debug_str(&self, _: TyCtxt<'tcx>) -> String { format!("{:?}", *self) } } impl<'tcx> DepNodeParams<'tcx> for DefId { const CAN_RECONSTRUCT_QUERY_KEY: bool = true; fn to_fingerprint(&self, tcx: TyCtxt<'_>) -> Fingerprint { tcx.def_path_hash(*self).0 } fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { tcx.def_path_str(*self) } } impl<'tcx> DepNodeParams<'tcx> for DefIndex { const CAN_RECONSTRUCT_QUERY_KEY: bool = true; fn to_fingerprint(&self, tcx: TyCtxt<'_>) -> Fingerprint { tcx.hir().definitions().def_path_hash(*self).0 } fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { tcx.def_path_str(DefId::local(*self)) } } impl<'tcx> DepNodeParams<'tcx> for CrateNum { const CAN_RECONSTRUCT_QUERY_KEY: bool = true; fn to_fingerprint(&self, tcx: TyCtxt<'_>) -> Fingerprint { let def_id = DefId { krate: *self, index: CRATE_DEF_INDEX, }; tcx.def_path_hash(def_id).0 } fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { tcx.crate_name(*self).as_str().to_string() } } impl<'tcx> DepNodeParams<'tcx> for (DefId, DefId) { const CAN_RECONSTRUCT_QUERY_KEY: bool = false; // We actually would not need to specialize the implementation of this // method but it's faster to combine the hashes than to instantiate a full // hashing context and stable-hashing state. fn to_fingerprint(&self, tcx: TyCtxt<'_>) -> Fingerprint { let (def_id_0, def_id_1) = *self; let def_path_hash_0 = tcx.def_path_hash(def_id_0); let def_path_hash_1 = tcx.def_path_hash(def_id_1); def_path_hash_0.0.combine(def_path_hash_1.0) } fn to_debug_str(&self, tcx: TyCtxt<'tcx>) -> String { let (def_id_0, def_id_1) = *self; format!("({}, {})", tcx.def_path_debug_str(def_id_0), tcx.def_path_debug_str(def_id_1)) } } impl<'tcx> DepNodeParams<'tcx> for HirId { const CAN_RECONSTRUCT_QUERY_KEY: bool = false; // We actually would not need to specialize the implementation of this // method but it's faster to combine the hashes than to instantiate a full // hashing context and stable-hashing state. fn to_fingerprint(&self, tcx: TyCtxt<'_>) -> Fingerprint { let HirId { owner, local_id, } = *self; let def_path_hash = tcx.def_path_hash(DefId::local(owner)); let local_id = Fingerprint::from_smaller_hash(local_id.as_u32().into()); def_path_hash.0.combine(local_id) } } /// A "work product" corresponds to a `.o` (or other) file that we /// save in between runs. These IDs do not have a `DefId` but rather /// some independent path or string that persists between runs without /// the need to be mapped or unmapped. (This ensures we can serialize /// them even in the absence of a tcx.) #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, RustcEncodable, RustcDecodable)] pub struct WorkProductId { hash: Fingerprint } impl WorkProductId { pub fn from_cgu_name(cgu_name: &str) -> WorkProductId { let mut hasher = StableHasher::new(); cgu_name.len().hash(&mut hasher); cgu_name.hash(&mut hasher); WorkProductId { hash: hasher.finish() } } pub fn from_fingerprint(fingerprint: Fingerprint) -> WorkProductId { WorkProductId { hash: fingerprint } } } impl_stable_hash_for!(struct crate::dep_graph::WorkProductId { hash });
36.286885
93
0.525909
70a32ba627c5dc119db6d6141b573c41e452b763
30
c
C
src/xer_decoder.c
rjenkins/c-RIBBIT
8dff78e1fe183d8e87974667cdca38420f6c46d3
[ "MIT" ]
null
null
null
src/xer_decoder.c
rjenkins/c-RIBBIT
8dff78e1fe183d8e87974667cdca38420f6c46d3
[ "MIT" ]
1
2016-03-13T18:39:54.000Z
2016-03-14T16:58:41.000Z
src/xer_decoder.c
rjenkins/c-RIBBIT
8dff78e1fe183d8e87974667cdca38420f6c46d3
[ "MIT" ]
2
2016-03-13T18:31:11.000Z
2018-02-01T03:11:03.000Z
/usr/share/asn1c/xer_decoder.c
30
30
0.833333
6d3218e802dcc9ff99fe197df87f7e7247e6029e
750
swift
Swift
NotCompiling/Enums/Generated/Strings.swift
Sajjon/SwiftGen3Error
c794f67beea8daac36e17fadc0178739133d340e
[ "Apache-2.0" ]
null
null
null
NotCompiling/Enums/Generated/Strings.swift
Sajjon/SwiftGen3Error
c794f67beea8daac36e17fadc0178739133d340e
[ "Apache-2.0" ]
null
null
null
NotCompiling/Enums/Generated/Strings.swift
Sajjon/SwiftGen3Error
c794f67beea8daac36e17fadc0178739133d340e
[ "Apache-2.0" ]
null
null
null
// Generated using SwiftGen, by O.Halligon — https://github.com/AliSoftware/SwiftGen import Foundation // swiftlint:disable file_length // swiftlint:disable type_body_length enum L10n { /// Your name is %@ case yourname(String) } // swiftlint:enable type_body_length extension L10n: CustomStringConvertible { var description: String { return self.string } var string: String { switch self { case .yourName(let p0): return L10n.tr(key: "YourName", p0) } } private static func tr(key: String, _ args: CVarArg...) -> String { let format = NSLocalizedString(key, comment: "") return String(format: format, locale: Locale.current, arguments: args) } } func tr(key: L10n) -> String { return key.string }
23.4375
84
0.692
0328862138c7f9eb2ebdb4ab6dfce32420240c3a
3,705
swift
Swift
PetIT/PetIT/Controllers/Map View Controllers/JobPostDetailViewController.swift
SLRAM/PetSittingApp
f1112171c12a832368cc8d6f48feadbf6029d7a3
[ "MIT" ]
4
2019-07-12T11:07:05.000Z
2020-10-22T01:25:13.000Z
PetIT/PetIT/Controllers/Map View Controllers/JobPostDetailViewController.swift
JianTing-Li/PetSittingApp
f1112171c12a832368cc8d6f48feadbf6029d7a3
[ "MIT" ]
null
null
null
PetIT/PetIT/Controllers/Map View Controllers/JobPostDetailViewController.swift
JianTing-Li/PetSittingApp
f1112171c12a832368cc8d6f48feadbf6029d7a3
[ "MIT" ]
2
2019-04-01T14:45:43.000Z
2019-06-11T03:02:36.000Z
// // PostingDetailViewController.swift // PetIT // // Created by Stephanie Ramirez on 3/27/19. // Copyright © 2019 Stephanie Ramirez. All rights reserved. // import UIKit import Firebase class JobPostDetailViewController: UIViewController { @IBOutlet weak var petOwnerProfileImage: CircularImageView! @IBOutlet weak var fullnameLabel: UILabel! @IBOutlet weak var usernameLable: UILabel! @IBOutlet weak var petImage: UIImageView! @IBOutlet weak var jobDescription: UITextView! @IBOutlet weak var petBio: UITextView! @IBOutlet weak var jobTimeFrame: UITextField! @IBOutlet weak var jobWages: UITextField! @IBOutlet weak var bookJobButton: UIButton! public var userModel: UserModel? { didSet { DispatchQueue.main.async { self.updateUI() } } } public var jobPost: JobPost! public var displayName: String? public var jobDescrip: String? private var authservice = AppDelegate.authservice override func viewDidLoad() { super.viewDidLoad() jobDescription.isEditable = false petBio.isEditable = false jobTimeFrame.isUserInteractionEnabled = false jobWages.isUserInteractionEnabled = false updateUserImageAndUsername() jobDescription.clipsToBounds = true jobDescription.layer.cornerRadius = 10.0 petBio.clipsToBounds = true petBio.layer.cornerRadius = 10.0 } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) updateUserImageAndUsername() } private func updateUI() { if let photoURL = self.userModel?.photoURL, !photoURL.isEmpty { petOwnerProfileImage.kf.setImage(with: URL(string: photoURL), placeholder: #imageLiteral(resourceName: "create_new")) } petImage.kf.setImage(with: URL(string: jobPost.imageURLString), placeholder: #imageLiteral(resourceName: "placeholder-image.png")) jobDescription.text = jobPost.jobDescription petBio.text = jobPost.petBio jobTimeFrame.text = jobPost.timeFrame jobWages.text = jobPost.wage fullnameLabel.text = userModel!.firstName usernameLable.text = "@" + (userModel!.displayName) if jobPost.status == "PENDING" { bookJobButton.setTitle("Book Job", for: .normal) bookJobButton.setTitleColor(.red, for: .normal) bookJobButton.isEnabled = true } else { bookJobButton.setTitle("BOOKED", for: .normal) bookJobButton.setTitleColor(.green, for: .normal) bookJobButton.isEnabled = false } } private func updateUserImageAndUsername() { DBService.fetchUser(userId: jobPost.ownerId) { [weak self] (error, user) in if let error = error { self?.showAlert(title: "Error getting username", message: error.localizedDescription) } else if let user = user { self?.userModel = user } } } @IBAction func bookJobButtonPressed(_ sender: UIButton) { sender.setTitle("Job Accepted", for: .normal) showAlert(title: "Job Booked", message: "Thank You for booking with us!") DBService.firestoreDB .collection(JobPostCollectionKeys.CollectionKey) .document(jobPost.postId) .updateData([JobPostCollectionKeys.StatusKey : "BOOKED" ]) { [weak self] (error) in if let error = error { self?.showAlert(title: "Editing Error", message: error.localizedDescription) } } } }
34.95283
138
0.637247
71a43ad63a60f9e36b68816b10c0a673dfed804f
1,413
sql
SQL
db/inputs.sql
qb00091/appointments
a1cd07f8ffd5165a269674845d24a1ff5022d7db
[ "MIT" ]
null
null
null
db/inputs.sql
qb00091/appointments
a1cd07f8ffd5165a269674845d24a1ff5022d7db
[ "MIT" ]
null
null
null
db/inputs.sql
qb00091/appointments
a1cd07f8ffd5165a269674845d24a1ff5022d7db
[ "MIT" ]
null
null
null
/* password for all is: welcome */ INSERT INTO Users(email, name, hash, salt) VALUES ('mike@knights.ucf.edu', 'Michael S', 'pbkdf2:sha256:150000$PWArbloj$32eada7dc35d8c8aa5a0908c8ed50ab2b0e8261ca10432ae6389036b7f2d62af', 'mMvzfT1_s35JRa4qKMzXOtEjoxRD5I9HAYu7v2cHo6k'), ('ash@ucla.edu', 'Ash', 'pbkdf2:sha256:150000$EoNsz8Ac$bc35a9823345ab62ca21c34e0322064ca1e0c9824633fdbbd0fb9a260efd84ea', 'VUwAeBx6qoJR9S7bcr1Z7wR8BntUWpKfeufRWhbC5dE'), ('brent@hunters.edu', 'Brent', 'pbkdf2:sha256:150000$96bPMIB3$8df9b8e23ab999b9469d0a5df213b24c4f4535adff95d7327645c6520117a802', 'KDR16a2Nq3YdtX3VzN1wrH3X0F2agCPDJbJjD5g_-78') ; INSERT INTO Managers(uid) VALUES (1) ; INSERT INTO Entities(eid, name, location, title, picture_filename) VALUES (1, 'Dr. Weiss', 'West Office', 'DVM', 'redhead_vet.jpg'), (2, 'Dr. Jonas', 'South Office', 'Doctor of Internal Medicine', 'blueeyes_doctor.jpeg'), (3, 'Dr. Kane', 'North Office', 'Doctor of Dentistry', 'blonde_dentist.jpg') ; INSERT INTO Appointments(uid, eid, description, datetime_start, datetime_end) VALUES (1, 1, 'Dental Checkup', '20210705T133701', '20210705T222222'), (1, 1, 'Dental Followup', '20210707T133701', '20210705T222223'), (2, 1, 'Comprehensive Exam', '20210707T133702', '20210705T222224'), (3, 2, 'Colonoscopy Appointment', '20210707T133703', '20210705T222225'), (3, 3, 'Numbing Prescription', '20210709T133703', '20210705T222226') ;
56.52
186
0.757254
85830478d7a0b3578ac48d137263513396875023
579
js
JavaScript
docs/node_modules/@vuepress/plugin-search/lib/client/clientAppEnhance.js
Rogerio-Viana/asdf
c12d463764675fdf955063ba6d455d698f37a310
[ "MIT" ]
null
null
null
docs/node_modules/@vuepress/plugin-search/lib/client/clientAppEnhance.js
Rogerio-Viana/asdf
c12d463764675fdf955063ba6d455d698f37a310
[ "MIT" ]
1
2021-07-28T22:38:51.000Z
2021-07-28T22:38:51.000Z
docs/node_modules/@vuepress/plugin-search/lib/client/clientAppEnhance.js
Rogerio-Viana/asdf
c12d463764675fdf955063ba6d455d698f37a310
[ "MIT" ]
null
null
null
import { h } from 'vue'; import { defineClientAppEnhance } from '@vuepress/client'; import { SearchBox } from './components/SearchBox'; import './styles/vars.css'; import './styles/search.css'; const locales = __SEARCH_LOCALES__; const hotKeys = __SEARCH_HOT_KEYS__; const maxSuggestions = __SEARCH_MAX_SUGGESTIONS__; export default defineClientAppEnhance(({ app }) => { // wrap the `<SearchBox />` component with plugin options app.component('SearchBox', (props) => h(SearchBox, { locales, hotKeys, maxSuggestions, ...props, })); });
32.166667
61
0.678756
99269bee9dbe99682ea810d98f544d5b70f27947
399
h
C
DetoxInstruments/DetoxInstruments/RemoteProfiling/_DTXActionButtonProvider.h
benlaverriere/DetoxInstruments
a9552432f1b613d703425fea1776f790e208d930
[ "MIT" ]
null
null
null
DetoxInstruments/DetoxInstruments/RemoteProfiling/_DTXActionButtonProvider.h
benlaverriere/DetoxInstruments
a9552432f1b613d703425fea1776f790e208d930
[ "MIT" ]
null
null
null
DetoxInstruments/DetoxInstruments/RemoteProfiling/_DTXActionButtonProvider.h
benlaverriere/DetoxInstruments
a9552432f1b613d703425fea1776f790e208d930
[ "MIT" ]
null
null
null
// // _DTXActionButtonProvider.h // DetoxInstruments // // Created by Leo Natan (Wix) on 4/8/18. // Copyright © 2017-2020 Wix. All rights reserved. // #import <Foundation/Foundation.h> @protocol _DTXActionButtonProvider <NSObject> @property (nonatomic, copy, readonly) NSArray<NSButton*>* actionButtons; @optional @property (nonatomic, copy, readonly) NSArray<NSButton*>* moreButtons; @end
21
72
0.736842
d5e8f366da5f9fb0c1afecd8ce51d2d0a3cdadb6
360
h
C
d/shadow/ratpaths/common.h
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/shadow/ratpaths/common.h
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
4
2021-03-15T18:56:39.000Z
2021-08-17T17:08:22.000Z
d/shadow/ratpaths/common.h
Dbevan/SunderingShadows
6c15ec56cef43c36361899bae6dc08d0ee907304
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#define RATPATHS "/d/shadow/ratpaths/inherits/rp_inherit" #define RATPATHS_EXIT "/d/shadow/ratpaths/inherits/rp_exit_inherit" #define DEEPROAD "/d/shadow/ratpaths/inherits/dr_inherit" #define DEEPROAD_TR "/d/shadow/ratpaths/inherits/dr_transition" #define PATH "/d/shadow/ratpaths/rooms/" #define SHMON "/d/shadow/mon/" #define RPMON "/d/shadow/ratpaths/mon/"
45
67
0.788889
70f4e111b05a2b9a73052a0cacf9cd81cbdaf314
12,057
c
C
ext/ov_xml_writer.c
oliel/python-ovirt-engine-sdk4
c0b13982b45dee664ebc063bda7686124b402c14
[ "Apache-2.0" ]
3
2022-01-14T00:37:58.000Z
2022-03-26T12:26:32.000Z
ext/ov_xml_writer.c
oliel/python-ovirt-engine-sdk4
c0b13982b45dee664ebc063bda7686124b402c14
[ "Apache-2.0" ]
29
2021-07-20T12:42:44.000Z
2022-03-28T13:01:33.000Z
ext/ov_xml_writer.c
oliel/python-ovirt-engine-sdk4
c0b13982b45dee664ebc063bda7686124b402c14
[ "Apache-2.0" ]
12
2021-07-20T12:27:07.000Z
2022-02-24T11:10:12.000Z
/* Copyright (c) 2016 Red Hat, 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. */ #include <Python.h> #include <structmember.h> #include <libxml/xmlwriter.h> #include <libxml/xmlstring.h> #include "ov_xml_module.h" #include "ov_xml_writer.h" #include "ov_xml_utils.h" /* Imported modules: */ static PyObject* io_module; /* Imported classes: */ static PyObject* bytes_io_class; typedef struct { PyObject_HEAD PyObject* io; xmlTextWriterPtr writer; } ov_xml_writer_object; static void ov_xml_writer_dealloc(ov_xml_writer_object* self) { /* Free the libxml reader: */ xmlTextWriterPtr tmp = self->writer; if (tmp != NULL) { self->writer = NULL; xmlFreeTextWriter(tmp); } /* Decrease references to other objects: */ Py_XDECREF(self->io); self->io = NULL; /* Free this object: */ Py_TYPE(self)->tp_free((PyObject*) self); } static int ov_xml_writer_callback(void* context, const char* buffer, int length) { PyObject* data = NULL; PyObject* io = NULL; PyObject* result = NULL; /* The context is a reference to the IO object: */ io = (PyObject*) context; /* Convert the buffer to a Python array of bytes and write it to the IO object, using the "write" method: */ #if PY_MAJOR_VERSION >= 3 data = PyBytes_FromStringAndSize(buffer, length); #else data = PyString_FromStringAndSize(buffer, length); #endif if (data == NULL) { return -1; } result = PyObject_CallMethod(io, "write", "O", data); if (result == NULL) { return -1; } return length; } static int ov_xml_writer_init(ov_xml_writer_object* self, PyObject* args, PyObject* kwds) { static char* kwlist[] = { "io", "indent", NULL }; PyObject* indent = NULL; PyObject* io = NULL; PyObject* write = NULL; /* Extract the values of the parameters: */ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O", kwlist, &io, &indent)) { return -1; } /* Check that the 'indent' parameter is a boolean: */ if (indent != NULL && !PyBool_Check(indent)) { PyErr_Format(PyExc_TypeError, "The 'indent' parameter must be a boolean"); return -1; } /* If the 'io' parameter is None then we need to create a new BytesIO object. Otherwise we need to check that it has 'write' method, as this catches most errors caused by passing a wrong type of object: */ if (io == Py_None) { io = PyObject_CallObject(bytes_io_class, NULL); if (io == NULL) { PyErr_Format( PyExc_Exception, "Can't create a new instance of 'BytesIO'" ); return -1; } } else { write = PyObject_GetAttrString(io, "write"); if (write == NULL) { PyErr_Format( PyExc_TypeError, "The 'io' parameter doesn't look like an IO object, doesn't have a 'write' method" ); return -1; } Py_DECREF(write); } Py_INCREF(io); self->io = io; /* Create the libxml buffer that writes to the IO object: */ xmlOutputBufferPtr buffer = xmlOutputBufferCreateIO(ov_xml_writer_callback, NULL, self->io, NULL); if (buffer == NULL) { Py_DECREF(self->io); self->io = NULL; PyErr_Format(PyExc_Exception, "Can't create XML buffer"); return -1; } /* Create the libxml writer: */ self->writer = xmlNewTextWriter(buffer); if (self->writer == NULL) { Py_DECREF(self->io); self->io = NULL; xmlOutputBufferClose(buffer); PyErr_Format(PyExc_Exception, "Can't create XML writer"); return -1; } /* Enable indentation: */ if (indent == Py_True) { xmlTextWriterSetIndent(self->writer, 1); xmlTextWriterSetIndentString(self->writer, BAD_CAST " "); } return 0; } static PyObject* ov_xml_writer_write_start(ov_xml_writer_object* self, PyObject* name) { xmlChar* c_name = NULL; int rc = 0; /* Extract the values of the parameters: */ c_name = ov_xml_get_string_parameter("name", name); if (c_name == NULL) { return NULL; } /* Start the element: */ rc = xmlTextWriterStartElement(self->writer, c_name); if (rc < 0) { PyErr_Format(PyExc_Exception, "Can't start XML element with name '%s'", c_name); xmlFree(c_name); return NULL; } xmlFree(c_name); Py_RETURN_NONE; } static PyObject* ov_xml_writer_write_end(ov_xml_writer_object* self) { int rc = 0; /* End the element: */ rc = xmlTextWriterEndElement(self->writer); if (rc < 0) { PyErr_Format(PyExc_Exception, "Can't end XML element"); return NULL; } Py_RETURN_NONE; } static PyObject* ov_xml_writer_write_attribute(ov_xml_writer_object* self, PyObject* args) { PyObject* name = NULL; PyObject* value = NULL; int rc = 0; xmlChar* c_name = NULL; xmlChar* c_value = NULL; /* Extract the values of the parameters: */ if (!PyArg_ParseTuple(args, "OO", &name, &value)) { return NULL; } c_name = ov_xml_get_string_parameter("name", name); if (c_name == NULL) { return NULL; } c_value = ov_xml_get_string_parameter("value", value); if (c_value == NULL) { xmlFree(c_name); return NULL; } /* Write the attribute: */ rc = xmlTextWriterWriteAttribute(self->writer, c_name, c_value); if (rc < 0) { PyErr_Format(PyExc_Exception, "Can't write attribute with name '%s' and value '%s'", c_name, c_value); xmlFree(c_name); xmlFree(c_value); return NULL; } xmlFree(c_name); xmlFree(c_value); Py_RETURN_NONE; } static PyObject* ov_xml_writer_write_element(ov_xml_writer_object* self, PyObject* args) { PyObject* name = NULL; PyObject* value = NULL; int rc = 0; xmlChar* c_name = NULL; xmlChar* c_value = NULL; /* Extract the values of the parameters: */ if (!PyArg_ParseTuple(args, "OO", &name, &value)) { return NULL; } c_name = ov_xml_get_string_parameter("name", name); if (c_name == NULL) { return NULL; } c_value = ov_xml_get_string_parameter("value", value); if (c_value == NULL) { xmlFree(c_name); return NULL; } /* Write the element: */ rc = xmlTextWriterWriteElement(self->writer, c_name, c_value); if (rc < 0) { PyErr_Format(PyExc_Exception, "Can't write element with name '%s' and value '%s'", c_name, c_value); xmlFree(c_name); xmlFree(c_value); return NULL; } xmlFree(c_name); xmlFree(c_value); Py_RETURN_NONE; } static PyObject* ov_xml_writer_flush(ov_xml_writer_object* self) { int rc; rc = xmlTextWriterFlush(self->writer); if (rc < 0) { PyErr_Format(PyExc_Exception, "Can't flush XML writer"); return NULL; } Py_RETURN_NONE; } static PyObject* ov_xml_writer_string(ov_xml_writer_object* self) { PyObject* raw = NULL; PyObject* decoded = NULL; /* Flush the writer: */ if (ov_xml_writer_flush(self) == NULL) { return NULL; } /* Extract the raw bytes from the 'io' object: */ raw = PyObject_CallMethod(self->io, "getvalue", NULL); if (raw == NULL) { return NULL; } /* Convert the raw bytes to UTF-8: */ decoded = PyObject_CallMethod(raw, "decode", "s", "UTF-8", NULL); Py_DECREF(raw); if (decoded == NULL) { return NULL; } return decoded; } static PyObject* ov_xml_writer_close(ov_xml_writer_object* self) { xmlFreeTextWriter(self->writer); self->writer = NULL; Py_RETURN_NONE; } static PyMethodDef ov_xml_writer_methods[] = { { "write_start", (PyCFunction) ov_xml_writer_write_start, METH_O, "Writes the start of an element with the given name." }, { "write_end", (PyCFunction) ov_xml_writer_write_end, METH_NOARGS, "Writes the end of the current element." }, { "write_attribute", (PyCFunction) ov_xml_writer_write_attribute, METH_VARARGS, "Writes an attribute with the given name and value." }, { "write_element", (PyCFunction) ov_xml_writer_write_element, METH_VARARGS, "Writes an element with the given name and value." }, { "flush", (PyCFunction) ov_xml_writer_flush, METH_NOARGS, "Flushes this writer, sending all the pending output th the underlying IO object." }, { "string", (PyCFunction) ov_xml_writer_string, METH_NOARGS, "Return the XML document text generated by this writer so far." }, { "close", (PyCFunction) ov_xml_writer_close, METH_NOARGS, "Closes this writer, releasing all the resources it uses. Note that this doesn't close the IO object." }, { NULL } }; static PyTypeObject ov_xml_writer_type = { #if PY_MAJOR_VERSION >= 3 PyVarObject_HEAD_INIT(NULL, 0) #else PyObject_HEAD_INIT(NULL) /* ob_size */ 0, #endif /* tp_name */ OV_XML_MODULE_NAME "." "XmlWriter", /* tp_basicsize */ sizeof(ov_xml_writer_object), /* tp_itemsize */ 0, /* tp_dealloc */ (destructor) ov_xml_writer_dealloc, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_compare */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ 0, /* tp_flags */ Py_TPFLAGS_DEFAULT, /* tp_doc */ "This is an utility class used to generate XML documents using an streaming approach. It is intended for use by " "other components of the SDK. Refrain from using it directly, as backwards compatibility isn't guaranteed.", /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ ov_xml_writer_methods, /* tp_members */ 0, /* tp_geteset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ 0, /* tp_init */ (initproc) ov_xml_writer_init, /* tp_alloc */ 0, /* tp_new */ 0, }; void ov_xml_writer_define(void) { /* Create the class: */ ov_xml_writer_type.tp_new = PyType_GenericNew; if (PyType_Ready(&ov_xml_writer_type) < 0) { return; } /* Add the classes to the module: */ Py_INCREF(&ov_xml_writer_type); PyModule_AddObject(ov_xml_module, "XmlWriter", (PyObject*) &ov_xml_writer_type); /* Import modules: */ io_module = PyImport_ImportModule("io"); if (io_module == NULL) { PyErr_Format(PyExc_Exception, "Can't import the 'io' module"); return; } Py_INCREF(io_module); /* Locate classes: */ bytes_io_class = PyObject_GetAttrString(io_module, "BytesIO"); if (bytes_io_class == NULL) { PyErr_Format(PyExc_Exception, "Can't locate the 'io.BytesIO' class"); return; } Py_INCREF(bytes_io_class); }
27.464692
117
0.60413
0cfa9b70f4dd085778dfa0f986d2747b6f89ea72
430
py
Python
bin/ADFRsuite/CCSBpckgs/mglkey/__init__.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
null
null
null
bin/ADFRsuite/CCSBpckgs/mglkey/__init__.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
null
null
null
bin/ADFRsuite/CCSBpckgs/mglkey/__init__.py
AngelRuizMoreno/Jupyter_Dock_devel
6d23bc174d5294d1e9909a0a1f9da0713042339e
[ "MIT" ]
1
2021-11-04T21:48:14.000Z
2021-11-04T21:48:14.000Z
############################################################################# # # Author: Michel F. SANNER # # Copyright: M. Sanner and TSRI 2015 # ######################################################################### # # $Header: /mnt/raid/services/cvs/mglkeyDIST/mglkey/__init__.py,v 1.1.1.1 2016/12/07 23:27:34 sanner Exp $ # # $Id: __init__.py,v 1.1.1.1 2016/12/07 23:27:34 sanner Exp $ # from mglkey import MGL_check_key
30.714286
106
0.448837
3fc13f2c75e32987e90f0d178b834e62b8388313
1,834
h
C
WisdomLife/WisdomLife/Helper/NMHUDManager/NMHUDManager.h
christes/WisdomLife
81a0c819eb6287cf5c01bb2d3f9779024eebd0b9
[ "Apache-2.0" ]
null
null
null
WisdomLife/WisdomLife/Helper/NMHUDManager/NMHUDManager.h
christes/WisdomLife
81a0c819eb6287cf5c01bb2d3f9779024eebd0b9
[ "Apache-2.0" ]
null
null
null
WisdomLife/WisdomLife/Helper/NMHUDManager/NMHUDManager.h
christes/WisdomLife
81a0c819eb6287cf5c01bb2d3f9779024eebd0b9
[ "Apache-2.0" ]
null
null
null
// // NMHUDManager.h // LemonLoan // // Created by xiaoping on 16/5/16. // Copyright © 2016年 coffee. All rights reserved. // #import <Foundation/Foundation.h> @class UIView,UIButton; @interface NMHUDManager : NSObject #pragma mark - show + (void)showWithText:(NSString *)text; + (void)showWithDefaultText; + (void)showWithText:(NSString *)text dismissDelay:(NSTimeInterval)delay; + (void)showErrorWithText:(NSString *)text; + (void)showErrorWithText:(NSString *)text dismissDelay:(NSTimeInterval)delay; + (void)showSuccessWithText:(NSString *)text; + (void)showSuccessWithText:(NSString *)text dismissDelay:(NSTimeInterval)delay; + (void)showSuccessWithView:(UIView *)view text:(NSString *)text dismissDelay:(NSTimeInterval)delay; + (void)showSuccessWithView:(UIView *)view text:(NSString *)text dismissDelay:(NSTimeInterval)delay finished:(void(^)(void))finishedBlock; + (void)showInfoWithText:(NSString *)text dismissDelay:(NSTimeInterval)delay; + (void)showProgress:(float)pro; + (void)showProgress:(float)pro text:(NSString *)text; #pragma mark - dismiss + (void)dismiss; + (void)dismissWithDelay:(NSTimeInterval)delay; #pragma mark - new apis + (void)showWithView:(UIView *)view text:(NSString *)text; + (void)dismissWithView:(UIView *)view; #pragma mark - failure view /** * failure view * * @param view view description * @param block block description */ + (void)showFailureViewWithView:(UIView *)view buttonActionBlock:(void(^)(UIButton *sender))block; + (void)showFailureViewWithView:(UIView *)view text:(NSString *)text buttonActionBlock:(void(^)(UIButton *sender))block; #pragma mark - load and dismiss for load + (void)showLoadViewWithView:(UIView *)view text:(NSString *)text; + (void)showDefaultTextForLoadViewWithView:(UIView *)view; + (void)dismissLoadViewWithView:(UIView *)view; @end
29.580645
138
0.748092
2f098ba56165940d4e38009d80c5bbf883f78790
1,032
php
PHP
Semester 4/WEB/pertemuan3/proses.php
bijancot/materikuliah
119c26238e08487dda9b0c4f700e393e581f59f8
[ "MIT" ]
null
null
null
Semester 4/WEB/pertemuan3/proses.php
bijancot/materikuliah
119c26238e08487dda9b0c4f700e393e581f59f8
[ "MIT" ]
null
null
null
Semester 4/WEB/pertemuan3/proses.php
bijancot/materikuliah
119c26238e08487dda9b0c4f700e393e581f59f8
[ "MIT" ]
null
null
null
<?php include_once('database.php'); $param = $_POST['buttonInput']; $id = $_POST['id']; $nama = $_POST['nama']; $kode = $_POST['kode']; $harga= $_POST['harga']; echo $param; if($param=="input"){ $yolo = $mysqli->prepare("INSERT INTO barang(kode,nama,harga) VALUES(?,?,?)"); $yolo->bind_param('sss',$kode,$nama,$harga); $nama = $_POST['nama']; $kode = $_POST['kode']; $harga= $_POST['harga']; $yolo->execute(); header("Refresh: 2; url=index.php"); }if($param=="edit"){ $ide = $_POST['id']; $yolo = $mysqli->prepare("UPDATE barang set kode=?,nama=?,harga=? where id=$ide"); $yolo->bind_param('sss',$kode,$nama,$harga); $nama = $_POST['nama']; $kode = $_POST['kode']; $harga= $_POST['harga']; $yolo->execute(); header("Refresh: 2; url=index.php"); }if($_GET['param']=="hapus"){ $yolo = $mysqli->prepare("DELETE FROM barang where id=?"); $yolo->bind_param('s',$id); $id=$_GET['id']; $yolo->execute(); header("Refresh: 1; url=index.php"); } ?>
29.485714
86
0.559109
9c206f2481166e3c973e2f2960fbabca4f05e50e
2,949
js
JavaScript
lib/actions.js
wangpin34/sqldog
dd5326b840c262791911d156bad2e14102a9636b
[ "MIT" ]
1
2019-08-24T02:59:01.000Z
2019-08-24T02:59:01.000Z
lib/actions.js
wangpin34/sqldog
dd5326b840c262791911d156bad2e14102a9636b
[ "MIT" ]
null
null
null
lib/actions.js
wangpin34/sqldog
dd5326b840c262791911d156bad2e14102a9636b
[ "MIT" ]
2
2015-10-30T08:31:54.000Z
2019-08-24T03:05:47.000Z
var child_process = require('child_process'); var util = require('util'); var _ = require('underscore'); var setup = require('./setup'); var data = require('./data'); var ft = require('./fileutils'); var conf = data.getConf(); var db = conf.db; var host = db.host; var port = db.port; var user = db.user; var password = db.password; var cwd = process.cwd(); function executeSqlFiles(patharray, callback) { for (var x in patharray) { executeSqlFile(patharray[x], callback); } } function executeSqlFile(file, callback) { child_process.exec(util.format('mysql -h %s -u%s -p%s < %s', host, user, password, file), callback); } exports.init = function() { setup.init(); } exports.initse = function() { setup.init(true); } exports.config = function (){ setup.config(); } exports.getStatus = function() { var allSqlfiles = data.getSqlfiles(); var uexnum = 0; var exnum = 0; var tnum = allSqlfiles.length; var unexecfile = []; for (var x in allSqlfiles) { if (allSqlfiles[x].executed) { exnum++; } else { uexnum++; unexecfile.push(allSqlfiles[x].name); } } console.log("\n >>> \n"); console.log('total sql files: ' + tnum + '\n'); console.log('executed sql files: ' + exnum + '\n'); console.log('un executed sql files: ' + uexnum + '\n'); for(var x in unexecfile){ console.log(' ' + unexecfile[x] + '\n'); } } exports.execute = function(file,force) { var sqlfiles = []; if(!ft.isFileExist(file)){ throw file + ' doesn\'t exist'; } if(!data.isSqlfileWatched(file)){ //add this file to status sqlfiles = data.getSqlfiles(); var fileobj = data.createSqlfileObj(file); sqlfiles.push(fileobj); } if (data.isExecuted(file) && !force) throw file + ' is also executed. \nBut you can still execute it using : sqldog ex -f ' + file; executeSqlFile(file, function(err) { if (err) throw 'Error occuard when executed sql ' + file; sqlfiles = data.getSqlfiles(); for (var x in sqlfiles) { var name = sqlfiles[x].name; if (name === file) { sqlfiles[x].executed = true; break; } } data.setSqlfiles(sqlfiles); }); } /** * Detect files, and sync them with tracked files */ exports.walk = function(){ var untracked = [], removed = [], exists = [], trackeds = data.getSqlfilemap(), sqlfiles = data.listSqlfiles(); _.each(trackeds,function(tracked,index,list){ if(_.indexOf(sqlfiles,tracked) === -1){ removed.push(tracked); } }); _.each(sqlfiles,function(sqlfile,index,list){ if(_.indexOf(trackeds,sqlfile) === -1){ untracked.push(sqlfile); } }); if(removed.length>0){ console.log(removed.join() + " removed!"); data.untrackSqlfiles(removed); } if(untracked.length>0){ console.log(untracked.join() + " untracked!"); data.trackSqlfiles(untracked); } if(removed.length == 0 && untracked.length == 0){ console.log('\nNothing strange found, my master.'); } data.setSqlfilemap(sqlfiles); }
19.66
132
0.6392
0c844a07b81367c6e40feb94bf39e5508b8f654c
1,134
py
Python
prac2_2.py
JulianAZW/bookish-lamp
24f354d8fa16841f256a2ad40668126604131cef
[ "MIT" ]
1
2022-03-26T01:07:57.000Z
2022-03-26T01:07:57.000Z
prac2_2.py
JulianAZW/bookish-lamp
24f354d8fa16841f256a2ad40668126604131cef
[ "MIT" ]
null
null
null
prac2_2.py
JulianAZW/bookish-lamp
24f354d8fa16841f256a2ad40668126604131cef
[ "MIT" ]
1
2022-03-27T02:32:39.000Z
2022-03-27T02:32:39.000Z
# -*- coding: utf-8 -*- """ Created on Thu Mar 17 19:08:54 2022 @author: julian """ import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def heatmap(df): correlation_matrix = df.corr().round(2) print(correlation_matrix) sns_h = sns.heatmap(data=correlation_matrix, annot=True) sns_h.figure.savefig("Mapa de calor de correlacion") sns_h.figure.clear() def plotXY(df): for i in range(0,8): plt_disp = plt.scatter(df.iloc[:,i],df.iloc[:,8]) plt.xlabel(df.columns[i]) plt.ylabel(df.columns[8]) cadena = "plt"+str(i)+"_"+str(8)+".png" print(cadena) plt_disp plt_disp.figure.clear() if __name__=='__main__': df1 = pd.read_csv("data_train.csv", sep=',', engine='python') df2 = pd.read_csv("medianHouseValue_train.csv", sep=',', engine='python') df = pd.concat([df1,df2], axis=1) print("El DataFrame con el 80 por ciento de los datos: \n", df) #plt.scatter(df.iloc[:,7],df.iloc[:,8]) #plt.xlabel(df.columns[7]) #plt.ylabel(df.columns[8]) #plt.show() heatmap(df) plotXY(df)
26.372093
77
0.613757
0b43e92ff65dfbae4bcf1fe66e16f6008f379b22
2,605
py
Python
test_hrm_code.py
liameirose/bme590hrm
d44573b73b46b121a31667c12bb6add4e8a8daa7
[ "MIT" ]
null
null
null
test_hrm_code.py
liameirose/bme590hrm
d44573b73b46b121a31667c12bb6add4e8a8daa7
[ "MIT" ]
2
2018-10-20T22:16:56.000Z
2018-10-25T23:56:43.000Z
test_hrm_code.py
liameirose/bme590hrm
d44573b73b46b121a31667c12bb6add4e8a8daa7
[ "MIT" ]
null
null
null
import pytest import json import numpy as np @pytest.mark.parametrize("candidate, expected", [ (1.345, True), (-4.554, True), ('9999', True) ]) def test_number_please(candidate, expected): from hrm_code import number_please assert number_please(candidate) == expected def test_import_data(): from hrm_code import import_data [time, voltage] = import_data("test_data/test_data2.csv") assert time[0] == 0 assert voltage[0] == -0.345 def test_calc_duration(): from hrm_code import calc_duration fake_time = [0, 1, 2, 3, 4.3, 5, 6, 7.2] dur = calc_duration(fake_time) assert dur == 7.2 def test_find_min_max_volt(): from hrm_code import find_max_min_volt fake_voltage = [1.2, -0.3, 4.8, 0, -3] both = find_max_min_volt(fake_voltage) assert both == [-3, 4.8] def test_calc_freq(): from hrm_code import calc_sample_freq fake_time = [0, 0.5, 1, 1.5, 2] fs = calc_sample_freq(fake_time) assert fs == 2 def test_detect_peak(): from hrm_code import detect_peak # Peaks should occur every 60 sec fs = 60 t = np.arange(0, 5, 1/fs) wave = abs(np.sin(t*np.pi)**20) peaks = detect_peak(wave, fs, hrw=0.1) assert peaks == [27, 87, 147, 207, 267] def test_num_beat(): from hrm_code import num_beat fake_peaklist = [1, 3, 4] fake_time = [0, 0.5, 1, 1.5, 2, 2.5, 3] [num_beats, beats] = num_beat(fake_time, fake_peaklist) assert num_beats == 3 assert beats == [0.5, 1.5, 2] def test_calc_bpm(): from hrm_code import calc_bpm fake_num_beats = 20 fake_dur = 40 bpm = calc_bpm(fake_num_beats, fake_dur) assert bpm == 30 def test_create_metrics(): from hrm_code import create_metrics bpm = 70 both = [-1.4, 5.6] dur = 30 num_beats = 80 beats = [0.5, 0.75, 0.8] metrics = create_metrics(bpm, beats, both, dur, num_beats) assert metrics == { "mean_hr_bpm": 70, "voltage extremes": [-1.4, 5.6], "duration": 30, "num_beats": 80, "beats": [0.5, 0.75, 0.8] } def test_create_jason(): from hrm_code import create_jason metrics = {"Favorite Ice Cream Flavor": "Chocolate", "Favorite Book": "A Tree Grows in Brooklyn", "Favorite Number": 8} filename = "test_output.csv" create_jason(filename, metrics) read_file = json.load(open('test_output.json')) assert read_file == {"Favorite Ice Cream Flavor": "Chocolate", "Favorite Book": "A Tree Grows in Brooklyn", "Favorite Number": 8}
26.05
69
0.621881
15d5cefc04958179351e40849db54ab2a2c9449b
1,060
rb
Ruby
spec/core/file/chmod_spec.rb
tqrg-bot/rubinius
beb0fe3968ea7ff3c09e192605eef066136105c8
[ "BSD-3-Clause" ]
null
null
null
spec/core/file/chmod_spec.rb
tqrg-bot/rubinius
beb0fe3968ea7ff3c09e192605eef066136105c8
[ "BSD-3-Clause" ]
null
null
null
spec/core/file/chmod_spec.rb
tqrg-bot/rubinius
beb0fe3968ea7ff3c09e192605eef066136105c8
[ "BSD-3-Clause" ]
null
null
null
require File.dirname(__FILE__) + '/../../spec_helper' describe "File#chmod" do before :each do @filename = File.dirname(__FILE__) + '/fixtures/i_exist' @file = File.open(@filename, 'w') end after :each do @file.close File.delete(@filename) if File.exist?(@filename) end it "returns 0 if successful" do @file.chmod(0755).should == 0 end platform :not, :mswin do it "should modify the permission bits of the files specified" do @file.chmod(0755) File.stat(@filename).mode.should == 33261 end end end describe "File.chmod" do before :each do @file = File.dirname(__FILE__) + '/fixtures/i_exist' File.open(@file, 'w') {} @count = File.chmod(0755, @file) end after :each do File.delete(@file) if File.exist?(@file) end it "should return the number of files modified" do @count.should == 1 end platform :not, :mswin do it "should modify the permission bits of the files specified" do File.stat(@file).mode.should == 33261 end end end
23.043478
68
0.636792
64e780c53b14b8d54e7b29765c0948e7c105d76b
2,974
swift
Swift
StripeIdentity/StripeIdentity/Source/NativeComponents/Detectors/BarcodeDetector.swift
1amageek/stripe-ios
742188f6f3b17c436fd95f6aa6edfd6dc0e560f7
[ "MIT" ]
null
null
null
StripeIdentity/StripeIdentity/Source/NativeComponents/Detectors/BarcodeDetector.swift
1amageek/stripe-ios
742188f6f3b17c436fd95f6aa6edfd6dc0e560f7
[ "MIT" ]
null
null
null
StripeIdentity/StripeIdentity/Source/NativeComponents/Detectors/BarcodeDetector.swift
1amageek/stripe-ios
742188f6f3b17c436fd95f6aa6edfd6dc0e560f7
[ "MIT" ]
null
null
null
// // BarcodeDetector.swift // StripeIdentity // // Created by Mel Ludowise on 2/25/22. // import Foundation import Vision struct BarcodeDetectorOutput: Equatable { let hasBarcode: Bool let isTimedOut: Bool let symbology: VNBarcodeSymbology let timeTryingToFindBarcode: TimeInterval } extension BarcodeDetectorOutput: VisionBasedDetectorOutput { init( detector: BarcodeDetector, observations: [VNObservation], originalImageSize: CGSize ) throws { let barcodeObservations: [VNBarcodeObservation] = observations.compactMap { guard let observation = $0 as? VNBarcodeObservation, detector.configuration.symbology == observation.symbology else { return nil } return observation } var timeTryingToFindBarcode: TimeInterval = -1 if let firstScanTimestamp = detector.firstScanTimestamp { timeTryingToFindBarcode = Date().timeIntervalSince(firstScanTimestamp) } self.init( hasBarcode: !barcodeObservations.isEmpty, isTimedOut: false, symbology: detector.configuration.symbology, timeTryingToFindBarcode: timeTryingToFindBarcode ) } } final class BarcodeDetector: VisionBasedDetector { struct Configuration { /// Which type of barcode symbology to scan for let symbology: VNBarcodeSymbology /// The amount of time to look for a barcode before accepting images without let timeout: TimeInterval } /// Wrap all instance property modifications in a serial queue private let serialQueue = DispatchQueue(label: "com.stripe.identity.barcode-detector") fileprivate var firstScanTimestamp: Date? let configuration: Configuration init(configuration: Configuration) { self.configuration = configuration } func visionBasedDetectorMakeRequest() -> VNImageBasedRequest { let request = VNDetectBarcodesRequest() request.symbologies = [configuration.symbology] return request } func visionBasedDetectorOutputIfSkipping() -> BarcodeDetectorOutput? { let timeOfScanRequest = Date() var timeSinceScan: TimeInterval = 0 serialQueue.sync { [weak self] in let firstScanTimestamp = self?.firstScanTimestamp ?? timeOfScanRequest self?.firstScanTimestamp = firstScanTimestamp timeSinceScan = timeOfScanRequest.timeIntervalSince(firstScanTimestamp) } guard timeSinceScan >= configuration.timeout else { return nil } return .init( hasBarcode: false, isTimedOut: true, symbology: configuration.symbology, timeTryingToFindBarcode: timeSinceScan ) } func reset() { serialQueue.async { [weak self] in self?.firstScanTimestamp = nil } } }
30.040404
90
0.658709
f55533f7b5c7e825ba68bb48c51017fdb01caa91
2,764
swift
Swift
examples/supplemental/TimelineView.swift
Saruul-Ulzii/material-motion-swift
40decaf295aa1e41417e7f4dec8a7391c29e27ab
[ "Apache-2.0" ]
1,500
2017-03-17T20:13:38.000Z
2022-03-16T09:29:32.000Z
examples/supplemental/TimelineView.swift
Saruul-Ulzii/material-motion-swift
40decaf295aa1e41417e7f4dec8a7391c29e27ab
[ "Apache-2.0" ]
76
2017-03-16T19:33:41.000Z
2020-02-04T07:05:03.000Z
examples/supplemental/TimelineView.swift
material-motion/reactive-motion-swift
fae8c59f53066e1d3fe6c5d39192e0c51303a656
[ "Apache-2.0" ]
103
2017-03-28T21:12:37.000Z
2021-02-04T18:43:36.000Z
/* Copyright 2016-present The Material Motion Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit import IndefiniteObservable import MaterialMotion protocol TimelineViewDelegate: NSObjectProtocol { func timelineView(_ timelineView: TimelineView, didChangeSliderValue sliderValue: CGFloat) func timelineViewDidTogglePause(_ timelineView: TimelineView) } class TimelineView: UIView { weak var delegate: TimelineViewDelegate? var timeline: Timeline? { didSet { pausedSubscription = timeline?.paused.subscribeToValue { [weak self] paused in self?.toggle.setTitle(paused ? "▶" : "❙❙", for: .normal) } } } private var pausedSubscription: Subscription? override init(frame: CGRect) { super.init(frame: frame) bgView = UIView(frame: .zero) bgView.backgroundColor = UIColor.init(white: 0.95, alpha: 1) self.addSubview(bgView) slider = UISlider(frame: .zero) slider.tintColor = .primaryColor slider.addTarget(self, action: #selector(didSlide), for: .valueChanged) self.addSubview(slider) toggle = UIButton(type: .custom) toggle.setTitle("▶", for: .normal) toggle.setTitleColor(.black, for: .normal) toggle.addTarget(self, action: #selector(didToggle), for: .touchUpInside) self.addSubview(toggle) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() bgView.frame = .init(x: 0, y: 20, width: bounds.size.width, height: bounds.size.height - 20) let center = CGPoint(x: bounds.size.width / 2.0, y: bounds.size.height / 2.0) slider.frame = .init(x: 16, y: 0, width: frame.width - 32, height: 40) toggle.frame = .init(x: center.x - 16, y: center.y - 16 + 12, width: 32, height: 32) } override public func sizeThatFits(_ size: CGSize) -> CGSize { return .init(width: size.width, height: 84) } func didSlide(_ slider: UISlider) { delegate?.timelineView(self, didChangeSliderValue: CGFloat(slider.value)) } func didToggle(_ button: UIButton) { delegate?.timelineViewDidTogglePause(self) } private var bgView: UIView! private var slider: UISlider! private var toggle: UIButton! }
31.409091
96
0.716353
98cf1edce86904ba3635c9314851e641ee411403
73
html
HTML
assets/src/template/scripts.html
EugeneKobeliaksky/print-online_webapp
043e111291636df20a7241c5888c607f497ac4ae
[ "MIT" ]
null
null
null
assets/src/template/scripts.html
EugeneKobeliaksky/print-online_webapp
043e111291636df20a7241c5888c607f497ac4ae
[ "MIT" ]
null
null
null
assets/src/template/scripts.html
EugeneKobeliaksky/print-online_webapp
043e111291636df20a7241c5888c607f497ac4ae
[ "MIT" ]
null
null
null
<script src="js/main.min.js"></script> <script src="js/main.js"></script>
36.5
38
0.671233
606ec77109dd4eece80fb8b06c8a818b38a01bf1
53,379
html
HTML
src/main/resources/words/6076.html
conanchen/easyhan-cloud
227ff71231607fe0f35d1f67236e830e86897c27
[ "Apache-2.0" ]
null
null
null
src/main/resources/words/6076.html
conanchen/easyhan-cloud
227ff71231607fe0f35d1f67236e830e86897c27
[ "Apache-2.0" ]
null
null
null
src/main/resources/words/6076.html
conanchen/easyhan-cloud
227ff71231607fe0f35d1f67236e830e86897c27
[ "Apache-2.0" ]
null
null
null
<body class="module" id="wise-word-body" data-prop="" data-name=""> <header id="header" class="headroom fixed"> <div class="headroom--container"> <div class="c-row fl-row"> <div class="word-name">恶</div> <div class="c-span9"> <script>window.xxx = {"ret_num":1,"ret_array":[{"antonym":["\u5584","\u597d","\u7231","\u7f8e"],"basic_source_url":["http:\/\/hanyu.baidu.com\/zici\/s?wd=%E6%81%B6","http:\/\/dict.baidu.com\/s?wd=%E6%81%B6"],"imgs":[{"200_B0":["http:\/\/t10.baidu.com\/it\/u=3900135336,867394369&fm=58"],"200_B1":["http:\/\/t11.baidu.com\/it\/u=4023809626,820913889&fm=58"],"400_B0":["http:\/\/t11.baidu.com\/it\/u=2649095068,3493286573&fm=58&s=6B61736EFBA4B37C4EF9DC0F0300E0C1"],"400_B1":["http:\/\/t12.baidu.com\/it\/u=1809005699,1582637489&fm=58&s=4A2C3062CEF077A31D15B1470300E0A0"],"80_B0":["http:\/\/t10.baidu.com\/it\/u=2546825793,4232929472&fm=58"],"80_B1":["http:\/\/t12.baidu.com\/it\/u=2663450432,305422532&fm=58"]}],"line_type":["\u571f"],"name":["\u6076"],"pinyin":["\u00e8","w\u00f9","\u011b","w\u016b"],"radicals":["\u5fc3"],"rough_comp":["\u4e9a","\u5fc3"],"sid":["49d6a1c0427711e58c23c8e0eb15ce01"],"stroke_count":["10"],"stroke_order":[{"img":"1","value":"\u6a2a"},{"img":"2","value":"\u7ad6"},{"img":"2","value":"\u7ad6"},{"img":"4","value":"\u70b9"},{"img":"3","value":"\u6487"},{"img":"1","value":"\u6a2a"},{"img":"10","value":"\u70b9"},{"img":"16","value":"\u659c\u94a9"},{"img":"4","value":"\u70b9"},{"img":"4","value":"\u70b9"}],"stroke_order_gif":["http:\/\/appcdn.fanyi.baidu.com\/zhdict\/gif\/b49d6a1c0427711e58c23c8e0eb15ce01.gif"],"struct_type":["\u4e0a\u4e0b\u7ed3\u6784"],"sug_py":["e","wu"],"traditional":["\u5641 \u3001 \u60e1"],"type":["word"],"update_time":["405342"],"word_radicals":["\u5fc3"],"word_stroke_count":["10"],"word_traditional":["\u5641 \u3001 \u60e1"],"word_wubi":["GOGN"],"wubi":["GOGN"],"add_mean":[{"pinyin":"\u00e8","mp3":"e4","definition":["1.\u4e0d\u597d<span>\uff1a\uff5e\u611f\u3002\uff5e\u679c\u3002\uff5e\u52a3\u3002\uff5e\u540d\u3002\u4e11\uff5e\u3002<\/span>","2.\u51f6\u72e0<span>\uff1a\uff5e\u9738\u3002\uff5e\u68cd\u3002\u9669\uff5e\u3002\u51f6\uff5e\u3002<\/span>","3.\u72af\u7f6a\u7684\u4e8b\uff0c\u6781\u574f\u7684\u884c\u4e3a<span>\uff1a\uff5e\u8d2f\u6ee1\u76c8\u3002<\/span>"]},{"pinyin":"w\u00f9","mp3":"wu4","definition":["\u8ba8\u538c\uff0c\u618e\u6068\uff0c\u4e0e\u201c\u597d\uff08h\u00e0o \uff09\u201d\u76f8\u5bf9<span>\uff1a\u53ef\uff5e\u3002\u538c\uff5e\u3002\u597d\uff08h\u00e0o\uff09\uff5e\u3002<\/span>"]},{"pinyin":"\u011b","mp3":"e3","definition":["1.\u3014\uff5e\u5fc3\u3015\u8981\u5455\u5410\u7684\u611f\u89c9\uff1b\u4ea6\u6307\u5bf9\u4eba\u548c\u4e8b\u7684\u538c\u6076\u6001\u5ea6\u3002","2.\uff08\u5641\uff09"]},{"pinyin":"w\u016b","mp3":"wu1","definition":["1.\u53e4\u540c\u201c\u4e4c\u201d\uff0c\u7591\u95ee\u8bcd\uff0c\u54ea\uff0c\u4f55\u3002","2.\u6587\u8a00\u53f9\u8bcd\uff0c\u8868\u793a\u60ca\u8bb6<span>\uff1a\uff5e\uff0c\u662f\u4f55\u8a00\u4e5f\uff01<\/span>"]}],"riddle":[],"detail_mean":["<p><strong>1. <a href=\"#xjcpgxon\">\u6076 [w\u00f9]<\/a><\/strong><strong>2. <a href=\"#odjqyhor\">\u6076 [w\u016b]<\/a><\/strong><strong>3. <a href=\"#oyhiqotj\">\u6076 [\u00e8]<\/a><\/strong><\/p><dl><dt><a name=\"xjcpgxon\">\u6076 [w\u00f9]<\/a><\/dt><dd><p><strong>\u3008\u52a8\u3009<\/strong><\/p><ol><li><p> \u8ba8\u538c;\u618e\u6076 <\/p><p>\u5929\u4e0d\u4e3a\u4eba\u4e4b\u6076\u5bd2\u800c\u8f8d\u51ac\u3002\u2014\u2014\u300a\u8340\u5b50\u00b7\u5929\u8bba\u300b<\/p><p>\u552f\u4ec1\u8005,\u80fd\u597d\u4eba,\u80fd\u6076\u4eba\u3002\u2014\u2014\u300a\u8bba\u8bed\u00b7\u91cc\u4ec1\u300b<\/p><p>\u8bda\u597d\u6076\u4f55\u5982\u3002\u2014\u2014\u5510\u00b7 \u67f3\u5b97\u5143\u300a\u67f3\u6cb3\u4e1c\u96c6\u300b<\/p><p>\u597d\u9038\u6076\u52b3\u3002\u2014\u2014\u6e05\u00b7 \u9ec4\u5b97\u7fb2\u300a\u539f\u541b\u300b<\/p><p>\u6028\u6076\u5176\u541b\u3002<\/p><p> \u53c8\u5982:\u751a\u6076(\u8ba8\u538c\u4e4b\u6781;\u975e\u5e38\u8ba8\u538c;\u53cd\u611f\u4e4b\u81f3);\u6076\u5fcc(\u538c\u6076\u731c\u5fcc);\u6076\u751f(\u538c\u751f);\u6076\u4e0d\u53bb\u5584(\u4e0d\u56e0\u538c\u6076\u5176\u4eba\u800c\u62b9\u6740\u4ed6\u7684\u4f18\u70b9);\u6076\u6740(\u538c\u6076\u6740\u751f);\u6076\u7d2b\u593a\u6731(\u538c\u6076\u4ee5\u90aa\u4ee3\u6b63);\u6076\u5acc(\u8ba8\u538c);\u6076\u60ee(\u538c\u6076\u754f\u60e7);\u6076\u8bc6(\u5192\u72af;\u5f97\u7f6a);\u6076\u4e0a(\u618e\u6076\u957f\u4e0a);\u8fd9\u4eba\u771f\u53ef\u6076;\u618e\u6076(\u618e\u6068;\u538c\u6076);\u6df1\u6076\u75db\u7edd;\u6076\u6076(\u618e\u6068\u90aa\u6076)<\/p><\/li><li><p> \u5ac9\u5992 <\/p><p>[\u5218]\u8868\u6076\u5176\u80fd\u800c\u4e0d\u80fd\u7528\u4e5f\u3002\u2014\u2014\u300a\u8d44\u6cbb\u901a\u9274\u300b<\/p><\/li><li><p> \u8bfd\u8c24;\u4e2d\u4f24 <\/p><p>\u4eba\u4e4b\u6709\u6280,\u5192\u75be\u4ee5\u6076\u4e4b\u3002\u2014\u2014\u300a\u4e66\u00b7\u79e6\u8a93\u300b<\/p><p>\u592a\u5b50\u75e4\u7f8e\u800c\u72e0,\u5408\u4f50\u5e08\u754f\u800c\u6076\u4e4b\u3002\u2014\u2014\u300a\u5de6\u4f20\u00b7\u8944\u516c\u4e8c\u5341\u516d\u5e74\u300b<\/p><p>\u6bd4\u800c\u6076\u4e4b\u3002\u2014\u2014\u300a\u5de6\u4f20\u00b7\u662d\u516c\u4e8c\u5341\u4e03\u5e74\u300b<\/p><p>\u4eba\u6709\u6076\u82cf\u79e6\u4e8e \u71d5\u738b\u8005,\u66f0:\u201c \u6b66\u5b89\u541b,\u5929\u4e0b\u4e0d\u4fe1\u4eba\u4e5f\u3002\u2014\u2014\u300a\u6218\u56fd\u7b56\u300b<\/p><p> \u53c8\u5982:\u6076\u8baa(\u8bfd\u8c24)<\/p><\/li><li><p> \u5fcc\u8bb3 <\/p><p>\u5927\u53f2\u5178\u793c,\u6267\u7b80\u8bb0\u5949\u8bb3\u6076\u3002\u2014\u2014\u300a\u793c\u8bb0\u300b<\/p><\/li><\/ol><p><strong>\u3008\u5f62\u3009<\/strong><\/p><ol><li><p> \u7f9e\u803b,\u7f9e\u6127 <\/p><p>\u65e0\u76d6\u6076\u4e4b\u5fc3,\u975e\u4eba\u4e5f\u3002\u2014\u2014\u300a\u5b5f\u5b50\u00b7\u516c\u5b59\u4e11\u4e0a\u300b<\/p><p> \u53c8\u5982:\u6076\u56ca(\u7a9d\u56ca)<\/p><\/li><li><p> \u53e6\u89c1 \u011b;\u00e8;w\u016b<\/p><\/li><\/ol><\/dd><\/dl><dl><dt><a name=\"odjqyhor\">\u6076 [w\u016b]<\/a><\/dt><dd><p><strong>\u3008\u4ee3\u3009<\/strong><\/p><ol><li><p>\u8868\u793a\u7591\u95ee,\u76f8\u5f53\u4e8e\u201c\u4f55\u201d\u3001\u201c\u600e\u4e48\u201d <\/p><p>\u6076,\u5b89\u4e5f\u3002\u2014\u2014\u300a\u5e7f\u97f5\u300b<\/p><p>\u6076\u8bc6\u5b97?\u2014\u2014\u300a\u5de6\u4f20\u00b7\u8944\u516c\u4e8c\u5341\u516b\u5e74\u300b<\/p><p>\u5f03\u7236\u4e4b\u547d,\u6076\u7528\u5b50\u77e3!\u2014\u2014\u300a\u5de6\u4f20\u00b7\u6853\u516c\u5341\u516d\u5e74\u300b<\/p><p>\u5f7c\u6076\u77e5\u4e4b\u3002\u2014\u2014\u300a\u5b5f\u5b50\u00b7\u6881\u60e0\u738b\u4e0a\u300b<\/p><p>\u6076\u80fd\u65e0\u7eaa\u3002\u2014\u2014\u660e\u00b7 \u8881\u5b8f\u9053\u300a\u6ee1\u4e95\u6e38\u8bb0\u300b<\/p><\/li><li><p> \u8868\u793a\u60ca\u8bb6 <\/p><p>\u6076,\u662f\u4f55\u8a00\u4e5f?\u2014\u2014\u300a\u5b5f\u5b50\u300b<\/p><p>\u6076,\u662f\u4f55\u8a00\u3002\u2014\u2014\u6e05\u00b7 \u6881\u542f\u8d85\u300a\u996e\u51b0\u5ba4\u5408\u96c6\u00b7\u6587\u96c6\u300b<\/p><\/li><li><p> \u53e6\u89c1 \u011b;\u00e8;w\u00f9<\/p><\/li><\/ol><\/dd><\/dl><dl><dt><a name=\"oyhiqotj\">\u6076 [\u00e8]<\/a><\/dt><dd><p><strong>\u3008\u540d\u3009<\/strong><\/p><ol><li><p> (\u5f62\u58f0\u3002\u4ece\u5fc3,\u4e9a\u58f0\u3002\u672c\u4e49:\u8fc7\u5931)<\/p><\/li><li><p> \u540c\u672c\u4e49 <\/p><p>\u6076,\u8fc7\u4e5f\u3002\u2014\u2014\u300a\u8bf4\u6587\u300b<\/p><p>\u6076\u4e0a\u5b89\u897f\u3002\u2014\u2014\u300a\u989c\u6c0f\u5bb6\u8bad\u300b<\/p><p>\u543e\u4ee5\u5fd7\u524d\u6076\u3002\u2014\u2014\u300a\u5de6\u4f20\u00b7\u5b9a\u516c\u4e94\u5e74\u300b<\/p><p>\u541b\u5b50\u4e4b\u904f\u6076\u626c\u5584\u3002\u2014\u2014\u300a\u6613\u00b7\u8c61\u4f20\u300b<\/p><p> \u53c8\u5982:\u6076\u6076\u4ece\u77ed(\u5bf9\u4e8e\u4eba\u7684\u8fc7\u5931,\u4e0d\u5341\u5206\u82db\u8d23,\u9002\u53ef\u800c\u6b62)<\/p><\/li><li><p> \u6cdb\u6307\u4e00\u822c\u7f6a\u6076 <\/p><p>\u6076\u79ef\u7978\u76c8\u3002\u2014\u2014\u5357\u671d\u9f50\u00b7 \u4e18\u8fdf\u300a\u4e0e\u9648\u4f2f\u4e4b\u4e66\u300b<\/p><p> \u53c8\u5982:\u6076\u9006(\u5978\u6076\u9006\u4e71\u3002\u53e4\u4ee3\u5211\u5f8b\u5341\u6076\u5927\u7f6a\u4e4b\u4e00);\u6076\u969c(\u4f5b\u8bed\u3002\u6307\u6740\u751f\u3001\u5077\u76d7\u7b49\u59a8\u788d\u4fee\u884c\u7684\u7f6a\u6076);\u6076\u5934\u513f(\u7f6a\u540d);\u6076\u5fc3\u94b1\u513f(\u5e72\u574f\u4e8b\u5f97\u6765\u7684\u94b1\u8d22);\u6076\u5b7d(\u7f6a\u6076;\u5f0a\u75c5)<\/p><\/li><li><p> \u6076\u4eba;\u574f\u4eba <\/p><p>\u5143\u6076\u4e0d\u5f85\u6559\u800c\u8bdb\u3002\u2014\u2014\u300a\u8340\u5b50\u00b7\u738b\u5236\u300b<\/p><p> \u53c8\u5982:\u6076\u6740\u90fd\u6765(\u523d\u5b50\u624b\u5728\u5211\u573a\u4e0a\u901e\u5a01\u98ce\u800c\u53d1\u51fa\u7684\u53eb\u558a\u58f0\u3002\u6076\u6740:\u5373\u51f6\u795e\u6076\u715e)<\/p><\/li><li><p> \u4e3a\u4e00\u9879\u7f6a\u884c\u88ab\u63a7\u544a\u7684\u4eba;\u72af\u7f6a\u7684\u4eba \u3002<\/p><p>\u5982:\u9996\u6076\u5fc5\u529e,\u534f\u4ece\u4e0d\u95ee<\/p><\/li><\/ol><p><strong>\u3008\u5f62\u3009<\/strong><\/p><ol><li><p> \u4e11\u964b <\/p><p>\u4e94\u66f0\u6076\u3002\u2014\u2014\u300a\u4e66\u00b7\u6d2a\u8303\u300b\u3002\u4f20:\u201c\u4e11\u964b\u4e5f\u3002\u201d<\/p><p>\u4eba\u83ab\u77e5\u5176\u5b50\u4e4b\u6076\u3002\u2014\u2014\u300a\u793c\u8bb0\u00b7\u5927\u5b66\u300b<\/p><p>\u6076\u8005\u7f8e\u4e4b\u5145\u4e5f\u3002\u2014\u2014\u300a\u7ba1\u5b50\u00b7\u67a2\u8a00\u300b<\/p><p>\u4eca\u5b50\u7f8e\u800c\u6211\u6076\u3002\u2014\u2014\u300a\u97e9\u975e\u5b50\u00b7\u8bf4\u6797\u4e0a\u300b<\/p><p>\u9b3c\u4faf\u6709\u5b50\u800c\u597d,\u6545\u5165\u4e4b\u4e8e \u7ea3, \u7ea3\u4ee5\u4e3a\u6076\u3002\u2014\u2014\u300a\u6218\u56fd\u7b56\u00b7\u8d75\u7b56\u300b<\/p><p>\u6614\u8d3e\u5927\u592b\u6076,\u53d6\u59bb\u800c\u7f8e\u3002\u2014\u2014\u300a\u5de6\u4f20\u00b7\u662d\u516c\u4e8c\u5341\u516b\u5e74\u300b<\/p><p> \u53c8\u5982:\u6076\u4e08\u592b(\u4e11\u964b\u6c49\u5b50);\u6076\u5973(\u5bb9\u8c8c\u4e11\u964b\u4e4b\u5973)<\/p><\/li><li><p> \u7c97\u52a3 \u3002<\/p><p>\u5982:\u6076\u98df(\u7c97\u52a3\u7684\u98df\u7269);\u6076\u8863(\u7c97\u52a3\u7684\u8863\u670d);\u6076\u672d(\u67ee\u52a3\u7684\u4e66\u672d\u3002\u591a\u6307\u4e66\u6cd5\u4e0d\u5584,\u5b57\u8ff9\u6b20\u4f73)<\/p><\/li><li><p> \u574f;\u4e0d\u597d <\/p><p>\u5ec9\u541b\u5ba3\u6076\u8a00\u3002\u2014\u2014\u300a\u53f2\u8bb0\u00b7\u5ec9\u9887\u853a\u76f8\u5982\u5217\u4f20\u300b<\/p><p>\u6076\u8863\u6076\u98df,\u964b\u8f66\u9a7d\u9a6c\u3002\u2014\u2014\u300a\u6c49\u4e66\u00b7\u738b\u83bd\u4f20\u4e0a\u300b<\/p><p>\u5c81\u6076\u4e0d\u5165\u3002\u2014\u2014\u8d3e\u8c0a\u300a\u8bba\u79ef\u8d2e\u758f\u300b<\/p><p> \u53c8\u5982:\u6076\u5bbe(\u4e0d\u53d7\u6b22\u8fce\u7684\u5ba2\u4eba\u3002\u5373\u6076\u5ba2);\u6076\u9006(\u4e0d\u5584,\u4e0d\u987a)<\/p><\/li><li><p> \u51f6\u66b4;\u51f6\u731b \u3002<\/p><p>\u5982:\u6076\u72de(\u51f6\u6076\u72f0\u72de);\u6076\u8336\u767d\u8d56(\u6076\u53c9\u767d\u8d56\u3002\u51f6\u6076\u5201\u94bb,\u65e0\u7406\u53d6\u95f9);\u6076\u8d56\u5bcc\u4e3d(\u65e0\u7406\u8d2a\u6c42\u5bcc\u6709\u8c6a\u534e\u3002\u6076\u8d56:\u65e0\u7406\u53d6\u95f9,\u800d\u65e0\u8d56)<\/p><\/li><li><p> \u6c61\u79fd;\u80ae\u810f <\/p><p>\u8272\u6076\u4e0d\u98df,\u81ed\u6076\u4e0d\u98df\u3002\u2014\u2014\u300a\u8bba\u8bed\u00b7\u4e61\u515a\u300b<\/p><p>\u7acb\u53a9\u4e2d\u4ec6\u9a6c\u4e4b\u95f4,\u6076\u6c14\u88ad\u8863\u88fe,\u5373\u9965\u5bd2\u6bd2\u70ed\u4e0d\u53ef\u5fcd,\u4e0d\u53bb\u4e5f\u3002\u2014\u2014\u660e\u00b7 \u5b97\u81e3\u300a\u62a5\u5218\u4e00\u4e08\u4e66\u300b<\/p><p> \u53c8\u5982:\u6076\u8def(\u6076\u9732\u3002\u5987\u5973\u4ea7\u540e\u7531\u9634\u9053\u6392\u51fa\u7684\u6db2\u4f53);\u6076\u6c34(\u6cd4\u6c34);\u6076\u6c34\u7f38\u513f(\u6cd4\u811a\u6c34\u7f38)<\/p><\/li><li><p> \u4ee4\u4eba\u96be\u582a \u3002<\/p><p>\u5982:\u6076\u620f(\u6076\u4f5c\u5267);\u6076\u5267(\u6076\u4f5c\u5267);\u6076\u8c11(\u4ee4\u4eba\u96be\u582a\u7684\u5632\u5f04)<\/p><\/li><li><p> \u6076\u6bd2 \u3002<\/p><p>\u5982:\u6076\u6b46\u6b46(\u51f6\u72e0\u6076\u6bd2\u7684\u6837\u5b50);\u6076\u652f\u6c99(\u6076\u652f\u6740\u3002\u6076\u72e0\u72e0\u5730,\u5341\u5206\u51f6\u6076\u7684\u6837\u5b50);\u6076\u52bf\u715e(\u51f6\u6076\u7684\u6837\u5b50)<\/p><\/li><li><p> \u5eb8\u4fd7 \u3002<\/p><p>\u5982:\u6076\u8f9e(\u5eb8\u4fd7\u4e4b\u8bcd);\u6076\u8c08(\u5eb8\u4fd7\u4e0d\u582a\u7684\u8bdd);\u6076\u5b57(\u4e0d\u582a\u5165\u76ee\u7684\u5b57\u773c)<\/p><\/li><li><p> \u8d2b\u7620 <\/p><p>\u7530\u867d\u8584\u6076,\u6536\u53ef\u4ea9\u5341\u77f3\u3002\u2014\u2014\u300a\u9f50\u6c11\u8981\u672f\u00b7\u8015\u7530\u300b<\/p><p> \u53c8\u5982:\u6076\u90e1(\u8d2b\u7620\u8352\u8fdc\u7684\u5dde\u90e1);\u6076\u5904(\u8d2b\u7620\u7684\u5730\u65b9)<\/p><\/li><\/ol><p><strong>\u3008\u52a8\u3009<\/strong><\/p><ol><li><p>\u5bb3;\u4f24\u5bb3\u6216\u635f\u5bb3 \u3002<\/p><p>\u5982:\u6076\u8bf4(\u8bf4\u8bdd\u89e6\u72af);\u6076\u8baa(\u5f97\u7f6a);\u6076\u4e8b(\u505a\u574f\u4e8b);\u6076\u6b3e(\u4f5c\u6076\u72af\u6cd5\u7684\u6761\u6b3e);\u6076\u5c3d\u4eba(\u628a\u4eba\u90fd\u5f97\u7f6a\u4e86)<\/p><\/li><\/ol><p><strong>\u3008\u526f\u3009<\/strong><\/p><ol><li><p> \u751a;\u5f88 \u8868\u793a\u7a0b\u5ea6\u3002<\/p><p>\u5982:\u6076\u70e6(\u975e\u5e38\u70e6\u607c)<\/p><\/li><li><p> \u53e6\u89c1 \u011b;w\u016b;w\u00f9<\/p><\/li><\/ol><\/dd><\/dl>","handian"],"zuci_array":{"ret_num":728,"ret_array":[{"definition":[" \u8ba8\u538c\uff0c\u618e\u6076"],"name":["\u538c\u6076"],"pinyin":["y\u00e0n w\u00f9"],"sid":["a5b50372f03e43baa0a35c1bea7e9c79"],"type":["term"],"mean_list":[{"definition":[" \u8ba8\u538c\uff0c\u618e\u6076"],"pinyin":["y\u00e0n w\u00f9"],"sug_py":["yanwu"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E5%8E%8C%28yan4%29%E6%81%B6%28wu4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":["1.\u4ee4\u4eba\u538c\u6076\u607c\u6068 ","2.\u618e\u6076"],"name":["\u53ef\u6076"],"pinyin":["k\u011b w\u00f9"],"sid":["27fc7394a7b046668e3248fa7bcaed00"],"type":["term"],"mean_list":[{"definition":["1.\u4ee4\u4eba\u538c\u6076\u607c\u6068 ","2.\u618e\u6076"],"pinyin":["k\u011b w\u00f9"],"sug_py":["kewu"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E5%8F%AF%28ke3%29%E6%81%B6%28wu4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":[" \u5371\u5bb3\u4e25\u91cd\u7684\u884c\u4e3a"],"name":["\u7f6a\u6076"],"pinyin":["zu\u00ec \u00e8"],"sid":["2d656f75fe1448f48f580681a4d672f3"],"type":["term"],"mean_list":[{"definition":[" \u5371\u5bb3\u4e25\u91cd\u7684\u884c\u4e3a"],"pinyin":["zu\u00ec \u00e8"],"sug_py":["zuie"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E7%BD%AA%28zui4%29%E6%81%B6%28e4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":[" \u5f88\u574f"],"name":["\u6076\u52a3"],"pinyin":["\u00e8 li\u00e8"],"sid":["9d5a30b90e8a4a4caa640a5ac15f238d"],"type":["term"],"mean_list":[{"definition":[" \u5f88\u574f"],"pinyin":["\u00e8 li\u00e8"],"sug_py":["elie"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E6%81%B6%28e4%29%E5%8A%A3%28lie4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":["\u618e\u6068\uff0c\u538c\u6076\u3002 "],"name":["\u618e\u6076"],"pinyin":["z\u0113ng w\u00f9"],"sid":["4205f9db1a774e0386041d5853a98e24"],"type":["term"],"mean_list":[{"definition":["\u618e\u6068\uff0c\u538c\u6076\u3002 "],"pinyin":["z\u0113ng w\u00f9"],"sug_py":["zengwu"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E6%86%8E%28zeng1%29%E6%81%B6%28wu4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":[" \u6781\u5ea6\u53cd\u611f\u6216\u538c\u6076"],"name":["\u5acc\u6076"],"pinyin":["xi\u00e1n w\u00f9"],"sid":["fc52aff3afaf4694bac424c29565fe84"],"type":["term"],"mean_list":[{"definition":[" \u6781\u5ea6\u53cd\u611f\u6216\u538c\u6076"],"pinyin":["xi\u00e1n w\u00f9"],"sug_py":["xianwu"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E5%AB%8C%28xian2%29%E6%81%B6%28wu4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":[" \u72ec\u9738\u4e00\u65b9\uff0c\u4f5c\u5a01\u4f5c\u798f\uff0c\u6b3a\u538b\u7fa4\u4f17\u7684\u4eba"],"name":["\u6076\u9738"],"pinyin":["\u00e8 b\u00e0"],"sid":["29b09ced38e2420bbe91388cb18a0c1d"],"type":["term"],"mean_list":[{"definition":[" \u72ec\u9738\u4e00\u65b9\uff0c\u4f5c\u5a01\u4f5c\u798f\uff0c\u6b3a\u538b\u7fa4\u4f17\u7684\u4eba"],"pinyin":["\u00e8 b\u00e0"],"sug_py":["eba"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E6%81%B6%28e4%29%E9%9C%B8%28ba4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":[" \u4e0d\u826f\u7684\u4e60\u60ef\uff0c\u591a\u6307\u8d4c\u535a\u3001\u5438\u6bd2\u7b49"],"name":["\u6076\u4e60"],"pinyin":["\u00e8 x\u00ed"],"sid":["02d4ba48b4bb4525baedfa53d1e4b6f9"],"type":["term"],"mean_list":[{"definition":[" \u4e0d\u826f\u7684\u4e60\u60ef\uff0c\u591a\u6307\u8d4c\u535a\u3001\u5438\u6bd2\u7b49"],"pinyin":["\u00e8 x\u00ed"],"sug_py":["exi"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E6%81%B6%28e4%29%E4%B9%A0%28xi2%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":["1.\u51f6\u9669\u53ef\u6015 ","2.\u9634\u9669\u6bd2\u8fa3"],"name":["\u9669\u6076"],"pinyin":["xi\u01cen \u00e8"],"sid":["1262883236104c16adc6cbc987ac498e"],"type":["term"],"mean_list":[{"definition":["1.\u51f6\u9669\u53ef\u6015 ","2.\u9634\u9669\u6bd2\u8fa3"],"pinyin":["xi\u01cen \u00e8"],"sug_py":["xiane"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E9%99%A9%28xian3%29%E6%81%B6%28e4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":["1.\u4f5b\u6559\u8c13\u4ece\u6076\u4e8b\u4e4b\u56e0\u800c\u751f\u7684\u82e6\u679c ","2.\u574f\u7ed3\u679c\u574f\u4e0b\u573a"],"name":["\u6076\u679c"],"pinyin":["\u00e8 gu\u01d2"],"sid":["1c4fe072ba72409aaa334a3471788be2"],"type":["term"],"mean_list":[{"definition":["1.\u4f5b\u6559\u8c13\u4ece\u6076\u4e8b\u4e4b\u56e0\u800c\u751f\u7684\u82e6\u679c ","2.\u574f\u7ed3\u679c\u574f\u4e0b\u573a"],"pinyin":["\u00e8 gu\u01d2"],"sug_py":["eguo"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E6%81%B6%28e4%29%E6%9E%9C%28guo3%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":[" \u5bf9\u67d0\u4eba\u4e0d\u6ee1\u6216\u618e\u6076\u7684\u611f\u60c5"],"name":["\u6076\u611f"],"pinyin":["\u00e8 g\u01cen"],"sid":["2c2a78b9e0dd474ca73e71f09aa2b1ab"],"type":["term"],"mean_list":[{"definition":[" \u5bf9\u67d0\u4eba\u4e0d\u6ee1\u6216\u618e\u6076\u7684\u611f\u60c5"],"pinyin":["\u00e8 g\u01cen"],"sug_py":["egan"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E6%81%B6%28e4%29%E6%84%9F%28gan3%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":["\u3008\u5f62\u3009\u597d\u548c\u574f\u3002 ","\u3008\u52a8\u3009\u559c\u597d\u548c\u618e\u6076\u3002"],"name":["\u597d\u6076"],"pinyin":["h\u01ceo \u00e8","h\u00e0o w\u00f9"],"sid":["392cd55958fb4ff49186039bbc2fda81"],"type":["term"],"mean_list":[{"definition":["\u3008\u5f62\u3009\u597d\u548c\u574f\u3002"],"pinyin":["h\u01ceo \u00e8"],"sug_py":["haoe"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E5%A5%BD%28hao3%29%E6%81%B6%28e4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]},{"definition":["\u3008\u52a8\u3009\u559c\u597d\u548c\u618e\u6076\u3002"],"pinyin":["h\u00e0o w\u00f9"],"sug_py":["haowu"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E5%A5%BD%28hao4%29%E6%81%B6%28wu4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":[" \u7f6a\u6076\u591a\u7aef"],"name":["\u4e07\u6076"],"pinyin":["w\u00e0n \u00e8"],"sid":["45cf97b35f8b4cec819f5e096b87d81e"],"type":["term"],"mean_list":[{"definition":[" \u7f6a\u6076\u591a\u7aef"],"pinyin":["w\u00e0n \u00e8"],"sug_py":["wane"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E4%B8%87%28wan4%29%E6%81%B6%28e4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]},{"definition":["1.\u80fd\u4ea7\u751f\u4e25\u91cd\u540e\u679c\u7684 ","2.\u53d1\u5c55\u8fc5\u901f\u7684\uff0c\u6027\u8d28\u4e25\u91cd\u7684"],"name":["\u6076\u6027"],"pinyin":["\u00e8 x\u00ecng"],"sid":["36167689ba784d888b854788de87d0ac"],"type":["term"],"mean_list":[{"definition":["1.\u80fd\u4ea7\u751f\u4e25\u91cd\u540e\u679c\u7684 ","2.\u53d1\u5c55\u8fc5\u901f\u7684\uff0c\u6027\u8d28\u4e25\u91cd\u7684"],"pinyin":["\u00e8 x\u00ecng"],"sug_py":["exing"],"tone_py":["https:\/\/ss0.baidu.com\/6KAZsjip0QIZ8tyhnq\/text2audio?tex=%E6%81%B6%28e4%29%E6%80%A7%28xing4%29&cuid=dict&lan=ZH&ctp=1&pdt=30&vol=9&spd=4"]}]}]},"has_mp4":[1],"mp4_addr":["http:\/\/app.dict.baidu.com\/static\/gif\/49d6a1c0427711e58c23c8e0eb15ce01.gif"],"mp4_updatetime":["1456747784"],"baike_info":{"baike_mean":"\u6076\uff0c\u4e3a\u4e2d\u56fd\u5e38\u7528\u8bcd\u6c47\uff0c\u7ecf\u5e38\u8868\u793a\u4e0d\u597d\u7684\uff0c\u51f6\u72e0\u7684\uff0c\u5bf9\u4eba\u548c\u4e8b\u7684\u538c\u6076\u6001\u5ea6\u7b49\u610f\u601d\u3002","baike_url":"http:\/\/baike.baidu.com\/subview\/260013\/13085806.htm"},"fanyi_mean":[{"dst":"to fear; to slander; see \u6076\u5fc3; to loathe; to hate; vicious; evil; variant of \u6076, esp. used in names of chemical components; ugly; to harm; coarse; ashamed; fierce"}]}],"related_words":{"list":[{"link":"?wd=%E4%B8%8B","name":"\u4e0b","img":"http:\/\/t10.baidu.com\/it\/u=3380384796,905417189&fm=58"},{"link":"?wd=%E4%BD%BF","name":"\u4f7f","img":"http:\/\/t12.baidu.com\/it\/u=3466172372,806464761&fm=58"},{"link":"?wd=%E5%85%B1","name":"\u5171","img":"http:\/\/t10.baidu.com\/it\/u=4166215605,955029573&fm=58"},{"link":"?wd=%E5%90%8D","name":"\u540d","img":"http:\/\/t10.baidu.com\/it\/u=4132128318,1035415264&fm=58"},{"link":"?wd=%E5%9B%BD","name":"\u56fd","img":"http:\/\/t10.baidu.com\/it\/u=3849120273,777136786&fm=58"},{"link":"?wd=%E5%AD%97","name":"\u5b57","img":"http:\/\/t12.baidu.com\/it\/u=3867550226,778939521&fm=58"}],"title":"\u76f8\u5173\u5b57"},"recommend_words":{"list":[{"link":"?wd=%E4%B9%96","name":"\u4e56","img":"http:\/\/t11.baidu.com\/it\/u=4112814733,1056453226&fm=58"},{"link":"?wd=%E4%BA%A6","name":"\u4ea6","img":"http:\/\/t11.baidu.com\/it\/u=4228195792,1036879251&fm=58"},{"link":"?wd=%E4%BB%80","name":"\u4ec0","img":"http:\/\/t12.baidu.com\/it\/u=4035754562,1083709521&fm=58"},{"link":"?wd=%E5%8A%B2","name":"\u52b2","img":"http:\/\/t12.baidu.com\/it\/u=4042365548,960788572&fm=58"},{"link":"?wd=%E5%9E%9A","name":"\u579a","img":"http:\/\/t12.baidu.com\/it\/u=3987014999,830246832&fm=58"},{"link":"?wd=%E6%9D%8E","name":"\u674e","img":"http:\/\/t11.baidu.com\/it\/u=3946335055,967861239&fm=58"}],"title":"\u70ed\u641c\u5b57"},"ret_type":"zici-single","bookInfo":"{\"name\":\"\\u6076\",\"type\":\"word\",\"radical\":null,\"strokes\":\"10\",\"definition\":\"\\u00e8#e4#1.\\u4e0d\\u597d\\uff1a\\uff5e\\u611f\\u3002\\uff5e\\u679c\\u3002\\uff5e\\u52a3\\u3002\\uff5e\\u540d\\u3002\\u4e11\\uff5e\\u3002\\\\n2.\\u51f6\\u72e0\\uff1a\\uff5e\\u9738\\u3002\\uff5e\\u68cd\\u3002\\u9669\\uff5e\\u3002\\u51f6\\uff5e\\u3002\\\\n3.\\u72af\\u7f6a\\u7684\\u4e8b\\uff0c\\u6781\\u574f\\u7684\\u884c\\u4e3a\\uff1a\\uff5e\\u8d2f\\u6ee1\\u76c8\\u3002||w\\u00f9#wu4#\\u8ba8\\u538c\\uff0c\\u618e\\u6068\\uff0c\\u4e0e\\u201c\\u597d\\uff08h\\u00e0o \\uff09\\u201d\\u76f8\\u5bf9\\uff1a\\u53ef\\uff5e\\u3002\\u538c\\uff5e\\u3002\\u597d\\uff08h\\u00e0o\\uff09\\uff5e\\u3002||\\u011b#e3#1.\\u3014\\uff5e\\u5fc3\\u3015\\u8981\\u5455\\u5410\\u7684\\u611f\\u89c9\\uff1b\\u4ea6\\u6307\\u5bf9\\u4eba\\u548c\\u4e8b\\u7684\\u538c\\u6076\\u6001\\u5ea6\\u3002\\\\n2.\\uff08\\u5641\\uff09||w\\u016b#wu1#1.\\u53e4\\u540c\\u201c\\u4e4c\\u201d\\uff0c\\u7591\\u95ee\\u8bcd\\uff0c\\u54ea\\uff0c\\u4f55\\u3002\\\\n2.\\u6587\\u8a00\\u53f9\\u8bcd\\uff0c\\u8868\\u793a\\u60ca\\u8bb6\\uff1a\\uff5e\\uff0c\\u662f\\u4f55\\u8a00\\u4e5f\\uff01\"}","type":"word","highlight":"\u6076","suggestion":["\u674e\u767d\u7684\u8bd7","aabb\u5f0f\u7684\u8bcd\u8bed","\u6ed5\u738b\u9601\u5e8f","\u665f\u7684\u62fc\u97f3","\u72b9\u8c6b\u7684\u8fd1\u4e49\u8bcd","\u6625\u534e\u79cb\u5b9e","\u63cf\u5199\u6625\u5929\u7684\u53e4\u8bd7","\u542b\u6709\u5f00\u7684\u6210\u8bed","\u4e0d\u8fa8\u83fd\u7c9f"],"userImage":null}</script> <div id="header-detail"> <div class="pronounce" id="pinyin"> <span> <b>è</b> <a herf="#" url="http://appcdn.fanyi.baidu.com/zhdict/mp3/e4.mp3" class="mp3-play">&nbsp;</a> </span> <span> <b>wù</b> <a herf="#" url="http://appcdn.fanyi.baidu.com/zhdict/mp3/wu4.mp3" class="mp3-play">&nbsp;</a> </span> <span> <b>ě</b> <a herf="#" url="http://appcdn.fanyi.baidu.com/zhdict/mp3/e3.mp3" class="mp3-play">&nbsp;</a> </span> <span> <b>wū</b> <a herf="#" url="http://appcdn.fanyi.baidu.com/zhdict/mp3/wu1.mp3" class="mp3-play">&nbsp;</a> </span> </div> </div> </div> <!-- 添加生词本 --> <a href="https://wappass.baidu.com/passport/?&amp;u=http%3A%2F%2Fhanyu.baidu.com%2Fzici%2Fs%3Fwd%3D%25E6%2581%25B6" class="wordbook" title="登录"></a> </div> </div> </header> <div id="search-bar"> <div class="wrapper"> <div class="c-container module" id="bar"> <div class="c-row fl-row"> <a class="dict-logo" href="/"></a> <div class="c-span10 search-input-frame"> <form name="f" id="form" action="" onsubmit="return checkform();" class="fm"> <input class="c-input search-box" name="wd" id="kw" value="恶" maxlength="40" autocomplete="off"> <img class="search-icon" src="/zici/source/img_wise/search.png"> <img class="input-clear" src="/static/asset/img_wise/input-clear.png"> <input id="q" name="q" value="" type="hidden"> <input name="from" value="zici" type="hidden"> </form> </div> <div class="c-span2 search-bar-btn">取消</div> <a class="c-span1 user-center-bar" href="/personal"> <li class="iconfont-addition icon-gerenzhongxin"></li> </a> </div> </div> <div class="suggest-div flat"> <div class="suggest-direct" style=""> <div class="search-suggestion-title">热搜</div> <div class="search-suggestion" style=""> <a href="/s?wd=李白的诗">李白的诗</a> <a href="/s?wd=aabb式的词语">aabb式的词语</a> <a href="/s?wd=滕王阁序">滕王阁序</a> <a href="/s?wd=晟的拼音">晟的拼音</a> <a href="/s?wd=犹豫的近义词">犹豫的近义词</a> <a href="/s?wd=春华秋实">春华秋实</a> <a href="/s?wd=描写春天的古诗">描写春天的古诗</a> <a href="/s?wd=含有开的成语">含有开的成语</a> <a href="/s?wd=不辨菽粟">不辨菽粟</a> </div> <div id="search_history"> <div style="height: 10px;background: #f1f1f1;"></div> <div class="search-suggestion-title">搜索历史 <div id="history_clear" style="float: right;">清空</div></div> <div class="search-history"> </div> </div> </div> <div class="suggest-panel sug-oper"> <div class="suggest-content"> </div> </div> </div> <script>var userInfo={"un": "", "uid": "" };</script> </div> </div> <!-- 汉语标注 弹窗部分 --> <!-- <div class="m-shadow hide"></div> <div class="m-help hide"> <div class="m-content"> <div class="m-head">为了改进百度汉语体验,特邀请您帮忙<img src="/static/asset/img_wise/tree-icon.png" alt=""></div> <div class="m-question"> <div class="m-word-pic"></div> <span class="m-word">骨瘦如柴</span> <span>是汉语词汇吗?</span> </div> <div class="m-anwser"> <span class="mark-tag" value="1"></span> 是,请收录到汉语词汇 </div> <div class="m-anwser"> <span class="mark-tag" value="0"></span> 否,不收录到汉语词汇 </div> <div class="m-footer"> <a class="m-next">再来一个</a> <a class="m-after">下次帮忙</a> </div> <img class="m-close" src="/static/asset/img_wise/close-icon.png" alt=""> </div> </div> <div class="mark_back_tips hide"> <span class="mark_back_copy">选项不能为空</span> </div> --> <!-- 外层包裹 --> <div id="page-hd"> <!-- 汉语标注 头部部分 --> <!-- <div class="m-container card" id="update_tips_div" style=""> <a class="tips-export-a" href="javascript:0"> <div>为了改进百度汉语体验,特邀请您帮忙<img src="/static/asset/img_wise/icon_hand_click.png"></div> </a> <a class="tips-div-close"> <img src="/static/asset/img_wise/icon_left_close.png"> </a> </div> --> <!-- 公益活动 头部部分 --> <!--<div class="m-container card" id="update_tips_div" style=""> <a class="tips-export-a" href="/gongyi?channel=hanyu"> <div>认领爱心字典,为山区儿童点亮希望<img src="/static/asset/img_wise/icon_hand_click.png"></div> </a> <a class="tips-div-close"> <img src="/static/asset/img_wise/icon_left_close.png"> </a> </div> --> <style data-merge=""> @font-face { font-family: "word_stroke_order-cicons"; src: url(/static/asset/dep/bishun/iconfont.woff) format('woff'); } </style> <div id="results" class="content-list"> <!-- 头部 --> <div class="result c-result" id="header-wrapper"> <div id="qa-tip" style="display:none"></div> <div class="c-container card"> <div class="c-row fl-row"> <div class="alter-text" style="background-image: url(http://t11.baidu.com/it/u=4023809626,820913889&amp;fm=58)"> <img class="bishun" src="/static/asset/img_wise/video-stroke.png"> </div> <div class="c-span12"> <div id="header-detail"> <ul id="header-list"> <li id="tone_py"> <label>拼 音</label> <span> <div class="pronounce" id="pinyin"> <span> <b>è</b> <a herf="#" url="http://appcdn.fanyi.baidu.com/zhdict/mp3/e4.mp3" class="mp3-play">&nbsp;</a> </span> <span> <b>wù</b> <a herf="#" url="http://appcdn.fanyi.baidu.com/zhdict/mp3/wu4.mp3" class="mp3-play">&nbsp;</a> </span> <span> <b>ě</b> <a herf="#" url="http://appcdn.fanyi.baidu.com/zhdict/mp3/e3.mp3" class="mp3-play">&nbsp;</a> </span> <span> <b>wū</b> <a herf="#" url="http://appcdn.fanyi.baidu.com/zhdict/mp3/wu1.mp3" class="mp3-play">&nbsp;</a> </span> </div> </span> </li> <li id="radical"> <label>部 首</label> <span>心</span> </li> <li id="stroke_count"> <label>笔 画</label> <span>10</span> </li> <li id="wuxing"> <label>五 行</label> <span>土</span> </li> <li> <label>部首</label> <span>心</span> </li> <li id="traditional"> <label>繁 体</label> <span>噁 、 惡</span> </li> <li id="wubi"> <label>五 笔</label> <span>GOGN</span> </li> </ul> </div> </div> <!-- 添加生词本 --> <a href="https://wappass.baidu.com/passport/?&amp;u=http%3A%2F%2Fhanyu.baidu.com%2Fzici%2Fs%3Fwd%3D%25E6%2581%25B6" class="wordbook" title="登录"></a> </div> <div> <div class="word_stroke_order c-line-clamp1"><span>笔画 :</span> 10 </div> <div class="word_stroke_order c-line-clamp1"><span>五笔 :</span> GOGN </div> <div class="word_stroke_order c-line-clamp1"><span>笔顺 :</span> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div> <div class="word_stroke_order" id="stroke"><span>名称 :</span> 横、 竖、 竖、 点、 撇、 横、 点、 斜钩、 点、 点、 </div> <div class="c-row expand-footer word-stroke-expend-footer" style="display:none;"></div> </div> </div> </div> <!-- 解释 --> <!-- 解释 --> <div class="result c-reslut module" id="basicmean-wrapper"> <div class="c-container card"> <h3 class="c-title title">基本释义</h3> <div class="c-row base-mean mean" id="base-mean"> <dl> <dt class="pinyin">[ è ]</dt> <dd> <p>1.不好<span>:~感。~果。~劣。~名。丑~。</span></p> <p>2.凶狠<span>:~霸。~棍。险~。凶~。</span></p> <p>3.犯罪的事,极坏的行为<span>:~贯满盈。</span></p> </dd> </dl> <dl> <dt class="pinyin">[ wù ]</dt> <dd> <p>讨厌,憎恨,与“好(hào )”相对<span>:可~。厌~。好(hào)~。</span></p> </dd> </dl> <dl> <dt class="pinyin">[ ě ]</dt> <dd> <p>1.〔~心〕要呕吐的感觉;亦指对人和事的厌恶态度。</p> <p>2.(噁)</p> </dd> </dl> <dl> <dt class="pinyin">[ wū ]</dt> <dd> <p>1.古同“乌”,疑问词,哪,何。</p> <p>2.文言叹词,表示惊讶<span>:~,是何言也!</span></p> </dd> </dl> </div> <div class="c-row mean-expand-footer" style="display:none;" id="basicmean-more-btn"></div> </div> </div> <!-- 详细解释 --> <div class="result c-reslut module" id="detailmean-wrapper"> <div class="c-container card"> <h3 class="c-title title">详细释义</h3> <div class="c-row detail-mean mean" id="detail-mean"> <div><p><strong>1. <a href="#xjcpgxon">恶 [wù]</a></strong><strong>2. <a href="#odjqyhor">恶 [wū]</a></strong><strong>3. <a href="#oyhiqotj">恶 [è]</a></strong></p><dl><dt><a name="xjcpgxon">恶 [wù]</a></dt><dd><p><strong>〈动〉</strong></p><ol><li><p> 讨厌;憎恶 </p><p>天不为人之恶寒而辍冬。——《荀子·天论》</p><p>唯仁者,能好人,能恶人。——《论语·里仁》</p><p>诚好恶何如。——唐· 柳宗元《柳河东集》</p><p>好逸恶劳。——清· 黄宗羲《原君》</p><p>怨恶其君。</p><p> 又如:甚恶(讨厌之极;非常讨厌;反感之至);恶忌(厌恶猜忌);恶生(厌生);恶不去善(不因厌恶其人而抹杀他的优点);恶杀(厌恶杀生);恶紫夺朱(厌恶以邪代正);恶嫌(讨厌);恶惮(厌恶畏惧);恶识(冒犯;得罪);恶上(憎恶长上);这人真可恶;憎恶(憎恨;厌恶);深恶痛绝;恶恶(憎恨邪恶)</p></li><li><p> 嫉妒 </p><p>[刘]表恶其能而不能用也。——《资治通鉴》</p></li><li><p> 诽谤;中伤 </p><p>人之有技,冒疾以恶之。——《书·秦誓》</p><p>太子痤美而狠,合佐师畏而恶之。——《左传·襄公二十六年》</p><p>比而恶之。——《左传·昭公二十七年》</p><p>人有恶苏秦于 燕王者,曰:“ 武安君,天下不信人也。——《战国策》</p><p> 又如:恶讪(诽谤)</p></li><li><p> 忌讳 </p><p>大史典礼,执简记奉讳恶。——《礼记》</p></li></ol><p><strong>〈形〉</strong></p><ol><li><p> 羞耻,羞愧 </p><p>无盖恶之心,非人也。——《孟子·公孙丑上》</p><p> 又如:恶囊(窝囊)</p></li><li><p> 另见 ě;è;wū</p></li></ol></dd></dl><dl><dt><a name="odjqyhor">恶 [wū]</a></dt><dd><p><strong>〈代〉</strong></p><ol><li><p>表示疑问,相当于“何”、“怎么” </p><p>恶,安也。——《广韵》</p><p>恶识宗?——《左传·襄公二十八年》</p><p>弃父之命,恶用子矣!——《左传·桓公十六年》</p><p>彼恶知之。——《孟子·梁惠王上》</p><p>恶能无纪。——明· 袁宏道《满井游记》</p></li><li><p> 表示惊讶 </p><p>恶,是何言也?——《孟子》</p><p>恶,是何言。——清· 梁启超《饮冰室合集·文集》</p></li><li><p> 另见 ě;è;wù</p></li></ol></dd></dl><dl><dt><a name="oyhiqotj">恶 [è]</a></dt><dd><p><strong>〈名〉</strong></p><ol><li><p> (形声。从心,亚声。本义:过失)</p></li><li><p> 同本义 </p><p>恶,过也。——《说文》</p><p>恶上安西。——《颜氏家训》</p><p>吾以志前恶。——《左传·定公五年》</p><p>君子之遏恶扬善。——《易·象传》</p><p> 又如:恶恶从短(对于人的过失,不十分苛责,适可而止)</p></li><li><p> 泛指一般罪恶 </p><p>恶积祸盈。——南朝齐· 丘迟《与陈伯之书》</p><p> 又如:恶逆(奸恶逆乱。古代刑律十恶大罪之一);恶障(佛语。指杀生、偷盗等妨碍修行的罪恶);恶头儿(罪名);恶心钱儿(干坏事得来的钱财);恶孽(罪恶;弊病)</p></li><li><p> 恶人;坏人 </p><p>元恶不待教而诛。——《荀子·王制》</p><p> 又如:恶杀都来(刽子手在刑场上逞威风而发出的叫喊声。恶杀:即凶神恶煞)</p></li><li><p> 为一项罪行被控告的人;犯罪的人 。</p><p>如:首恶必办,协从不问</p></li></ol><p><strong>〈形〉</strong></p><ol><li><p> 丑陋 </p><p>五曰恶。——《书·洪范》。传:“丑陋也。”</p><p>人莫知其子之恶。——《礼记·大学》</p><p>恶者美之充也。——《管子·枢言》</p><p>今子美而我恶。——《韩非子·说林上》</p><p>鬼侯有子而好,故入之于 纣, 纣以为恶。——《战国策·赵策》</p><p>昔贾大夫恶,取妻而美。——《左传·昭公二十八年》</p><p> 又如:恶丈夫(丑陋汉子);恶女(容貌丑陋之女)</p></li><li><p> 粗劣 。</p><p>如:恶食(粗劣的食物);恶衣(粗劣的衣服);恶札(柮劣的书札。多指书法不善,字迹欠佳)</p></li><li><p> 坏;不好 </p><p>廉君宣恶言。——《史记·廉颇蔺相如列传》</p><p>恶衣恶食,陋车驽马。——《汉书·王莽传上》</p><p>岁恶不入。——贾谊《论积贮疏》</p><p> 又如:恶宾(不受欢迎的客人。即恶客);恶逆(不善,不顺)</p></li><li><p> 凶暴;凶猛 。</p><p>如:恶狞(凶恶狰狞);恶茶白赖(恶叉白赖。凶恶刁钻,无理取闹);恶赖富丽(无理贪求富有豪华。恶赖:无理取闹,耍无赖)</p></li><li><p> 污秽;肮脏 </p><p>色恶不食,臭恶不食。——《论语·乡党》</p><p>立厩中仆马之间,恶气袭衣裾,即饥寒毒热不可忍,不去也。——明· 宗臣《报刘一丈书》</p><p> 又如:恶路(恶露。妇女产后由阴道排出的液体);恶水(泔水);恶水缸儿(泔脚水缸)</p></li><li><p> 令人难堪 。</p><p>如:恶戏(恶作剧);恶剧(恶作剧);恶谑(令人难堪的嘲弄)</p></li><li><p> 恶毒 。</p><p>如:恶歆歆(凶狠恶毒的样子);恶支沙(恶支杀。恶狠狠地,十分凶恶的样子);恶势煞(凶恶的样子)</p></li><li><p> 庸俗 。</p><p>如:恶辞(庸俗之词);恶谈(庸俗不堪的话);恶字(不堪入目的字眼)</p></li><li><p> 贫瘠 </p><p>田虽薄恶,收可亩十石。——《齐民要术·耕田》</p><p> 又如:恶郡(贫瘠荒远的州郡);恶处(贫瘠的地方)</p></li></ol><p><strong>〈动〉</strong></p><ol><li><p>害;伤害或损害 。</p><p>如:恶说(说话触犯);恶讪(得罪);恶事(做坏事);恶款(作恶犯法的条款);恶尽人(把人都得罪了)</p></li></ol><p><strong>〈副〉</strong></p><ol><li><p> 甚;很 表示程度。</p><p>如:恶烦(非常烦恼)</p></li><li><p> 另见 ě;wū;wù</p></li></ol></dd></dl></div> </div> <div class="c-row mean-expand-footer" style="display:none;" id="detailmean-more-btn"></div> </div> </div> <div class="result c-result" id="download-wrapper"> <div class="c-container card detail-download-tip"> <div class="icon-div"><img src="/static/asset/img_wise/icon_dict_app.png"></div> <div class="title-text-div"> <span class="title-span1">百度汉语</span> <span class="title-span2">离线使用更方便</span> </div> <a href="http://mobile.baidu.com/item?docid=22686414&amp;from=1017435a" name="tj_cidian" class="download-btn" onclick="_hmt.push(['_trackEvent','汉语导流', 'App导流', '详情页banner下载点击']);"> 立即下载</a> </div> </div> <!-- 组词 --> <div class="result c-result" id="zuci-wrapper"> <div class="c-container card"> <h3 class="c-title title">组词</h3> <div class="c-row c-span12" id="term"> <div class="related_idiom"> <a href="?wd=厌恶&amp;cf=zuci&amp;ptype=term">厌恶</a> <a href="?wd=可恶&amp;cf=zuci&amp;ptype=term">可恶</a> <a href="?wd=罪恶&amp;cf=zuci&amp;ptype=term">罪恶</a> <a href="?wd=恶劣&amp;cf=zuci&amp;ptype=term">恶劣</a> <a href="?wd=憎恶&amp;cf=zuci&amp;ptype=term">憎恶</a> <a href="?wd=嫌恶&amp;cf=zuci&amp;ptype=term">嫌恶</a> <a href="?wd=恶霸&amp;cf=zuci&amp;ptype=term">恶霸</a> <a href="?wd=恶习&amp;cf=zuci&amp;ptype=term">恶习</a> <a href="?wd=险恶&amp;cf=zuci&amp;ptype=term">险恶</a> <a href="?wd=恶果&amp;cf=zuci&amp;ptype=term">恶果</a> <a href="?wd=恶感&amp;cf=zuci&amp;ptype=term">恶感</a> <a href="?wd=好恶&amp;cf=zuci&amp;ptype=term">好恶</a> <a href="?wd=万恶&amp;cf=zuci&amp;ptype=term">万恶</a> <a href="?wd=恶性&amp;cf=zuci&amp;ptype=term">恶性</a> <a id="zuci_more" href="?wd=恶组词&amp;cf=zuci&amp;ptype=term">更多</a> </div> </div> <div class="c-row expand-footer" style="display:none;"></div> </div> </div> <!-- 表格解释 --> <!-- 近义词部分 --> <!-- 近反义词 --> <div class="result c-result module" id="syn_ant_wrapper"> <div class="c-container card" id="syn_ant"> <div class="c-row tab-title fl-row"> <div class="c-span6 sa-title selected" id="synonym">近义词</div> <div class="seg"></div> <div class="c-span6 sa-title" id="antonym">反义词</div> </div> <div class="c-row c-span12" id="synonym-content"> <div class="synonym-content"> <p>暂无近义词</p> </div> </div> <div class="c-row c-span12" style="display:none;" id="antonym-content"> <div class="antonym-content"> <a href="?wd=善&amp;cf=antonym&amp;ptype=word">善</a> <a href="?wd=好&amp;cf=antonym&amp;ptype=word">好</a> <a href="?wd=爱&amp;cf=antonym&amp;ptype=word">爱</a> <a href="?wd=美&amp;cf=antonym&amp;ptype=word">美</a> </div> </div> </div> </div> <!-- 谜语部分 --> <!-- 百科解释部分 --> <div class="result c-reslut module" id="baike-wrapper"> <div class="c-container card"> <div style="position:relative;"> <h3 class="c-title title">百科释义</h3> <span class="baike-feedback" data="恶" style="position: absolute;top: 1px;right: 10px;color: #999;">报错</span> </div> <div class="c-row baike"> <div>恶,为中国常用词汇,经常表示不好的,凶狠的,对人和事的厌恶态度等意思。<a href="http://baike.baidu.com/subview/260013/13085806.htm">查看百科</a></div> </div> <div class="c-row baike" style="color: #d0d0d0;">注:百科释义来自于百度百科,由网友自行编辑。</div> </div> </div> <!-- 度秘推荐 --> <div class="result c-reslut module" id="dumi-wrapper" style="display:none"> <div class="c-container card"> <h3 class="c-title">度秘为您推荐</h3> <div id="dumi"></div> </div> </div> <!-- 翻译部分 --> <div class="result c-reslut module" id="fanyi-wrapper"> <div class="c-container card"> <h3 class="c-title title">英文翻译</h3> <div class="c-row base-mean"> <p>to fear; to slander; see 恶心; to loathe; to hate; vicious; evil; variant of 恶, esp. used in names of chemical components; ugly; to harm; coarse; ashamed; fierce</p> </div> </div> </div> <!-- 好学导流 --> <section class="result c-reslut module" id="fanyi-wrapper"> <div class="c-container card"> <h3 class="c-title title" style="text-align: left;">新产品体验</h3> <a href="http://haoxue.baidu.com/maths/equation?wd=x%5E2%2B2x-1%3D0" onclick="_hmt.push(['_trackEvent','汉语导流', '中间页导流', '好学数学自动解方程banner点击']);"> <div class="c-row base-mean" style="color: #333;"> <p>数学自动解方程<br>x²+2x-1=0</p> <div style="color: #999;"><br>了解更多</div> </div> </a> <div style="clear: both;"></div> </div> </section> <!-- 底部bar --> <section class="c-result c-row-tile"> <div class="c-container card" style="padding: 10px 20px;"> <a href="http://mobile.baidu.com/item?docid=22686414&amp;from=1017435a" name="tj_cidian" style="display: none;"> <div class="c-row detail-footer-download" style="padding-bottom: 10px;padding-top: 10px;"> <img src="/zici/asset/img_wise/icon_logo_app.png"> <div class="c-span9"> <div class="c-line-clamp3">拍照识字的掌上汉语助手</div> </div> <div class="c-span3 download-btn"> <button class="c-btn">下载</button> </div> </div> </a> <div class="c-row" style="height:1px;margin:0 15px;border-bottom: 1px solid #ddd;display: none"></div> <div class="detail-footer" style="margin-top: 0px;"> <span class="detail-footer-item"> <a href="/"> 首页 </a> </span> <!-- <div class="detail-footer-item" style=""> <a class="download-item" href="http://mobile.baidu.com/item?docid=22686414&from=1017435a" name="tj_cidian" onclick="_hmt.push(['_trackEvent','汉语导流', 'App导流', '诗词详情页banner下载点击']);"> 下载APP </a> </div> --> <div class="detail-footer-item"> <a class="detail-feedback" href="javascript:void(0);" style="position: relative; "> <font color="#f15713">有奖报错</font> <img src="/static/asset/img_wise/hot.png" style="position: absolute;right: -5px;top: -16px;width: 10px;"> </a> </div> <span class="detail-footer-item" style="display: none;"> <a href="http://m.weibo.cn/u/5789783834"> 关注微博 </a> </span> <span class="detail-footer-item detail-footer-item-last"> <a href="http://qm.qq.com/cgi-bin/qm/qr?k=WUsL3Jbek0Km8R4r-m1dK4JZjGw_A8Ba" target="_blank">Q群:484758177</a> </span> </div> </div> </section> <div class="feed-back-dialog"> <div class="dialog-div"> <div class="title-div"> <span>选择报错的内容</span> <div class="feed-back-close">&nbsp;&nbsp;</div> </div> <div class="content-div"> <div class="feed-back-item"> <label><input name="feed_back_item" checked="checked" type="radio" value="1">&nbsp;拼音错误</label><br> <label><input name="feed_back_item" checked="checked" type="radio" value="2">&nbsp;笔顺错误</label><br> <label><input name="feed_back_item" checked="checked" type="radio" value="3">&nbsp;释义错误</label><br> <label><input name="feed_back_item" checked="checked" type="radio" value="4">&nbsp;百科释义错误</label><br> <label><input name="feed_back_item" type="radio" value="0">&nbsp;其它</label> </div> <textarea id="feed-back-content" rows="3" maxlength="40" placeholder="输入报错内容(最多40个字--必填)"></textarea> <div class="c-row"> <div class="c-span3"> <img width="100%" src="/static/asset/img_wise/icon_activity_xiong.png"> </div> <div class="c-span9" style="font-size: 11px;padding: 0px;"> <div><font size="1">高质量报错用户有机会获得【百度熊积木】一份(每月30名),请留下你的联系方式</font></div> <div style="width: 100%;margin-top: 5px;"> <input style="border: 1px solid #c0c0c0;width: 100%;" type="text" id="user-contact" placeholder="QQ或电话号码(非必填)"> </div> </div> </div> <div class="submit-div"> <div class="feed-back-submit">提交</div> </div> </div> </div> </div> <div id="feed_back_tips" style="position: fixed; bottom: 30px;text-align: center;width: 100%;display: none;"> <span style="margin: 0 auto;border-radius: 3px;background: rgba(0,0,0,0.5);color: white;padding: 10px;">谢谢你的反馈</span> </div> <!-- 笔顺全屏图 --> <div class="bishun-outer"> <img id="word_bishun" class="bishun-inner" data-src="https://ss0.baidu.com/9_QWbzqaKgAFnsKb8IqW0jdnxx1xbK/zhdict/gif/b49d6a1c0427711e58c23c8e0eb15ce01.gif"> </div> </div> </div> <!--content-panel--> <!--body-wapper--> <div class="banner module" id="download-app" style="display:none;"> <div class="appbanner" id="download-banner"> <a href="javascript:" class="close-appbanner" id="close-appbanner"></a> <a href="javascript:" class="download-app"> <div class="appbanner-text"> <p>下载百度汉语</p> <p class="appbanner-text-small">随手拍,随口问,更智能!</p> </div> <p href="javescript:" class="app-download-btn" id="app-download-btn">打开百度汉语</p> </a> </div> </div> <div class="goto-top module" id="top-button" style="display:none;"><img src="/zici/source/img_wise/icon_go_top.png"></div> <div id="fmp_flash_div" style="display:none"> <audio id="audio"></audio> </div> <script> window.basicInfo = {"name":"\u6076","type":"word","radical":null,"strokes":"10","definition":"\u00e8#e4#1.\u4e0d\u597d\uff1a\uff5e\u611f\u3002\uff5e\u679c\u3002\uff5e\u52a3\u3002\uff5e\u540d\u3002\u4e11\uff5e\u3002\\n2.\u51f6\u72e0\uff1a\uff5e\u9738\u3002\uff5e\u68cd\u3002\u9669\uff5e\u3002\u51f6\uff5e\u3002\\n3.\u72af\u7f6a\u7684\u4e8b\uff0c\u6781\u574f\u7684\u884c\u4e3a\uff1a\uff5e\u8d2f\u6ee1\u76c8\u3002||w\u00f9#wu4#\u8ba8\u538c\uff0c\u618e\u6068\uff0c\u4e0e\u201c\u597d\uff08h\u00e0o \uff09\u201d\u76f8\u5bf9\uff1a\u53ef\uff5e\u3002\u538c\uff5e\u3002\u597d\uff08h\u00e0o\uff09\uff5e\u3002||\u011b#e3#1.\u3014\uff5e\u5fc3\u3015\u8981\u5455\u5410\u7684\u611f\u89c9\uff1b\u4ea6\u6307\u5bf9\u4eba\u548c\u4e8b\u7684\u538c\u6076\u6001\u5ea6\u3002\\n2.\uff08\u5641\uff09||w\u016b#wu1#1.\u53e4\u540c\u201c\u4e4c\u201d\uff0c\u7591\u95ee\u8bcd\uff0c\u54ea\uff0c\u4f55\u3002\\n2.\u6587\u8a00\u53f9\u8bcd\uff0c\u8868\u793a\u60ca\u8bb6\uff1a\uff5e\uff0c\u662f\u4f55\u8a00\u4e5f\uff01"}; var queryStr = "恶"; var deviceType = "wise"; </script> <script> require.config( { 'baseUrl': '/static/asset/asset', 'urlArgs': 'v=201603301709', 'packages': [ { 'name': 'etpl', 'location': '/static/asset/dep/etpl', 'main': 'main' } ] } ); require(['wise']); // 汉语标注时需要mark_help文件 // require(['wise', 'mark_help']); </script> <script> var _trace_page_logid = 3562527274; </script></body>
93.977113
23,633
0.555068
2d4e4bd5484a170f36e3fde409bbd658b9cf24aa
6,904
lua
Lua
tek/class/sessionrequest.lua
RangelReale/luaexec
c1729e1b86b46de68030de037f2d95eb56ad296b
[ "MIT" ]
null
null
null
tek/class/sessionrequest.lua
RangelReale/luaexec
c1729e1b86b46de68030de037f2d95eb56ad296b
[ "MIT" ]
null
null
null
tek/class/sessionrequest.lua
RangelReale/luaexec
c1729e1b86b46de68030de037f2d95eb56ad296b
[ "MIT" ]
null
null
null
------------------------------------------------------------------------------- -- -- tek.class.sessionrequest -- (C) by Timm S. Mueller <tmueller@schulze-mueller.de> -- -- OVERVIEW:: -- [[#ClassOverview]] : -- [[#tek.class : Class]] / -- [[#tek.class.httprequest : HTTPRequest]] / -- SessionRequest ${subclasses(SessionRequest)} -- -- MEMBERS:: -- - {{CookieName [ISG]}} (string) -- Default basename for cookies, default {{"luawtf"}} -- - {{SessionExpirationTime [ISG]}} (number) -- Number of seconds before a session expires, default: 600 -- - {{Sessions [ISG]}} (table) -- Table of sessions, indexed by session Id. Must be provided during -- initialization so that session states can be held and found later -- -- IMPLEMENTS:: -- - SessionRequest.getRawId() - Get binary data for unique session Id -- - SessionRequest:createSessionCookie() - Create session cookie string -- - SessionRequest:deleteSession() - Delete current session -- - SessionRequest:getSession() - Find session (by session Id in cookie) -- - SessionRequest:newSession() - Create new session -- -- OVERRIDES:: -- - Class.new() -- ------------------------------------------------------------------------------- local db = require "tek.lib.debug" local HTTPRequest = require "tek.class.httprequest" local os_time = os.time local assert = assert local open = io.open local pairs = pairs local stderr = io.stderr local SessionRequest = HTTPRequest.module("tek.class.sessionrequest", "tek.class.httprequest") SessionRequest._VERSION = "SessionRequest 3.0" ------------------------------------------------------------------------------- -- getRawId([len[, rlen]]): Get unique binary data of given length to be -- used for a session Id. {{rlen}} is the desired number of bytes of entropy, -- the regular length (default 6) is usually made up of pseudo random data. ------------------------------------------------------------------------------- function SessionRequest.getRawId(len, rlen) local token = "" if rlen and rlen > 0 then local f = open("/dev/random", "rb") if f then token = f:read(rlen) f:close() end end local f = open("/dev/urandom", "rb") if f then token = token .. f:read(len or 6) f:close() else db.warn("** cannot get entropy - using extremely weak random number!") token = token .. math.floor(math.random() * 100000000) end return token end ------------------------------------------------------------------------------- -- getId() ------------------------------------------------------------------------------- function SessionRequest.getId(len, rlen) local token = SessionRequest.getRawId(len, rlen) return token:gsub('.', function(c) return ("%02x"):format(c:byte()) end) end ------------------------------------------------------------------------------- -- new: overrides ------------------------------------------------------------------------------- function SessionRequest.new(class, self) self = self or { } self.CookieName = self.CookieName or "luawtf" self.Prefix = self.Prefix or "" self.Session = false self.Sessions = self.Sessions or { } self.SessionKey = false self.SessionExpirationTime = self.SessionExpirationTime or 600 return HTTPRequest.new(class, self) end ------------------------------------------------------------------------------- -- skey = getSessionKey() ------------------------------------------------------------------------------- function SessionRequest:getSessionKey() local skey = self.SessionKey if not skey then local cookie = self:getEnv("HTTP_COOKIE") skey = cookie and cookie:match(self.CookieName .. "_session=(%x+);?") or false self.SessionKey = skey end db.trace("getsessionkey: %s", skey) return skey end ------------------------------------------------------------------------------- -- cookie = createSessionCookie([expire]): Create session cookie string ------------------------------------------------------------------------------- function SessionRequest:createSessionCookie(expires) local prefix = self.Prefix local prefix = prefix == "" and "/" or prefix local cookie if expires then cookie = ('Set-Cookie: %s_session=%s; Path=%s; Expires=%s; Version=1\r\n'): format(self.CookieName, (self.SessionKey or "disabled"), prefix, expires) else cookie = ('Set-Cookie: %s_session=%s; Path=%s; Version=1\r\n'):format( self.CookieName, (self.SessionKey or "disabled"), prefix) end return cookie end ------------------------------------------------------------------------------- -- expireSessions() ------------------------------------------------------------------------------- function SessionRequest:expireSessions() local nowtime = os_time() local sessions = self.Sessions for skey, session in pairs(sessions) do if session.expirydate and nowtime > session.expirydate then db.info("session %s expired", skey) sessions[skey] = nil end end end ------------------------------------------------------------------------------- -- session, sid = getSession(): Find session by session Id in cookie ------------------------------------------------------------------------------- function SessionRequest:getSession() self:expireSessions() local skey = self:getSessionKey() local session = self.Session if not session then local sessions = self.Sessions if skey then session = sessions[skey] end if session then sessions[skey].expirydate = os_time() + self.SessionExpirationTime end session = session or false self.Session = session end return session, skey end ------------------------------------------------------------------------------- -- sid = newSession(sessiondata[, sid]): Place {{sessiondata}} table in a new -- session ------------------------------------------------------------------------------- function SessionRequest:newSession(sessiondata, skey) if not skey or self.Sessions[skey] then -- do not bind to an already existing session! skey = self.getId() end local sessions = self.Sessions sessions[skey] = sessiondata self.Session = sessiondata self.SessionKey = skey return skey end ------------------------------------------------------------------------------- -- updateSession(sessiondata) ------------------------------------------------------------------------------- function SessionRequest:updateSession(sessiondata) sessiondata = sessiondata or { } local skey = self:getSessionKey() self.Session = sessiondata local sessions = self.Sessions sessions[skey] = sessiondata end ------------------------------------------------------------------------------- -- deleteSession(): Delete the current session ------------------------------------------------------------------------------- function SessionRequest:deleteSession() local skey = self:getSessionKey() if skey then self.Sessions[skey] = nil end self.SessionKey = false self.Session = false end return SessionRequest
33.033493
94
0.534038
c43094749ad3a23a77bcbd0c367ec4d553104b36
1,610
h
C
tests/juliet/testcases/CWE400_Resource_Exhaustion/s01/CWE400_Resource_Exhaustion__fscanf_sleep_84.h
RanerL/analyzer
a401da4680f163201326881802ee535d6cf97f5a
[ "MIT" ]
28
2017-01-20T15:25:54.000Z
2020-03-17T00:28:31.000Z
testcases/CWE400_Resource_Exhaustion/s01/CWE400_Resource_Exhaustion__fscanf_sleep_84.h
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
1
2017-01-20T15:26:27.000Z
2018-08-20T00:55:37.000Z
testcases/CWE400_Resource_Exhaustion/s01/CWE400_Resource_Exhaustion__fscanf_sleep_84.h
mellowCS/cwe_checker_juliet_suite
ae604f6fd94964251fbe88ef04d5287f6c1ffbe2
[ "MIT" ]
2
2019-07-15T19:07:04.000Z
2019-09-07T14:21:04.000Z
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE400_Resource_Exhaustion__fscanf_sleep_84.h Label Definition File: CWE400_Resource_Exhaustion.label.xml Template File: sources-sinks-84.tmpl.h */ /* * @description * CWE: 400 Resource Exhaustion * BadSource: fscanf Read data from the console using fscanf() * GoodSource: Assign count to be a relatively small number * Sinks: sleep * GoodSink: Validate count before using it as a parameter in sleep function * BadSink : Use count as the parameter for sleep withhout checking it's size first * Flow Variant: 84 Data flow: data passed to class constructor and destructor by declaring the class object on the heap and deleting it after use * * */ #include "std_testcase.h" namespace CWE400_Resource_Exhaustion__fscanf_sleep_84 { #ifndef OMITBAD class CWE400_Resource_Exhaustion__fscanf_sleep_84_bad { public: CWE400_Resource_Exhaustion__fscanf_sleep_84_bad(int countCopy); ~CWE400_Resource_Exhaustion__fscanf_sleep_84_bad(); private: int count; }; #endif /* OMITBAD */ #ifndef OMITGOOD class CWE400_Resource_Exhaustion__fscanf_sleep_84_goodG2B { public: CWE400_Resource_Exhaustion__fscanf_sleep_84_goodG2B(int countCopy); ~CWE400_Resource_Exhaustion__fscanf_sleep_84_goodG2B(); private: int count; }; class CWE400_Resource_Exhaustion__fscanf_sleep_84_goodB2G { public: CWE400_Resource_Exhaustion__fscanf_sleep_84_goodB2G(int countCopy); ~CWE400_Resource_Exhaustion__fscanf_sleep_84_goodB2G(); private: int count; }; #endif /* OMITGOOD */ }
25.967742
147
0.765839
993c066f4858b1bfbb33131c062540e5a13d4d4c
1,165
h
C
sort.h
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
2
2021-06-23T04:33:18.000Z
2021-06-23T12:55:26.000Z
sort.h
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
null
null
null
sort.h
LANL-Bioinformatics/BIGSI-
ccf1b1878b10f40ab475499aadcdb7c238e257e1
[ "BSD-3-Clause" ]
1
2021-06-22T22:05:56.000Z
2021-06-22T22:05:56.000Z
#ifndef __SORT #define __SORT // While we can get OpenMP working on clang, I have not yet found a // way to use the Gnu parallel C++ api ... #if defined(_OPENMP) && !defined(__clang__) #include <parallel/algorithm> // The default parallel sort algorithm used in __gnu_parallel::sort (potentially // called via the SORT macro) is the "multiway merge sort" (MWMS) and // requires *twice* the memory of input array to sort in parallel! The other // sort algorithm implemented by __gnu_parallel::sort, i.e. quick sort // (and balanced quick sort), does not require any extra RAM, but offers a // much worse parallel speed up (two fold at best, unless nested parallelism // is enabled for OpenMP). // * Fast/High memory using MWMS: __gnu_parallel::multiway_mergesort_tag() // * Slow/Low memory using balanced QS: __gnu_parallel::balanced_quicksort_tag() // Enable OpenMP-based parallel sorting //#define SORT __gnu_parallel::sort #define SORT(X, Y) __gnu_parallel::sort( (X), (Y), __gnu_parallel::balanced_quicksort_tag() ) #else #include <algorithm> // Use standard serial-based sorting #define SORT std::sort #endif // _OPENMP #endif // __SORT
37.580645
94
0.736481
be998c9768096037d488975146ad235f71b0782e
1,537
kt
Kotlin
retainmvp/src/main/java/com/retainmvp/Presenters.kt
lukas1/RetainMVP
9ce592ddd44d8b64444830a9a85a2aef4a022f9d
[ "Apache-2.0" ]
null
null
null
retainmvp/src/main/java/com/retainmvp/Presenters.kt
lukas1/RetainMVP
9ce592ddd44d8b64444830a9a85a2aef4a022f9d
[ "Apache-2.0" ]
null
null
null
retainmvp/src/main/java/com/retainmvp/Presenters.kt
lukas1/RetainMVP
9ce592ddd44d8b64444830a9a85a2aef4a022f9d
[ "Apache-2.0" ]
null
null
null
package com.retainmvp import android.content.Intent import android.os.Bundle import android.support.v4.app.FragmentManager import android.support.v7.app.AppCompatActivity object Presenters { private const val TAG_PRESENTER_HOLDER_FRAGMENT = "presenter_holder" fun <P : Presenter<V, S>, V, S> getPresenterForActivity( activity: AppCompatActivity, presenterFactory: PresenterFactory<V, S, P>, storedStateConverter: StoredStateConverter<S>, view: V, launchingIntent: Intent, bundle: Bundle? ): P = with(getHolderFragment<P, V, S>(activity.supportFragmentManager)) { setup(presenterFactory, view, storedStateConverter, launchingIntent, bundle) activity.application.registerActivityLifecycleCallbacks( RetainMVPLIfeCycleCallbacksListener(activity, storedStateConverter, presenter) ) return@with presenter } @Suppress("UNCHECKED_CAST") private fun <P : Presenter<V, S>, V, S> getHolderFragment( fragmentManager: FragmentManager ): PresenterHolderFragment<P, V, S> = (fragmentManager.findFragmentByTag(TAG_PRESENTER_HOLDER_FRAGMENT) as? PresenterHolderFragment<P, V, S>) ?: PresenterHolderFragment<P, V, S>().apply { fragmentManager .beginTransaction() .add(this, TAG_PRESENTER_HOLDER_FRAGMENT) .commit() } }
41.540541
115
0.637606
c3149e4b0a29495c05195124e03427173bb2b875
694
lua
Lua
hub.lua
vishal272/Mastermine
e69439bb53e30435970afdc6aa7f30d76be26772
[ "MIT" ]
42
2020-11-21T22:18:59.000Z
2022-03-31T13:19:53.000Z
hub.lua
RaptorPort/Mastermine
0b96a1a2418e0e16ed95b7c4ebcfd7ffb70fae6c
[ "MIT" ]
33
2020-12-17T08:16:28.000Z
2022-02-03T03:16:12.000Z
hub.lua
RaptorPort/Mastermine
0b96a1a2418e0e16ed95b7c4ebcfd7ffb70fae6c
[ "MIT" ]
16
2020-12-08T19:31:02.000Z
2022-01-25T06:55:57.000Z
if fs.exists('/disk/hub_files/session_id') then fs.delete('/disk/hub_files/session_id') end if fs.exists('/session_id') then fs.copy('/session_id', '/disk/hub_files/session_id') end if fs.exists('/disk/hub_files/mine') then fs.delete('/disk/hub_files/mine') end if fs.exists('/mine') then fs.copy('/mine', '/disk/hub_files/mine') end for _, filename in pairs(fs.list('/')) do if filename ~= 'rom' and filename ~= 'disk' and filename ~= 'openp' and filename ~= 'ppp' and filename ~= 'persistent' then fs.delete(filename) end end for _, filename in pairs(fs.list('/disk/hub_files')) do fs.copy('/disk/hub_files/' .. filename, '/' .. filename) end os.reboot()
30.173913
127
0.665706
b2f671ce255a5bba8f874bbc3dd12c5ed3323b5b
324
swift
Swift
crashes-duplicates/03159-swift-sourcemanager-getmessage.swift
radex/swift-compiler-crashes
41a18a98ae38e40384a38695805745d509b6979e
[ "MIT" ]
null
null
null
crashes-duplicates/03159-swift-sourcemanager-getmessage.swift
radex/swift-compiler-crashes
41a18a98ae38e40384a38695805745d509b6979e
[ "MIT" ]
null
null
null
crashes-duplicates/03159-swift-sourcemanager-getmessage.swift
radex/swift-compiler-crashes
41a18a98ae38e40384a38695805745d509b6979e
[ "MIT" ]
null
null
null
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing var e(h(v: C { protocol a { enum S<T { struct S<T where g: AnyObject) { func g: a { struct S<T.h(v: d = a struct Q<T where g<D> Void>(") class case c, var
20.25
87
0.697531
198a4c698cbf95fafdf28ea88532bbc64397efe3
3,411
swift
Swift
Sources/Toggl2Redmine/Future.swift
svastven/Toggl2Redmine
3a9b262b049367a22dc3d559554b8f5ab2c38f1b
[ "MIT" ]
6
2020-03-05T07:15:02.000Z
2020-07-19T14:45:24.000Z
Sources/Toggl2Redmine/Future.swift
svastven/Toggl2Redmine
3a9b262b049367a22dc3d559554b8f5ab2c38f1b
[ "MIT" ]
9
2020-03-05T07:22:26.000Z
2021-05-12T18:46:25.000Z
Sources/Toggl2Redmine/Future.swift
svastven/Toggl2Redmine
3a9b262b049367a22dc3d559554b8f5ab2c38f1b
[ "MIT" ]
4
2020-03-05T08:43:00.000Z
2021-11-06T23:54:06.000Z
/** * Swift by Sundell sample code * Copyright (c) John Sundell 2020 * See LICENSE file for license * * Read the article at https://swiftbysundell.com/posts/under-the-hood-of-futures-and-promises-in-swift */ import Foundation class Future<Value> { typealias Result = Swift.Result<Value, Error> fileprivate var result: Result? { // Observe whenever a result is assigned, and report it: didSet { result.map(report) } } private var callbacks = [(Result) -> Void]() func observe(using callback: @escaping (Result) -> Void) { // If a result has already been set, call the callback directly: if let result = result { return callback(result) } callbacks.append(callback) } private func report(result: Result) { callbacks.forEach { $0(result) } callbacks = [] } } class Promise<Value>: Future<Value> { init(value: Value? = nil) { super.init() // If the value was already known at the time the promise // was constructed, we can report it directly: result = value.map(Result.success) } func resolve(with value: Value) { result = .success(value) } func reject(with error: Error) { result = .failure(error) } } extension Future { func chained<T>(using closure: @escaping (Value) throws -> Future<T>) -> Future<T> { // We'll start by constructing a "wrapper" promise that will be // returned from this method: let promise = Promise<T>() // Observe the current future: observe { result in switch result { case .success(let value): do { // Attempt to construct a new future using the value // returned from the first one: let future = try closure(value) // Observe the "nested" future, and once it // completes, resolve/reject the "wrapper" future: future.observe { result in switch result { case .success(let value): promise.resolve(with: value) case .failure(let error): promise.reject(with: error) } } } catch { promise.reject(with: error) } case .failure(let error): promise.reject(with: error) } } return promise } func transformed<T>(with closure: @escaping (Value) throws -> T) -> Future<T> { chained { value in try Promise(value: closure(value)) } } func synchronize() -> Value? { let semaphore = DispatchSemaphore(value: 0) var result: Value? observe { switch $0 { case .failure: result = nil case .success(let value): result = value } semaphore.signal() } semaphore.wait() return result } } extension Future where Value == Data { func decoded<T: Decodable>(as type: T.Type = T.self, using decoder: JSONDecoder = .init()) -> Future<T> { transformed { data in try decoder.decode(T.self, from: data) } } }
28.425
109
0.527118
143918dd5dc9bae2123779dac43035c914daee15
265
css
CSS
frontend/src/components/reactions/Reactions.css
Chia-Network/keybase-live-feed
a744e7eece8dc6636fb4fe137a5f5250c29e9ea7
[ "Apache-2.0" ]
16
2019-04-05T00:24:31.000Z
2021-06-06T11:31:09.000Z
frontend/src/components/reactions/Reactions.css
Chia-Network/keybase-live-feed
a744e7eece8dc6636fb4fe137a5f5250c29e9ea7
[ "Apache-2.0" ]
6
2019-12-24T17:55:52.000Z
2022-02-27T13:47:28.000Z
frontend/src/components/reactions/Reactions.css
Chia-Network/keybase-live-feed
a744e7eece8dc6636fb4fe137a5f5250c29e9ea7
[ "Apache-2.0" ]
7
2019-04-17T18:33:45.000Z
2021-11-13T04:00:47.000Z
.reaction { border: 1px solid #E7E7E7; border-radius: 10px; margin-left: 0.5rem; margin-bottom: 0.2rem; padding: 0.7rem; text-align: center; } .reaction-contents { font-weight: bold; display: inline-block; margin-left: 0.5rem; }
18.928571
30
0.626415
0cc0bf99ee01e613b032f7efe713db47ddaef6b6
1,137
py
Python
ossdbtoolsservice/metadata/contracts/object_metadata.py
DaeunYim/pgtoolsservice
b7e548718d797883027b2caee2d4722810b33c0f
[ "MIT" ]
33
2019-05-27T13:04:35.000Z
2022-03-17T13:33:05.000Z
ossdbtoolsservice/metadata/contracts/object_metadata.py
DaeunYim/pgtoolsservice
b7e548718d797883027b2caee2d4722810b33c0f
[ "MIT" ]
31
2019-06-10T01:55:47.000Z
2022-03-09T07:27:49.000Z
ossdbtoolsservice/metadata/contracts/object_metadata.py
DaeunYim/pgtoolsservice
b7e548718d797883027b2caee2d4722810b33c0f
[ "MIT" ]
25
2019-05-13T18:39:24.000Z
2021-11-16T03:07:33.000Z
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- import enum from typing import Optional from ossdbtoolsservice.serialization import Serializable class MetadataType(enum.Enum): """Contract enum for representing metadata types""" TABLE = 0 VIEW = 1 SPROC = 2 FUNCTION = 3 class ObjectMetadata(Serializable): """Database object metadata""" @classmethod def get_child_serializable_types(cls): return {'metadata_type': MetadataType} def __init__(self, urn: str = None, metadata_type: MetadataType = None, metadata_type_name: str = None, name: str = None, schema: Optional[str] = None): self.metadata_type: MetadataType = metadata_type self.metadata_type_name: str = metadata_type_name self.name: str = name self.schema: str = schema self.urn: str = urn
34.454545
156
0.591029
96f514fbab55fa8bf9361c1f913e6c6f6fdb8fd5
772
kt
Kotlin
core/core/src/jsMain/kotlin/zakadabar/core/browser/util/log.kt
tbml/zakadabar-stack
ee0b8916fe805ab0d460371365e97a9eac1c42dd
[ "Apache-2.0" ]
16
2020-12-04T19:48:52.000Z
2022-03-14T20:26:54.000Z
core/core/src/jsMain/kotlin/zakadabar/core/browser/util/log.kt
tbml/zakadabar-stack
ee0b8916fe805ab0d460371365e97a9eac1c42dd
[ "Apache-2.0" ]
97
2020-08-30T08:23:04.000Z
2022-03-27T05:39:50.000Z
core/core/src/jsMain/kotlin/zakadabar/core/browser/util/log.kt
tbml/zakadabar-stack
ee0b8916fe805ab0d460371365e97a9eac1c42dd
[ "Apache-2.0" ]
3
2021-04-06T09:50:23.000Z
2022-02-11T00:53:03.000Z
/* * Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.core.browser.util fun log(ex: dynamic): String { if (ex == null) return "" val stack = ex.stack return if (stack is String) { val message = ex.message?.toString() ?: "" val error = js("Error()") error.name = ex.toString().substringBefore(':') error.message = message.substringAfter(':') error.stack = stack @Suppress("UnsafeCastFromDynamic") // magic, this whole function is pure magic console.error(error) error.toString() } else { console.log(ex) ex.toString() } } fun dumpStackTrace() { js("console.trace()") }
28.592593
126
0.612694
039cdcc0167d58951b57ea6f3b195501bb32cf35
123
swift
Swift
.insert() and .remove() Methods.swift
WeKnow-io/Swift-lang
783f2c5575a1fa6b759dc6c739f86cdea8a89a36
[ "Unlicense" ]
1
2020-12-17T20:01:32.000Z
2020-12-17T20:01:32.000Z
.insert() and .remove() Methods.swift
WeKnow-io/Swift-lang
783f2c5575a1fa6b759dc6c739f86cdea8a89a36
[ "Unlicense" ]
null
null
null
.insert() and .remove() Methods.swift
WeKnow-io/Swift-lang
783f2c5575a1fa6b759dc6c739f86cdea8a89a36
[ "Unlicense" ]
1
2020-12-21T11:05:03.000Z
2020-12-21T11:05:03.000Z
var dna = ["ATG", "ACG", "GAA", "TAT"] // Write your code below 🧬 dna.insert("GTG", at: 3) dna.remove(at: 0) print(dna)
13.666667
38
0.577236
f0357d3c2268f1eddbd82d1aab92c32847e51c31
1,267
swift
Swift
Example/xSDK/测试视图/06 输入框附加视图/Kit06ViewController.swift
kaibuleite/xSDK
7674da16521c6673b27f4ef77c174e6879358415
[ "MIT" ]
1
2020-10-12T16:27:08.000Z
2020-10-12T16:27:08.000Z
Example/xSDK/测试视图/06 输入框附加视图/Kit06ViewController.swift
kaibuleite/xSDK
7674da16521c6673b27f4ef77c174e6879358415
[ "MIT" ]
null
null
null
Example/xSDK/测试视图/06 输入框附加视图/Kit06ViewController.swift
kaibuleite/xSDK
7674da16521c6673b27f4ef77c174e6879358415
[ "MIT" ]
null
null
null
// // Kit06ViewController.swift // xSDK_Example // // Created by Mac on 2020/9/18. // Copyright © 2020 CocoaPods. All rights reserved. // import UIKit import xSDK class Kit06ViewController: UIViewController { @IBOutlet weak var normalInput: xTextField! @IBOutlet weak var numberInput: xTextField! override func viewDidLoad() { super.viewDidLoad() self.normalInput.addBeginEditHandler { xLog("开始输入") } self.normalInput.addEditingHandler { (txt) in } self.normalInput.addReturnHandler { [weak self] in guard let ws = self else { return } ws.view.endEditing(true) xLog("完成、搜索。。。按钮") } self.normalInput.addEndEditHandler { xLog("结束输入") } self.numberInput.addEditingHandler { [weak self] (txt) in guard let ws = self else { return } let str = txt.xToInternationalNumberString() ws.numberInput.text = str // ws.numberInput.reset(text: str) } let inputArr = [self.normalInput, self.numberInput] xTextField.relateInput(list: inputArr) } }
25.34
56
0.558011
65a724e29f7df9378443c3fd175efecb499b1a33
774
lua
Lua
python/output/towers.lua
CppCXY/excel-to-lua
2c6b1803cf29481638a718ec43357f360d6c7421
[ "MIT" ]
4
2019-03-14T12:50:47.000Z
2020-01-05T05:17:25.000Z
python/output/towers.lua
luoxixuan/excel-to-lua
2c6b1803cf29481638a718ec43357f360d6c7421
[ "MIT" ]
null
null
null
python/output/towers.lua
luoxixuan/excel-to-lua
2c6b1803cf29481638a718ec43357f360d6c7421
[ "MIT" ]
1
2020-01-05T05:17:41.000Z
2020-01-05T05:17:41.000Z
local towers={ {key="江湖异人",desc="与江湖上各种奇人异士一争高下。", None={ { type="", }, },}, {key="决战光明顶",desc="你将扮演六大派高手,围剿明教光明顶。", None={ { type="have_item", value="天关.决战光明顶之证", }, },}, {key="林平之的复仇",desc="你将扮演林平之,完成对木高峰、余沧海的复仇。", None={ { type="have_item", value="天关.林平之的复仇", }, },}, {key="血战少室山",desc="你将扮演庄聚贤,慕容复,丁春秋对战天龙三兄弟", None={ { type="have_item", value="天关.血战少室山", }, },}, {key="越女剑",desc="挑战《越女剑》顶级BOSS 阿青", None={ { type="have_item", value="天关.越女剑", }, },}, {key="炼狱",desc="炼狱级天关,挑战各个绝顶高手,获取丰厚的奖励。", None={ { type="have_item", value="天关.炼狱之证", },{ type="game_mode", value="crazy", }, },}, {key="华山论剑",desc="最终华山论剑", None={ { type="have_item", value="天关.华山论剑之证", }, },}, {key="江湖生死战",desc=" ", None={ { type="have_item", value="天关.不可能之证", }, },}, } return towers
29.769231
90
0.589147
45c91829e30426832e4043bfea5815574b844887
75
rs
Rust
render/src/buffer/mod.rs
monocodus-demonstrations/flowbetween
78cab5dff9183cdf659405fe465013527eb08879
[ "Apache-2.0" ]
13
2021-02-17T22:28:06.000Z
2022-03-05T16:04:09.000Z
render/src/buffer/mod.rs
monocodus-demonstrations/flowbetween
78cab5dff9183cdf659405fe465013527eb08879
[ "Apache-2.0" ]
2
2021-03-10T10:32:21.000Z
2022-01-21T10:48:13.000Z
render/src/buffer/mod.rs
Logicalshift/flo_draw
e1bc89fc9f4796a40c9c3afbc702b520568e25c4
[ "Apache-2.0" ]
null
null
null
mod vertex; mod matrix; pub use self::vertex::*; pub use self::matrix::*;
12.5
24
0.666667
9ead4730320dd24da4336825bf6e1014ce6a444c
69
rs
Rust
near-contract-standards/src/lib.rs
sept-en/near-sdk-rs
fa2383ebac1dd5f10487f95a4eaca4db8e994630
[ "Apache-2.0", "MIT" ]
null
null
null
near-contract-standards/src/lib.rs
sept-en/near-sdk-rs
fa2383ebac1dd5f10487f95a4eaca4db8e994630
[ "Apache-2.0", "MIT" ]
null
null
null
near-contract-standards/src/lib.rs
sept-en/near-sdk-rs
fa2383ebac1dd5f10487f95a4eaca4db8e994630
[ "Apache-2.0", "MIT" ]
null
null
null
pub mod fungible_token; pub mod storage_management; pub mod upgrade;
17.25
27
0.826087
164083bbd011e6d920f831725b40fb95b6b4c3e7
554
tsx
TypeScript
src/Select/Select.stories.tsx
Yair-Ohana/react-daisyui
fa27b85de012b8e298aec36595efa99eb5880aa5
[ "MIT" ]
28
2022-03-09T20:44:20.000Z
2022-03-11T20:43:08.000Z
src/Select/Select.stories.tsx
Yair-Ohana/react-daisyui
fa27b85de012b8e298aec36595efa99eb5880aa5
[ "MIT" ]
null
null
null
src/Select/Select.stories.tsx
Yair-Ohana/react-daisyui
fa27b85de012b8e298aec36595efa99eb5880aa5
[ "MIT" ]
1
2022-03-11T02:04:02.000Z
2022-03-11T02:04:02.000Z
import React from 'react' import { Story, Meta } from '@storybook/react' import Select, { SelectProps } from '.' const { Option } = Select export default { title: 'Data Input/Select', component: Select, parameters: { controls: { exclude: ['ref'] }, }, } as Meta export const Default: Story<SelectProps<string>> = (args) => { return ( <Select {...args}> <Option value={1}>A</Option> <Option value={2}>B</Option> <Option value={3}>C</Option> </Select> ) } Default.args = { onChange: (e) => console.log(e), }
19.785714
62
0.601083
16ac5f47d30e47eb1b4d18a0af622c2a26eb2bdc
1,193
ts
TypeScript
stronghold/src/serde/iJson.ts
stronghold-financial/stronghold
7461cbdc6c67459517f10205bd918111ad109100
[ "MIT" ]
1
2021-06-24T20:23:50.000Z
2021-06-24T20:23:50.000Z
stronghold/src/serde/iJson.ts
nairyl/stronghold
cdceab6cdcc027f9bf173e1bd17a04d1c7d6eca9
[ "MIT" ]
null
null
null
stronghold/src/serde/iJson.ts
nairyl/stronghold
cdceab6cdcc027f9bf173e1bd17a04d1c7d6eca9
[ "MIT" ]
1
2021-10-20T07:30:49.000Z
2021-10-20T07:30:49.000Z
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ import BJSON from 'buffer-json' /** * IJSON, for Stronghold JSON. Supports parsing/stringifying Buffers and BigInts. */ export const IJSON = { stringify(value: unknown, space?: string | number): string { return JSON.stringify( value, (key, value) => typeof value === 'bigint' ? `${value.toString()}n` : (BJSON.replacer(key, value) as unknown), space, ) }, parse(text: string): unknown { return JSON.parse(text, (key, value) => { if (typeof value === 'string' && value.endsWith('n') && value.length > 1) { const slice = value.slice(0, value.length - 1) const sliceWithoutMinus = slice.startsWith('-') ? slice.slice(1) : slice // If every character except the last is a number, parse as a bigint if (sliceWithoutMinus.split('').every((char) => !isNaN(Number(char)))) { return BigInt(slice) } } return BJSON.reviver(key, value) as unknown }) }, }
33.138889
81
0.609388
fe0f1695986075999438e16894e47748103e1ae9
87,172
c
C
base/fs/srv/io.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
base/fs/srv/io.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
base/fs/srv/io.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1989 Microsoft Corporation Module Name: io.c Abstract: !!! Need to handle inability to allocate IRP. !!! Need to modify to accept file object pointer, not file handle, to avoid unnecessary translations. Author: Chuck Lenzmeier (chuckl) 28-Oct-1989 Revision History: --*/ #include "precomp.h" #include "io.tmh" #pragma hdrstop #define BugCheckFileId SRV_FILE_IO // // Forward declarations // PIRP BuildCoreOfSyncIoRequest ( IN HANDLE FileHandle, IN PFILE_OBJECT FileObject OPTIONAL, IN PKEVENT Event, IN PIO_STATUS_BLOCK IoStatusBlock, IN OUT PDEVICE_OBJECT *DeviceObject ); NTSTATUS StartIoAndWait ( IN PIRP Irp, IN PDEVICE_OBJECT DeviceObject, IN PKEVENT Event, IN PIO_STATUS_BLOCK IoStatusBlock ); #ifdef ALLOC_PRAGMA #pragma alloc_text( PAGE, BuildCoreOfSyncIoRequest ) #pragma alloc_text( PAGE, StartIoAndWait ) #pragma alloc_text( PAGE, SrvBuildFlushRequest ) #pragma alloc_text( PAGE, SrvBuildLockRequest ) #pragma alloc_text( PAGE, SrvBuildMailslotWriteRequest ) #pragma alloc_text( PAGE, SrvBuildReadOrWriteRequest ) #pragma alloc_text( PAGE, SrvBuildNotifyChangeRequest ) #pragma alloc_text( PAGE, SrvIssueAssociateRequest ) #pragma alloc_text( PAGE, SrvIssueDisconnectRequest ) #pragma alloc_text( PAGE, SrvIssueTdiAction ) #pragma alloc_text( PAGE, SrvIssueTdiQuery ) #pragma alloc_text( PAGE, SrvIssueQueryDirectoryRequest ) #pragma alloc_text( PAGE, SrvIssueQueryEaRequest ) #pragma alloc_text( PAGE, SrvIssueSendDatagramRequest ) #pragma alloc_text( PAGE, SrvIssueSetClientProcessRequest ) #pragma alloc_text( PAGE, SrvIssueSetEaRequest ) #pragma alloc_text( PAGE, SrvIssueSetEventHandlerRequest ) #pragma alloc_text( PAGE, SrvIssueUnlockRequest ) #pragma alloc_text( PAGE, SrvIssueUnlockSingleRequest ) #pragma alloc_text( PAGE, SrvIssueWaitForOplockBreak ) #pragma alloc_text( PAGE, SrvQuerySendEntryPoint ) #endif #if 0 NOT PAGEABLE -- SrvBuildIoControlRequest #endif STATIC PIRP BuildCoreOfSyncIoRequest ( IN HANDLE FileHandle, IN PFILE_OBJECT FileObject OPTIONAL, IN PKEVENT Event, IN PIO_STATUS_BLOCK IoStatusBlock, IN OUT PDEVICE_OBJECT *DeviceObject ) /*++ Routine Description: This (local) function builds the request-independent portion of an I/O request packet for an I/O operation that will be performed synchronously. It initializes a kernel event object, references the target file object, and allocates and initializes an IRP. Arguments: FileHandle - Supplies a handle to the target file object. FileObject - Optionall supplies a pointer to the target file object. Event - Supplies a pointer to a kernel event object. This routine initializes the event. IoStatusBlock - Supplies a pointer to an I/O status block. This pointer is placed in the IRP. DeviceObject - Supplies or receives the address of the device object associated with the target file object. This address is subsequently used by StartIoAndWait. *DeviceObject must be valid or NULL on entry if FileObject != NULL. Return Value: PIRP - Returns a pointer to the constructed IRP. --*/ { NTSTATUS status; PIRP irp; PIO_STACK_LOCATION irpSp; PAGED_CODE(); // // Initialize the kernel event that will signal I/O completion. // KeInitializeEvent( Event, SynchronizationEvent, FALSE ); // // Get the file object corresponding to the directory's handle. // Referencing the file object every time is necessary because the // IO completion routine dereferneces it. // if ( ARGUMENT_PRESENT(FileObject) ) { ObReferenceObject(FileObject); } else { *DeviceObject = NULL; status = ObReferenceObjectByHandle( FileHandle, 0L, // DesiredAccess NULL, // ObjectType KernelMode, (PVOID *)&FileObject, NULL ); if ( !NT_SUCCESS(status) ) { return NULL; } } // // Set the file object event to a non-signaled state. // KeClearEvent( &FileObject->Event ); // // Attempt to allocate and initialize the I/O Request Packet (IRP) // for this operation. // if ( *DeviceObject == NULL ) { *DeviceObject = IoGetRelatedDeviceObject( FileObject ); } irp = IoAllocateIrp( (*DeviceObject)->StackSize, TRUE ); if ( irp == NULL ) { ULONG packetSize = sizeof(IRP) + ((*DeviceObject)->StackSize * sizeof(IO_STACK_LOCATION)); INTERNAL_ERROR( ERROR_LEVEL_EXPECTED, "BuildCoreOfSyncIoRequest: Failed to allocate IRP", NULL, NULL ); SrvLogError( SrvDeviceObject, EVENT_SRV_NO_NONPAGED_POOL, STATUS_INSUFFICIENT_RESOURCES, &packetSize, sizeof(ULONG), NULL, 0 ); return NULL; } // // Fill in the service independent parameters in the IRP. // irp->MdlAddress = NULL; irp->Flags = (LONG)IRP_SYNCHRONOUS_API; irp->RequestorMode = KernelMode; irp->PendingReturned = FALSE; irp->UserIosb = IoStatusBlock; irp->UserEvent = Event; irp->Overlay.AsynchronousParameters.UserApcRoutine = NULL; irp->AssociatedIrp.SystemBuffer = NULL; irp->UserBuffer = NULL; irp->Tail.Overlay.Thread = PsGetCurrentThread(); irp->Tail.Overlay.OriginalFileObject = FileObject; irp->Tail.Overlay.AuxiliaryBuffer = NULL; irp->IoStatus.Status = 0; irp->IoStatus.Information = 0; // // Put the file object pointer in the stack location. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->FileObject = FileObject; irpSp->DeviceObject = *DeviceObject; return irp; } // BuildCoreOfSyncIoRequest STATIC NTSTATUS StartIoAndWait ( IN PIRP Irp, IN PDEVICE_OBJECT DeviceObject, IN PKEVENT Event, IN PIO_STATUS_BLOCK IoStatusBlock ) /*++ Routine Description: This (local) function passes a fully built I/O request packet to the target driver, then waits for the driver to complete the request. Arguments: Irp - Supplies a pointer to the I/O request packet. DeviceObject - Supplies a pointer to the target device object. Event - Supplies a pointer to a kernel event object. This routine waits for the I/O to complete using this event. IoStatusBlock - Supplies a pointer to an I/O status block. The Status field of this structure becomes the return status of this function. Return Value: NTSTATUS - Either an error status returned by the driver from IoCallDriver, indicating that the driver rejected the request, or the I/O status placed in the I/O status block by the driver at I/O completion. --*/ { NTSTATUS status; KIRQL oldIrql; PAGED_CODE(); // // Queue the IRP to the thread and pass it to the driver. // IoQueueThreadIrp( Irp ); status = IoCallDriver( DeviceObject, Irp ); // // If necessary, wait for the I/O to complete. // if ( status == STATUS_PENDING ) { KeWaitForSingleObject( Event, UserRequest, KernelMode, // don't let stack be paged -- event is on stack! FALSE, NULL ); } // // If the request was successfully queued, get the final I/O status. // if ( NT_SUCCESS(status) ) { status = IoStatusBlock->Status; } return status; } // StartIoAndWait PIRP SrvBuildIoControlRequest ( IN OUT PIRP Irp OPTIONAL, IN PFILE_OBJECT FileObject OPTIONAL, IN PVOID Context, IN UCHAR MajorFunction, IN ULONG IoControlCode, IN PVOID MainBuffer, IN ULONG InputBufferLength, IN PVOID AuxiliaryBuffer OPTIONAL, IN ULONG OutputBufferLength, IN OUT PMDL Mdl OPTIONAL, IN PIO_COMPLETION_ROUTINE CompletionRoutine OPTIONAL ) /*++ Routine Description: This function builds an I/O request packet for a device or file system I/O control request. *** This routine sure takes a lot of arguments! Arguments: Irp - Supplies a pointer to an IRP. If NULL, this routine allocates an IRP and returns its address. Otherwise, it supplies the address of an IRP allocated by the caller. FileObject - Supplies a pointer the file object to which this request is directed. This pointer is copied into the IRP, so that the called driver can find its file-based context. NOTE THAT THIS IS NOT A REFERENCED POINTER. The caller must ensure that the file object is not deleted while the I/O operation is in progress. The server accomplishes this by incrementing a reference count in a local block to account for the I/O; the local block in turn references the file object. If this parameter is omitted, it is the responsiblity of the calling program to load the file object address before starting the I/O. Context - Supplies a PVOID value that is passed to the completion routine. MajorFunction - The major function that we are calling. Currently this most be one of IRP_MJ_FILE_SYSTEM_CONTROL or IRP_MJ_DEVICE_IO_CONTROL. IoControlCode - Supplies the control code for the operation. MainBuffer - Supplies the address of the main buffer. This must be a system virtual address, and the buffer must be locked in memory. If ControlCode specifies a method 0 request, the actual length of the buffer must be the greater of InputBufferLength and OutputBufferLength. InputBufferLength - Supplies the length of the input buffer. AuxiliaryBuffer - Supplies the address of the auxiliary buffer. If the control code method is 0, this is a buffered I/O buffer, but the data returned by the called driver in the system buffer is not automatically copied into the auxiliary buffer. Instead, the auxiliary data ends up in MainBuffer. If the caller wishes the data to be in AuxiliaryBuffer, it must copy the data at some point after the completion routine runs. If the control code method is 1 or 2, this parameter is ignored; instead, the Mdl parameter is used to obtain the starting virtual address of the buffer. OutputBufferLength - Supplies the length of the output buffer. Note that this parameter must be specified even when the Mdl parameter is specified. Mdl - If the control code method is 1 or 2, indicating direct I/O on the "output" buffer, this parameter is used to supply a pointer to an MDL describing a buffer. Mdl must not be NULL, and the AuxiliaryBuffer parameter is ignored. The buffer must reside in the system virtual address space (for the benefit of the transport provider). If the buffer is not already locked, this routine locks it. It is the calling program's responsibility to unlock the buffer and (potentially) deallocate the MDL after the I/O is complete. This parameter is ignored if the control method is not 1 or 2. CompletionRoutine - An optional IO completion routine. If none is specified, SrvFsdIoCompletionRoutine is used. Return Value: PIRP - Returns a pointer to the constructed IRP. If the Irp parameter was not NULL on input, the function return value will be the same value (so it is safe to discard the return value in this case). It is the responsibility of the calling program to deallocate the IRP after the I/O request is complete. --*/ { CLONG method; PDEVICE_OBJECT deviceObject; PIO_STACK_LOCATION irpSp; ASSERT( MajorFunction == IRP_MJ_DEVICE_CONTROL || MajorFunction == IRP_MJ_INTERNAL_DEVICE_CONTROL || MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL ); // // Get the method with which the buffers are being passed. // if ((MajorFunction == IRP_MJ_DEVICE_CONTROL) || (MajorFunction == IRP_MJ_FILE_SYSTEM_CONTROL)) { method = IoControlCode & 3; } else { method = 4; } if ( ARGUMENT_PRESENT(Irp) ) { if( Irp->AssociatedIrp.SystemBuffer && (Irp->Flags & IRP_DEALLOCATE_BUFFER) ) { ExFreePool( Irp->AssociatedIrp.SystemBuffer ); Irp->Flags &= ~IRP_DEALLOCATE_BUFFER; } IoReuseIrp( Irp, STATUS_SUCCESS ); } // // If the FileObject parameter was specified, obtain the address of // the device object and allocate the IRP based on the stack size // for that device. Otherwise, allocate the IRP based on the // server's receive IRP stack size. // if ( ARGUMENT_PRESENT(FileObject) ) { // // Allocate an IRP, if necessary. The stack size is one higher // than that of the target device, to allow for the caller's // completion routine. // deviceObject = IoGetRelatedDeviceObject( FileObject ); if ( ARGUMENT_PRESENT(Irp) ) { ASSERT( Irp->StackCount >= deviceObject->StackSize ); } else { // // Get the address of the target device object. // Irp = IoAllocateIrp( SrvReceiveIrpStackSize, FALSE ); if ( Irp == NULL ) { // // Unable to allocate an IRP. Inform the caller. // return NULL; } } } else { deviceObject = NULL; if ( !ARGUMENT_PRESENT(Irp) ) { Irp = IoAllocateIrp( SrvReceiveIrpStackSize, FALSE ); if ( Irp == NULL ) { return NULL; } } } Irp->Tail.Overlay.OriginalFileObject = FileObject; Irp->Tail.Overlay.Thread = PROCESSOR_TO_QUEUE()->IrpThread; Irp->RequestorMode = KernelMode; Irp->IoStatus.Status = 0; Irp->IoStatus.Information = 0; // // Get a pointer to the next stack location. This one is used to // hold the parameters for the device I/O control request. // irpSp = IoGetNextIrpStackLocation( Irp ); // // Set up the completion routine. // IoSetCompletionRoutine( Irp, (ARGUMENT_PRESENT( CompletionRoutine ) ? CompletionRoutine : SrvFsdIoCompletionRoutine), Context, TRUE, TRUE, TRUE ); irpSp->MajorFunction = MajorFunction; irpSp->MinorFunction = 0; if ( MajorFunction == IRP_MJ_INTERNAL_DEVICE_CONTROL ) { irpSp->MinorFunction = (UCHAR)IoControlCode; } irpSp->FileObject = FileObject; irpSp->DeviceObject = deviceObject; // // Copy the caller's parameters to the service-specific portion of the // IRP for those parameters that are the same for all three methods. // if ( MajorFunction == IRP_MJ_DEVICE_CONTROL ) { irpSp->Parameters.DeviceIoControl.OutputBufferLength = OutputBufferLength; irpSp->Parameters.DeviceIoControl.InputBufferLength = InputBufferLength; irpSp->Parameters.DeviceIoControl.IoControlCode = IoControlCode; } else if ( MajorFunction == IRP_MJ_INTERNAL_DEVICE_CONTROL ) { if ( IoControlCode == TDI_RECEIVE ) { PTDI_REQUEST_KERNEL_RECEIVE parameters = (PTDI_REQUEST_KERNEL_RECEIVE)&irpSp->Parameters; parameters->ReceiveLength = OutputBufferLength; parameters->ReceiveFlags = 0; method = 1; } else if ( IoControlCode == TDI_ACCEPT ) { PTDI_REQUEST_KERNEL_ACCEPT parameters = (PTDI_REQUEST_KERNEL_ACCEPT)&irpSp->Parameters; parameters->RequestConnectionInformation = NULL; parameters->ReturnConnectionInformation = NULL; method = 0; } else { ASSERTMSG( "Invalid TDI request type", 0 ); } } else { irpSp->Parameters.FileSystemControl.OutputBufferLength = OutputBufferLength; irpSp->Parameters.FileSystemControl.InputBufferLength = InputBufferLength; irpSp->Parameters.FileSystemControl.FsControlCode = IoControlCode; } // // Based on the method by which the buffers are being passed, // describe a system buffer and optionally build an MDL. // switch ( method ) { case 0: // // For this case, InputBuffer must be large enough to contain // both the input and the output buffers. // Irp->MdlAddress = NULL; Irp->AssociatedIrp.SystemBuffer = MainBuffer; Irp->UserBuffer = AuxiliaryBuffer; // // !!! Does Irp->Flags need to be set? Isn't this only looked // at by I/O competion, which we bypass? // Irp->Flags = (ULONG)IRP_BUFFERED_IO; if ( ARGUMENT_PRESENT(AuxiliaryBuffer) ) { Irp->Flags |= IRP_INPUT_OPERATION; } break; case 1: case 2: // // For these two cases, InputBuffer is the buffered I/O "system // buffer". Build an MDL for either read or write access, // depending on the method, for the output buffer. // Irp->MdlAddress = Mdl; Irp->AssociatedIrp.SystemBuffer = MainBuffer; // !!! Ditto above about setting Flags. Irp->Flags = (ULONG)IRP_BUFFERED_IO; break; case 3: // // For this case, do nothing. Everything is up to the driver. // Simply give the driver a copy of the caller's parameters and // let the driver do everything itself. // Irp->MdlAddress = NULL; Irp->AssociatedIrp.SystemBuffer = NULL; Irp->UserBuffer = AuxiliaryBuffer; Irp->Flags = 0; irpSp->Parameters.DeviceIoControl.Type3InputBuffer = MainBuffer; break; case 4: // // This is the case for file system io request. Both MainBuffer // and AuxiliaryBuffer are locked system buffers. // Irp->MdlAddress = NULL; Irp->Flags = 0; Irp->AssociatedIrp.SystemBuffer = MainBuffer; irpSp->Parameters.DeviceIoControl.Type3InputBuffer = AuxiliaryBuffer; break; } return Irp; } // SrvBuildIoControlRequest VOID SrvBuildFlushRequest ( IN PIRP Irp, IN PFILE_OBJECT FileObject, IN PVOID Context OPTIONAL ) /*++ Routine Description: This function builds an I/O request packet for a flush request. Arguments: Irp - Supplies a pointer to an IRP. FileObject - Supplies a pointer the file object to which this request is directed. This pointer is copied into the IRP, so that the called driver can find its file-based context. NOTE THAT THIS IS NOT A REFERENCED POINTER. The caller must ensure that the file object is not deleted while the I/O operation is in progress. The server accomplishes this by incrementing a reference count in a local block to account for the I/O; the local block in turn references the file object. Context - Supplies a PVOID value that is passed to the completion routine. Return Value: None. --*/ { PDEVICE_OBJECT deviceObject; PIO_STACK_LOCATION irpSp; PAGED_CODE( ); deviceObject = IoGetRelatedDeviceObject( FileObject ); ASSERT( Irp->StackCount >= deviceObject->StackSize ); Irp->Tail.Overlay.OriginalFileObject = FileObject; Irp->Tail.Overlay.Thread = PROCESSOR_TO_QUEUE()->IrpThread; DEBUG Irp->RequestorMode = KernelMode; Irp->IoStatus.Status = 0; Irp->IoStatus.Information = 0; // // Get a pointer to the next stack location. This one is used to // hold the parameters for the read request. Fill in the // service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( Irp ); // // Set up the completion routine. // IoSetCompletionRoutine( Irp, SrvFsdIoCompletionRoutine, Context, TRUE, TRUE, TRUE ); irpSp->MajorFunction = IRP_MJ_FLUSH_BUFFERS; irpSp->FileObject = FileObject; irpSp->DeviceObject = deviceObject; irpSp->Flags = 0; return; } // SrvBuildFlushRequest VOID SrvBuildLockRequest ( IN PIRP Irp, IN PFILE_OBJECT FileObject, IN PVOID Context OPTIONAL, IN LARGE_INTEGER ByteOffset, IN LARGE_INTEGER Length, IN ULONG Key, IN BOOLEAN FailImmediately, IN BOOLEAN ExclusiveLock ) /*++ Routine Description: This function builds an I/O request packet for a lock request. Arguments: Irp - Supplies a pointer to an IRP. FileObject - Supplies a pointer the file object to which this request is directed. This pointer is copied into the IRP, so that the called driver can find its file-based context. NOTE THAT THIS IS NOT A REFERENCED POINTER. The caller must ensure that the file object is not deleted while the I/O operation is in progress. The server accomplishes this by incrementing a reference count in a local block to account for the I/O; the local block in turn references the file object. Context - Supplies a PVOID value that is passed to the completion routine. StartingBlock - the block number of the beginning of the locked range. ByteOffset - the offset within block of the beginning of the locked range. Length - the length of the locked range. Key - the key value to be associated with the lock. Return Value: None. --*/ { PDEVICE_OBJECT deviceObject; PIO_STACK_LOCATION irpSp; PAGED_CODE( ); deviceObject = IoGetRelatedDeviceObject( FileObject ); ASSERT( Irp->StackCount >= deviceObject->StackSize ); Irp->Tail.Overlay.OriginalFileObject = FileObject; Irp->Tail.Overlay.Thread = PROCESSOR_TO_QUEUE()->IrpThread; DEBUG Irp->RequestorMode = KernelMode; Irp->IoStatus.Status = 0; Irp->IoStatus.Information = 0; // // Get a pointer to the next stack location. This one is used to // hold the parameters for the read request. Fill in the // service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( Irp ); // // Set up the completion routine. // IoSetCompletionRoutine( Irp, SrvFsdIoCompletionRoutine, Context, TRUE, TRUE, TRUE ); irpSp->MajorFunction = IRP_MJ_LOCK_CONTROL; irpSp->MinorFunction = IRP_MN_LOCK; irpSp->FileObject = FileObject; irpSp->DeviceObject = deviceObject; irpSp->Flags = 0; if ( FailImmediately ) { irpSp->Flags = SL_FAIL_IMMEDIATELY; } if ( ExclusiveLock ) { irpSp->Flags |= SL_EXCLUSIVE_LOCK; } ((PWORK_CONTEXT)Context)->Parameters2.LockLength = Length; irpSp->Parameters.LockControl.Length = &((PWORK_CONTEXT)Context)->Parameters2.LockLength; irpSp->Parameters.LockControl.Key = Key; irpSp->Parameters.LockControl.ByteOffset = ByteOffset; return; } // SrvBuildLockRequest NTSTATUS SrvIssueMdlCompleteRequest ( IN PWORK_CONTEXT WorkContext OPTIONAL, IN PFILE_OBJECT FileObject OPTIONAL, IN PMDL Mdl, IN UCHAR Function, IN PLARGE_INTEGER ByteOffset, IN ULONG Length ) { PIRP irp; PIO_STACK_LOCATION irpSp; PFILE_OBJECT fileObject = FileObject ? FileObject : WorkContext->Rfcb->Lfcb->FileObject; PDEVICE_OBJECT deviceObject = IoGetRelatedDeviceObject( fileObject ); KEVENT userEvent; NTSTATUS status; IO_STATUS_BLOCK ioStatusBlock; if( (irp = IoAllocateIrp( deviceObject->StackSize, TRUE )) == NULL ) { return STATUS_INSUFFICIENT_RESOURCES; } // Reference the file object ObReferenceObject( fileObject ); KeInitializeEvent( &userEvent, SynchronizationEvent, FALSE ); KeClearEvent( &userEvent ); irp->MdlAddress = Mdl; irp->Flags = IRP_SYNCHRONOUS_API; irp->UserEvent = &userEvent; irp->UserIosb = &ioStatusBlock; irp->RequestorMode = KernelMode; irp->PendingReturned = FALSE; irp->Tail.Overlay.Thread = PsGetCurrentThread(); irp->Tail.Overlay.OriginalFileObject = fileObject; irp->IoStatus.Status = 0; irp->IoStatus.Information = 0; irpSp = IoGetNextIrpStackLocation( irp ); irpSp->FileObject = fileObject; irpSp->DeviceObject = deviceObject; irpSp->Flags = 0; irpSp->MinorFunction = IRP_MN_MDL | IRP_MN_COMPLETE; irpSp->MajorFunction = Function; if( Function == IRP_MJ_WRITE ) { irpSp->Parameters.Write.ByteOffset = *ByteOffset; irpSp->Parameters.Write.Length = Length; } else { irpSp->Parameters.Read.ByteOffset = *ByteOffset; irpSp->Parameters.Read.Length = Length; } status = IoCallDriver( deviceObject, irp ); if (status == STATUS_PENDING) { (VOID) KeWaitForSingleObject( &userEvent, UserRequest, KernelMode, FALSE, (PLARGE_INTEGER) NULL ); status = ioStatusBlock.Status; } ASSERT( status == STATUS_SUCCESS ); return status; } VOID SrvBuildMailslotWriteRequest ( IN PIRP Irp, IN PFILE_OBJECT FileObject, IN PVOID Context OPTIONAL, IN PVOID Buffer OPTIONAL, IN ULONG Length ) /*++ Routine Description: This function builds an I/O request packet for a mailslot write request. Arguments: Irp - Supplies a pointer to an IRP. FileObject - Supplies a pointer the file object to which this request is directed. This pointer is copied into the IRP, so that the called driver can find its file-based context. NOTE THAT THIS IS NOT A REFERENCED POINTER. The caller must ensure that the file object is not deleted while the I/O operation is in progress. The server accomplishes this by incrementing a reference count in a local block to account for the I/O; the local block in turn references the file object. Context - Supplies a PVOID value that is passed to the completion routine. Buffer - Supplies the system virtual address of the write buffer. Length - Supplies the length of the write. Return Value: None. --*/ { PDEVICE_OBJECT deviceObject; PIO_STACK_LOCATION irpSp; PAGED_CODE( ); deviceObject = IoGetRelatedDeviceObject( FileObject ); ASSERT( Irp->StackCount >= deviceObject->StackSize ); Irp->Tail.Overlay.OriginalFileObject = FileObject; Irp->Tail.Overlay.Thread = PROCESSOR_TO_QUEUE()->IrpThread; DEBUG Irp->RequestorMode = KernelMode; Irp->IoStatus.Status = 0; Irp->IoStatus.Information = 0; // // Get a pointer to the next stack location. This one is used to // hold the parameters for the read request. // irpSp = IoGetNextIrpStackLocation( Irp ); // // Set up the completion routine. // IoSetCompletionRoutine( Irp, SrvFsdIoCompletionRoutine, Context, TRUE, TRUE, TRUE ); irpSp->MajorFunction = IRP_MJ_WRITE; irpSp->MinorFunction = 0; irpSp->FileObject = FileObject; irpSp->DeviceObject = deviceObject; // // Set the write buffer. // //Irp->AssociatedIrp.SystemBuffer = Buffer; Irp->UserBuffer = Buffer; Irp->Flags = IRP_BUFFERED_IO; // // Set the write parameters. // irpSp->Parameters.Write.Length = Length; return; } // SrvBuildMailslotWriteRequest VOID SrvBuildReadOrWriteRequest ( IN OUT PIRP Irp, IN PFILE_OBJECT FileObject, IN PVOID Context OPTIONAL, IN UCHAR MajorFunction, IN UCHAR MinorFunction, IN PVOID Buffer OPTIONAL, IN ULONG Length, IN OUT PMDL Mdl OPTIONAL, IN LARGE_INTEGER ByteOffset, IN ULONG Key OPTIONAL ) /*++ Routine Description: This function builds an I/O request packet for a read or write request. Arguments: Irp - Supplies a pointer to an IRP. FileObject - Supplies a pointer the file object to which this request is directed. This pointer is copied into the IRP, so that the called driver can find its file-based context. NOTE THAT THIS IS NOT A REFERENCED POINTER. The caller must ensure that the file object is not deleted while the I/O operation is in progress. The server accomplishes this by incrementing a reference count in a local block to account for the I/O; the local block in turn references the file object. Context - Supplies a PVOID value that is passed to the completion routine. MajorFunction - Indicates the function to be performed. Must be either IRP_MJ_READ or IRP_MJ_WRITE. MinorFunction - Qualifies the function to be performed. (For example, issued at DPC level, MDL read, etc.) Buffer - Supplies the system virtual address of the read or write buffer. This parameter is ignored when MinorFunction is IRP_MN_*_MDL_*. Otherwise, the buffer must be mapped in the system virtual address space in order to support buffered I/O devices and other device drivers that need to look at the user data. This routine always treats the buffer as a direct I/O buffer, locking it for I/O with an MDL. It does, however, set up the IRP appropriately for the device type. If the Mdl parameter is NULL, this routine locks the buffer in memory for the I/O. It is then the responsibility of the calling program to unlock the buffer and deallocate the MDL after the I/O is complete. Length - Supplies the length of the read or write. Mdl - This parameter is used to supply a pointer to an MDL describing a buffer. It is ignored when MinorFunction is IRP_MN_MDL_*. Otherwise, Mdl must not be NULL. The buffer must reside in the system virtual address space (for the benefit of buffered I/O devices/drivers). If the buffer is not already locked, this routine locks it. It is the calling program's responsibility to unlock the buffer and (potentially) deallocate the MDL after the I/O is complete. ByteOffset - the offset within the file of the beginning of the read or write. Key - the key value to be associated with the read or write. Return Value: None. --*/ { PDEVICE_OBJECT deviceObject; PIO_STACK_LOCATION irpSp; PAGED_CODE( ); if( Irp->AssociatedIrp.SystemBuffer && (Irp->Flags & IRP_DEALLOCATE_BUFFER) ) { ExFreePool( Irp->AssociatedIrp.SystemBuffer ); Irp->Flags &= ~IRP_DEALLOCATE_BUFFER; } // // Obtain the address of the device object and allocate the IRP // based on the stack size for that device. // deviceObject = IoGetRelatedDeviceObject( FileObject ); ASSERT( Irp->StackCount >= deviceObject->StackSize ); Irp->Tail.Overlay.OriginalFileObject = FileObject; Irp->Tail.Overlay.Thread = PROCESSOR_TO_QUEUE()->IrpThread; DEBUG Irp->RequestorMode = KernelMode; Irp->IoStatus.Status = 0; Irp->IoStatus.Information = 0; // // Get a pointer to the next stack location. This one is used to // hold the parameters for the read request. // irpSp = IoGetNextIrpStackLocation( Irp ); // // Set up the completion routine. // IoSetCompletionRoutine( Irp, SrvFsdIoCompletionRoutine, Context, TRUE, TRUE, TRUE ); irpSp->MajorFunction = MajorFunction; irpSp->MinorFunction = MinorFunction; irpSp->FileObject = FileObject; irpSp->DeviceObject = deviceObject; // // This routine used to handle MDL read/write completion, but it // doesn't now. // ASSERT( IRP_MN_DPC == 1 ); ASSERT( IRP_MN_MDL == 2 ); ASSERT( IRP_MN_MDL_DPC == 3 ); ASSERT( IRP_MN_COMPLETE_MDL == 6 ); ASSERT( IRP_MN_COMPLETE_MDL_DPC == 7 ); ASSERT( (MinorFunction & 4) == 0 ); // // Set the parameters according to whether this is a read or a write // operation. Notice that these parameters must be set even if the // driver has not specified buffered or direct I/O. // if ( MajorFunction == IRP_MJ_WRITE ) { irpSp->Parameters.Write.ByteOffset = ByteOffset; irpSp->Parameters.Write.Length = Length; irpSp->Parameters.Write.Key = Key; } else { irpSp->Parameters.Read.ByteOffset = ByteOffset; irpSp->Parameters.Read.Length = Length; irpSp->Parameters.Read.Key = Key; } // // Indicate to the file system that this operation can be handled // synchronously. Basically, this means that the file system can // use the server's thread to fault pages in, etc. This avoids // having to context switch to a file system thread. // Irp->Flags = IRP_SYNCHRONOUS_API; // // If this is the start of an MDL-based read or write, we simply // need to put the supplied MDL address in the IRP. This optional // MDL address can provide a partial chain for a read or write that // was partially satisfied using the fast I/O path. // if ( (MinorFunction & IRP_MN_MDL) != 0 ) { Irp->MdlAddress = Mdl; DEBUG Irp->UserBuffer = NULL; DEBUG Irp->AssociatedIrp.SystemBuffer = NULL; return; } // // Normal ("copy") read or write. // ASSERT( Buffer != NULL ); ASSERT( Mdl != NULL ); // // If the target device does buffered I/O, load the address of the // caller's buffer as the "system buffered I/O buffer". If the // target device does direct I/O, load the MDL address. If it does // neither, load both the user buffer address and the MDL address. // (This is necessary to support file systems, such as HPFS, that // sometimes treat the I/O as buffered and sometimes treat it as // direct.) // if ( (deviceObject->Flags & DO_BUFFERED_IO) != 0 ) { Irp->AssociatedIrp.SystemBuffer = Buffer; if ( MajorFunction == IRP_MJ_WRITE ) { Irp->Flags |= IRP_BUFFERED_IO; } else { Irp->Flags |= IRP_BUFFERED_IO | IRP_INPUT_OPERATION; } } else if ( (deviceObject->Flags & DO_DIRECT_IO) != 0 ) { Irp->MdlAddress = Mdl; } else { Irp->UserBuffer = Buffer; Irp->MdlAddress = Mdl; } return; } // SrvBuildReadOrWriteRequest PIRP SrvBuildNotifyChangeRequest ( IN OUT PIRP Irp, IN PFILE_OBJECT FileObject, IN PVOID Context OPTIONAL, IN ULONG CompletionFilter, IN PVOID Buffer, IN ULONG BufferLength, IN BOOLEAN WatchTree ) /*++ Routine Description: This function builds an I/O request packet for a notify change request. Arguments: Irp - Supplies a pointer to an IRP. FileObject - Supplies a pointer the file object to which this request is directed. This pointer is copied into the IRP, so that the called driver can find its file-based context. NOTE THAT THIS IS NOT A REFERENCED POINTER. The caller must ensure that the file object is not deleted while the I/O operation is in progress. The server accomplishes this by incrementing a reference count in a local block to account for the I/O; the local block in turn references the file object. Context - Supplies a PVOID value that is passed to the completion routine. CompletionFilter - Specifies which directory changes will cause the File sytsem to complete the IRP. Buffer - The buffer to receive the directory change data. BufferLength - The size, in bytes, of the buffer. WatchTree - If TRUE, recursively watch all subdirectories for changes. Return Value: PIRP - Returns a pointer to the constructed IRP. If the Irp parameter was not NULL on input, the function return value will be the same value (so it is safe to discard the return value in this case). It is the responsibility of the calling program to deallocate the IRP after the I/O request is complete. --*/ { PDEVICE_OBJECT deviceObject; PIO_STACK_LOCATION irpSp; PMDL mdl; PAGED_CODE( ); if( Irp->AssociatedIrp.SystemBuffer && (Irp->Flags & IRP_DEALLOCATE_BUFFER) ) { ExFreePool( Irp->AssociatedIrp.SystemBuffer ); Irp->Flags &= ~IRP_DEALLOCATE_BUFFER; } // // Obtain the address of the device object and initialize the IRP. // deviceObject = IoGetRelatedDeviceObject( FileObject ); Irp->Tail.Overlay.OriginalFileObject = FileObject; Irp->Tail.Overlay.Thread = PROCESSOR_TO_QUEUE()->IrpThread; Irp->RequestorMode = KernelMode; Irp->MdlAddress = NULL; Irp->IoStatus.Status = 0; Irp->IoStatus.Information = 0; // // Get a pointer to the next stack location. This one is used to // hold the parameters for the read request. Fill in the // service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( Irp ); // // Set up the completion routine. // IoSetCompletionRoutine( Irp, SrvFsdIoCompletionRoutine, Context, TRUE, TRUE, TRUE ); irpSp->MajorFunction = IRP_MJ_DIRECTORY_CONTROL; irpSp->MinorFunction = IRP_MN_NOTIFY_CHANGE_DIRECTORY; irpSp->FileObject = FileObject; irpSp->DeviceObject = deviceObject; irpSp->Flags = 0; if (WatchTree) { irpSp->Flags = SL_WATCH_TREE; } irpSp->Parameters.NotifyDirectory.Length = BufferLength; irpSp->Parameters.NotifyDirectory.CompletionFilter = CompletionFilter; if ( (deviceObject->Flags & DO_DIRECT_IO) != 0 ) { mdl = IoAllocateMdl( Buffer, BufferLength, FALSE, FALSE, Irp // stores MDL address in irp->MdlAddress ); if ( mdl == NULL ) { // // Unable to allocate an MDL. Fail the I/O. // return NULL; } try { MmProbeAndLockPages( mdl, KernelMode, IoWriteAccess ); } except( EXCEPTION_EXECUTE_HANDLER ) { IoFreeMdl( mdl ); return NULL; } Irp->AssociatedIrp.SystemBuffer = NULL; Irp->UserBuffer = NULL; } else { Irp->AssociatedIrp.SystemBuffer = Buffer; Irp->UserBuffer = NULL; } // // Return a pointer to the IRP. // return Irp; } // SrvBuildNotifyChangeRequest NTSTATUS SrvIssueAssociateRequest ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN HANDLE AddressFileHandle ) /*++ Routine Description: This function issues an I/O request packet for a TdiAssociateAddress request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - pointer to file object for a connection. DeviceObject - pointer to pointer to device object for a connection. AddressFileHandle - handle to an address endpoint. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; PTDI_REQUEST_KERNEL_ASSOCIATE parameters; KEVENT event; IO_STATUS_BLOCK iosb; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the I/O. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); parameters = (PTDI_REQUEST_KERNEL_ASSOCIATE)&irpSp->Parameters; irpSp->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL; irpSp->MinorFunction = TDI_ASSOCIATE_ADDRESS; parameters->AddressHandle = AddressFileHandle; // // Start the I/O, wait for it to complete, and return the final status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueAssociateRequest NTSTATUS SrvIssueDisconnectRequest ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN ULONG Flags ) /*++ Routine Description: This function issues an I/O request packet for a TdiDisconnect request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - pointer to file object for a connection. DeviceObject - pointer to pointer to device object for a connection. Flags - Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; PTDI_REQUEST_KERNEL parameters; KEVENT event; IO_STATUS_BLOCK iosb; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the I/O. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); parameters = (PTDI_REQUEST_KERNEL)&irpSp->Parameters; irpSp->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL; irpSp->MinorFunction = TDI_DISCONNECT; parameters->RequestFlags = Flags; // // Start the I/O, wait for it to complete, and return the final status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueDisconnectRequest NTSTATUS SrvIssueTdiAction ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN PCHAR Buffer, IN ULONG BufferLength ) /*++ Routine Description: This function issues an I/O request packet for a TdiQueryInformation (Query Adapter Status) request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - pointer to file object for a connection. DeviceObject - pointer to pointer to device object for a connection. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; PMDL mdl; PAGED_CODE( ); // // Allocate and build an MDL that we'll use to describe the output // buffer for the request. // mdl = IoAllocateMdl( Buffer, BufferLength, FALSE, FALSE, NULL ); if ( mdl == NULL ) { return STATUS_INSUFF_SERVER_RESOURCES; } try { MmProbeAndLockPages( mdl, KernelMode, IoWriteAccess ); } except( EXCEPTION_EXECUTE_HANDLER ) { IoFreeMdl( mdl ); return GetExceptionCode(); } // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the I/O. // MmUnlockPages( mdl ); IoFreeMdl( mdl ); return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); TdiBuildAction( irp, *DeviceObject, FileObject, NULL, NULL, mdl ); // // Start the I/O, wait for it to complete, and return the final status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueTdiAction NTSTATUS SrvIssueTdiQuery ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN PCHAR Buffer, IN ULONG BufferLength, IN ULONG QueryType ) /*++ Routine Description: This function issues an I/O request packet for a TdiQueryInformation (Query Adapter Status) request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - pointer to file object for a connection. DeviceObject - pointer to pointer to device object for a connection. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; PMDL mdl; PAGED_CODE( ); // // Allocate and build an MDL that we'll use to describe the output // buffer for the request. // mdl = IoAllocateMdl( Buffer, BufferLength, FALSE, FALSE, NULL ); if ( mdl == NULL ) { return STATUS_INSUFF_SERVER_RESOURCES; } try { MmProbeAndLockPages( mdl, KernelMode, IoWriteAccess ); } except( EXCEPTION_EXECUTE_HANDLER ) { IoFreeMdl( mdl ); return GetExceptionCode(); } // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the I/O. // MmUnlockPages( mdl ); IoFreeMdl( mdl ); return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); TdiBuildQueryInformation( irp, *DeviceObject, FileObject, NULL, NULL, QueryType, mdl ); // // Start the I/O, wait for it to complete, and return the final status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueTdiQuery NTSTATUS SrvIssueQueryDirectoryRequest ( IN HANDLE FileHandle, IN PCHAR Buffer, IN ULONG Length, IN FILE_INFORMATION_CLASS FileInformationClass, IN PUNICODE_STRING FileName OPTIONAL, IN PULONG FileIndex OPTIONAL, IN BOOLEAN RestartScan, IN BOOLEAN SingleEntriesOnly ) /*++ Routine Description: This function issues an I/O request packet for a query directory request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileHandle - handle to a directory open with FILE_LIST_DIRECTORY access. Buffer - supplies the system virtual address of the buffer. The buffer must be in nonpaged pool. Length - supplies the length of the buffer. FileInformationClass - Specfies the type of information that is to be returned about the files in the specified directory. FileName - an optional pointer to a file name. If FileIndex is NULL, then this is the search specification, i.e. the template that files must match in order to be returned. If FileIndex is non-NULL, then this is the name of a file after which to resume a search. FileIndex - if specified, the index of a file after which to resume the search (first file returned is the one after the one corresponding to the index). RestartScan - Supplies a BOOLEAN value that, if TRUE, indicates that the scan should be restarted from the beginning. SingleEntriesOnly - Supplies a BOOLEAN value that, if TRUE, indicates that the scan should ask only for one entry at a time. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { ULONG actualBufferLength; PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; PDEVICE_OBJECT deviceObject; PUNICODE_STRING fileNameString; PMDL mdl; PAGED_CODE( ); // // Reject rewind requests if debugging for it. If a file index is // specified, this must be a rewind request, so reject the request. // IF_DEBUG(BRUTE_FORCE_REWIND) { if ( ARGUMENT_PRESENT( FileIndex ) ) { return STATUS_NOT_IMPLEMENTED; } } // // Copy the file name into the end of the specified buffer, setting // the actualBufferLength accordingly. // if ( !ARGUMENT_PRESENT(FileName) || FileName->Length == 0 ) { actualBufferLength = Length; fileNameString = NULL; } else { // // *** Remember that the string must be longword-aligned! // actualBufferLength = (Length - FileName->Length - sizeof(UNICODE_STRING)) & ~(sizeof(PVOID)-1); fileNameString = (PUNICODE_STRING)( Buffer + actualBufferLength ); RtlCopyMemory( fileNameString + 1, FileName->Buffer, FileName->Length ); fileNameString->Length = FileName->Length; fileNameString->MaximumLength = FileName->Length; fileNameString->Buffer = (PWCH)(fileNameString + 1); } // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( FileHandle, NULL, &event, &iosb, &deviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the I/O. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_DIRECTORY_CONTROL; irpSp->MinorFunction = IRP_MN_QUERY_DIRECTORY; irpSp->Parameters.QueryDirectory.FileName = fileNameString; irpSp->Parameters.QueryDirectory.FileIndex = (ULONG)( ARGUMENT_PRESENT( FileIndex ) ? *FileIndex : 0 ); irpSp->Parameters.QueryDirectory.Length = actualBufferLength; irpSp->Parameters.QueryDirectory.FileInformationClass = FileInformationClass; // // Set the flags in the stack location. // irpSp->Flags = 0; if ( ARGUMENT_PRESENT( FileIndex ) ) { IF_DEBUG( SEARCH ) { KdPrint(("SrvIssueQueryDirectoryRequest: SL_INDEX_SPECIFIED\n" )); } irpSp->Flags |= SL_INDEX_SPECIFIED; } if ( RestartScan ) { IF_DEBUG( SEARCH ) { KdPrint(("SrvIssueQueryDirectoryRequest: SL_RESTART_SCAN\n" )); } irpSp->Flags |= SL_RESTART_SCAN; } if( SingleEntriesOnly ) { IF_DEBUG( SEARCH ) { KdPrint(("SrvIssueQueryDirectoryRequest: SL_RETURN_SINGLE_ENTRY\n" )); } irpSp->Flags |= SL_RETURN_SINGLE_ENTRY; } // // The file system has been updated. Determine whether the driver wants // buffered, direct, or "neither" I/O. // if ( (deviceObject->Flags & DO_BUFFERED_IO) != 0 ) { // // The file system wants buffered I/O. Pass the address of the // "system buffer" in the IRP. Note that we don't want the buffer // deallocated, nor do we want the I/O system to copy to a user // buffer, so we don't set the corresponding flags in irp->Flags. // irp->AssociatedIrp.SystemBuffer = Buffer; } else if ( (deviceObject->Flags & DO_DIRECT_IO) != 0 ) { // // The file system wants direct I/O. Allocate an MDL and lock the // buffer into memory. // mdl = IoAllocateMdl( Buffer, actualBufferLength, FALSE, FALSE, irp // stores MDL address in irp->MdlAddress ); if ( mdl == NULL ) { // // Unable to allocate an MDL. Fail the I/O. // IoFreeIrp( irp ); return STATUS_INSUFF_SERVER_RESOURCES; } try { MmProbeAndLockPages( mdl, KernelMode, IoWriteAccess ); } except( EXCEPTION_EXECUTE_HANDLER ) { IoFreeIrp( irp ); MmUnlockPages( mdl ); IoFreeMdl( mdl ); return GetExceptionCode(); } } else { // // The file system wants "neither" I/O. Simply pass the address // of the buffer. // // *** Note that if the file system decides to do this as buffered // I/O, it will be wasting nonpaged pool, since our buffer is // already in nonpaged pool. But since we're doing this as a // synchronous request, the file system probably won't do that. // irp->UserBuffer = Buffer; } // // Start the I/O, wait for it to complete, and return the final status. // return StartIoAndWait( irp, deviceObject, &event, &iosb ); } // SrvIssueQueryDirectoryRequest NTSTATUS SrvIssueQueryEaRequest ( IN HANDLE FileHandle, IN PVOID Buffer, IN ULONG Length, IN PVOID EaList OPTIONAL, IN ULONG EaListLength, IN BOOLEAN RestartScan, OUT PULONG EaErrorOffset OPTIONAL ) /*++ Routine Description: This function issues an I/O request packet for an EA query request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileHandle - handle to a file open with FILE_READ_EA access. Buffer - supplies the system virtual address of the buffer. The buffer must be in nonpaged pool. Length - supplies the length of the buffer. EaList - supplies a pointer to a list of EAs to query. If omitted, all EAs are returned. EaListLength - supplies the length of EaList. RestartScan - if TRUE, then the query of EAs is to start from the beginning. Otherwise, continue from where we left off. EaErrorOffset - if not NULL, returns the offset into EaList of an invalid EA, if any. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { NTSTATUS status; PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; PDEVICE_OBJECT deviceObject; PMDL mdl; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( FileHandle, NULL, &event, &iosb, &deviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the i/o. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_QUERY_EA; irpSp->MinorFunction = 0; irpSp->Parameters.QueryEa.Length = Length; irpSp->Parameters.QueryEa.EaList = EaList; irpSp->Parameters.QueryEa.EaListLength = EaListLength; irpSp->Parameters.QueryEa.EaIndex = 0L; irpSp->Flags = (UCHAR)( RestartScan ? SL_RESTART_SCAN : 0 ); // // The file system has been updated. Determine whether the // driver wants buffered, direct, or "neither" I/O. // if ( (deviceObject->Flags & DO_BUFFERED_IO) != 0 ) { // // The file system wants buffered I/O. Pass the address of the // "system buffer" in the IRP. Note that we don't want the buffer // deallocated, nor do we want the I/O system to copy to a user // buffer, so we don't set the corresponding flags in irp->Flags. // irp->AssociatedIrp.SystemBuffer = Buffer; } else if ( (deviceObject->Flags & DO_DIRECT_IO) != 0 ) { // // The file system wants direct I/O. Allocate an MDL and lock the // buffer into memory. // mdl = IoAllocateMdl( Buffer, Length, FALSE, FALSE, irp // stores MDL address in irp->MdlAddress ); if ( mdl == NULL ) { // // Unable to allocate an MDL. Fail the I/O. // IoFreeIrp( irp ); return STATUS_INSUFF_SERVER_RESOURCES; } try { MmProbeAndLockPages( mdl, KernelMode, IoWriteAccess ); } except( EXCEPTION_EXECUTE_HANDLER ) { IoFreeIrp( irp ); IoFreeMdl( mdl ); return GetExceptionCode(); } } else { // // The file system wants "neither" I/O. Simply pass the address // of the buffer. // // *** Note that if the file system decides to do this as buffered // I/O, it will be wasting nonpaged pool, since out buffer is // already in nonpaged pool. But since we're doing this as a // synchronous request, the file system probably won't do that. // irp->UserBuffer = Buffer; } // // Start the I/O, wait for it to complete, and return the final // status. // status = StartIoAndWait( irp, deviceObject, &event, &iosb ); if ( ARGUMENT_PRESENT(EaErrorOffset) ) { *EaErrorOffset = (ULONG)iosb.Information; } return status; } // SrvIssueQueryEaRequest NTSTATUS SrvIssueSendDatagramRequest ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN PTDI_CONNECTION_INFORMATION SendDatagramInformation, IN PVOID Buffer, IN ULONG Length ) /*++ Routine Description: This function issues an I/O request packet for a TDI Send Datagram request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - pointer to file object for an endpoint. DeviceObject - pointer to pointer to device object for an endpoint. SendDatagramInformation - pointer to a buffer describing the target of the datagram. Buffer - Supplies the system virtual address of the buffer. The buffer must be in nonpaged pool. Length - Supplies the length of the buffer. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; PTDI_REQUEST_KERNEL_SENDDG parameters; KEVENT event; IO_STATUS_BLOCK iosb; PMDL mdl; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the i/o. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); parameters = (PTDI_REQUEST_KERNEL_SENDDG)&irpSp->Parameters; irpSp->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL; irpSp->MinorFunction = TDI_SEND_DATAGRAM; parameters->SendLength = Length; parameters->SendDatagramInformation = SendDatagramInformation; // // The file system wants direct I/O. Allocate an MDL and lock the // buffer into memory. // mdl = IoAllocateMdl( Buffer, Length, FALSE, FALSE, irp // stores MDL address in irp->MdlAddress ); if ( mdl == NULL ) { // // Unable to allocate an MDL. Fail the I/O. // IoFreeIrp( irp ); return STATUS_INSUFF_SERVER_RESOURCES; } try { MmProbeAndLockPages( mdl, KernelMode, IoWriteAccess ); } except( EXCEPTION_EXECUTE_HANDLER ) { IoFreeIrp( irp ); IoFreeMdl( mdl ); return GetExceptionCode(); } // // Start the I/O, wait for it to complete, and return the final // status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueSendDatagramRequest NTSTATUS SrvIssueSetClientProcessRequest ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN PCONNECTION Connection, IN PVOID ClientSession, IN PVOID ClientProcess ) /*++ Routine Description: This function issues an I/O request packet for a named pipe Set Client Process file system control function. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - pointer to file object for a pipe. DeviceObject - pointer to pointer to device object for a pipe. ClientSession - A unique identifier for the client's session with the server. Assigned by the server. ClientProcess - A unique identifier for the client process. Assigned by the redirector. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; FILE_PIPE_CLIENT_PROCESS_BUFFER_EX clientIdBuffer; KEVENT event; IO_STATUS_BLOCK iosb; UNICODE_STRING unicodeString; NTSTATUS status; PAGED_CODE( ); // // Set the client ID in the FSCTL buffer. // clientIdBuffer.ClientSession = ClientSession; clientIdBuffer.ClientProcess = ClientProcess; // Set ClientComputerName in the buffer // The Rtl function terminates the string, so leave enough room unicodeString.Buffer = clientIdBuffer.ClientComputerBuffer; unicodeString.MaximumLength = (USHORT) ((FILE_PIPE_COMPUTER_NAME_LENGTH+1) * sizeof(WCHAR)); status = RtlOemStringToUnicodeString( &unicodeString, &Connection->OemClientMachineNameString, FALSE ); if (!NT_SUCCESS(status)) { // Set length to zero in case conversion fails unicodeString.Length = 0; } clientIdBuffer.ClientComputerNameLength = unicodeString.Length; // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the i/o. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_FILE_SYSTEM_CONTROL; irpSp->MinorFunction = IRP_MN_KERNEL_CALL; irpSp->Parameters.FileSystemControl.OutputBufferLength = 0; irpSp->Parameters.FileSystemControl.InputBufferLength = sizeof( clientIdBuffer ); irpSp->Parameters.FileSystemControl.FsControlCode = FSCTL_PIPE_SET_CLIENT_PROCESS; irp->MdlAddress = NULL; irp->AssociatedIrp.SystemBuffer = &clientIdBuffer; irp->Flags |= IRP_BUFFERED_IO; irp->UserBuffer = NULL; // // Start the I/O, wait for it to complete, and return the final // status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueSetClientProcessRequest NTSTATUS SrvIssueSetEaRequest ( IN HANDLE FileHandle, IN PVOID Buffer, IN ULONG Length, OUT PULONG EaErrorOffset OPTIONAL ) /*++ Routine Description: This function issues an I/O request packet for an EA set request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. WARNING! The server must walk the list of EAs to set if it comes directly from a client. This is because the file system trusts that this list is legitimate and could run into problems if the list has an error. Arguments: FileHandle - handle to a file open with FILE_WRITE_EA access. Buffer - Supplies the system virtual address of the buffer. The buffer must be in nonpaged pool. Length - Supplies the length of the buffer. EaErrorOffset - if not NULL, returns the offset into EaList of an invalid EA, if any. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { NTSTATUS status; PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; PDEVICE_OBJECT deviceObject; PMDL mdl; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( FileHandle, NULL, &event, &iosb, &deviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the i/o. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_SET_EA; irpSp->MinorFunction = 0; irpSp->Parameters.SetEa.Length = Length; irpSp->Flags = 0; // // The file system has been updated. Determine whether the driver // wants buffered, direct, or "neither" I/O. // if ( (deviceObject->Flags & DO_BUFFERED_IO) != 0 ) { // // The file system wants buffered I/O. Pass the address of the // "system buffer" in the IRP. Note that we don't want the buffer // deallocated, nor do we want the I/O system to copy to a user // buffer, so we don't set the corresponding flags in irp->Flags. // irp->AssociatedIrp.SystemBuffer = Buffer; } else if ( (deviceObject->Flags & DO_DIRECT_IO) != 0 ) { // // The file system wants direct I/O. Allocate an MDL and lock the // buffer into memory. // mdl = IoAllocateMdl( Buffer, Length, FALSE, FALSE, irp // stores MDL address in irp->MdlAddress ); if ( mdl == NULL ) { // // Unable to allocate an MDL. Fail the I/O. // IoFreeIrp( irp ); return STATUS_INSUFF_SERVER_RESOURCES; } try { MmProbeAndLockPages( mdl, KernelMode, IoWriteAccess ); } except( EXCEPTION_EXECUTE_HANDLER ) { IoFreeIrp( irp ); IoFreeMdl( mdl ); return GetExceptionCode(); } } else { // // The file system wants "neither" I/O. Simply pass the address // of the buffer. // // *** Note that if the file system decides to do this as buffered // I/O, it will be wasting nonpaged pool, since our buffer is // already in nonpaged pool. But since we're doing this as a // synchronous request, the file system probably won't do that. // irp->UserBuffer = Buffer; } // // Start the I/O, wait for it to complete, and return the final // status. // status = StartIoAndWait( irp, deviceObject, &event, &iosb ); if ( ARGUMENT_PRESENT(EaErrorOffset) ) { *EaErrorOffset = (ULONG)iosb.Information; } return status; } // SrvIssueSetEaRequest NTSTATUS SrvIssueSetEventHandlerRequest ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN ULONG EventType, IN PVOID EventHandler, IN PVOID EventContext ) /*++ Routine Description: This function issues an I/O request packet for a TdiSetEventHandler request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - pointer to file object for a connection. DeviceObject - pointer to pointer to device object for a connection. EventType - EventHandler - EventContext - Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; PTDI_REQUEST_KERNEL_SET_EVENT parameters; KEVENT event; IO_STATUS_BLOCK iosb; PDEVICE_OBJECT deviceObject = NULL; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the I/O. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); parameters = (PTDI_REQUEST_KERNEL_SET_EVENT)&irpSp->Parameters; irpSp->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL; irpSp->MinorFunction = TDI_SET_EVENT_HANDLER; parameters->EventType = EventType; parameters->EventHandler = EventHandler; parameters->EventContext = EventContext; // // Start the I/O, wait for it to complete, and return the final status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueSetEventHandlerRequest NTSTATUS SrvIssueUnlockRequest ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN UCHAR UnlockOperation, IN LARGE_INTEGER ByteOffset, IN LARGE_INTEGER Length, IN ULONG Key ) /*++ Routine Description: This function issues an I/O request packet for an unlock request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - Pointer to the file object. DeviceObject - Pointer to pointer to the related device object. UnlockOperation - the minor function code describing the unlock operation -- IRP_MN_UNLOCK_SINGLE or IRP_MN_UNLOCK_ALL_BY_KEY. StartingBlock - the block number of the beginning of the locked range. Ignored if UnlockOperation is IRP_MN_UNLOCK_ALL_BY_KEY. ByteOffset - the offset within block of the beginning of the locked range. Ignored if UnlockOperation is IRP_MN_UNLOCK_ALL_BY_KEY. Length - the length of the locked range. Ignored if UnlockOperation is IRP_MN_UNLOCK_ALL_BY_KEY. Key - the key value used to obtain the lock. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; PFAST_IO_DISPATCH fastIoDispatch; PAGED_CODE( ); // // Try the turbo unlock path first. // fastIoDispatch = (*DeviceObject)->DriverObject->FastIoDispatch; if ( fastIoDispatch != NULL ) { if ( (UnlockOperation == IRP_MN_UNLOCK_SINGLE) && (fastIoDispatch->FastIoUnlockSingle != NULL) ) { INCREMENT_DEBUG_STAT2( SrvDbgStatistics.FastUnlocksAttempted ); if ( fastIoDispatch->FastIoUnlockSingle( FileObject, &ByteOffset, &Length, IoGetCurrentProcess(), Key, &iosb, *DeviceObject ) ) { return iosb.Status; } INCREMENT_DEBUG_STAT2( SrvDbgStatistics.FastUnlocksFailed ); } else if ( (UnlockOperation == IRP_MN_UNLOCK_ALL_BY_KEY) && (fastIoDispatch->FastIoUnlockAllByKey != NULL) ) { INCREMENT_DEBUG_STAT2( SrvDbgStatistics.FastUnlocksAttempted ); if ( fastIoDispatch->FastIoUnlockAllByKey( FileObject, IoGetCurrentProcess(), Key, &iosb, *DeviceObject ) ) { return iosb.Status; } INCREMENT_DEBUG_STAT2( SrvDbgStatistics.FastUnlocksFailed ); } } // // The turbo path failed or was unavailable. Allocate an IRP and // fill in the service-independent parameters for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the i/o. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_LOCK_CONTROL; irpSp->MinorFunction = UnlockOperation; irpSp->Parameters.LockControl.Length = &Length; irpSp->Parameters.LockControl.Key = Key; irpSp->Parameters.LockControl.ByteOffset = ByteOffset; // // Start the I/O, wait for it to complete, and return the final // status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueUnlockRequest NTSTATUS SrvIssueUnlockSingleRequest ( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN LARGE_INTEGER ByteOffset, IN LARGE_INTEGER Length, IN ULONG Key ) /*++ Routine Description: This function issues an I/O request packet for an unlock single request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileObject - Pointer to the file object. DeviceObject - Pointer to pointer to the related device object. StartingBlock - the block number of the beginning of the locked range. Ignored if UnlockOperation is IRP_MN_UNLOCK_ALL_BY_KEY. ByteOffset - the offset within block of the beginning of the locked range. Ignored if UnlockOperation is IRP_MN_UNLOCK_ALL_BY_KEY. Length - the length of the locked range. Ignored if UnlockOperation is IRP_MN_UNLOCK_ALL_BY_KEY. Key - the key value used to obtain the lock. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent // parameters for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the i/o. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_LOCK_CONTROL; irpSp->MinorFunction = IRP_MN_UNLOCK_SINGLE; irpSp->Parameters.LockControl.Length = &Length; irpSp->Parameters.LockControl.Key = Key; irpSp->Parameters.LockControl.ByteOffset = ByteOffset; // // Start the I/O, wait for it to complete, and return the final // status. // return StartIoAndWait( irp, *DeviceObject, &event, &iosb ); } // SrvIssueUnlockSingleRequest NTSTATUS SrvIssueWaitForOplockBreak ( IN HANDLE FileHandle, PWAIT_FOR_OPLOCK_BREAK WaitForOplockBreak ) /*++ Routine Description: This function issues an I/O request packet for a wait for oplock break request. It builds an I/O request packet, passes the IRP to the driver (using IoCallDriver), and waits for the I/O to complete. Arguments: FileHandle - handle to a file. WaitForOplockBreak - Context information for this wait for oplock break. Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; PDEVICE_OBJECT deviceObject; NTSTATUS status; KIRQL oldIrql; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( FileHandle, NULL, &event, &iosb, &deviceObject ); if (irp == NULL) { // // Unable to allocate an IRP. Fail the i/o. // return STATUS_INSUFF_SERVER_RESOURCES; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_FILE_SYSTEM_CONTROL; irpSp->MinorFunction = 0; irpSp->Parameters.FileSystemControl.OutputBufferLength = 0; irpSp->Parameters.FileSystemControl.InputBufferLength = 0; irpSp->Parameters.FileSystemControl.FsControlCode = FSCTL_OPLOCK_BREAK_NOTIFY; // // Queue the WaitForOplockBreak block on the global list. // // We must hold the lock that protects wait for oplock breaks // from the time we queue this wait for oplock break on the global // list, to the time the IRP has actually been submitted. Otherwise // the scavenger might wake up and attempt to cancel an IRP that // has not yet been submitted. // WaitForOplockBreak->Irp = irp; ACQUIRE_LOCK( &SrvOplockBreakListLock ); SrvInsertTailList( &SrvWaitForOplockBreakList, &WaitForOplockBreak->ListEntry ); // // The following code is a duplicate of the code from StartIoAndWait(). // // Start the I/O, wait for it to complete, and return the final // status. // // // Queue the IRP to the thread and pass it to the driver. // IoQueueThreadIrp( irp ); status = IoCallDriver( deviceObject, irp ); RELEASE_LOCK( &SrvOplockBreakListLock ); // // If necessary, wait for the I/O to complete. // if ( status == STATUS_PENDING ) { KeWaitForSingleObject( &event, UserRequest, KernelMode, // don't let stack be paged -- event is on stack! FALSE, NULL ); } // // If the request was successfully queued, get the final I/O status. // if ( NT_SUCCESS(status) ) { status = iosb.Status; } return status; } // SrvIssueWaitForOplockBreak VOID SrvQuerySendEntryPoint( IN PFILE_OBJECT FileObject, IN PDEVICE_OBJECT *DeviceObject, IN ULONG IoControlCode, IN PVOID *EntryPoint ) /*++ Routine Description: This function queries the transport for its send entry point. Arguments: FileObject - pointer to file object for a connection. DeviceObject - pointer to pointer to device object for a connection. EntryPoint - Return Value: NTSTATUS - the status of the operation. Either the return value of IoCallDriver, if the driver didn't accept the request, or the value returned by the driver in the I/O status block. --*/ { PIRP irp; PIO_STACK_LOCATION irpSp; KEVENT event; IO_STATUS_BLOCK iosb; NTSTATUS status; PAGED_CODE( ); // // Allocate an IRP and fill in the service-independent parameters // for the request. // irp = BuildCoreOfSyncIoRequest( NULL, FileObject, &event, &iosb, DeviceObject ); if ( irp == NULL ) { // // Unable to allocate an IRP. Fail the I/O. // *EntryPoint = NULL; return; } // // Fill in the service-dependent parameters for the request. // irpSp = IoGetNextIrpStackLocation( irp ); irpSp->MajorFunction = IRP_MJ_DEVICE_CONTROL; irpSp->MinorFunction = 0; irpSp->Parameters.DeviceIoControl.IoControlCode = IoControlCode; irpSp->Parameters.DeviceIoControl.Type3InputBuffer = EntryPoint; // // Start the I/O, wait for it to complete, and return the final status. // status = StartIoAndWait( irp, *DeviceObject, &event, &iosb ); if ( !NT_SUCCESS(status) ) { *EntryPoint = NULL; } return; } // SrvQuerySendEntryPoint
27.07205
94
0.608223
1341277756b6992bad602366d60b034ecc3e9fb9
2,184
lua
Lua
doc/extract_doc.lua
LuaDist-testing/lua-xmlreader
00ef07503b45c37e584ccb6ccc512a4581751a9f
[ "MIT" ]
2
2017-08-04T11:08:49.000Z
2019-03-10T20:02:41.000Z
doc/extract_doc.lua
LuaDist-testing/lua-xmlreader
00ef07503b45c37e584ccb6ccc512a4581751a9f
[ "MIT" ]
null
null
null
doc/extract_doc.lua
LuaDist-testing/lua-xmlreader
00ef07503b45c37e584ccb6ccc512a4581751a9f
[ "MIT" ]
4
2017-12-16T23:45:05.000Z
2022-01-14T10:41:18.000Z
modules={} function module(name) if modules[name] then current_module=modules[name] else current_module={name=name, description=""} modules[#modules+1]=name modules[name]=current_module end current_obj=current_module end function signature(name) current_obj = {name=name, params={}, returns={}} current_module[#current_module+1]=current_obj end function description(str) current_obj.description=str end function param(name, desc) current_obj.params[#current_obj.params+1]=name current_obj.params[name]=desc end function returns(name, desc) current_obj.returns[#current_obj.returns+1]=name current_obj.returns[name]=desc end local fn = arg[1] assert(fn, "Usage: extract_doc filename") local lines={} local in_lua = false for line in io.lines(fn) do if line:match("^%?%*/") then in_lua = false end lines[#lines+1] = in_lua and line or "" if line:match("^/%*%?lua") then in_lua = true end end assert(loadstring(table.concat(lines, "\n")))() function fwrite(fmt, ...) io.write(fmt:format(...)) end table.sort(modules) fwrite([[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <title>%s</title> <link rel="stylesheet" href="doc_style.css" type="text/css" /> </head> <body> ]], lib_name) for _,n in ipairs(modules) do local m = modules[n] fwrite("<h1>%s</h1>\n<p>%s</p>\n", m.name, m.description) fwrite("<dl class=\"function\">\n") for _,f in ipairs(m) do fwrite("<dt>%s</dt>\n", f.name) fwrite("<dd>\n%s\n", f.description) if (#f.params > 0) then fwrite("<h3>Parameters</h3>\n") fwrite("<ul>\n") for i,p in ipairs(f.params) do fwrite("<li>%s: %s</li>\n", p, f.params[p]) end fwrite("</ul>\n") end if (#f.returns > 0) then fwrite("<h3>Return values</h3>\n") fwrite("<ol>\n") for i,r in ipairs(f.returns) do fwrite("<li>%s: %s</li>\n", r, f.returns[r]) end fwrite("</ol>\n") end fwrite("</dd>\n") end fwrite("</dl>\n") end fwrite("</body>") fwrite("</html>")
23.483871
67
0.628663
bcba0bcd6830246d99c81921b335eee871f2c4d9
1,937
js
JavaScript
src/pages/index.js
fune0/portfolio
5a86c4b7ac2c13483b1a503664d8086af24408de
[ "MIT" ]
null
null
null
src/pages/index.js
fune0/portfolio
5a86c4b7ac2c13483b1a503664d8086af24408de
[ "MIT" ]
4
2021-09-21T00:20:49.000Z
2022-02-26T11:27:39.000Z
src/pages/index.js
fune0/portfolio
5a86c4b7ac2c13483b1a503664d8086af24408de
[ "MIT" ]
null
null
null
import React from "react" import Layout from "../components/layout/index" import Image from "../components/image" import SEO from "../components/seo" import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faGithub, faTwitter, faWordpressSimple } from '@fortawesome/free-brands-svg-icons' const IndexPage = () => ( <Layout> <SEO title="Home" /> <div id="wrap"> <div className="container"> <div className="column" style={{ maxWidth: '200px', marginBottom: '1.45rem'}}> <Image filename="fune0icon.png" alt="フネオ"/> </div> <div class="profile"> <h4>Fune0</h4> <h4>Web Engineer/Director</h4> </div> <div className="message" style={{marginBottom: 50,}}> <h3 style={{textAlign: 'center',}}>Hello, SHIBUYA!</h3> <p style={{textAlign: 'center'}}>I live in Shibuya ward to enjoy solitude.</p> <p style={{textAlign: 'center'}}>But I sometimes feel lonely.</p> </div> <div className="snsicon"> <span className="btn-social github"> <a href="https://github.com/fune0"> <FontAwesomeIcon color="#333" size='2x' icon={faGithub} /> </a> </span> <span className="btn-social twiiter"> <a href=""> <FontAwesomeIcon color="#3eaded" size='2x' icon={faTwitter} /> </a> </span> <span className="btn-social wordpress"> <a href=""> <FontAwesomeIcon color="#23282d" size='2x' icon={faWordpressSimple} /> </a> </span> <p style={{textAlign: 'center'}}>Please contact me</p> </div> </div> </div> </Layout> ) export default IndexPage
27.671429
91
0.508002
3923622e878f882480926b6d3b8ec69a597cf96a
128
sql
SQL
engine/tests/test_files/sql/one_statement_with_comments.sql
paulana/Elgg
2535fb6eeca635d7bca2fdd0f5dbfdb7c4c2185f
[ "MIT" ]
1,090
2015-01-08T23:46:03.000Z
2022-03-31T00:52:22.000Z
engine/tests/test_files/sql/one_statement_with_comments.sql
paulana/Elgg
2535fb6eeca635d7bca2fdd0f5dbfdb7c4c2185f
[ "MIT" ]
4,918
2015-01-01T00:59:12.000Z
2022-03-31T14:05:53.000Z
engine/tests/test_files/sql/one_statement_with_comments.sql
paulana/Elgg
2535fb6eeca635d7bca2fdd0f5dbfdb7c4c2185f
[ "MIT" ]
513
2015-01-03T21:27:59.000Z
2022-03-15T16:50:04.000Z
-- This is the first comment INSERT INTO prefix_sometable (`key`) VALUES ('Value -- not a comment'); -- This is another comment
32
71
0.71875
d253924d3b42d2da44471e627835eb2f7e079a9f
9,508
php
PHP
controllers/SiteController.php
yuralyashkov/beicon
c0f77a17181729f2b52eff5a6e92ba8b069f85b7
[ "BSD-3-Clause" ]
null
null
null
controllers/SiteController.php
yuralyashkov/beicon
c0f77a17181729f2b52eff5a6e92ba8b069f85b7
[ "BSD-3-Clause" ]
null
null
null
controllers/SiteController.php
yuralyashkov/beicon
c0f77a17181729f2b52eff5a6e92ba8b069f85b7
[ "BSD-3-Clause" ]
null
null
null
<?php namespace app\controllers; use app\models\forms\Subscribe; use app\models\Meta; use app\models\Sitemap; use Bitrix\Main\Context\Site; use Yii; use yii\filters\AccessControl; use yii\web\Controller; use yii\web\HttpException; use yii\web\Response; use yii\filters\VerbFilter; use app\models\LoginForm; use app\models\ContactForm; use app\models\Articles; use app\models\Rss; use app\models\ImageSizes; use yii\helpers\Url; class SiteController extends Controller { public function actionRss($url){ Yii::$app->response->format = \yii\web\Response::FORMAT_RAW; $headers = Yii::$app->response->headers; $headers->add('Content-Type', 'text/xml'); $rss = Rss::find()->where(['url' => $url])->with('articles')->one(); if($rss->active == 1) { $sitemap = new Sitemap; if ($rss) { $array = []; foreach ($rss->articles as $article) { // $article->content = str_replace('[[BANNER_BLOCK]]', \Yii::$app->view->renderFile('@app/views/articles/banerBlock.php'), $model->content); $article->content = str_replace('files/', Url::to('/', true).'basic/web/files/', $article->content); if(preg_match_all("/{{GALLERY=\d+}}/", $article->content, $matches) || preg_match_all("/{{GALLERY=\d+}}/", $article->preview_content, $matches)) { $matches = $matches[0]; foreach ($matches as $shortcode) { $article->content = str_replace($shortcode, '', $article->content); } } $article->content = preg_replace('/<iframe.*?\/iframe>/i','', $article->content); $article->content = preg_replace('/<script.*?\/script>/i','', $article->content); $fields = [ 'link' => Url::to(['articles/view', 'url' => $article->url, 'section' => $article->sectionData->url]), 'title' => $article->name, 'pubDate' => date(DATE_RFC822, strtotime($article->date_publish)), 'content' => $article->content ]; if($article->preview_img) $fields['img'] = $article->preview_img; if($article->publisher->role != 'admin') $fields['author'] = $article->publisher->name; if($article->other_author != '') $fields["author"] = $article->other_author; $array[] = $fields; } $xml = $sitemap->getRss($array, $rss->name); } // print_r($array); return $xml; } } //Карта сайта. Выводит в виде XML файла. public function actionSitemap(){ // \Yii::$app->response->format = Response::FORMAT_XML; $sitemap = new Sitemap(); //Если в кэше нет карты сайта // if (!$xml_sitemap = Yii::$app->cache->get('sitemap')) { //Получаем мыссив всех ссылок $urls = $sitemap->getUrl(); //Формируем XML файл $xml_sitemap = $sitemap->getXml($urls); // кэшируем результат // Yii::$app->cache->set('sitemap', $xml_sitemap, 3600*12); // } //Выводим карту сайта Yii::$app->response->format = \yii\web\Response::FORMAT_RAW; $headers = Yii::$app->response->headers; $headers->add('Content-Type', 'text/xml'); return $sitemap->showXml($xml_sitemap); } public function actionRobots(){ Yii::$app->response->format = \yii\web\Response::FORMAT_RAW; $headers = Yii::$app->response->headers; $headers->add('Content-Type', 'text/plain'); $robots = Meta::find()->where(['keyname' => 'robots'])->one(); if($robots){ return $robots["value"]; } else return ''; } /** * {@inheritdoc} */ public function behaviors() { return [ // 'access' => [ // 'class' => AccessControl::className(), // 'only' => ['logout'], // 'rules' => [ // [ // 'actions' => ['logout'], // 'allow' => true, // 'roles' => ['@'], // ], // ], // ], // 'verbs' => [ // 'class' => VerbFilter::className(), // 'actions' => [ // 'logout' => ['post'], // ], // ], 'corsFilter' => [ 'class' => \yii\filters\Cors::className(), 'cors' => [ 'Origin' => ['*', 'http://bi.verworren.net'], 'Access-Control-Request-Method' => ['POST', 'GET','PUT','DELETE','PATCH','OPTIONS'], 'Access-Control-Allow-Credentials' => true, 'Access-Control-Request-Headers' => ['*'], 'Access-Control-Max-Age' => 3600, // Cache (seconds) 'Access-Control-Expose-Headers' => ['*'], 'Access-Control-Allow-Origin' => ['*', 'http://bi.verworren.net'], ] ] ]; } /** * {@inheritdoc} */ public function actions() { return [ 'error' => [ 'class' => 'yii\web\ErrorAction', ], 'captcha' => [ 'class' => 'yii\captcha\CaptchaAction', 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null, ], ]; } public function actionAjaxSubscribe() { if (Yii::$app->request->isAjax) { $model = new Subscribe(); if ($model->load(Yii::$app->request->post())) { Yii::$app->response->format = yii\web\Response::FORMAT_JSON; return \yii\widgets\ActiveForm::validate($model); } } else { throw new HttpException(404 ,'Page not found'); } } /** * Displays homepage. * * @return string */ public function actionIndex() { $articles = Articles::find()->where(['show_on_main' => 1, 'status' => 'publish'])->andWhere(['<=', 'date_publish', date('Y-m-d H:i:s')])->orderBy(['date_publish' => SORT_DESC])->limit(25)->all(); // $articles = Articles::find()->where(['show_on_main' => 1, 'status' => 'publish'])->orderBy(['date_publish' => SORT_DESC])->orderBy('main_sort')->limit(17)->all(); $recomended = Articles::find()->where(['status' => 'publish', 'choise' => 1])->andWhere(['<=', 'date_publish', date('Y-m-d H:i:s')])->orderBy(['date_publish' => SORT_DESC])->limit(10)->all(); if($recomended) { foreach ($recomended as $k => $value) { if ($value->preview_img) { $recomended[$k]->preview_img = ImageSizes::getResizesName($value->preview_img, '1_1_352_exact'); } if ($value->header_img) { $recomended[$k]->header_img = ImageSizes::getResizesName($value->header_img, '1_1_352_exact'); } } } return $this->render('index', [ 'head_articles' => $articles, 'recomended' => $recomended ]); } /** * Login action. * * @return Response|string */ public function actionLogin() { if (!Yii::$app->user->isGuest) { return $this->goHome(); } $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->login()) { return $this->goBack(); } $model->password = ''; return $this->render('login', [ 'model' => $model, ]); } public function actionAddAdmin() { $model = User::find()->where(['username' => 'admin'])->one(); if (empty($model)) { $user = new User(); $user->username = 'admin'; $user->email = 'admin@кодер.укр'; $user->setPassword('admin'); $user->generateAuthKey(); if ($user->save()) { echo 'good'; } } } /** * Logout action. * * @return Response */ public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } /** * Displays contact page. * * @return Response|string */ public function actionContact() { $model = new ContactForm(); if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) { Yii::$app->session->setFlash('contactFormSubmitted'); return $this->refresh(); } return $this->render('contact', [ 'model' => $model, ]); } /** * Displays about page. * * @return string */ public function actionAbout() { return $this->render('about'); } }
33.361404
204
0.457089
a1c647e106dda8e524c0cfd63476275a556b6ac5
341
h
C
SwiftFramework/SLPCommon.framework/Headers/SLPSleepaceMusicInfo.h
sunderlow/SwiftFramework
97f805851934395cb713acf0beee04dcdab9a8ea
[ "MIT" ]
1
2020-09-25T01:02:17.000Z
2020-09-25T01:02:17.000Z
SwiftFramework/SLPCommon.framework/Headers/SLPSleepaceMusicInfo.h
sunderlow/SwiftFramework
97f805851934395cb713acf0beee04dcdab9a8ea
[ "MIT" ]
null
null
null
SwiftFramework/SLPCommon.framework/Headers/SLPSleepaceMusicInfo.h
sunderlow/SwiftFramework
97f805851934395cb713acf0beee04dcdab9a8ea
[ "MIT" ]
null
null
null
// // SLPSleepaceMusicInfo.h // SDK // // Created by Martin on 2018/3/1. // Copyright © 2018年 Martin. All rights reserved. // #import <Foundation/Foundation.h> @interface SLPSleepaceMusicInfo : NSObject @property (nonatomic, assign) UInt16 musicID;//音乐ID @property (nonatomic, assign) UInt8 playMode;//播放模式 0:顺序播放 1: 随机播放 2: 单曲播放 @end
22.733333
74
0.721408
d25cd28e249fd0dc17efd5c8c64ea85e8ee32ab3
7,604
php
PHP
application/views/php_decode.php
YAJIMA/code-toolbox
c48f76945e9539f75fdaf2d5bbe820058403ac54
[ "MIT" ]
null
null
null
application/views/php_decode.php
YAJIMA/code-toolbox
c48f76945e9539f75fdaf2d5bbe820058403ac54
[ "MIT" ]
null
null
null
application/views/php_decode.php
YAJIMA/code-toolbox
c48f76945e9539f75fdaf2d5bbe820058403ac54
[ "MIT" ]
null
null
null
<?php /** * Created by PhpStorm. * User: yajima * Date: 2018-8月-29 * Time: 1:40 */ ?> <div class="container-fluid"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <nav class="nav nav-sidebar"> <li><a href="<?php echo base_url('php/date'); ?>">日付変換</a></li> <li><a href="<?php echo base_url('php/decode'); ?>">テキスト変換</a></li> <li><a href="<?php echo base_url('php/mailencode'); ?>">メールエンコード</a></li> <li><a href="<?php echo base_url('php/crypt'); ?>">Crypt変換</a></li> <li><a href="<?php echo base_url('php/pregmatch'); ?>">正規表現 - pregmatch</a></li> <li><a href="<?php echo base_url('php/kakunin'); ?>">接続環境の確認</a></li> </nav> <a href="https://px.a8.net/svt/ejp?a8mat=2HFF0A+B7NWXE+7YE+67RK1" target="_blank" rel="nofollow"> <img border="0" width="160" height="600" alt="" src="https://www25.a8.net/svt/bgt?aid=150205114678&wid=001&eno=01&mid=s00000001031001044000&mc=1"></a> <img border="0" width="1" height="1" src="https://www18.a8.net/0.gif?a8mat=2HFF0A+B7NWXE+7YE+67RK1" alt=""> </div> <div class="col-sm-9 col-sm-offset-3 col-md-10 col-md-offset-2 main"> <h1 class="page-header">テキスト変換</h1> <?php echo form_open('php/decode',array('class'=>'form')); ?> <div class="row"> <div class="col-md-5"> <div class="form-group"> <label for="orgtext" class="control-label">変換元のテキスト</label> <textarea name="orgtext" id="orgtext" rows="6" class="form-control"><?php echo $orgtext; ?></textarea> </div> </div> <div class="col-md-2"> <label for="mode" class="control-label">変換種別</label> <button type="submit" name="mode" value="md5" class="btn btn-sm btn-block btn-default <?php echo ($active == "md5") ? 'active' : ''; ?>">MD5</button> <button type="submit" name="mode" value="sha1" class="btn btn-sm btn-block btn-default <?php echo ($active == "sha1") ? 'active' : ''; ?>">SHA1</button> <button type="submit" name="mode" value="base64_encode" class="btn btn-sm btn-block btn-default <?php echo ($active == "base64_encode") ? 'active' : ''; ?>">BASE64エンコード</button> <button type="submit" name="mode" value="base64_decode" class="btn btn-sm btn-block btn-default <?php echo ($active == "base64_decode") ? 'active' : ''; ?>">BASE64デコード</button> <button type="submit" name="mode" value="urlencode" class="btn btn-sm btn-block btn-default <?php echo ($active == "urlencode") ? 'active' : ''; ?>">URLエンコード</button> <button type="submit" name="mode" value="urldecode" class="btn btn-sm btn-block btn-default <?php echo ($active == "urldecode") ? 'active' : ''; ?>">URLデコード</button> <button type="submit" name="mode" value="serialize" class="btn btn-sm btn-block btn-default <?php echo ($active == "serialize") ? 'active' : ''; ?>">serialize</button> <button type="submit" name="mode" value="unserialize" class="btn btn-sm btn-block btn-default <?php echo ($active == "unserialize") ? 'active' : ''; ?>">unserialize</button> <button type="submit" name="mode" value="json_encode" class="btn btn-sm btn-block btn-default <?php echo ($active == "json_encode") ? 'active' : ''; ?>">JSONエンコード</button> <button type="submit" name="mode" value="json_decode" class="btn btn-sm btn-block btn-default <?php echo ($active == "json_decode") ? 'active' : ''; ?>">JSONデコード</button> <button type="submit" name="mode" value="reverse" class="btn btn-link">テキスト入替 <span class="glyphicon glyphicon-transfer"></span></button> </div> <div class="col-md-5"> <label for="result" class="control-label">変換結果テキスト</label> <textarea name="result" id="result" rows="6" class="form-control"><?php echo $result; ?></textarea> </div> </div> <?php echo form_close(); ?> <div class="row"> <div class="col-md-12"> <table class="table table-striped table-bordered"> <caption>テキスト変換</caption> <thead> <tr> <th style="width:18rem;">変換種別</th> <th>説明</th> </tr> </thead> <tbody> <tr> <td>MD5</td> <td>MD5メッセージダイジェストアルゴリズム を用いてテキストの MD5 ハッシュ値を計算し、 そのハッシュを返します。<br> 32 文字の 16 進数からなるハッシュを返します。</td> </tr> <tr> <td>SHA1</td> <td>US Secure Hash Algorithm 1 を使用してテキストの sha1 ハッシュを計算します。<br> 返り値は40文字の16進数となります。</td> </tr> <tr> <td>BASE64エンコード</td> <td>MIME base64 方式でデータをエンコードします。<br> Base64 でエンコードされたデータは、エンコード前のデータにくらべて 33% 余計に容量が必要です。</td> </tr> <tr> <td>BASE64デコード</td> <td>MIME base64 方式によりエンコードされたデータをデコードします。</td> </tr> <tr> <td>URLエンコード</td> <td>文字列を URL エンコードします。<br> -_. を除くすべての非英数文字が % 記号 (%)に続く二桁の数字で置き換えられ、 空白は + 記号(+)にエンコードされます。</td> </tr> <tr> <td>URLデコード</td> <td>URL エンコードされた文字列をデコードします。<br> 与えられた文字列中のあらゆるエンコード文字 %## をデコードします。 プラス記号 ('+') は、スペース文字にデコードします。</td> </tr> <tr> <td>serialize</td> <td>値の保存可能な表現を生成します。<br> 型や構造を失わずに PHP の値を保存または渡す際に有用です。</td> </tr> <tr> <td>unserialize</td> <td>保存用表現から PHP の値を生成します。</td> </tr> <tr> <td>JSONエンコード</td> <td>テキストを JSON 形式にして返します。</td> </tr> <tr> <td>JSONデコード</td> <td>JSON 文字列をデコードします。</td> </tr> </tbody> </table> </div> </div> <div class="row"> <script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script> <!-- code.hatchbit.jp.001 --> <ins class="adsbygoogle" style="display:block" data-ad-client="ca-pub-6204628612026249" data-ad-slot="4581966295" data-ad-format="auto"></ins> <script> (adsbygoogle = window.adsbygoogle || []).push({}); </script> </div> </div> </div> </div>
58.045802
197
0.451341
e4f08db0e34aa31236ce2365683acf553e5618b3
2,496
swift
Swift
Sources/ALPopup/Source.swift
isaranjha/ALPopup
918f4bbb84015cb53fb0a9815ed96257f601106f
[ "MIT" ]
43
2021-08-16T14:19:12.000Z
2022-03-07T07:07:42.000Z
Sources/ALPopup/Source.swift
isaranjha/ALPopup
918f4bbb84015cb53fb0a9815ed96257f601106f
[ "MIT" ]
4
2021-09-26T12:48:20.000Z
2021-11-06T01:11:54.000Z
Sources/ALPopup/Source.swift
isaranjha/ALPopup
918f4bbb84015cb53fb0a9815ed96257f601106f
[ "MIT" ]
3
2021-08-23T10:30:20.000Z
2022-01-02T18:05:46.000Z
// The MIT License (MIT) // // Copyright (c) 2021 Alexandr Guzenko (alxrguz@icloud.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit enum Source { static var bundle: Bundle { // If installed via SPM, will be available bundle .module. #if ALPOPUP_SPM return .module #else // If installed via Cocoapods, should use bundle from podspec. let path = Bundle(for: ALPopup.self).path(forResource: "ALPopup", ofType: "bundle") ?? "" let bundle = Bundle(path: path) ?? Bundle.main return bundle #endif } enum Color { static var contentColor: UIColor { .init(light: .init(hex: "fff"), dark: .init(hex: "1C1C1E")) } static var accent: UIColor { .init(hex: "237EF0") } static var overlayAccentColor: UIColor { .init(hex: "fff") } static var labelPrimary: UIColor { .init(light: .init(hex: "000"), dark: .init(hex: "fff")) } static var labelSecondary: UIColor { .init(light: .init(hex: "#3C3C43", alpha: 0.6), dark: .init(hex: "#EBEBF5", alpha: 0.6)) } } enum Image { static var smallCloseButton: UIImage? { UIImage(named: "smallCloseButton", in: bundle, compatibleWith: nil)?.withRenderingMode(.alwaysOriginal) } } }
35.15493
115
0.634215
5520a96c3b6996e73430847e51bee3c79a648101
741
asm
Assembly
oeis/000/A000501.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/000/A000501.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/000/A000501.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A000501: a(n) = floor(cosh(n)). ; Submitted by Christian Krause ; 1,1,3,10,27,74,201,548,1490,4051,11013,29937,81377,221206,601302,1634508,4443055,12077476,32829984,89241150,242582597,659407867,1792456423,4872401723,13244561064,36002449668,97864804714,266024120300,723128532145,1965667148572,5343237290762,14524424832623,39481480091340,107321789892958,291730871263727,793006726156715,2155615773557597,5859571186401305,15927965878556878,43296700211996873,117692633418509992,319921746765027474,869637470760250523,2363919734114673280,6425800057179654137 mov $1,1 mov $3,$0 mul $3,4 mov $5,1 lpb $3 mul $1,$3 mov $4,$0 cmp $4,0 add $0,$4 div $1,$0 add $2,$1 sub $3,1 lpe div $2,2 cmp $5,0 cmp $5,0 add $2,$5 div $2,$1 mov $0,$2
30.875
486
0.778677
9ae7fe8faf6fcf4efc9c6563179db7466c2e5849
214
swift
Swift
SwiftyFaker/faker/Animal.swift
schultzjim/SwiftyFakerOld
7f34d3d6e1beb822f90b3c926d2d280561eb61e2
[ "MIT" ]
null
null
null
SwiftyFaker/faker/Animal.swift
schultzjim/SwiftyFakerOld
7f34d3d6e1beb822f90b3c926d2d280561eb61e2
[ "MIT" ]
null
null
null
SwiftyFaker/faker/Animal.swift
schultzjim/SwiftyFakerOld
7f34d3d6e1beb822f90b3c926d2d280561eb61e2
[ "MIT" ]
null
null
null
// // Animal.swift // SwiftyFaker // // Created by Jim Schultz on 10/10/15. // Copyright © 2015 Jim Schultz. All rights reserved. // import Foundation extension Faker { open class Animal: Faker { } }
14.266667
54
0.649533
c17fec6f5a601eef5f16ab83cbd1f66f1b83bc33
34,514
rs
Rust
diem-move/diem-vm/src/diem_vm.rs
dimroc/diem
5af341e53c9a24ebe24596f4890fcaaef3bcdc54
[ "Apache-2.0" ]
1
2022-02-07T21:57:17.000Z
2022-02-07T21:57:17.000Z
diem-move/diem-vm/src/diem_vm.rs
dimroc/diem
5af341e53c9a24ebe24596f4890fcaaef3bcdc54
[ "Apache-2.0" ]
80
2022-02-15T20:14:00.000Z
2022-03-31T07:36:21.000Z
diem-move/diem-vm/src/diem_vm.rs
cperez08/libra
fc59a36f345d997c27f2eedc2b651bf4977ded7a
[ "Apache-2.0" ]
null
null
null
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ adapter_common, adapter_common::{ discard_error_output, discard_error_vm_status, validate_signature_checked_transaction, validate_signed_transaction, PreprocessedTransaction, VMAdapter, }, counters::*, data_cache::{RemoteStorage, StateViewCache}, diem_vm_impl::{ charge_global_write_gas_usage, convert_changeset_and_events, get_currency_info, get_gas_currency_code, get_transaction_output, DiemVMImpl, DiemVMInternals, }, errors::expect_only_successful_execution, logging::AdapterLogSchema, script_to_script_function, system_module_names::*, transaction_metadata::TransactionMetadata, VMExecutor, VMValidator, }; use anyhow::Result; use diem_logger::prelude::*; use diem_state_view::StateView; use diem_types::{ account_config, block_metadata::BlockMetadata, on_chain_config::{ DiemVersion, OnChainConfig, ParallelExecutionConfig, VMConfig, VMPublishingOption, DIEM_VERSION_2, DIEM_VERSION_3, }, transaction::{ ChangeSet, ModuleBundle, SignatureCheckedTransaction, SignedTransaction, Transaction, TransactionOutput, TransactionPayload, TransactionStatus, VMValidatorResult, WriteSetPayload, }, vm_status::{KeptVMStatus, StatusCode, VMStatus}, write_set::{WriteSet, WriteSetMut}, }; use fail::fail_point; use move_binary_format::errors::VMResult; use move_core_types::{ account_address::AccountAddress, gas_schedule::GasAlgebra, identifier::IdentStr, language_storage::ModuleId, resolver::MoveResolver, transaction_argument::convert_txn_args, value::{serialize_values, MoveValue}, }; use move_vm_runtime::session::Session; use move_vm_types::gas_schedule::GasStatus; use read_write_set_dynamic::NormalizedReadWriteSetAnalysis; use std::{ collections::HashSet, convert::{AsMut, AsRef}, }; #[derive(Clone)] pub struct DiemVM(pub(crate) DiemVMImpl); impl DiemVM { pub fn new<S: StateView>(state: &S) -> Self { Self(DiemVMImpl::new(state)) } pub fn new_for_validation<S: StateView>(state: &S) -> Self { info!( AdapterLogSchema::new(state.id(), 0), "Adapter created for Validation" ); Self::new(state) } pub fn init_with_config( version: DiemVersion, on_chain_config: VMConfig, publishing_option: VMPublishingOption, ) -> Self { info!("Adapter restarted for Validation"); DiemVM(DiemVMImpl::init_with_config( version, on_chain_config, publishing_option, )) } pub fn internals(&self) -> DiemVMInternals { DiemVMInternals::new(&self.0) } /// Load a module into its internal MoveVM's code cache. pub fn load_module<S: MoveResolver>(&self, module_id: &ModuleId, state: &S) -> VMResult<()> { self.0.load_module(module_id, state) } /// Generates a transaction output for a transaction that encountered errors during the /// execution process. This is public for now only for tests. pub fn failed_transaction_cleanup<S: MoveResolver>( &self, error_code: VMStatus, gas_status: &mut GasStatus, txn_data: &TransactionMetadata, storage: &S, account_currency_symbol: &IdentStr, log_context: &AdapterLogSchema, ) -> TransactionOutput { self.failed_transaction_cleanup_and_keep_vm_status( error_code, gas_status, txn_data, storage, account_currency_symbol, log_context, ) .1 } fn failed_transaction_cleanup_and_keep_vm_status<S: MoveResolver>( &self, error_code: VMStatus, gas_status: &mut GasStatus, txn_data: &TransactionMetadata, storage: &S, account_currency_symbol: &IdentStr, log_context: &AdapterLogSchema, ) -> (VMStatus, TransactionOutput) { gas_status.set_metering(false); let mut session = self.0.new_session(storage); match TransactionStatus::from(error_code.clone()) { TransactionStatus::Keep(status) => { // The transaction should be charged for gas, so run the epilogue to do that. // This is running in a new session that drops any side effects from the // attempted transaction (e.g., spending funds that were needed to pay for gas), // so even if the previous failure occurred while running the epilogue, it // should not fail now. If it somehow fails here, there is no choice but to // discard the transaction. if let Err(e) = self.0.run_failure_epilogue( &mut session, gas_status, txn_data, account_currency_symbol, log_context, ) { return discard_error_vm_status(e); } let txn_output = get_transaction_output( &mut (), session, gas_status.remaining_gas(), txn_data, status, ) .unwrap_or_else(|e| discard_error_vm_status(e).1); (error_code, txn_output) } TransactionStatus::Discard(status) => { (VMStatus::Error(status), discard_error_output(status)) } TransactionStatus::Retry => unreachable!(), } } fn success_transaction_cleanup<S: MoveResolver>( &self, mut session: Session<S>, gas_status: &mut GasStatus, txn_data: &TransactionMetadata, account_currency_symbol: &IdentStr, log_context: &AdapterLogSchema, ) -> Result<(VMStatus, TransactionOutput), VMStatus> { gas_status.set_metering(false); self.0.run_success_epilogue( &mut session, gas_status, txn_data, account_currency_symbol, log_context, )?; Ok(( VMStatus::Executed, get_transaction_output( &mut (), session, gas_status.remaining_gas(), txn_data, KeptVMStatus::Executed, )?, )) } fn execute_script_or_script_function<S: MoveResolver>( &self, mut session: Session<S>, gas_status: &mut GasStatus, txn_data: &TransactionMetadata, payload: &TransactionPayload, account_currency_symbol: &IdentStr, log_context: &AdapterLogSchema, ) -> Result<(VMStatus, TransactionOutput), VMStatus> { fail_point!("move_adapter::execute_script_or_script_function", |_| { Err(VMStatus::Error( StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR, )) }); // Run the execution logic { gas_status .charge_intrinsic_gas(txn_data.transaction_size()) .map_err(|e| e.into_vm_status())?; match payload { TransactionPayload::Script(script) => { let diem_version = self.0.get_diem_version()?; let remapped_script = if diem_version < diem_types::on_chain_config::DIEM_VERSION_2 { None } else { script_to_script_function::remapping(script.code()) }; let mut senders = vec![txn_data.sender()]; if diem_version >= DIEM_VERSION_3 { senders.extend(txn_data.secondary_signers()); } match remapped_script { // We are in this case before VERSION_2 // or if there is no remapping for the script None => session.execute_script( script.code().to_vec(), script.ty_args().to_vec(), convert_txn_args(script.args()), senders, gas_status, ), Some((module, function)) => session.execute_script_function( module, function, script.ty_args().to_vec(), convert_txn_args(script.args()), senders, gas_status, ), } } TransactionPayload::ScriptFunction(script_fn) => { let diem_version = self.0.get_diem_version()?; let mut senders = vec![txn_data.sender()]; if diem_version >= DIEM_VERSION_3 { senders.extend(txn_data.secondary_signers()); } session.execute_script_function( script_fn.module(), script_fn.function(), script_fn.ty_args().to_vec(), script_fn.args().to_vec(), senders, gas_status, ) } TransactionPayload::ModuleBundle(_) | TransactionPayload::WriteSet(_) => { return Err(VMStatus::Error(StatusCode::UNREACHABLE)); } } .map_err(|e| e.into_vm_status())?; charge_global_write_gas_usage(gas_status, &session, &txn_data.sender())?; self.success_transaction_cleanup( session, gas_status, txn_data, account_currency_symbol, log_context, ) } } fn execute_modules<S: MoveResolver>( &self, mut session: Session<S>, gas_status: &mut GasStatus, txn_data: &TransactionMetadata, modules: &ModuleBundle, account_currency_symbol: &IdentStr, log_context: &AdapterLogSchema, ) -> Result<(VMStatus, TransactionOutput), VMStatus> { fail_point!("move_adapter::execute_module", |_| { Err(VMStatus::Error( StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR, )) }); // Publish the module let module_address = if self.0.publishing_option(log_context)?.is_open_module() { txn_data.sender() } else { account_config::CORE_CODE_ADDRESS }; gas_status .charge_intrinsic_gas(txn_data.transaction_size()) .map_err(|e| e.into_vm_status())?; session .publish_module_bundle(modules.clone().into_inner(), module_address, gas_status) .map_err(|e| e.into_vm_status())?; charge_global_write_gas_usage(gas_status, &session, &txn_data.sender())?; self.success_transaction_cleanup( session, gas_status, txn_data, account_currency_symbol, log_context, ) } pub(crate) fn execute_user_transaction<S: MoveResolver>( &self, storage: &S, txn: &SignatureCheckedTransaction, log_context: &AdapterLogSchema, ) -> (VMStatus, TransactionOutput) { macro_rules! unwrap_or_discard { ($res: expr) => { match $res { Ok(s) => s, Err(e) => return discard_error_vm_status(e), } }; } let account_currency_symbol = match get_gas_currency_code(txn) { Ok(symbol) => symbol, Err(err) => { return discard_error_vm_status(err); } }; if self.0.chain_info().currency_code_required { if let Err(err) = get_currency_info(&account_currency_symbol, storage) { return discard_error_vm_status(err); } } // Revalidate the transaction. let mut session = self.0.new_session(storage); if let Err(err) = validate_signature_checked_transaction::<S, Self>( self, &mut session, txn, false, log_context, ) { return discard_error_vm_status(err); }; let gas_schedule = unwrap_or_discard!(self.0.get_gas_schedule(log_context)); let txn_data = TransactionMetadata::new(txn); let mut gas_status = GasStatus::new(gas_schedule, txn_data.max_gas_amount()); let result = match txn.payload() { payload @ TransactionPayload::Script(_) | payload @ TransactionPayload::ScriptFunction(_) => self .execute_script_or_script_function( session, &mut gas_status, &txn_data, payload, &account_currency_symbol, log_context, ), TransactionPayload::ModuleBundle(m) => self.execute_modules( session, &mut gas_status, &txn_data, m, &account_currency_symbol, log_context, ), TransactionPayload::WriteSet(_) => { return discard_error_vm_status(VMStatus::Error(StatusCode::UNREACHABLE)) } }; let gas_usage = txn_data .max_gas_amount() .sub(gas_status.remaining_gas()) .get(); TXN_GAS_USAGE.observe(gas_usage as f64); match result { Ok(output) => output, Err(err) => { let txn_status = TransactionStatus::from(err.clone()); if txn_status.is_discarded() { discard_error_vm_status(err) } else { self.failed_transaction_cleanup_and_keep_vm_status( err, &mut gas_status, &txn_data, storage, &account_currency_symbol, log_context, ) } } } } fn execute_writeset<S: MoveResolver>( &self, storage: &S, writeset_payload: &WriteSetPayload, txn_sender: Option<AccountAddress>, ) -> Result<ChangeSet, Result<(VMStatus, TransactionOutput), VMStatus>> { let mut gas_status = GasStatus::new_unmetered(); Ok(match writeset_payload { WriteSetPayload::Direct(change_set) => change_set.clone(), WriteSetPayload::Script { script, execute_as } => { let mut tmp_session = self.0.new_session(storage); let diem_version = self.0.get_diem_version().map_err(Err)?; let senders = match txn_sender { None => vec![*execute_as], Some(sender) => vec![sender, *execute_as], }; let remapped_script = if diem_version < diem_types::on_chain_config::DIEM_VERSION_2 { None } else { script_to_script_function::remapping(script.code()) }; let execution_result = match remapped_script { // We are in this case before VERSION_2 // or if there is no remapping for the script None => tmp_session.execute_script( script.code().to_vec(), script.ty_args().to_vec(), convert_txn_args(script.args()), senders, &mut gas_status, ), Some((module, function)) => tmp_session.execute_script_function( module, function, script.ty_args().to_vec(), convert_txn_args(script.args()), senders, &mut gas_status, ), } .and_then(|_| tmp_session.finish()) .map_err(|e| e.into_vm_status()); match execution_result { Ok((changeset, events)) => { let (cs, events) = convert_changeset_and_events(changeset, events).map_err(Err)?; ChangeSet::new(cs, events) } Err(e) => { return Err(Ok((e, discard_error_output(StatusCode::INVALID_WRITE_SET)))) } } } }) } fn read_writeset( &self, state_view: &impl StateView, write_set: &WriteSet, ) -> Result<(), VMStatus> { // All Move executions satisfy the read-before-write property. Thus we need to read each // access path that the write set is going to update. for (ap, _) in write_set.iter() { state_view .get(ap) .map_err(|_| VMStatus::Error(StatusCode::STORAGE_ERROR))?; } Ok(()) } pub(crate) fn process_waypoint_change_set<S: MoveResolver + StateView>( &self, storage: &S, writeset_payload: WriteSetPayload, ) -> Result<(VMStatus, TransactionOutput), VMStatus> { let change_set = match self.execute_writeset(storage, &writeset_payload, None) { Ok(cs) => cs, Err(e) => return e, }; let (write_set, events) = change_set.into_inner(); self.read_writeset(storage, &write_set)?; SYSTEM_TRANSACTIONS_EXECUTED.inc(); Ok(( VMStatus::Executed, TransactionOutput::new(write_set, events, 0, VMStatus::Executed.into()), )) } pub(crate) fn process_block_prologue<S: MoveResolver>( &self, storage: &S, block_metadata: BlockMetadata, log_context: &AdapterLogSchema, ) -> Result<(VMStatus, TransactionOutput), VMStatus> { fail_point!("move_adapter::process_block_prologue", |_| { Err(VMStatus::Error( StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR, )) }); let txn_data = TransactionMetadata { sender: account_config::reserved_vm_address(), ..Default::default() }; let mut gas_status = GasStatus::new_unmetered(); let mut session = self.0.new_session(storage); let (round, timestamp, previous_vote, proposer) = block_metadata.into_inner(); let args = serialize_values(&vec![ MoveValue::Signer(txn_data.sender), MoveValue::U64(round), MoveValue::U64(timestamp), MoveValue::Vector(previous_vote.into_iter().map(MoveValue::Address).collect()), MoveValue::Address(proposer), ]); session .execute_function( &DIEM_BLOCK_MODULE, BLOCK_PROLOGUE, vec![], args, &mut gas_status, ) .map(|_return_vals| ()) .or_else(|e| { expect_only_successful_execution(e, BLOCK_PROLOGUE.as_str(), log_context) })?; SYSTEM_TRANSACTIONS_EXECUTED.inc(); let output = get_transaction_output( &mut (), session, gas_status.remaining_gas(), &txn_data, KeptVMStatus::Executed, )?; Ok((VMStatus::Executed, output)) } pub(crate) fn process_writeset_transaction<S: MoveResolver + StateView>( &self, storage: &S, txn: &SignatureCheckedTransaction, log_context: &AdapterLogSchema, ) -> Result<(VMStatus, TransactionOutput), VMStatus> { fail_point!("move_adapter::process_writeset_transaction", |_| { Err(VMStatus::Error( StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR, )) }); let account_currency_symbol = match get_gas_currency_code(txn) { Ok(symbol) => symbol, Err(err) => { return Ok(discard_error_vm_status(err)); } }; if self.0.chain_info().currency_code_required { if let Err(err) = get_currency_info(&account_currency_symbol, storage) { return Ok(discard_error_vm_status(err)); } } // Revalidate the transaction. let mut session = self.0.new_session(storage); if let Err(e) = validate_signature_checked_transaction::<S, Self>( self, &mut session, txn, false, log_context, ) { return Ok(discard_error_vm_status(e)); }; self.execute_writeset_transaction( storage, match txn.payload() { TransactionPayload::WriteSet(writeset_payload) => writeset_payload, TransactionPayload::ModuleBundle(_) | TransactionPayload::Script(_) | TransactionPayload::ScriptFunction(_) => { log_context.alert(); error!(*log_context, "[diem_vm] UNREACHABLE"); return Ok(discard_error_vm_status(VMStatus::Error( StatusCode::UNREACHABLE, ))); } }, TransactionMetadata::new(txn), log_context, ) } pub fn execute_writeset_transaction<S: MoveResolver + StateView>( &self, storage: &S, writeset_payload: &WriteSetPayload, txn_data: TransactionMetadata, log_context: &AdapterLogSchema, ) -> Result<(VMStatus, TransactionOutput), VMStatus> { let change_set = match self.execute_writeset(storage, writeset_payload, Some(txn_data.sender())) { Ok(change_set) => change_set, Err(e) => return e, }; // Run the epilogue function. let mut session = self.0.new_session(storage); self.0.run_writeset_epilogue( &mut session, &txn_data, writeset_payload.should_trigger_reconfiguration_by_default(), log_context, )?; if let Err(e) = self.read_writeset(storage, change_set.write_set()) { // Any error at this point would be an invalid writeset return Ok((e, discard_error_output(StatusCode::INVALID_WRITE_SET))); }; let (changeset, events) = session.finish().map_err(|e| e.into_vm_status())?; let (epilogue_writeset, epilogue_events) = convert_changeset_and_events(changeset, events)?; // Make sure epilogue WriteSet doesn't intersect with the writeset in TransactionPayload. if !epilogue_writeset .iter() .map(|(ap, _)| ap) .collect::<HashSet<_>>() .is_disjoint( &change_set .write_set() .iter() .map(|(ap, _)| ap) .collect::<HashSet<_>>(), ) { let vm_status = VMStatus::Error(StatusCode::INVALID_WRITE_SET); return Ok(discard_error_vm_status(vm_status)); } if !epilogue_events .iter() .map(|event| event.key()) .collect::<HashSet<_>>() .is_disjoint( &change_set .events() .iter() .map(|event| event.key()) .collect::<HashSet<_>>(), ) { let vm_status = VMStatus::Error(StatusCode::INVALID_WRITE_SET); return Ok(discard_error_vm_status(vm_status)); } let write_set = WriteSetMut::new( epilogue_writeset .iter() .chain(change_set.write_set().iter()) .cloned() .collect(), ) .freeze() .map_err(|_| VMStatus::Error(StatusCode::INVALID_WRITE_SET))?; let events = change_set .events() .iter() .chain(epilogue_events.iter()) .cloned() .collect(); SYSTEM_TRANSACTIONS_EXECUTED.inc(); Ok(( VMStatus::Executed, TransactionOutput::new( write_set, events, 0, TransactionStatus::Keep(KeptVMStatus::Executed), ), )) } /// Alternate form of 'execute_block' that keeps the vm_status before it goes into the /// `TransactionOutput` pub fn execute_block_and_keep_vm_status( transactions: Vec<Transaction>, state_view: &impl StateView, ) -> Result<Vec<(VMStatus, TransactionOutput)>, VMStatus> { let mut state_view_cache = StateViewCache::new(state_view); let count = transactions.len(); let vm = DiemVM::new(&state_view_cache); let res = adapter_common::execute_block_impl(&vm, transactions, &mut state_view_cache)?; // Record the histogram count for transactions per block. BLOCK_TRANSACTION_COUNT.observe(count as f64); Ok(res) } } // Executor external API impl VMExecutor for DiemVM { /// Execute a block of `transactions`. The output vector will have the exact same length as the /// input vector. The discarded transactions will be marked as `TransactionStatus::Discard` and /// have an empty `WriteSet`. Also `state_view` is immutable, and does not have interior /// mutability. Writes to be applied to the data view are encoded in the write set part of a /// transaction output. fn execute_block( transactions: Vec<Transaction>, state_view: &impl StateView, ) -> Result<Vec<TransactionOutput>, VMStatus> { fail_point!("move_adapter::execute_block", |_| { Err(VMStatus::Error( StatusCode::UNKNOWN_INVARIANT_VIOLATION_ERROR, )) }); // Execute transactions in parallel if on chain config is set and loaded. if let Some(read_write_set_analysis) = ParallelExecutionConfig::fetch_config(&RemoteStorage::new(state_view)) .and_then(|config| config.read_write_analysis_result) .map(|config| config.into_inner()) { let analysis_reuslt = NormalizedReadWriteSetAnalysis::new(read_write_set_analysis); // Note that writeset transactions will be executed sequentially as it won't be inferred // by the read write set analysis and thus fall into the sequential path. let (result, _) = crate::parallel_executor::ParallelDiemVM::execute_block( &analysis_reuslt, transactions, state_view, )?; Ok(result) } else { let output = Self::execute_block_and_keep_vm_status(transactions, state_view)?; Ok(output .into_iter() .map(|(_vm_status, txn_output)| txn_output) .collect()) } } } // VMValidator external API impl VMValidator for DiemVM { /// Determine if a transaction is valid. Will return `None` if the transaction is accepted, /// `Some(Err)` if the VM rejects it, with `Err` as an error code. Verification performs the /// following steps: /// 1. The signature on the `SignedTransaction` matches the public key included in the /// transaction /// 2. The script to be executed is under given specific configuration. /// 3. Invokes `DiemAccount.prologue`, which checks properties such as the transaction has the /// right sequence number and the sender has enough balance to pay for the gas. /// TBD: /// 1. Transaction arguments matches the main function's type signature. /// We don't check this item for now and would execute the check at execution time. fn validate_transaction( &self, transaction: SignedTransaction, state_view: &impl StateView, ) -> VMValidatorResult { validate_signed_transaction(self, transaction, state_view) } } impl VMAdapter for DiemVM { fn new_session<'r, R: MoveResolver>(&self, remote: &'r R) -> Session<'r, '_, R> { self.0.new_session(remote) } fn check_signature(txn: SignedTransaction) -> Result<SignatureCheckedTransaction> { txn.check_signature() } fn check_transaction_format(&self, txn: &SignedTransaction) -> Result<(), VMStatus> { if txn.is_multi_agent() && self.0.get_diem_version()? < DIEM_VERSION_3 { // Multi agent is not allowed return Err(VMStatus::Error(StatusCode::FEATURE_UNDER_GATING)); } if txn.contains_duplicate_signers() { return Err(VMStatus::Error(StatusCode::SIGNERS_CONTAIN_DUPLICATES)); } Ok(()) } fn get_gas_price<S: MoveResolver>( &self, txn: &SignedTransaction, remote_cache: &S, ) -> Result<u64, VMStatus> { let gas_price = txn.gas_unit_price(); let currency_code = get_gas_currency_code(txn)?; let normalized_gas_price = if self.0.chain_info().currency_code_required { match get_currency_info(&currency_code, remote_cache) { Ok(info) => info.convert_to_xdx(gas_price), Err(err) => { return Err(err); } } } else { gas_price }; Ok(normalized_gas_price) } fn run_prologue<S: MoveResolver>( &self, session: &mut Session<S>, transaction: &SignatureCheckedTransaction, log_context: &AdapterLogSchema, ) -> Result<(), VMStatus> { let currency_code = get_gas_currency_code(transaction)?; let txn_data = TransactionMetadata::new(transaction); //let account_blob = session.data_cache.get_resource match transaction.payload() { TransactionPayload::Script(_) => { self.0.check_gas(&txn_data, log_context)?; self.0 .run_script_prologue(session, &txn_data, &currency_code, log_context) } TransactionPayload::ScriptFunction(_) => { // gate the behavior until the Diem version is ready if self.0.get_diem_version()? < DIEM_VERSION_2 { return Err(VMStatus::Error(StatusCode::FEATURE_UNDER_GATING)); } // NOTE: Script and ScriptFunction shares the same prologue self.0.check_gas(&txn_data, log_context)?; self.0 .run_script_prologue(session, &txn_data, &currency_code, log_context) } TransactionPayload::ModuleBundle(_module) => { self.0.check_gas(&txn_data, log_context)?; self.0 .run_module_prologue(session, &txn_data, &currency_code, log_context) } TransactionPayload::WriteSet(_cs) => { self.0 .run_writeset_prologue(session, &txn_data, log_context) } } } fn should_restart_execution(vm_output: &TransactionOutput) -> bool { let new_epoch_event_key = diem_types::on_chain_config::new_epoch_event_key(); vm_output .events() .iter() .any(|event| *event.key() == new_epoch_event_key) } fn execute_single_transaction<S: MoveResolver + StateView>( &self, txn: &PreprocessedTransaction, data_cache: &S, log_context: &AdapterLogSchema, ) -> Result<(VMStatus, TransactionOutput, Option<String>), VMStatus> { Ok(match txn { PreprocessedTransaction::BlockMetadata(block_metadata) => { let (vm_status, output) = self.process_block_prologue(data_cache, block_metadata.clone(), log_context)?; (vm_status, output, Some("block_prologue".to_string())) } PreprocessedTransaction::WaypointWriteSet(write_set_payload) => { let (vm_status, output) = self.process_waypoint_change_set(data_cache, write_set_payload.clone())?; (vm_status, output, Some("waypoint_write_set".to_string())) } PreprocessedTransaction::UserTransaction(txn) => { let sender = txn.sender().to_string(); let _timer = TXN_TOTAL_SECONDS.start_timer(); let (vm_status, output) = self.execute_user_transaction(data_cache, txn, log_context); // Increment the counter for user transactions executed. let counter_label = match output.status() { TransactionStatus::Keep(_) => Some("success"), TransactionStatus::Discard(_) => Some("discarded"), TransactionStatus::Retry => None, }; if let Some(label) = counter_label { USER_TRANSACTIONS_EXECUTED.with_label_values(&[label]).inc(); } (vm_status, output, Some(sender)) } PreprocessedTransaction::WriteSet(txn) => { let (vm_status, output) = self.process_writeset_transaction(data_cache, txn, log_context)?; (vm_status, output, Some("write_set".to_string())) } PreprocessedTransaction::InvalidSignature => { let (vm_status, output) = discard_error_vm_status(VMStatus::Error(StatusCode::INVALID_SIGNATURE)); (vm_status, output, None) } }) } } impl AsRef<DiemVMImpl> for DiemVM { fn as_ref(&self) -> &DiemVMImpl { &self.0 } } impl AsMut<DiemVMImpl> for DiemVM { fn as_mut(&mut self) -> &mut DiemVMImpl { &mut self.0 } }
37.111828
100
0.55195
0cb6a5d9b64c81ee9b97838a133419cdba2cb50d
326
py
Python
benchmark/mysql_benchmark.py
AlonFischer/SpatialDatabaseBench
1fe933bd4196ba17c687f04c37cb5a34acc6d824
[ "Apache-2.0" ]
1
2020-11-17T22:56:56.000Z
2020-11-17T22:56:56.000Z
benchmark/mysql_benchmark.py
AlonFischer/SpatialDatabaseBench
1fe933bd4196ba17c687f04c37cb5a34acc6d824
[ "Apache-2.0" ]
null
null
null
benchmark/mysql_benchmark.py
AlonFischer/SpatialDatabaseBench
1fe933bd4196ba17c687f04c37cb5a34acc6d824
[ "Apache-2.0" ]
null
null
null
from benchmark.benchmark import Benchmark from mysqlutils.mysqladapter import MySQLAdapter class MysqlBenchmark(Benchmark): """Abstract parent class for mysql benchmarks""" def __init__(self, adapter, title, repeat_count=7): super().__init__(title, repeat_count=repeat_count) self.adapter = adapter
29.636364
58
0.754601
9e76ff972cea0fc1fd755d1edb5182025793449d
645
asm
Assembly
oeis/157/A157844.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
11
2021-08-22T19:44:55.000Z
2022-03-20T16:47:57.000Z
oeis/157/A157844.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
9
2021-08-29T13:15:54.000Z
2022-03-09T19:52:31.000Z
oeis/157/A157844.asm
neoneye/loda-programs
84790877f8e6c2e821b183d2e334d612045d29c0
[ "Apache-2.0" ]
3
2021-08-22T20:56:47.000Z
2021-09-29T06:26:12.000Z
; A157844: 103680000n^2 - 161251200n + 62697601. ; 5126401,154915201,512064001,1076572801,1848441601,2827670401,4014259201,5408208001,7009516801,8818185601,10834214401,13057603201,15488352001,18126460801,20971929601,24024758401,27284947201,30752496001,34427404801,38309673601,42399302401,46696291201,51200640001,55912348801,60831417601,65957846401,71291635201,76832784001,82581292801,88537161601,94700390401,101070979201,107648928001,114434236801,121426905601,128626934401,136034323201,143649072001,151471180801,159500649601,167737478401,176181667201 seq $0,157843 ; 1728000n - 1343760. pow $0,2 sub $0,147640377600 div $0,28800 add $0,5126401
71.666667
501
0.868217
fae16821e2aca0292632ba77c0313703014d9047
1,075
sql
SQL
data/books.sql
redbearin/books
0ffc57bdf5e6bf735f1610b723c7a151dcc85aca
[ "MIT" ]
null
null
null
data/books.sql
redbearin/books
0ffc57bdf5e6bf735f1610b723c7a151dcc85aca
[ "MIT" ]
null
null
null
data/books.sql
redbearin/books
0ffc57bdf5e6bf735f1610b723c7a151dcc85aca
[ "MIT" ]
null
null
null
DROP TABLE IF EXISTS books; CREATE TABLE books( id SERIAL PRIMARY KEY, authors VARCHAR(255), title VARCHAR(255), description TEXT, isbn VARCHAR(50), thumbnail VARCHAR(255) ); INSERT INTO books (authors, title, description, isbn, thumbnail) VALUES('John Wright', 'Mushrooms', '"In the first of the River Cottage Handbook series, mycologist John Wright uncovers the secret habits and habitats of Britains thriving mushrooms - and the team at River Cottage explain how to cook them to perfection.', '9781408896273', 'http://books.google.com/books/content?id=wP5DDwAAQBAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api'); INSERT INTO books (authors, title, description, isbn, thumbnail) VALUES('Emily K. Green', 'Goats', '"The hairiest animal on the farm might be the goat. Goats have long beards that hang below their chins! This book introduces children to how goats look and how they live on the farm.', '9781408896273', 'https://books.google.com/books/content?id=bs_m8WmmnMkC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api');
71.666667
389
0.76093
70d4ac5c718869f2ccf27bf7e6942e483951759b
582
go
Go
djbot/handlers.go
ksunhokim123/sdbx-discord-dj-bot
b5e8dc77ea1bf2d78c62e6f17396ce2028308b25
[ "MIT" ]
1
2018-01-18T04:25:03.000Z
2018-01-18T04:25:03.000Z
djbot/handlers.go
ksunhokim123/sdbx-discord-dj-bot
b5e8dc77ea1bf2d78c62e6f17396ce2028308b25
[ "MIT" ]
null
null
null
djbot/handlers.go
ksunhokim123/sdbx-discord-dj-bot
b5e8dc77ea1bf2d78c62e6f17396ce2028308b25
[ "MIT" ]
1
2018-02-27T05:46:22.000Z
2018-02-27T05:46:22.000Z
package djbot import ( "log" "runtime/debug" "github.com/bwmarrin/discordgo" ) func (dj *DJBot) HandleNewMessage(sess *discordgo.Session, msg *discordgo.MessageCreate) { if msg == nil || sess == nil { return } defer func() { if r := recover(); r != nil { log.Println("recoverd:", r) log.Println(string(debug.Stack())) } }() if msg.Author.ID == sess.State.User.ID { return } if msg.ChannelID != dj.ChannelID { return } log.Println(msg.Author.ID, ":", msg.Content) dj.RequestHandler.handleMessage(msg) dj.CommandHandler.handleMessage(sess, msg) }
17.117647
90
0.659794
f0790474dabf6b841f25ca95dab836ba82a66003
2,146
js
JavaScript
bin/commands/init.js
beyo/beyo
48292d8baedf767fe6eb6ecc117da9ea22609a4c
[ "MIT" ]
1
2015-04-23T19:15:22.000Z
2015-04-23T19:15:22.000Z
bin/commands/init.js
beyo/beyo
48292d8baedf767fe6eb6ecc117da9ea22609a4c
[ "MIT" ]
null
null
null
bin/commands/init.js
beyo/beyo
48292d8baedf767fe6eb6ecc117da9ea22609a4c
[ "MIT" ]
null
null
null
const APPLICATION_NAME_REGEXP = /^[a-z]+[a-zA-Z0-9-_.]*$/; const MODULE_NAME_REGEXP = /^[a-z]+[a-zA-Z0-9]*$/; var crypto = require('crypto'); var co = require('co'); var errorFactory = require('error-factory'); var basename = require('path').basename; var fileProc = require('../../lib/io/file-processor'); var BeyoInitException = errorFactory('beyo.BeyoInitException', [ 'message', 'messageData' ]); module.exports = function init(command, actionWrapper) { command .description('Initialize a new project') .usage('init [options] [url|file]') .option('-n, --app-name <name>', 'the project name [' + basename(process.cwd()) + ']', basename(process.cwd())) .option('-m, --module-name <name>', 'the default module name [default]', 'default') .option('-p, --create-package', '(optional) create a package.json file', false) .option('-I, --no-npm-install', '(optional) do not run npm install', false) .option('-X, --no-shell-exec', '(optional) do not run shell commands', false) .option('-f, --fixture <git-repo>', '(optional) use fixture from git repo', false) .action(actionWrapper(['url|file'], null, _initAction)) ; }; function * _initAction(beyo, args, options) { var context = { 'hash_auth_key': hash(), 'hash_secure_auth_key': hash(), 'hash_logged_in_key': hash(), 'hash_nonce_in_key': hash(), 'hash_auth_salt': hash(), 'hash_secure_auth_salt': hash(), 'hash_logged_in_salt': hash(), 'hash_nonce_salt': hash(), 'app_name': validateApplicationName(options.appName), 'module_name': validateModuleName(options.moduleName) }; console.log('[*]', 'Initialization complete!'); } function hash() { return crypto.randomBytes(128).toString('base64') } function validateApplicationName(appName) { if (!APPLICATION_NAME_REGEXP.test(appName)) { throw BeyoInitException('Invalid application name: {{name}}', { name: appName }); } return appName; } function validateModuleName(moduleName) { if (!MODULE_NAME_REGEXP.test(moduleName)) { throw BeyoInitException('Invalid module name: {{name}}', { name: moduleName }); } return moduleName; }
32.515152
115
0.668686
85250e16240843382a3431c622a7d1c3a66f7c5f
851
kt
Kotlin
secure-shared-preferences/src/sharedTest/java/com/github/ibara1454/secure_shared_preferences/cipher/StringEncrypterTest.kt
ibara1454/secure-shared-preferences
b0173fe5fc802472e68634372fe2b94150a6101a
[ "MIT" ]
2
2020-05-13T01:11:33.000Z
2020-08-27T02:20:55.000Z
secure-shared-preferences/src/sharedTest/java/com/github/ibara1454/secure_shared_preferences/cipher/StringEncrypterTest.kt
ibara1454/secure-shared-preferences
b0173fe5fc802472e68634372fe2b94150a6101a
[ "MIT" ]
5
2020-05-14T19:01:29.000Z
2020-05-19T18:48:56.000Z
secure-shared-preferences/src/sharedTest/java/com/github/ibara1454/secure_shared_preferences/cipher/StringEncrypterTest.kt
ibara1454/secure-shared-preferences
b0173fe5fc802472e68634372fe2b94150a6101a
[ "MIT" ]
1
2020-05-15T00:32:22.000Z
2020-05-15T00:32:22.000Z
package com.github.ibara1454.secure_shared_preferences.cipher import com.google.common.truth.Truth.assertThat import org.junit.Test class StringEncrypterTest { @Test fun test_primary_constructor_finished_without_exception() { val byteArrayEncrypter = object : Encrypter<ByteArray> { override fun encrypt(text: ByteArray): ByteArray = text } StringEncrypter(byteArrayEncrypter) } @Test fun test_secondary_constructor_finished_without_exception() { StringEncrypter { bytes -> bytes } } @Test fun test_decrypt_convert_cipher_text_to_plain_text() { val encrypter = StringEncrypter { bytes -> bytes } val input = "hello world" val actual = encrypter.encrypt(input) assertThat(actual).isEqualTo(input) } }
26.59375
68
0.67215
e7531417036085ec09fb5980457107c3ef71cc83
329
swift
Swift
validation-test/compiler_crashers_fixed/02044-swift-typechecker-typecheckpattern.swift
ghostbar/swift-lang.deb
b1a887edd9178a0049a0ef839c4419142781f7a0
[ "Apache-2.0" ]
10
2015-12-25T02:19:46.000Z
2021-11-14T15:37:57.000Z
validation-test/compiler_crashers_fixed/02044-swift-typechecker-typecheckpattern.swift
ghostbar/swift-lang.deb
b1a887edd9178a0049a0ef839c4419142781f7a0
[ "Apache-2.0" ]
2
2016-02-01T08:51:00.000Z
2017-04-07T09:04:30.000Z
validation-test/compiler_crashers_fixed/02044-swift-typechecker-typecheckpattern.swift
ghostbar/swift-lang.deb
b1a887edd9178a0049a0ef839c4419142781f7a0
[ "Apache-2.0" ]
3
2016-04-02T15:05:27.000Z
2019-08-19T15:25:02.000Z
// RUN: not %target-swift-frontend %s -parse // Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing func a() { protocol a { typealias e> Self { } func b, object2) extension A { } typealias b where T> T func e(b> S
20.5625
87
0.717325
9e54fd0c13898010bb962bba370a7616de9485ea
932
lua
Lua
spec/integration/admin_api/helpers.lua
ejoncas/kong
aa8812d43fe8eb8241e7a524f9ba33c86e206917
[ "Apache-2.0" ]
3
2016-06-27T15:50:58.000Z
2018-03-21T07:38:22.000Z
spec/integration/admin_api/helpers.lua
ejoncas/kong
aa8812d43fe8eb8241e7a524f9ba33c86e206917
[ "Apache-2.0" ]
null
null
null
spec/integration/admin_api/helpers.lua
ejoncas/kong
aa8812d43fe8eb8241e7a524f9ba33c86e206917
[ "Apache-2.0" ]
1
2018-12-26T20:57:12.000Z
2018-12-26T20:57:12.000Z
local json = require "cjson" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" local assert = require "luassert" local function send_content_types(url, method, body, res_status, res_body, options) if not options then options = {} end local form_response, form_status = http_client[method:lower()](url, body) assert.equal(res_status, form_status) if options.drop_db then spec_helper.drop_db() end local json_response, json_status = http_client[method:lower()](url, body, {["content-type"]="application/json"}) assert.equal(res_status, json_status) if res_body then assert.same(res_body.."\n", form_response) assert.same(res_body.."\n", json_response) end local res_obj local status, res = pcall(function() res_obj = json.decode(json_response) end) if not status then error(res, 2) end return res_obj end return send_content_types
27.411765
114
0.741416
2f627c7beec4f4e37d6ee3b778388acba30adc4d
165
php
PHP
src/hugocorp/contactBundle/Tests/Controller/FichierControllerTest.php
AshvinPainiaye/Gestion-Contact
e31c76f08782d4e9bb307d4366209bea9fe786f2
[ "MIT" ]
null
null
null
src/hugocorp/contactBundle/Tests/Controller/FichierControllerTest.php
AshvinPainiaye/Gestion-Contact
e31c76f08782d4e9bb307d4366209bea9fe786f2
[ "MIT" ]
null
null
null
src/hugocorp/contactBundle/Tests/Controller/FichierControllerTest.php
AshvinPainiaye/Gestion-Contact
e31c76f08782d4e9bb307d4366209bea9fe786f2
[ "MIT" ]
null
null
null
<?php namespace hugocorp\contactBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class FichierControllerTest extends WebTestCase { }
16.5
52
0.836364
0ff7fb54c50620f3394a91cfd2c24d22687d8cc2
1,731
kt
Kotlin
app/src/main/java/io/github/bradpatras/bikeomaha/data/GeoJsonLayerFactory.kt
BradPatras/bike-omaha
0519808ff6e0b468da1f423d83f22315c8e74b5e
[ "MIT" ]
null
null
null
app/src/main/java/io/github/bradpatras/bikeomaha/data/GeoJsonLayerFactory.kt
BradPatras/bike-omaha
0519808ff6e0b468da1f423d83f22315c8e74b5e
[ "MIT" ]
3
2021-01-16T01:24:43.000Z
2021-01-17T01:47:00.000Z
app/src/main/java/io/github/bradpatras/bikeomaha/data/GeoJsonLayerFactory.kt
BradPatras/bike-omaha
0519808ff6e0b468da1f423d83f22315c8e74b5e
[ "MIT" ]
null
null
null
package io.github.bradpatras.bikeomaha.data import com.google.android.gms.maps.GoogleMap import com.google.maps.android.collections.GroundOverlayManager import com.google.maps.android.collections.MarkerManager import com.google.maps.android.collections.PolygonManager import com.google.maps.android.collections.PolylineManager import com.google.maps.android.data.geojson.GeoJsonFeature import com.google.maps.android.data.geojson.GeoJsonLayer import io.github.bradpatras.bikeomaha.util.applyPropertyStyles import org.json.JSONObject /** * Factory is needed for GeoJsonLayers because the styling values contained in the * GeoJsonFeature's 'properties' object are not automatically applied when the google map * adds the feature geometry to the map. * * The responsibility of this factory is to take a geojson JSONObject and create a geojsonlayer * using the built in constructor of the GeoJsonLayer class. Then for each feature of the layer, * it will grab the styling properties and apply them to a GeoJsonLineStringStyle object that * will then be added to that feature. */ class GeoJsonLayerFactory( private val map: GoogleMap ) { private val polylineManager = PolylineManager(map) private val groundOverlayManager = GroundOverlayManager(map) private val polygonManager = PolygonManager(map) private val markerManager = MarkerManager(map) fun create(geoJsonRootObject: JSONObject): GeoJsonLayer { return GeoJsonLayer( map, geoJsonRootObject, markerManager, polygonManager, polylineManager, groundOverlayManager ).apply { features.forEach(GeoJsonFeature::applyPropertyStyles) } } }
40.255814
97
0.76141
ddcf9d55148ff28b1cd203c8268b3de21d2396ec
569
go
Go
remote/entity.go
davinci26/falco
4ba11e7d53f29482606a64a44994ec72fa894dd9
[ "MIT" ]
45
2021-07-06T09:48:22.000Z
2022-03-31T01:34:32.000Z
remote/entity.go
davinci26/falco
4ba11e7d53f29482606a64a44994ec72fa894dd9
[ "MIT" ]
15
2021-07-06T16:37:44.000Z
2022-03-31T17:16:46.000Z
remote/entity.go
davinci26/falco
4ba11e7d53f29482606a64a44994ec72fa894dd9
[ "MIT" ]
8
2021-07-06T14:36:57.000Z
2022-03-21T12:06:10.000Z
package remote type Version struct { Number int64 `json:"number"` } type EdgeDictionary struct { Id string `json:"id"` Name string `json:"name"` Items []*EdgeDictionaryItem } type EdgeDictionaryItem struct { Key string `json:"item_key"` Value string `json:"item_value"` } type AccessControl struct { Id string `json:"id"` Name string `json:"name"` Entries []*AccessControlEntry } type AccessControlEntry struct { Ip string `json:"ip"` Negated string `json:"negated"` Subnet *int64 `json:"subnet"` Comment string `json:"comment"` }
18.966667
33
0.6942
ddf168ffb1b1a134175fa190c7d65e00d954eb33
6,829
h
C
System/Library/PrivateFrameworks/NewsTransport.framework/NTPBReadingHistoryItem.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
2
2021-11-02T09:23:27.000Z
2022-03-28T08:21:57.000Z
System/Library/PrivateFrameworks/NewsTransport.framework/NTPBReadingHistoryItem.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
null
null
null
System/Library/PrivateFrameworks/NewsTransport.framework/NTPBReadingHistoryItem.h
lechium/iOS1351Headers
6bed3dada5ffc20366b27f7f2300a24a48a6284e
[ "MIT" ]
1
2022-03-28T08:21:59.000Z
2022-03-28T08:21:59.000Z
/* * This header is generated by classdump-dyld 1.5 * on Friday, April 30, 2021 at 11:37:49 AM Mountain Standard Time * Operating System: Version 13.5.1 (Build 17F80) * Image Source: /System/Library/PrivateFrameworks/NewsTransport.framework/NewsTransport * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley. */ #import <NewsTransport/NewsTransport-Structs.h> #import <ProtocolBuffer/PBCodable.h> #import <libobjc.A.dylib/FCMutableReadingHistoryItem.h> #import <libobjc.A.dylib/FCKeyValueStoreCoding.h> #import <libobjc.A.dylib/NSCopying.h> @class NSString, NSDate, NTPBDate, CKRecord; @interface NTPBReadingHistoryItem : PBCodable <FCMutableReadingHistoryItem, FCKeyValueStoreCoding, NSCopying> { long long _maxVersionRead; long long _maxVersionSeen; long long _readCount; NSString* _articleID; NSString* _deviceID; NTPBDate* _firstSeenDate; NTPBDate* _firstSeenDateOfMaxVersionSeen; unsigned _flags; NTPBDate* _lastVisitedDate; NSString* _sourceChannelTagID; SCD_Struct_NT5 _has; } @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,copy,readonly) NSString * identifier; @property (nonatomic,copy,readonly) NSString * articleID; @property (nonatomic,copy,readonly) NSString * sourceChannelTagID; @property (nonatomic,copy,readonly) NSString * deviceID; @property (nonatomic,copy,readonly) NSDate * lastVisitedAt; @property (nonatomic,readonly) long long maxVersionRead; @property (nonatomic,copy,readonly) NSDate * firstSeenAt; @property (nonatomic,copy,readonly) NSDate * firstSeenAtOfMaxVersionSeen; @property (nonatomic,readonly) long long maxVersionSeen; @property (nonatomic,readonly) long long readCount; @property (nonatomic,readonly) unsigned long long flags; @property (nonatomic,readonly) BOOL hasArticleBeenRead; @property (nonatomic,readonly) BOOL hasArticleBeenSeen; @property (nonatomic,readonly) BOOL hasArticleBeenMarkedOffensive; @property (nonatomic,readonly) BOOL hasArticleBeenConsumed; @property (nonatomic,readonly) unsigned long long articleLikingStatus; @property (nonatomic,readonly) CKRecord * asCKRecord; @property (nonatomic,readonly) BOOL hasArticleID; @property (nonatomic,retain) NSString * articleID; //@synthesize articleID=_articleID - In the implementation block @property (nonatomic,readonly) BOOL hasLastVisitedDate; @property (nonatomic,retain) NTPBDate * lastVisitedDate; //@synthesize lastVisitedDate=_lastVisitedDate - In the implementation block @property (assign,nonatomic) BOOL hasFlags; @property (assign,nonatomic) unsigned flags; //@synthesize flags=_flags - In the implementation block @property (assign,nonatomic) BOOL hasMaxVersionRead; @property (assign,nonatomic) long long maxVersionRead; //@synthesize maxVersionRead=_maxVersionRead - In the implementation block @property (nonatomic,readonly) BOOL hasFirstSeenDate; @property (nonatomic,retain) NTPBDate * firstSeenDate; //@synthesize firstSeenDate=_firstSeenDate - In the implementation block @property (nonatomic,readonly) BOOL hasFirstSeenDateOfMaxVersionSeen; @property (nonatomic,retain) NTPBDate * firstSeenDateOfMaxVersionSeen; //@synthesize firstSeenDateOfMaxVersionSeen=_firstSeenDateOfMaxVersionSeen - In the implementation block @property (assign,nonatomic) BOOL hasMaxVersionSeen; @property (assign,nonatomic) long long maxVersionSeen; //@synthesize maxVersionSeen=_maxVersionSeen - In the implementation block @property (nonatomic,readonly) BOOL hasSourceChannelTagID; @property (nonatomic,retain) NSString * sourceChannelTagID; //@synthesize sourceChannelTagID=_sourceChannelTagID - In the implementation block @property (nonatomic,readonly) BOOL hasDeviceID; @property (nonatomic,retain) NSString * deviceID; //@synthesize deviceID=_deviceID - In the implementation block @property (assign,nonatomic) BOOL hasReadCount; @property (assign,nonatomic) long long readCount; //@synthesize readCount=_readCount - In the implementation block +(id)readingHistoryItemWithCKRecord:(id)arg1 ; +(int)keyValuePairType; +(id)readValueFromKeyValuePair:(id)arg1 ; -(id)mutableCopyWithZone:(NSZone*)arg1 ; -(NSString *)identifier; -(CKRecord *)asCKRecord; -(NSDate *)lastVisitedAt; -(BOOL)hasArticleBeenRead; -(BOOL)hasArticleBeenSeen; -(BOOL)hasArticleBeenConsumed; -(void)setHasArticleBeenSeen:(BOOL)arg1 ; -(void)setFirstSeenAt:(NSDate *)arg1 ; -(void)setFirstSeenAtOfMaxVersionSeen:(NSDate *)arg1 ; -(unsigned long long)articleLikingStatus; -(void)setArticleLikingStatus:(unsigned long long)arg1 ; -(BOOL)hasArticleBeenMarkedOffensive; -(void)setHasArticleBeenMarkedOffensive:(BOOL)arg1 ; -(void)setHasArticleBeenConsumed:(BOOL)arg1 ; -(void)setLastVisitedAt:(NSDate *)arg1 ; -(void)setHasArticleBeenRead:(BOOL)arg1 ; -(NSDate *)firstSeenAt; -(NSDate *)firstSeenAtOfMaxVersionSeen; -(void)writeToKeyValuePair:(id)arg1 ; -(void)dealloc; -(BOOL)isEqual:(id)arg1 ; -(unsigned long long)hash; -(NSString *)description; -(id)copyWithZone:(NSZone*)arg1 ; -(unsigned long long)flags; -(id)dictionaryRepresentation; -(void)writeTo:(id)arg1 ; -(void)setReadCount:(long long)arg1 ; -(NSString *)deviceID; -(void)setDeviceID:(NSString *)arg1 ; -(void)mergeFrom:(id)arg1 ; -(BOOL)readFrom:(id)arg1 ; -(BOOL)hasDeviceID; -(long long)readCount; -(void)setFlags:(unsigned long long)arg1 ; -(void)setLastVisitedDate:(NTPBDate *)arg1 ; -(NSString *)articleID; -(NTPBDate *)lastVisitedDate; -(NSString *)sourceChannelTagID; -(void)setArticleID:(NSString *)arg1 ; -(long long)maxVersionSeen; -(void)setMaxVersionSeen:(long long)arg1 ; -(void)setSourceChannelTagID:(NSString *)arg1 ; -(long long)maxVersionRead; -(void)setMaxVersionRead:(long long)arg1 ; -(NTPBDate *)firstSeenDate; -(void)setFirstSeenDate:(NTPBDate *)arg1 ; -(NTPBDate *)firstSeenDateOfMaxVersionSeen; -(void)setFirstSeenDateOfMaxVersionSeen:(NTPBDate *)arg1 ; -(BOOL)hasArticleID; -(BOOL)hasSourceChannelTagID; -(BOOL)hasLastVisitedDate; -(void)setHasFlags:(BOOL)arg1 ; -(BOOL)hasFlags; -(void)setHasMaxVersionRead:(BOOL)arg1 ; -(BOOL)hasMaxVersionRead; -(BOOL)hasFirstSeenDate; -(BOOL)hasFirstSeenDateOfMaxVersionSeen; -(void)setHasMaxVersionSeen:(BOOL)arg1 ; -(BOOL)hasMaxVersionSeen; -(void)setHasReadCount:(BOOL)arg1 ; -(BOOL)hasReadCount; @end
48.091549
191
0.743008
bbc659a0c76f4b02ef5d7b19a51b3e9e08d82dce
1,192
rs
Rust
src/apis/emscripten/utils.rs
bjfish/wasmer
bb91006158c9ab79726738ebe65a24e8eb16e854
[ "MIT" ]
null
null
null
src/apis/emscripten/utils.rs
bjfish/wasmer
bb91006158c9ab79726738ebe65a24e8eb16e854
[ "MIT" ]
null
null
null
src/apis/emscripten/utils.rs
bjfish/wasmer
bb91006158c9ab79726738ebe65a24e8eb16e854
[ "MIT" ]
null
null
null
use crate::webassembly::module::Module; /// We check if a provided module is an Emscripten generated one pub fn is_emscripten_module(module: &Module) -> bool { for (module, _field) in &module.info.imported_funcs { if module == "env" { return true; } } return false; } #[cfg(test)] mod tests { use super::super::generate_emscripten_env; use super::is_emscripten_module; use crate::webassembly::instantiate; #[test] fn should_detect_emscripten_files() { let wasm_bytes = include_wast2wasm_bytes!("tests/is_emscripten_true.wast"); let import_object = generate_emscripten_env(); let result_object = instantiate(wasm_bytes, import_object).expect("Not compiled properly"); assert!(is_emscripten_module(&result_object.module)); } #[test] fn should_detect_non_emscripten_files() { let wasm_bytes = include_wast2wasm_bytes!("tests/is_emscripten_false.wast"); let import_object = generate_emscripten_env(); let result_object = instantiate(wasm_bytes, import_object).expect("Not compiled properly"); assert!(!is_emscripten_module(&result_object.module)); } }
34.057143
99
0.692114
c36a7a90b104d3001efece4a34f42ceae3177389
3,462
rs
Rust
src/cli_opt.rs
lo48576/burne
160399bad1c5019cf564b0f4e022548e53d3ca37
[ "Apache-2.0", "MIT" ]
null
null
null
src/cli_opt.rs
lo48576/burne
160399bad1c5019cf564b0f4e022548e53d3ca37
[ "Apache-2.0", "MIT" ]
null
null
null
src/cli_opt.rs
lo48576/burne
160399bad1c5019cf564b0f4e022548e53d3ca37
[ "Apache-2.0", "MIT" ]
null
null
null
//! CLI options. use std::env; use std::ffi::OsString; use std::fs; use std::io; #[cfg(unix)] use std::path::PathBuf; use anyhow::{bail, Context as _}; use clap::Clap; use crate::renamer::{Escape, LineSeparator, RenameSetup, Renamer}; /// Renames child files in a directory using editor. #[derive(Debug, Clone, Clap)] pub(crate) struct Opt { /// Source directory that contains files to rename. #[clap(default_value = ".")] pub(crate) source_dir: PathBuf, /// Escape method. #[clap( short, long, parse(try_from_str = Escape::try_from_cli_str), possible_values(Escape::cli_possible_values()), default_value = "none" )] escape: Escape, /// Instead of running rename, just prints filenames before and after the rename. #[clap(short = 'n', long)] dry_run: bool, /// *UNIMPLEMENTED*: Makes parent directories for destination paths as needed. /// /// Not yet implemented. #[clap(short, long)] parents: bool, /// Separates the lines by NUL characters. #[clap(short = 'z', long = "null-data", parse(from_flag = line_separator_from_null_data_flag))] line_sep: LineSeparator, } impl Opt { /// Runs the rename procedure. pub(crate) fn run(&self) -> anyhow::Result<()> { let setup = RenameSetup::new(&self.source_dir)?; log::debug!("setup = {:?}", setup); let (mut tempfile, temp_path) = tempfile::NamedTempFile::new() .context("failed to create a temporary file")? .into_parts(); log::trace!("temporary file path: {}", temp_path.display()); setup.write(&mut tempfile, self.escape, self.line_sep)?; tempfile.sync_all()?; drop(tempfile); { let editor = Self::get_editor()?; let mut command = std::process::Command::new(&editor); command.arg(&temp_path); let status = command.status()?; if !status.success() { bail!( "the editor exited unsuccessfully: exit_code={:?}", status.code() ); } }; let mut tempfile = io::BufReader::new(fs::File::open(&temp_path)?); let plan = setup.plan(&mut tempfile, self.escape, self.line_sep)?; log::trace!("plan = {:#?}", plan); let renamer = if self.dry_run { Renamer::DryRun } else { Renamer::StdFs }; plan.run(&renamer)?; Ok(()) } /// Attempt to get editor command from the environment. fn get_editor() -> anyhow::Result<OsString> { // See `$VISUAL` environment variable. if let Some(visual) = env::var_os("VISUAL") { log::trace!( "`$VISUAL` environment variable found (value = {:?})", visual ); return Ok(visual); } // See `$EDITOR` environment variable. if let Some(editor) = env::var_os("EDITOR") { log::trace!( "`$EDITOR` environment variable found (value = {:?})", editor ); return Ok(editor); } bail!("failed to get editor"); } } /// Creates a `LineSeparator` from a `null-data` flag. #[inline] #[must_use] fn line_separator_from_null_data_flag(null_data: bool) -> LineSeparator { if null_data { LineSeparator::Null } else { LineSeparator::LineFeed } }
29.589744
99
0.56037
85ae3ffcf8ca8828b73d1970873b75d8543a692a
3,095
kt
Kotlin
app/src/main/kotlin/com/ashish/movieguide/ui/rated/movie/RatedMovieFragment.kt
AshishKayastha/Movies
f455e468b917491fd1e35b07f70e9e9e2d00649d
[ "Apache-2.0" ]
19
2017-08-06T07:35:54.000Z
2022-03-05T04:57:01.000Z
app/src/main/kotlin/com/ashish/movieguide/ui/rated/movie/RatedMovieFragment.kt
AshishKayastha/Movie-Guide
f455e468b917491fd1e35b07f70e9e9e2d00649d
[ "Apache-2.0" ]
3
2018-02-22T03:16:27.000Z
2020-08-21T00:40:41.000Z
app/src/main/kotlin/com/ashish/movieguide/ui/rated/movie/RatedMovieFragment.kt
AshishKayastha/Movies
f455e468b917491fd1e35b07f70e9e9e2d00649d
[ "Apache-2.0" ]
10
2017-07-21T12:36:13.000Z
2021-01-29T17:31:43.000Z
package com.ashish.movieguide.ui.rated.movie import android.content.Intent import android.os.Bundle import android.view.View import com.ashish.movieguide.R import com.ashish.movieguide.data.models.Movie import com.ashish.movieguide.di.modules.FragmentModule import com.ashish.movieguide.di.multibindings.fragment.FragmentComponentBuilderHost import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewFragment import com.ashish.movieguide.ui.base.recyclerview.BaseRecyclerViewMvpView import com.ashish.movieguide.ui.common.rating.RatingChangeObserver import com.ashish.movieguide.ui.movie.detail.MovieDetailActivity import com.ashish.movieguide.utils.Constants.ADAPTER_TYPE_MOVIE import icepick.State import io.reactivex.disposables.Disposable import javax.inject.Inject class RatedMovieFragment : BaseRecyclerViewFragment<Movie, BaseRecyclerViewMvpView<Movie>, RatedMoviePresenter>() { companion object { @JvmStatic fun newInstance() = RatedMovieFragment() } @Inject lateinit var ratingChangeObserver: RatingChangeObserver @JvmField @State var clickedItemPosition: Int = -1 private var disposable: Disposable? = null override fun injectDependencies(builderHost: FragmentComponentBuilderHost) { builderHost.getFragmentComponentBuilder(RatedMovieFragment::class.java, RatedMovieComponent.Builder::class.java) .withModule(FragmentModule(activity)) .build() .inject(this) } override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observeMovieRatingChanged() } override fun getAdapterType() = ADAPTER_TYPE_MOVIE override fun getEmptyTextId() = R.string.no_rated_movies_available override fun getEmptyImageId() = R.drawable.ic_movie_white_100dp override fun getTransitionNameId(position: Int) = R.string.transition_movie_poster override fun getDetailIntent(position: Int): Intent? { clickedItemPosition = position val movie = recyclerViewAdapter.getItem<Movie>(position) return MovieDetailActivity.createIntent(activity, movie) } private fun observeMovieRatingChanged() { disposable = ratingChangeObserver.getRatingObservable() .filter { clickedItemPosition > -1 } .filter { (movieId, _) -> val movie = recyclerViewAdapter.getItem<Movie>(clickedItemPosition) return@filter movie.id == movieId } .subscribe({ (_, rating) -> if (rating > 0) { val movie = recyclerViewAdapter.getItem<Movie>(clickedItemPosition) recyclerViewAdapter.replaceItem(clickedItemPosition, movie.copy(rating = rating)) } else { recyclerViewAdapter.removeItem(clickedItemPosition) } }) } override fun onDestroyView() { disposable?.dispose() super.onDestroyView() } }
38.6875
105
0.700162
ddf7e3f3a55befc782c3c80218c747b8a469594a
326
go
Go
server/model/request/err_warn.go
niejian/gin-vue-admin
164c4cbc7a06a320767c9ad889c2f23e00297a2c
[ "Apache-2.0" ]
null
null
null
server/model/request/err_warn.go
niejian/gin-vue-admin
164c4cbc7a06a320767c9ad889c2f23e00297a2c
[ "Apache-2.0" ]
null
null
null
server/model/request/err_warn.go
niejian/gin-vue-admin
164c4cbc7a06a320767c9ad889c2f23e00297a2c
[ "Apache-2.0" ]
null
null
null
// request doc package request type ErrorWarnStruct struct { IndexName string `json:"indexName"` ToUserIds []string `json:"toUserIds"` SendTime string `json:"sendTime"` ChatId string `json:"chatId"` ID int `json:"ID"` GroupName string `json:"groupName"` IsEnable int `json:"isEnable"` }
23.285714
38
0.659509
4895b3ed8ef8e1fd74bc3c05c4c832a4e2d056e0
673
asm
Assembly
Library/User/Gen/genSummons.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
504
2018-11-18T03:35:53.000Z
2022-03-29T01:02:51.000Z
Library/User/Gen/genSummons.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
96
2018-11-19T21:06:50.000Z
2022-03-06T10:26:48.000Z
Library/User/Gen/genSummons.asm
steakknife/pcgeos
95edd7fad36df400aba9bab1d56e154fc126044a
[ "Apache-2.0" ]
73
2018-11-19T20:46:53.000Z
2022-03-29T00:59:26.000Z
COMMENT @----------------------------------------------------------------------- Copyright (c) GeoWorks 1988 -- All Rights Reserved PROJECT: PC GEOS MODULE: UserInterface/Gen FILE: genSummonsClass.asm ROUTINES: Name Description ---- ----------- GLB GenSummonsClass Summons object REVISION HISTORY: Name Date Description ---- ---- ----------- Doug 6/89 Initial version DESCRIPTION: This file contains routines to implement the Summons class $Id: genSummons.asm,v 1.1 97/04/07 11:45:10 newdeal Exp $ -------------------------------------------------------------------------------@ ;GenSummons is no more - brianc 12/30/91
25.884615
81
0.509658
92f5b832ba1e2f3cf691b3dadaf4a6f6eff0879c
1,407
h
C
Cpp/SDK/IWidget_Interactable_parameters.h
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
1
2020-08-15T08:31:55.000Z
2020-08-15T08:31:55.000Z
Cpp/SDK/IWidget_Interactable_parameters.h
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
2
2020-08-15T08:43:56.000Z
2021-01-15T05:04:48.000Z
Cpp/SDK/IWidget_Interactable_parameters.h
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
2
2020-08-10T12:05:42.000Z
2021-02-12T19:56:10.000Z
#pragma once // Name: S, Version: b #include "../SDK.h" #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function IWidget_Interactable.IWidget_Interactable_C.Clear Interactable struct UIWidget_Interactable_C_Clear_Interactable_Params { }; // Function IWidget_Interactable.IWidget_Interactable_C.Set Interact Data struct UIWidget_Interactable_C_Set_Interact_Data_Params { struct FSQUsableWidgetData Interact_Data; // (BlueprintVisible, BlueprintReadOnly, Parm) class AActor* Actor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; // Function IWidget_Interactable.IWidget_Interactable_C.Set Interactable Actor struct UIWidget_Interactable_C_Set_Interactable_Actor_Params { class AActor* Actor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
31.977273
225
0.575693
93128e934b9ff4f4a78535222d4c77a0c431f03b
629
rs
Rust
phantomos-kernel/src/state.rs
PhantomOS/PhantomOS-Rust
ff1fb3db74db076e97c760dfc77e694d698c658d
[ "BSD-2-Clause-Patent" ]
1
2022-03-06T04:33:27.000Z
2022-03-06T04:33:27.000Z
phantomos-kernel/src/state.rs
PhantomOS/PhantomOS-Rust
ff1fb3db74db076e97c760dfc77e694d698c658d
[ "BSD-2-Clause-Patent" ]
null
null
null
phantomos-kernel/src/state.rs
PhantomOS/PhantomOS-Rust
ff1fb3db74db076e97c760dfc77e694d698c658d
[ "BSD-2-Clause-Patent" ]
null
null
null
#[cfg(target_arch = "x86_64")] pub mod system { use super::KernelState; #[repr(C)] pub struct SystemKernelState { ss: u64, rsp: u64, } pub fn get_kernel_state() -> &'static KernelState { let mut ret: *const KernelState; unsafe { core::arch::asm!("lea {}, gs:0", out(reg) ret); } unsafe { &*ret } } } #[repr(C)] pub struct KernelState { pub sys: system::SystemKernelState, pub uthread: Cell<HandlePtr<ThreadHandle>>, } use core::cell::Cell; pub use system::get_kernel_state; use crate::{addr_space::HandlePtr, thread::ThreadHandle};
20.966667
59
0.594595
0cbd16de6a3b89e4146e58d8e4a4fcddb5bba48b
7,173
py
Python
src/mtweepy/__init__.py
Souvic/mtweepy
26c5480aee1032a38335018efc66610b6960f7d4
[ "MIT" ]
1
2021-07-04T09:30:10.000Z
2021-07-04T09:30:10.000Z
src/mtweepy/__init__.py
Souvic/mtweepy
26c5480aee1032a38335018efc66610b6960f7d4
[ "MIT" ]
null
null
null
src/mtweepy/__init__.py
Souvic/mtweepy
26c5480aee1032a38335018efc66610b6960f7d4
[ "MIT" ]
null
null
null
import json import multiprocessing import os import requests from requests_oauthlib import OAuth1 from time import sleep import tweepy def get_users_single(x,auth,output_folder): while(True): url=f"https://api.twitter.com/1.1/users/lookup.json?user_id={','.join([str(i) for i in x])}" if(type(auth)==str): headers = {"Authorization": "Bearer "+auth} r = requests.get(url = url,headers=headers) else: r = requests.get(url = url, auth=auth) if(r.status_code != 200): print("sleeping") url="https://api.twitter.com/1.1/application/rate_limit_status.json?resources=help,users,search,statuses" while(True): sleep(30) try: if(type(auth)==str): headers = {"Authorization": "Bearer "+auth} l = requests.get(url = url,headers=headers).json() else: l = requests.get(url = url, auth=auth).json() if(l["resources"]["users"]["/users/lookup"]["remaining"]!=0): break; except: pass; continue; else: l = r.json() return(l) break; def get_users_single_mp_aux(x,index,auths,output_folder): n=100 auth=auths[index] with open(f'{output_folder}/{index}.jsonl', 'w') as outfile: for i in range(0,len(x),n): json1=get_users_single(x[i:i+n],auth,output_folder) json.dump(json1, outfile) outfile.write('\n') def get_users(auths,user_ids,output_folder): if(not os.path.isdir(output_folder)): print(f"Not a directory: {output_folder}") return(None) if(len(auths)==0): return(None) if(type(auths[0])!=str): auths=[OAuth1(auths[i][0],auths[i][1],auths[i][2],auths[i][3]) for i in range(len(auths))] Process_jobs = [] k=len(auths) n=(1+len(user_ids)//k) index=0 for i in range(0,len(user_ids),n): p = multiprocessing.Process(target = get_users_single_mp_aux, args = (user_ids[i:i+n],index,auths,output_folder)) index+=1 Process_jobs.append(p) p.start() for p in Process_jobs: p.join() def get_timeline_single(auth,user_id=None,screen_name=None,count=200,trim_user=True,exclude_replies=False,include_rts=True,max_id=None): l=[1] ans=[] while(len(l)!=0): if(user_id is not None): url=f"https://api.twitter.com/1.1/statuses/user_timeline.json?user_id={user_id}&count={count}&trim_user={trim_user}&exclude_replies={exclude_replies}&include_rts={include_rts}" else: url=f"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={screen_name}&count={count}&trim_user={trim_user}&exclude_replies={exclude_replies}&include_rts={include_rts}" url+="&tweet_mode=extended" if(max_id is not None): #print(max_id,"here") url+=f"&max_id={max_id}" #r = requests.get(url = url, auth=auth) if(type(auth)==str): headers = {"Authorization": "Bearer "+auth} r = requests.get(url = url,headers=headers) else: r = requests.get(url = url, auth=auth) #print(url) if(r.status_code == 401): break; if(r.status_code != 200): print("sleeping") url="https://api.twitter.com/1.1/application/rate_limit_status.json?resources=help,users,search,statuses" while(True): sleep(30) try: if(type(auth)==str): l=requests.get(url = url,headers=headers).json() else: l=requests.get(url = url, auth=auth).json() if(l["resources"]["statuses"]["/statuses/user_timeline"]["remaining"]!=0): break; except Exception as e: print(e) pass; continue; else: l = r.json() ans.extend(l) if(len(l)==0 or max_id==l[-1]["id_str"]): break; else: max_id=l[-1]["id_str"] return(ans) def get_timeline_single_mp_aux(index,auths,users,output_folder): auth=auths[index] with open(f'{output_folder}/{index}.jsonl', 'w') as outfile: for user_id in users: try: json1=get_timeline_single(auth=auth,user_id=user_id) except: sleep(30) continue; json.dump(json1, outfile) outfile.write('\n') def get_timelines(auths,users,output_folder): if(not os.path.isdir(output_folder)): print(f"Not a directory: {output_folder}") return(None) if(len(auths)==0): return(None) if(type(auths[0])!=str): auths=[OAuth1(auths[i][0],auths[i][1],auths[i][2],auths[i][3]) for i in range(len(auths))] Process_jobs = [] k=len(auths) n=(1+len(users)//k) index=-1 for i in range(0,len(users),n): p = multiprocessing.Process(target = get_timeline_single_mp_aux, args = (index,auths,users[i:i+n],output_folder)) index+=1 Process_jobs.append(p) p.start() for p in Process_jobs: p.join() def get_followers_aux(auth,screen_name_or_userid,cursor=-1,use_userid=False): url="https://api.twitter.com/1.1/followers/ids.json" params={"screen_name":screen_name_or_userid,"count":"5000","cursor":cursor} if(use_userid): params={"user_id":screen_name_or_userid,"count":"5000","cursor":cursor} if(type(auth)==str): headers = {"Authorization": "Bearer "+auth} temp=requests.get(url=url,headers=headers,params=params).json() else: temp=requests.get(url=url,auth=auth,params=params).json() if(len(temp["ids"])==0): return(temp["ids"],None) else: return(temp["ids"],temp["next_cursor"]) def get_followers(auths,screen_name_or_userid,max_num=-1,use_userid=False): cursor=-1 if(len(auths)==0): return(None) if(type(auths[0])!=str): auths=[OAuth1(auths[i][0],auths[i][1],auths[i][2],auths[i][3]) for i in range(len(auths))] res=[] index=0 auth=auths[index] flag=False while(cursor is not None and (max_num==-1 or max_num>len(res))): try: a,cursor=get_followers_aux(auth,screen_name_or_userid,cursor,use_userid) flag=False res.extend(a) print(len(res)) except Exception as e: print(e) print("done",len(res)) if(flag): sleep(30) else: flag=True index+=1 index%=len(auths) auth=auths[index] pass; return(res)
33.518692
196
0.539384
9e412215512c90bc4e978bea8116d88a8637a9ee
155
rs
Rust
src/test/ui/traits/auxiliary/trait_alias.rs
Eric-Arellano/rust
0f6f2d681b39c5f95459cd09cb936b6ceb27cd82
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
66,762
2015-01-01T08:32:03.000Z
2022-03-31T23:26:40.000Z
src/test/ui/traits/auxiliary/trait_alias.rs
Eric-Arellano/rust
0f6f2d681b39c5f95459cd09cb936b6ceb27cd82
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
76,993
2015-01-01T00:06:33.000Z
2022-03-31T23:59:15.000Z
src/test/ui/traits/auxiliary/trait_alias.rs
Eric-Arellano/rust
0f6f2d681b39c5f95459cd09cb936b6ceb27cd82
[ "ECL-2.0", "Apache-2.0", "MIT-0", "MIT" ]
11,787
2015-01-01T00:01:19.000Z
2022-03-31T19:03:42.000Z
#![feature(trait_alias)] pub trait Hello { fn hello(&self); } pub struct Hi; impl Hello for Hi { fn hello(&self) {} } pub trait Greet = Hello;
11.071429
24
0.619355