file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
member.component.spec.ts | import { SocialSharingComponent } from './social-sharing/social-sharing.component';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MemberComponent } from './member.component';
import { MaterialModule } from '../material/material.module';
import { NO_ERRORS_SCHEMA } from '@angular/core';
describe('MemberComponent', () => {
let component: MemberComponent;
let fixture: ComponentFixture<MemberComponent>;
beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [MemberComponent],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
})
); | component = fixture.componentInstance;
component.member = {
name: 'ben lesh',
role: 'lead',
githubUrl: '',
avatar: '',
twitterUrl: '',
webpageUrl: ''
};
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
}); |
beforeEach(() => {
fixture = TestBed.createComponent(MemberComponent); | random_line_split |
close-method.window.js | function assert_closed_opener(w, closed, opener) |
async_test(t => {
const openee = window.open();
assert_closed_opener(openee, false, self);
openee.onunload = t.step_func(() => {
assert_closed_opener(openee, true, self);
t.step_timeout(() => {
assert_closed_opener(openee, true, null);
t.done();
}, 0);
});
openee.close();
assert_closed_opener(openee, true, self);
}, "window.close() queues a task to discard, but window.closed knows immediately");
async_test(t => {
const openee = window.open("", "greatname");
assert_closed_opener(openee, false, self);
openee.close();
assert_closed_opener(openee, true, self);
const openee2 = window.open("", "greatname");
assert_not_equals(openee, openee2);
assert_closed_opener(openee, true, self); // Ensure second window.open() call was synchronous
openee2.onunload = t.step_func(() => {
assert_closed_opener(openee2, true, self);
t.step_timeout(() => {
assert_closed_opener(openee, true, null);
assert_closed_opener(openee2, true, null);
t.done();
}, 0);
});
openee2.close();
assert_closed_opener(openee, true, self); // Ensure second close() call was synchronous
assert_closed_opener(openee2, true, self);
}, "window.close() affects name targeting immediately");
| {
assert_equals(w.closed, closed);
assert_equals(w.opener, opener);
} | identifier_body |
close-method.window.js | function assert_closed_opener(w, closed, opener) {
assert_equals(w.closed, closed);
assert_equals(w.opener, opener);
}
async_test(t => {
const openee = window.open();
assert_closed_opener(openee, false, self);
openee.onunload = t.step_func(() => {
assert_closed_opener(openee, true, self);
t.step_timeout(() => {
assert_closed_opener(openee, true, null);
t.done();
}, 0); | assert_closed_opener(openee, true, self);
}, "window.close() queues a task to discard, but window.closed knows immediately");
async_test(t => {
const openee = window.open("", "greatname");
assert_closed_opener(openee, false, self);
openee.close();
assert_closed_opener(openee, true, self);
const openee2 = window.open("", "greatname");
assert_not_equals(openee, openee2);
assert_closed_opener(openee, true, self); // Ensure second window.open() call was synchronous
openee2.onunload = t.step_func(() => {
assert_closed_opener(openee2, true, self);
t.step_timeout(() => {
assert_closed_opener(openee, true, null);
assert_closed_opener(openee2, true, null);
t.done();
}, 0);
});
openee2.close();
assert_closed_opener(openee, true, self); // Ensure second close() call was synchronous
assert_closed_opener(openee2, true, self);
}, "window.close() affects name targeting immediately"); | });
openee.close(); | random_line_split |
close-method.window.js | function | (w, closed, opener) {
assert_equals(w.closed, closed);
assert_equals(w.opener, opener);
}
async_test(t => {
const openee = window.open();
assert_closed_opener(openee, false, self);
openee.onunload = t.step_func(() => {
assert_closed_opener(openee, true, self);
t.step_timeout(() => {
assert_closed_opener(openee, true, null);
t.done();
}, 0);
});
openee.close();
assert_closed_opener(openee, true, self);
}, "window.close() queues a task to discard, but window.closed knows immediately");
async_test(t => {
const openee = window.open("", "greatname");
assert_closed_opener(openee, false, self);
openee.close();
assert_closed_opener(openee, true, self);
const openee2 = window.open("", "greatname");
assert_not_equals(openee, openee2);
assert_closed_opener(openee, true, self); // Ensure second window.open() call was synchronous
openee2.onunload = t.step_func(() => {
assert_closed_opener(openee2, true, self);
t.step_timeout(() => {
assert_closed_opener(openee, true, null);
assert_closed_opener(openee2, true, null);
t.done();
}, 0);
});
openee2.close();
assert_closed_opener(openee, true, self); // Ensure second close() call was synchronous
assert_closed_opener(openee2, true, self);
}, "window.close() affects name targeting immediately");
| assert_closed_opener | identifier_name |
mona.rs | extern crate mon_artist;
use mon_artist::render::svg::{SvgRender};
use mon_artist::render::{RenderS};
use mon_artist::grid::{Grid, ParseError};
use mon_artist::{SceneOpts};
use std::convert::From;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write};
fn main() {
let mut args = env::args();
args.next(); // skip program name
loop {
let table = if let Some(arg) = args.next() { arg } else { break; };
let in_file = if let Some(arg) = args.next() { arg } else { break; };
let out_file = if let Some(arg) = args.next() { arg } else { break; };
println!("processing {} to {} via {}", in_file, out_file, table);
process(&table, &in_file, &out_file).unwrap();
}
// describe_table();
}
#[allow(dead_code)]
fn describe_table() {
use mon_artist::format::{Table, Neighbor};
let t: Table = Default::default();
let mut may_both_count = 0;
let mut may_start_count = 0;
let mut may_end_count = 0;
let mut neither_count = 0;
for (j, e) in t.entries().enumerate() {
println!("{} {:?}", j+1, e);
match (&e.incoming(), &e.outgoing()) {
(&Neighbor::May(..), &Neighbor::May(..)) => may_both_count += 1,
(&Neighbor::May(..), _) => may_start_count += 1,
(_, &Neighbor::May(..)) => may_end_count += 1,
_ => neither_count += 1,
}
}
println!("");
println!("both: {} may_start: {} may_end: {} neither: {}",
may_both_count, may_start_count, may_end_count, neither_count);
}
#[derive(Debug)]
enum Error { | Parse(ParseError),
}
impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IO(e) } }
impl From<ParseError> for Error { fn from(e: ParseError) -> Self { Error::Parse(e) } }
use mon_artist::format::Table;
fn get_table(table: &str) -> Table {
match File::open(table) {
Ok(input) => Table::from_lines(BufReader::new(input).lines()),
Err(err) => match table {
"default" => Table::default(),
"demo" => Table::demo(),
_ => panic!("Unknown table name: {}, file err: {:?}", table, err),
},
}
}
fn process(table: &str, in_file: &str, out_file: &str) -> Result<(), Error> {
let mut input = File::open(in_file)?;
let mut content = String::new();
input.read_to_string(&mut content)?;
let table = get_table(table);
let s = content.parse::<Grid>()?.into_scene(
&table,
Some(SceneOpts { text_infer_id: false, ..Default::default() }));
let r = SvgRender {
x_scale: 8, y_scale: 13,
font_family: "monospace".to_string(), font_size: 13,
show_gridlines: false,
infer_rect_elements: false,
name: in_file.to_string(),
format_table: table,
};
let svg = r.render_s(&s);
let mut output = File::create(out_file)?;
Ok(write!(&mut output, "{}", svg)?)
} | IO(io::Error), | random_line_split |
mona.rs | extern crate mon_artist;
use mon_artist::render::svg::{SvgRender};
use mon_artist::render::{RenderS};
use mon_artist::grid::{Grid, ParseError};
use mon_artist::{SceneOpts};
use std::convert::From;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write};
fn main() {
let mut args = env::args();
args.next(); // skip program name
loop {
let table = if let Some(arg) = args.next() { arg } else { break; };
let in_file = if let Some(arg) = args.next() { arg } else { break; };
let out_file = if let Some(arg) = args.next() { arg } else { break; };
println!("processing {} to {} via {}", in_file, out_file, table);
process(&table, &in_file, &out_file).unwrap();
}
// describe_table();
}
#[allow(dead_code)]
fn describe_table() {
use mon_artist::format::{Table, Neighbor};
let t: Table = Default::default();
let mut may_both_count = 0;
let mut may_start_count = 0;
let mut may_end_count = 0;
let mut neither_count = 0;
for (j, e) in t.entries().enumerate() {
println!("{} {:?}", j+1, e);
match (&e.incoming(), &e.outgoing()) {
(&Neighbor::May(..), &Neighbor::May(..)) => may_both_count += 1,
(&Neighbor::May(..), _) => may_start_count += 1,
(_, &Neighbor::May(..)) => may_end_count += 1,
_ => neither_count += 1,
}
}
println!("");
println!("both: {} may_start: {} may_end: {} neither: {}",
may_both_count, may_start_count, may_end_count, neither_count);
}
#[derive(Debug)]
enum Error {
IO(io::Error),
Parse(ParseError),
}
impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IO(e) } }
impl From<ParseError> for Error { fn from(e: ParseError) -> Self { Error::Parse(e) } }
use mon_artist::format::Table;
fn | (table: &str) -> Table {
match File::open(table) {
Ok(input) => Table::from_lines(BufReader::new(input).lines()),
Err(err) => match table {
"default" => Table::default(),
"demo" => Table::demo(),
_ => panic!("Unknown table name: {}, file err: {:?}", table, err),
},
}
}
fn process(table: &str, in_file: &str, out_file: &str) -> Result<(), Error> {
let mut input = File::open(in_file)?;
let mut content = String::new();
input.read_to_string(&mut content)?;
let table = get_table(table);
let s = content.parse::<Grid>()?.into_scene(
&table,
Some(SceneOpts { text_infer_id: false, ..Default::default() }));
let r = SvgRender {
x_scale: 8, y_scale: 13,
font_family: "monospace".to_string(), font_size: 13,
show_gridlines: false,
infer_rect_elements: false,
name: in_file.to_string(),
format_table: table,
};
let svg = r.render_s(&s);
let mut output = File::create(out_file)?;
Ok(write!(&mut output, "{}", svg)?)
}
| get_table | identifier_name |
mona.rs | extern crate mon_artist;
use mon_artist::render::svg::{SvgRender};
use mon_artist::render::{RenderS};
use mon_artist::grid::{Grid, ParseError};
use mon_artist::{SceneOpts};
use std::convert::From;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Read, Write};
fn main() {
let mut args = env::args();
args.next(); // skip program name
loop {
let table = if let Some(arg) = args.next() | else { break; };
let in_file = if let Some(arg) = args.next() { arg } else { break; };
let out_file = if let Some(arg) = args.next() { arg } else { break; };
println!("processing {} to {} via {}", in_file, out_file, table);
process(&table, &in_file, &out_file).unwrap();
}
// describe_table();
}
#[allow(dead_code)]
fn describe_table() {
use mon_artist::format::{Table, Neighbor};
let t: Table = Default::default();
let mut may_both_count = 0;
let mut may_start_count = 0;
let mut may_end_count = 0;
let mut neither_count = 0;
for (j, e) in t.entries().enumerate() {
println!("{} {:?}", j+1, e);
match (&e.incoming(), &e.outgoing()) {
(&Neighbor::May(..), &Neighbor::May(..)) => may_both_count += 1,
(&Neighbor::May(..), _) => may_start_count += 1,
(_, &Neighbor::May(..)) => may_end_count += 1,
_ => neither_count += 1,
}
}
println!("");
println!("both: {} may_start: {} may_end: {} neither: {}",
may_both_count, may_start_count, may_end_count, neither_count);
}
#[derive(Debug)]
enum Error {
IO(io::Error),
Parse(ParseError),
}
impl From<io::Error> for Error { fn from(e: io::Error) -> Self { Error::IO(e) } }
impl From<ParseError> for Error { fn from(e: ParseError) -> Self { Error::Parse(e) } }
use mon_artist::format::Table;
fn get_table(table: &str) -> Table {
match File::open(table) {
Ok(input) => Table::from_lines(BufReader::new(input).lines()),
Err(err) => match table {
"default" => Table::default(),
"demo" => Table::demo(),
_ => panic!("Unknown table name: {}, file err: {:?}", table, err),
},
}
}
fn process(table: &str, in_file: &str, out_file: &str) -> Result<(), Error> {
let mut input = File::open(in_file)?;
let mut content = String::new();
input.read_to_string(&mut content)?;
let table = get_table(table);
let s = content.parse::<Grid>()?.into_scene(
&table,
Some(SceneOpts { text_infer_id: false, ..Default::default() }));
let r = SvgRender {
x_scale: 8, y_scale: 13,
font_family: "monospace".to_string(), font_size: 13,
show_gridlines: false,
infer_rect_elements: false,
name: in_file.to_string(),
format_table: table,
};
let svg = r.render_s(&s);
let mut output = File::create(out_file)?;
Ok(write!(&mut output, "{}", svg)?)
}
| { arg } | conditional_block |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use regex::Regex;
use toml::Value;
use store::Result;
use store::Header;
use error::StoreErrorKind as SEK;
use error::StoreError as SE;
#[cfg(feature = "early-panic")]
#[macro_export]
macro_rules! if_cfg_panic {
() => { panic!() };
($msg:expr) => { panic!($msg) };
($fmt:expr, $($arg:tt)+) => { panic!($fmt, $($arg),+) };
}
#[cfg(not(feature = "early-panic"))]
#[macro_export]
macro_rules! if_cfg_panic {
() => { };
($msg:expr) => { };
($fmt:expr, $($arg:tt)+) => { };
}
pub fn entry_buffer_to_header_content(buf: &str) -> Result<(Value, String)> {
debug!("Building entry from string");
lazy_static! {
static ref RE: Regex = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$\n
(?P<content>.*) # Content
").unwrap();
}
let matches = match RE.captures(buf) {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s,
};
let header = match matches.name("header") {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s
}; | let content = matches.name("content").map(|r| r.as_str()).unwrap_or("");
Ok((Value::parse(header.as_str())?, String::from(content)))
} | random_line_split | |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use regex::Regex;
use toml::Value;
use store::Result;
use store::Header;
use error::StoreErrorKind as SEK;
use error::StoreError as SE;
#[cfg(feature = "early-panic")]
#[macro_export]
macro_rules! if_cfg_panic {
() => { panic!() };
($msg:expr) => { panic!($msg) };
($fmt:expr, $($arg:tt)+) => { panic!($fmt, $($arg),+) };
}
#[cfg(not(feature = "early-panic"))]
#[macro_export]
macro_rules! if_cfg_panic {
() => { };
($msg:expr) => { };
($fmt:expr, $($arg:tt)+) => { };
}
pub fn | (buf: &str) -> Result<(Value, String)> {
debug!("Building entry from string");
lazy_static! {
static ref RE: Regex = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$\n
(?P<content>.*) # Content
").unwrap();
}
let matches = match RE.captures(buf) {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s,
};
let header = match matches.name("header") {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s
};
let content = matches.name("content").map(|r| r.as_str()).unwrap_or("");
Ok((Value::parse(header.as_str())?, String::from(content)))
}
| entry_buffer_to_header_content | identifier_name |
util.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; version
// 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
use regex::Regex;
use toml::Value;
use store::Result;
use store::Header;
use error::StoreErrorKind as SEK;
use error::StoreError as SE;
#[cfg(feature = "early-panic")]
#[macro_export]
macro_rules! if_cfg_panic {
() => { panic!() };
($msg:expr) => { panic!($msg) };
($fmt:expr, $($arg:tt)+) => { panic!($fmt, $($arg),+) };
}
#[cfg(not(feature = "early-panic"))]
#[macro_export]
macro_rules! if_cfg_panic {
() => { };
($msg:expr) => { };
($fmt:expr, $($arg:tt)+) => { };
}
pub fn entry_buffer_to_header_content(buf: &str) -> Result<(Value, String)> | {
debug!("Building entry from string");
lazy_static! {
static ref RE: Regex = Regex::new(r"(?smx)
^---$
(?P<header>.*) # Header
^---$\n
(?P<content>.*) # Content
").unwrap();
}
let matches = match RE.captures(buf) {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s,
};
let header = match matches.name("header") {
None => return Err(SE::from_kind(SEK::MalformedEntry)),
Some(s) => s
};
let content = matches.name("content").map(|r| r.as_str()).unwrap_or("");
Ok((Value::parse(header.as_str())?, String::from(content)))
} | identifier_body | |
dbscanplot.py | import requests
import time
import dblayer
from sklearn.cluster import DBSCAN
import plotly
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import random
import testfile
# Create random colors in list
color_list = []
def generate_color(ncluster):
for i in range(ncluster):
color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(ncluster)))
color_list.append(color)
def showLatLongInCluster(data):
# Run the DBSCAN from sklearn
dbscan = DBSCAN(eps=2, min_samples=5, metric='euclidean', algorithm='auto').fit(data)
cluster_labels = dbscan.labels_
n_clusters = len(set(cluster_labels)) - (1 if -1 in cluster_labels else 0)
generate_color(n_clusters)
plot_data = []
# get the cluster
for i in range(n_clusters):
ds = data[np.where(cluster_labels == i)]
clustername = "Cluster " + str(i + 1)
trace = go.Scattergeo(lon=ds[:,0], lat=ds[:,1],mode='markers',marker=dict(color=color_list[i], size=5),
name=clustername)
plot_data.append(trace)
layout = go.Layout(showlegend=False, title='Earthquakes In North and South America',
titlefont=dict(family='Courier New, monospace',size=20,color='#7f7f7f'),
geo=dict(scope=('north america', 'south america'),
projection=dict(type='orthographic',rotation=dict(lon=-60)),
showland=True, landcolor='#191919',
showcountries=True,
showocean=True, oceancolor='rgb(217,217,255)',
showframe=False,
),
xaxis=dict(showgrid=False, zeroline=False),
yaxis=dict(showgrid=False, zeroline=False))
fig = go.Figure(data=plot_data, layout=layout)
div = plotly.offline.plot(fig, include_plotlyjs=True, output_type='div')
return div
def mkLatLong():
#### TME: Get start time
| start_time = time.time()
####
sess = requests.Session()
dbobj=dblayer.classDBLayer()
projection = [{"$project": {"_id": 0, "mag": "$properties.mag",
"depth": {"$arrayElemAt": ["$geometry.coordinates", 2]},
"longitude": {"$arrayElemAt": ["$geometry.coordinates", 0]},
"latitude": {"$arrayElemAt": ["$geometry.coordinates", 1]}}}]
df = pd.DataFrame(list(dbobj.doaggregate(projection)))
df = df[['longitude', 'latitude']].copy()
#### TME: Elapsed time taken to read data from MongoDB
fileobj = testfile.classFileWrite()
elapsed = time.time() - start_time
fileobj.writeline()
str1 = str(elapsed) + " secs required to read " + str(df['latitude'].count()) + " records from database."
fileobj.writelog("Reading Longitude and Latitude")
fileobj.writelog(str1)
####
#### TME: Get start time
start_time = time.time()
####
div = showLatLongInCluster(df.values)
response = """<html><title></title><head><meta charset=\"utf8\"> </head> <body>""" + div + """</body> </html>"""
dbobj.closedb()
#### TME: Elapsed time taken to cluster and plot data
elapsed = time.time() - start_time
fileobj.writeline()
str1 = "Time taken: " + str(elapsed)
fileobj.writelog("Applying DBSCAN clustering and plotting its output")
fileobj.writelog(str1)
fileobj.writeline()
fileobj.closefile()
####
return response | identifier_body | |
dbscanplot.py | import requests
import time
import dblayer
from sklearn.cluster import DBSCAN
import plotly
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import random
import testfile
# Create random colors in list
color_list = []
def generate_color(ncluster):
for i in range(ncluster):
|
def showLatLongInCluster(data):
# Run the DBSCAN from sklearn
dbscan = DBSCAN(eps=2, min_samples=5, metric='euclidean', algorithm='auto').fit(data)
cluster_labels = dbscan.labels_
n_clusters = len(set(cluster_labels)) - (1 if -1 in cluster_labels else 0)
generate_color(n_clusters)
plot_data = []
# get the cluster
for i in range(n_clusters):
ds = data[np.where(cluster_labels == i)]
clustername = "Cluster " + str(i + 1)
trace = go.Scattergeo(lon=ds[:,0], lat=ds[:,1],mode='markers',marker=dict(color=color_list[i], size=5),
name=clustername)
plot_data.append(trace)
layout = go.Layout(showlegend=False, title='Earthquakes In North and South America',
titlefont=dict(family='Courier New, monospace',size=20,color='#7f7f7f'),
geo=dict(scope=('north america', 'south america'),
projection=dict(type='orthographic',rotation=dict(lon=-60)),
showland=True, landcolor='#191919',
showcountries=True,
showocean=True, oceancolor='rgb(217,217,255)',
showframe=False,
),
xaxis=dict(showgrid=False, zeroline=False),
yaxis=dict(showgrid=False, zeroline=False))
fig = go.Figure(data=plot_data, layout=layout)
div = plotly.offline.plot(fig, include_plotlyjs=True, output_type='div')
return div
def mkLatLong():
#### TME: Get start time
start_time = time.time()
####
sess = requests.Session()
dbobj=dblayer.classDBLayer()
projection = [{"$project": {"_id": 0, "mag": "$properties.mag",
"depth": {"$arrayElemAt": ["$geometry.coordinates", 2]},
"longitude": {"$arrayElemAt": ["$geometry.coordinates", 0]},
"latitude": {"$arrayElemAt": ["$geometry.coordinates", 1]}}}]
df = pd.DataFrame(list(dbobj.doaggregate(projection)))
df = df[['longitude', 'latitude']].copy()
#### TME: Elapsed time taken to read data from MongoDB
fileobj = testfile.classFileWrite()
elapsed = time.time() - start_time
fileobj.writeline()
str1 = str(elapsed) + " secs required to read " + str(df['latitude'].count()) + " records from database."
fileobj.writelog("Reading Longitude and Latitude")
fileobj.writelog(str1)
####
#### TME: Get start time
start_time = time.time()
####
div = showLatLongInCluster(df.values)
response = """<html><title></title><head><meta charset=\"utf8\"> </head> <body>""" + div + """</body> </html>"""
dbobj.closedb()
#### TME: Elapsed time taken to cluster and plot data
elapsed = time.time() - start_time
fileobj.writeline()
str1 = "Time taken: " + str(elapsed)
fileobj.writelog("Applying DBSCAN clustering and plotting its output")
fileobj.writelog(str1)
fileobj.writeline()
fileobj.closefile()
####
return response
| color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(ncluster)))
color_list.append(color) | conditional_block |
dbscanplot.py | import requests
import time
import dblayer
from sklearn.cluster import DBSCAN
import plotly
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import random
import testfile
# Create random colors in list
color_list = []
def | (ncluster):
for i in range(ncluster):
color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(ncluster)))
color_list.append(color)
def showLatLongInCluster(data):
# Run the DBSCAN from sklearn
dbscan = DBSCAN(eps=2, min_samples=5, metric='euclidean', algorithm='auto').fit(data)
cluster_labels = dbscan.labels_
n_clusters = len(set(cluster_labels)) - (1 if -1 in cluster_labels else 0)
generate_color(n_clusters)
plot_data = []
# get the cluster
for i in range(n_clusters):
ds = data[np.where(cluster_labels == i)]
clustername = "Cluster " + str(i + 1)
trace = go.Scattergeo(lon=ds[:,0], lat=ds[:,1],mode='markers',marker=dict(color=color_list[i], size=5),
name=clustername)
plot_data.append(trace)
layout = go.Layout(showlegend=False, title='Earthquakes In North and South America',
titlefont=dict(family='Courier New, monospace',size=20,color='#7f7f7f'),
geo=dict(scope=('north america', 'south america'),
projection=dict(type='orthographic',rotation=dict(lon=-60)),
showland=True, landcolor='#191919',
showcountries=True,
showocean=True, oceancolor='rgb(217,217,255)',
showframe=False,
),
xaxis=dict(showgrid=False, zeroline=False),
yaxis=dict(showgrid=False, zeroline=False))
fig = go.Figure(data=plot_data, layout=layout)
div = plotly.offline.plot(fig, include_plotlyjs=True, output_type='div')
return div
def mkLatLong():
#### TME: Get start time
start_time = time.time()
####
sess = requests.Session()
dbobj=dblayer.classDBLayer()
projection = [{"$project": {"_id": 0, "mag": "$properties.mag",
"depth": {"$arrayElemAt": ["$geometry.coordinates", 2]},
"longitude": {"$arrayElemAt": ["$geometry.coordinates", 0]},
"latitude": {"$arrayElemAt": ["$geometry.coordinates", 1]}}}]
df = pd.DataFrame(list(dbobj.doaggregate(projection)))
df = df[['longitude', 'latitude']].copy()
#### TME: Elapsed time taken to read data from MongoDB
fileobj = testfile.classFileWrite()
elapsed = time.time() - start_time
fileobj.writeline()
str1 = str(elapsed) + " secs required to read " + str(df['latitude'].count()) + " records from database."
fileobj.writelog("Reading Longitude and Latitude")
fileobj.writelog(str1)
####
#### TME: Get start time
start_time = time.time()
####
div = showLatLongInCluster(df.values)
response = """<html><title></title><head><meta charset=\"utf8\"> </head> <body>""" + div + """</body> </html>"""
dbobj.closedb()
#### TME: Elapsed time taken to cluster and plot data
elapsed = time.time() - start_time
fileobj.writeline()
str1 = "Time taken: " + str(elapsed)
fileobj.writelog("Applying DBSCAN clustering and plotting its output")
fileobj.writelog(str1)
fileobj.writeline()
fileobj.closefile()
####
return response
| generate_color | identifier_name |
dbscanplot.py | import requests
import time
import dblayer
from sklearn.cluster import DBSCAN
import plotly
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import random
import testfile
# Create random colors in list
color_list = [] | color = '#{:02x}{:02x}{:02x}'.format(*map(lambda x: random.randint(0, 255), range(ncluster)))
color_list.append(color)
def showLatLongInCluster(data):
# Run the DBSCAN from sklearn
dbscan = DBSCAN(eps=2, min_samples=5, metric='euclidean', algorithm='auto').fit(data)
cluster_labels = dbscan.labels_
n_clusters = len(set(cluster_labels)) - (1 if -1 in cluster_labels else 0)
generate_color(n_clusters)
plot_data = []
# get the cluster
for i in range(n_clusters):
ds = data[np.where(cluster_labels == i)]
clustername = "Cluster " + str(i + 1)
trace = go.Scattergeo(lon=ds[:,0], lat=ds[:,1],mode='markers',marker=dict(color=color_list[i], size=5),
name=clustername)
plot_data.append(trace)
layout = go.Layout(showlegend=False, title='Earthquakes In North and South America',
titlefont=dict(family='Courier New, monospace',size=20,color='#7f7f7f'),
geo=dict(scope=('north america', 'south america'),
projection=dict(type='orthographic',rotation=dict(lon=-60)),
showland=True, landcolor='#191919',
showcountries=True,
showocean=True, oceancolor='rgb(217,217,255)',
showframe=False,
),
xaxis=dict(showgrid=False, zeroline=False),
yaxis=dict(showgrid=False, zeroline=False))
fig = go.Figure(data=plot_data, layout=layout)
div = plotly.offline.plot(fig, include_plotlyjs=True, output_type='div')
return div
def mkLatLong():
#### TME: Get start time
start_time = time.time()
####
sess = requests.Session()
dbobj=dblayer.classDBLayer()
projection = [{"$project": {"_id": 0, "mag": "$properties.mag",
"depth": {"$arrayElemAt": ["$geometry.coordinates", 2]},
"longitude": {"$arrayElemAt": ["$geometry.coordinates", 0]},
"latitude": {"$arrayElemAt": ["$geometry.coordinates", 1]}}}]
df = pd.DataFrame(list(dbobj.doaggregate(projection)))
df = df[['longitude', 'latitude']].copy()
#### TME: Elapsed time taken to read data from MongoDB
fileobj = testfile.classFileWrite()
elapsed = time.time() - start_time
fileobj.writeline()
str1 = str(elapsed) + " secs required to read " + str(df['latitude'].count()) + " records from database."
fileobj.writelog("Reading Longitude and Latitude")
fileobj.writelog(str1)
####
#### TME: Get start time
start_time = time.time()
####
div = showLatLongInCluster(df.values)
response = """<html><title></title><head><meta charset=\"utf8\"> </head> <body>""" + div + """</body> </html>"""
dbobj.closedb()
#### TME: Elapsed time taken to cluster and plot data
elapsed = time.time() - start_time
fileobj.writeline()
str1 = "Time taken: " + str(elapsed)
fileobj.writelog("Applying DBSCAN clustering and plotting its output")
fileobj.writelog(str1)
fileobj.writeline()
fileobj.closefile()
####
return response | def generate_color(ncluster):
for i in range(ncluster): | random_line_split |
ContestEditor.tsx | /* 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 http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net>
*/
import * as React from 'react';
import { connect } from 'react-redux';
import SafetyBox from '../components/SafetyBox';
import { updateContest } from '../modules/contests';
interface Props {
dispatch: Function;
active: any;
}
class | extends React.Component<Props, {}> {
static formatTimestamp(stamp) {
if (stamp == null || !stamp.isValid()) {
return '';
}
return stamp.format('YYYY-MM-DD HH:mm:ss Z');
}
saveContest = e => {
const { dispatch, active } = this.props;
const fields = e.target.elements;
e.preventDefault();
function nully(v) {
if (v.length === 0) {
return null;
}
return v;
}
dispatch(updateContest(active.id, {
title: nully(fields.contest_title.value),
start_time: nully(fields.contest_start_time.value),
end_time: nully(fields.contest_end_time.value),
mode: fields.contest_mode.value,
code: nully(fields.contest_code.value),
problems: fields.contest_problems.value.trim().split('\n'),
archived: fields.contest_archived.checked,
}));
}
render() {
const { active } = this.props;
const startTime = ContestEditor.formatTimestamp(active.start_time);
const endTime = ContestEditor.formatTimestamp(active.end_time);
return (
<SafetyBox>
<form onSubmit={this.saveContest} className="container">
<div className="form-group row">
<label htmlFor="contest_title" className="col-3 col-form-label col-form-label-sm">Title</label>
<div className="col-9">
<input id="contest_title" type="text" defaultValue={active.title} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_start_time" className="col-3 col-form-label col-form-label-sm">Start Time</label>
<div className="col-9">
<input id="contest_start_time" type="text" defaultValue={startTime} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_end_time" className="col-3 col-form-label col-form-label-sm">End Time</label>
<div className="col-9">
<input id="contest_end_time" type="text" defaultValue={endTime} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_mode" className="col-3 col-form-label col-form-label-sm">Registration Mode</label>
<div className="col-9">
<select disabled id="contest_mode" defaultValue={active.mode} className="form-control form-control-sm"><option value="code">registration code</option></select>
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_code" className="col-3 col-form-label col-form-label-sm">Registration Code</label>
<div className="col-9">
<input id="contest_code" type="text" defaultValue={active.code} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_problems" className="col-3 col-form-label col-form-label-sm">Problems</label>
<div className="col-9">
<textarea id="contest_problems" defaultValue={active.problems.join('\n')} rows={6} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<div className="form-check col">
<label htmlFor="contest_archived" className="form-check-label">
<input id="contest_archived" type="checkbox" value="true" defaultChecked={active.archived} className="form-check-input" /> Archived
</label>
</div>
</div>
<button type="submit" className="btn btn-primary">Save</button>
</form>
</SafetyBox>
);
}
}
export default connect(state => {
return {
active: state.contests.active,
};
})(ContestEditor) as React.ComponentClass<{}>;
| ContestEditor | identifier_name |
ContestEditor.tsx | /* 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 http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net>
*/
import * as React from 'react';
import { connect } from 'react-redux';
import SafetyBox from '../components/SafetyBox';
import { updateContest } from '../modules/contests';
interface Props {
dispatch: Function;
active: any;
}
class ContestEditor extends React.Component<Props, {}> {
static formatTimestamp(stamp) {
if (stamp == null || !stamp.isValid()) {
return '';
}
return stamp.format('YYYY-MM-DD HH:mm:ss Z');
}
saveContest = e => {
const { dispatch, active } = this.props;
const fields = e.target.elements;
e.preventDefault();
function nully(v) {
if (v.length === 0) {
return null;
}
return v;
}
dispatch(updateContest(active.id, {
title: nully(fields.contest_title.value),
start_time: nully(fields.contest_start_time.value),
end_time: nully(fields.contest_end_time.value),
mode: fields.contest_mode.value,
code: nully(fields.contest_code.value),
problems: fields.contest_problems.value.trim().split('\n'),
archived: fields.contest_archived.checked,
}));
}
render() {
const { active } = this.props;
const startTime = ContestEditor.formatTimestamp(active.start_time);
const endTime = ContestEditor.formatTimestamp(active.end_time);
return (
<SafetyBox>
<form onSubmit={this.saveContest} className="container">
<div className="form-group row">
<label htmlFor="contest_title" className="col-3 col-form-label col-form-label-sm">Title</label>
<div className="col-9">
<input id="contest_title" type="text" defaultValue={active.title} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_start_time" className="col-3 col-form-label col-form-label-sm">Start Time</label>
<div className="col-9">
<input id="contest_start_time" type="text" defaultValue={startTime} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_end_time" className="col-3 col-form-label col-form-label-sm">End Time</label>
<div className="col-9">
<input id="contest_end_time" type="text" defaultValue={endTime} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_mode" className="col-3 col-form-label col-form-label-sm">Registration Mode</label>
<div className="col-9">
<select disabled id="contest_mode" defaultValue={active.mode} className="form-control form-control-sm"><option value="code">registration code</option></select>
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_code" className="col-3 col-form-label col-form-label-sm">Registration Code</label>
<div className="col-9">
<input id="contest_code" type="text" defaultValue={active.code} className="form-control form-control-sm" /> | <div className="form-group row">
<label htmlFor="contest_problems" className="col-3 col-form-label col-form-label-sm">Problems</label>
<div className="col-9">
<textarea id="contest_problems" defaultValue={active.problems.join('\n')} rows={6} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<div className="form-check col">
<label htmlFor="contest_archived" className="form-check-label">
<input id="contest_archived" type="checkbox" value="true" defaultChecked={active.archived} className="form-check-input" /> Archived
</label>
</div>
</div>
<button type="submit" className="btn btn-primary">Save</button>
</form>
</SafetyBox>
);
}
}
export default connect(state => {
return {
active: state.contests.active,
};
})(ContestEditor) as React.ComponentClass<{}>; | </div>
</div>
| random_line_split |
ContestEditor.tsx | /* 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 http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net>
*/
import * as React from 'react';
import { connect } from 'react-redux';
import SafetyBox from '../components/SafetyBox';
import { updateContest } from '../modules/contests';
interface Props {
dispatch: Function;
active: any;
}
class ContestEditor extends React.Component<Props, {}> {
static formatTimestamp(stamp) {
if (stamp == null || !stamp.isValid()) {
return '';
}
return stamp.format('YYYY-MM-DD HH:mm:ss Z');
}
saveContest = e => {
const { dispatch, active } = this.props;
const fields = e.target.elements;
e.preventDefault();
function nully(v) {
if (v.length === 0) |
return v;
}
dispatch(updateContest(active.id, {
title: nully(fields.contest_title.value),
start_time: nully(fields.contest_start_time.value),
end_time: nully(fields.contest_end_time.value),
mode: fields.contest_mode.value,
code: nully(fields.contest_code.value),
problems: fields.contest_problems.value.trim().split('\n'),
archived: fields.contest_archived.checked,
}));
}
render() {
const { active } = this.props;
const startTime = ContestEditor.formatTimestamp(active.start_time);
const endTime = ContestEditor.formatTimestamp(active.end_time);
return (
<SafetyBox>
<form onSubmit={this.saveContest} className="container">
<div className="form-group row">
<label htmlFor="contest_title" className="col-3 col-form-label col-form-label-sm">Title</label>
<div className="col-9">
<input id="contest_title" type="text" defaultValue={active.title} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_start_time" className="col-3 col-form-label col-form-label-sm">Start Time</label>
<div className="col-9">
<input id="contest_start_time" type="text" defaultValue={startTime} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_end_time" className="col-3 col-form-label col-form-label-sm">End Time</label>
<div className="col-9">
<input id="contest_end_time" type="text" defaultValue={endTime} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_mode" className="col-3 col-form-label col-form-label-sm">Registration Mode</label>
<div className="col-9">
<select disabled id="contest_mode" defaultValue={active.mode} className="form-control form-control-sm"><option value="code">registration code</option></select>
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_code" className="col-3 col-form-label col-form-label-sm">Registration Code</label>
<div className="col-9">
<input id="contest_code" type="text" defaultValue={active.code} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_problems" className="col-3 col-form-label col-form-label-sm">Problems</label>
<div className="col-9">
<textarea id="contest_problems" defaultValue={active.problems.join('\n')} rows={6} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<div className="form-check col">
<label htmlFor="contest_archived" className="form-check-label">
<input id="contest_archived" type="checkbox" value="true" defaultChecked={active.archived} className="form-check-input" /> Archived
</label>
</div>
</div>
<button type="submit" className="btn btn-primary">Save</button>
</form>
</SafetyBox>
);
}
}
export default connect(state => {
return {
active: state.contests.active,
};
})(ContestEditor) as React.ComponentClass<{}>;
| {
return null;
} | conditional_block |
ContestEditor.tsx | /* 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 http://mozilla.org/MPL/2.0/.
*
* Copyright (c) 2016 Jacob Peddicord <jacob@peddicord.net>
*/
import * as React from 'react';
import { connect } from 'react-redux';
import SafetyBox from '../components/SafetyBox';
import { updateContest } from '../modules/contests';
interface Props {
dispatch: Function;
active: any;
}
class ContestEditor extends React.Component<Props, {}> {
static formatTimestamp(stamp) {
if (stamp == null || !stamp.isValid()) {
return '';
}
return stamp.format('YYYY-MM-DD HH:mm:ss Z');
}
saveContest = e => {
const { dispatch, active } = this.props;
const fields = e.target.elements;
e.preventDefault();
function nully(v) {
if (v.length === 0) {
return null;
}
return v;
}
dispatch(updateContest(active.id, {
title: nully(fields.contest_title.value),
start_time: nully(fields.contest_start_time.value),
end_time: nully(fields.contest_end_time.value),
mode: fields.contest_mode.value,
code: nully(fields.contest_code.value),
problems: fields.contest_problems.value.trim().split('\n'),
archived: fields.contest_archived.checked,
}));
}
render() |
}
export default connect(state => {
return {
active: state.contests.active,
};
})(ContestEditor) as React.ComponentClass<{}>;
| {
const { active } = this.props;
const startTime = ContestEditor.formatTimestamp(active.start_time);
const endTime = ContestEditor.formatTimestamp(active.end_time);
return (
<SafetyBox>
<form onSubmit={this.saveContest} className="container">
<div className="form-group row">
<label htmlFor="contest_title" className="col-3 col-form-label col-form-label-sm">Title</label>
<div className="col-9">
<input id="contest_title" type="text" defaultValue={active.title} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_start_time" className="col-3 col-form-label col-form-label-sm">Start Time</label>
<div className="col-9">
<input id="contest_start_time" type="text" defaultValue={startTime} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_end_time" className="col-3 col-form-label col-form-label-sm">End Time</label>
<div className="col-9">
<input id="contest_end_time" type="text" defaultValue={endTime} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_mode" className="col-3 col-form-label col-form-label-sm">Registration Mode</label>
<div className="col-9">
<select disabled id="contest_mode" defaultValue={active.mode} className="form-control form-control-sm"><option value="code">registration code</option></select>
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_code" className="col-3 col-form-label col-form-label-sm">Registration Code</label>
<div className="col-9">
<input id="contest_code" type="text" defaultValue={active.code} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<label htmlFor="contest_problems" className="col-3 col-form-label col-form-label-sm">Problems</label>
<div className="col-9">
<textarea id="contest_problems" defaultValue={active.problems.join('\n')} rows={6} className="form-control form-control-sm" />
</div>
</div>
<div className="form-group row">
<div className="form-check col">
<label htmlFor="contest_archived" className="form-check-label">
<input id="contest_archived" type="checkbox" value="true" defaultChecked={active.archived} className="form-check-input" /> Archived
</label>
</div>
</div>
<button type="submit" className="btn btn-primary">Save</button>
</form>
</SafetyBox>
);
} | identifier_body |
LogService.js | module.exports = {
login: function(user, req)
{
// Parse detailed information from user-agent string
var r = require('ua-parser').parse(req.headers['user-agent']);
// Create new UserLogin row to database
sails.models.loglogin.create({
ip: req.ip,
host: req.host,
agent: req.headers['user-agent'],
browser: r.ua.toString(),
browserVersion: r.ua.toVersionString(),
browserFamily: r.ua.family,
os: r.os.toString(),
osVersion: r.os.toVersionString(),
osFamily: r.os.family,
device: r.device.family,
user: user.id
})
.exec(function(err, created) {
if(err) sails.log(err);
| request: function(log, req, resp)
{
//var userId = -1;
// if (req.token) {
// userId = req.token;
// } else {
// userId = -1;
// }
sails.models.logrequest.create({
ip: log.ip,
protocol: log.protocol,
method: log.method,
url: log.diagnostic.url,
headers: req.headers || {},
parameters: log.diagnostic.routeParams,
body: log.diagnostic.bodyParams,
query: log.diagnostic.queryParams,
responseTime: log.responseTime || 0,
middlewareLatency: log.diagnostic.middlewareLatency || 0,
user: req.token || 0
})
.exec(function(err, created) {
if(err) sails.log(err);
sails.models.logrequest.publishCreate(created);
});
}
}; | created.user = user;
sails.models.loglogin.publishCreate(created);
});
},
| random_line_split |
upgrade042.py | self.description = "Backup file relocation"
lp1 = pmpkg("bash")
lp1.files = ["etc/profile*"]
lp1.backup = ["etc/profile"]
self.addpkg2db("local", lp1)
p1 = pmpkg("bash", "1.0-2")
self.addpkg(p1)
lp2 = pmpkg("filesystem")
self.addpkg2db("local", lp2)
p2 = pmpkg("filesystem", "1.0-2")
p2.files = ["etc/profile**"]
p2.backup = ["etc/profile"] | self.addpkg(p2)
self.args = "-U %s" % " ".join([p.filename() for p in (p1, p2)])
self.filesystem = ["etc/profile"]
self.addrule("PACMAN_RETCODE=0")
self.addrule("PKG_VERSION=bash|1.0-2")
self.addrule("PKG_VERSION=filesystem|1.0-2")
self.addrule("!FILE_PACSAVE=etc/profile")
self.addrule("FILE_PACNEW=etc/profile")
self.addrule("FILE_EXIST=etc/profile") | p2.depends = [ "bash" ] | random_line_split |
helpper.js | //Init
var CANVAS_WIDTH = 512;
var CANVAS_HEIGHT = 512;
var MOVABLE = "movable";
//jiglib body types in strings
var BODY_TYPES = ["SPHERE", "BOX","CAPSULE", "PLANE"];
//enums for indexing BODY_TYPES
var BodyValues = {"SPHERE":0, "BOX":1, "CAPSULE":2, "PLANE":3};
var SCORE_LOC_X = 130;
var SCORE_LOC_Y = 475; | var SCORE_TEXT_CONTENT = "score:";
//Factors for the ray xyz-values. Used in initStatusScene()
var RAY_FACTOR_X = -5;
var RAY_FACTOR_Y = 5;
var RAY_FACTOR_Z = -5;
//Start and end message constants
var GAME_OVER_TEXT = "Game over!";
var START_GAME_TEXT = "Press 'enter' to start!";
var START_OFFSET_X = 0;
var START_OFFSET_Y = 0;
var START_OFFSET_Z = -5;
var END_OFFSET_X = 0;
var END_OFFSET_Y = 0;
var END_OFFSET_Z = -5;
var DEFAULT_FOG_COLOR = "#3F3F3F";
var EFFECT_FOG_COLOR = "#DCFCCC";
var SCORE_TEXT_COLOR = "#D0F0C0";
var SCORE_TEXT_SIZE = 10;
var STATE_TEXT_COLOR = "#D0F0C0";//"#ffdd00";
var STATE_TEXT_SIZE = 17;
var calculateSize = function(side1, side2){
if(side2 == side1){
return 0;
}
else if(side2 < 0.0 && side1 >= 0.0){
return(Math.abs(side2) + side1);
}
else if(side1 < 0.0 && side2 >= 0.0){
return(Math.abs(side1) + side2);
}
else if(side1 >= 0.0 && side2 >= 0.0 && side1 > side2){
return(side1-side2);
}
else if(side1 >= 0.0 && side2 >= 0.0 && side2 > side1){
return(side2-side1);
}
else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side1) > Math.abs(side2)){
return(Math.abs(side1)-Math.abs(side2));
}
else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side2) > Math.abs(side1)){
return(Math.abs(side2)-Math.abs(side1));
}
} | var SCORETEXT_LOC_X = 70;
var SCORETEXT_LOC_Y = 478; | random_line_split |
helpper.js | //Init
var CANVAS_WIDTH = 512;
var CANVAS_HEIGHT = 512;
var MOVABLE = "movable";
//jiglib body types in strings
var BODY_TYPES = ["SPHERE", "BOX","CAPSULE", "PLANE"];
//enums for indexing BODY_TYPES
var BodyValues = {"SPHERE":0, "BOX":1, "CAPSULE":2, "PLANE":3};
var SCORE_LOC_X = 130;
var SCORE_LOC_Y = 475;
var SCORETEXT_LOC_X = 70;
var SCORETEXT_LOC_Y = 478;
var SCORE_TEXT_CONTENT = "score:";
//Factors for the ray xyz-values. Used in initStatusScene()
var RAY_FACTOR_X = -5;
var RAY_FACTOR_Y = 5;
var RAY_FACTOR_Z = -5;
//Start and end message constants
var GAME_OVER_TEXT = "Game over!";
var START_GAME_TEXT = "Press 'enter' to start!";
var START_OFFSET_X = 0;
var START_OFFSET_Y = 0;
var START_OFFSET_Z = -5;
var END_OFFSET_X = 0;
var END_OFFSET_Y = 0;
var END_OFFSET_Z = -5;
var DEFAULT_FOG_COLOR = "#3F3F3F";
var EFFECT_FOG_COLOR = "#DCFCCC";
var SCORE_TEXT_COLOR = "#D0F0C0";
var SCORE_TEXT_SIZE = 10;
var STATE_TEXT_COLOR = "#D0F0C0";//"#ffdd00";
var STATE_TEXT_SIZE = 17;
var calculateSize = function(side1, side2){
if(side2 == side1){
return 0;
}
else if(side2 < 0.0 && side1 >= 0.0){
return(Math.abs(side2) + side1);
}
else if(side1 < 0.0 && side2 >= 0.0){
return(Math.abs(side1) + side2);
}
else if(side1 >= 0.0 && side2 >= 0.0 && side1 > side2){
| else if(side1 >= 0.0 && side2 >= 0.0 && side2 > side1){
return(side2-side1);
}
else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side1) > Math.abs(side2)){
return(Math.abs(side1)-Math.abs(side2));
}
else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side2) > Math.abs(side1)){
return(Math.abs(side2)-Math.abs(side1));
}
} | return(side1-side2);
}
| conditional_block |
theming-tests.tsx | import * as React from "react";
import {
channel,
ContextWithTheme,
Theme,
themeListener,
ThemeProvider,
withTheme
} from "theming";
// Typings currently accept non-plain-objects while they get rejected at runtime.
// There exists currently no typing for plain objects.
const runtimeErrorTheme: Theme = [];
const customTheme = { | primary: "red",
secondary: "blue"
}
};
type CustomTheme = typeof customTheme;
interface DemoBoxProps {
text: string;
theme: CustomTheme;
}
const DemoBox = ({ text, theme }: DemoBoxProps) => {
return <div style={{ color: theme.color.primary }}>{text}</div>;
};
const ThemedDemoBox = withTheme(DemoBox);
const renderDemoBox = () => <ThemedDemoBox text="Hello, World!" />;
const App = () => {
return (
<ThemeProvider theme={customTheme}>
<ThemedDemoBox text="Theme provided" />
</ThemeProvider>
);
};
const AugmentedApp = () => {
return (
<ThemeProvider theme={customTheme}>
<ThemeProvider theme={outerTheme => ({ ...outerTheme, augmented: true })}>
<ThemedDemoBox text="Theme provided" />
</ThemeProvider>
</ThemeProvider>
);
};
function customWithTheme<P>(
// tslint:disable-next-line: no-unnecessary-generics
Component: React.ComponentType<P & { theme: object }>
) {
return class CustomWithTheme extends React.Component<P, { theme: object }> {
static contextTypes = themeListener.contextTypes;
context: any;
setTheme = (theme: object) => this.setState({ theme });
subscription: number | undefined;
constructor(props: P, context: ContextWithTheme<typeof channel>) {
super(props, context);
this.state = { theme: themeListener.initial(context) };
}
componentDidMount() {
this.subscription = themeListener.subscribe(this.context, this.setTheme);
}
componentWillUnmount() {
const { subscription } = this;
if (subscription != null) {
themeListener.unsubscribe(this.context, subscription);
}
}
render() {
const { theme } = this.state;
return <Component theme={theme} {...this.props} />;
}
};
} | color: { | random_line_split |
theming-tests.tsx | import * as React from "react";
import {
channel,
ContextWithTheme,
Theme,
themeListener,
ThemeProvider,
withTheme
} from "theming";
// Typings currently accept non-plain-objects while they get rejected at runtime.
// There exists currently no typing for plain objects.
const runtimeErrorTheme: Theme = [];
const customTheme = {
color: {
primary: "red",
secondary: "blue"
}
};
type CustomTheme = typeof customTheme;
interface DemoBoxProps {
text: string;
theme: CustomTheme;
}
const DemoBox = ({ text, theme }: DemoBoxProps) => {
return <div style={{ color: theme.color.primary }}>{text}</div>;
};
const ThemedDemoBox = withTheme(DemoBox);
const renderDemoBox = () => <ThemedDemoBox text="Hello, World!" />;
const App = () => {
return (
<ThemeProvider theme={customTheme}>
<ThemedDemoBox text="Theme provided" />
</ThemeProvider>
);
};
const AugmentedApp = () => {
return (
<ThemeProvider theme={customTheme}>
<ThemeProvider theme={outerTheme => ({ ...outerTheme, augmented: true })}>
<ThemedDemoBox text="Theme provided" />
</ThemeProvider>
</ThemeProvider>
);
};
function customWithTheme<P>(
// tslint:disable-next-line: no-unnecessary-generics
Component: React.ComponentType<P & { theme: object }>
) {
return class CustomWithTheme extends React.Component<P, { theme: object }> {
static contextTypes = themeListener.contextTypes;
context: any;
setTheme = (theme: object) => this.setState({ theme });
subscription: number | undefined;
constructor(props: P, context: ContextWithTheme<typeof channel>) |
componentDidMount() {
this.subscription = themeListener.subscribe(this.context, this.setTheme);
}
componentWillUnmount() {
const { subscription } = this;
if (subscription != null) {
themeListener.unsubscribe(this.context, subscription);
}
}
render() {
const { theme } = this.state;
return <Component theme={theme} {...this.props} />;
}
};
}
| {
super(props, context);
this.state = { theme: themeListener.initial(context) };
} | identifier_body |
theming-tests.tsx | import * as React from "react";
import {
channel,
ContextWithTheme,
Theme,
themeListener,
ThemeProvider,
withTheme
} from "theming";
// Typings currently accept non-plain-objects while they get rejected at runtime.
// There exists currently no typing for plain objects.
const runtimeErrorTheme: Theme = [];
const customTheme = {
color: {
primary: "red",
secondary: "blue"
}
};
type CustomTheme = typeof customTheme;
interface DemoBoxProps {
text: string;
theme: CustomTheme;
}
const DemoBox = ({ text, theme }: DemoBoxProps) => {
return <div style={{ color: theme.color.primary }}>{text}</div>;
};
const ThemedDemoBox = withTheme(DemoBox);
const renderDemoBox = () => <ThemedDemoBox text="Hello, World!" />;
const App = () => {
return (
<ThemeProvider theme={customTheme}>
<ThemedDemoBox text="Theme provided" />
</ThemeProvider>
);
};
const AugmentedApp = () => {
return (
<ThemeProvider theme={customTheme}>
<ThemeProvider theme={outerTheme => ({ ...outerTheme, augmented: true })}>
<ThemedDemoBox text="Theme provided" />
</ThemeProvider>
</ThemeProvider>
);
};
function customWithTheme<P>(
// tslint:disable-next-line: no-unnecessary-generics
Component: React.ComponentType<P & { theme: object }>
) {
return class CustomWithTheme extends React.Component<P, { theme: object }> {
static contextTypes = themeListener.contextTypes;
context: any;
setTheme = (theme: object) => this.setState({ theme });
subscription: number | undefined;
constructor(props: P, context: ContextWithTheme<typeof channel>) {
super(props, context);
this.state = { theme: themeListener.initial(context) };
}
componentDidMount() {
this.subscription = themeListener.subscribe(this.context, this.setTheme);
}
| () {
const { subscription } = this;
if (subscription != null) {
themeListener.unsubscribe(this.context, subscription);
}
}
render() {
const { theme } = this.state;
return <Component theme={theme} {...this.props} />;
}
};
}
| componentWillUnmount | identifier_name |
theming-tests.tsx | import * as React from "react";
import {
channel,
ContextWithTheme,
Theme,
themeListener,
ThemeProvider,
withTheme
} from "theming";
// Typings currently accept non-plain-objects while they get rejected at runtime.
// There exists currently no typing for plain objects.
const runtimeErrorTheme: Theme = [];
const customTheme = {
color: {
primary: "red",
secondary: "blue"
}
};
type CustomTheme = typeof customTheme;
interface DemoBoxProps {
text: string;
theme: CustomTheme;
}
const DemoBox = ({ text, theme }: DemoBoxProps) => {
return <div style={{ color: theme.color.primary }}>{text}</div>;
};
const ThemedDemoBox = withTheme(DemoBox);
const renderDemoBox = () => <ThemedDemoBox text="Hello, World!" />;
const App = () => {
return (
<ThemeProvider theme={customTheme}>
<ThemedDemoBox text="Theme provided" />
</ThemeProvider>
);
};
const AugmentedApp = () => {
return (
<ThemeProvider theme={customTheme}>
<ThemeProvider theme={outerTheme => ({ ...outerTheme, augmented: true })}>
<ThemedDemoBox text="Theme provided" />
</ThemeProvider>
</ThemeProvider>
);
};
function customWithTheme<P>(
// tslint:disable-next-line: no-unnecessary-generics
Component: React.ComponentType<P & { theme: object }>
) {
return class CustomWithTheme extends React.Component<P, { theme: object }> {
static contextTypes = themeListener.contextTypes;
context: any;
setTheme = (theme: object) => this.setState({ theme });
subscription: number | undefined;
constructor(props: P, context: ContextWithTheme<typeof channel>) {
super(props, context);
this.state = { theme: themeListener.initial(context) };
}
componentDidMount() {
this.subscription = themeListener.subscribe(this.context, this.setTheme);
}
componentWillUnmount() {
const { subscription } = this;
if (subscription != null) |
}
render() {
const { theme } = this.state;
return <Component theme={theme} {...this.props} />;
}
};
}
| {
themeListener.unsubscribe(this.context, subscription);
} | conditional_block |
setup.py | #!/usr/bin/env python
# This file is part of Py6S.
#
# Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file.
#
# Py6S is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Py6S is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License |
PROJECT_ROOT = os.path.dirname(__file__)
def read_file(filepath, root=PROJECT_ROOT):
"""
Return the contents of the specified `filepath`.
* `root` is the base path and it defaults to the `PROJECT_ROOT` directory.
* `filepath` should be a relative path, starting from `root`.
"""
with open(os.path.join(root, filepath)) as fd:
text = fd.read()
return text
LONG_DESCRIPTION = read_file("README.rst")
SHORT_DESCRIPTION = "A wrapper for the 6S Radiative Transfer Model to make it easy to run simulations with a variety of input parameters, and to produce outputs in an easily processable form."
REQS = [
'pysolar==0.6',
'matplotlib',
'scipy'
]
setup(
name = "Py6S",
packages = ['Py6S', 'Py6S.Params', 'Py6S.SixSHelpers'],
install_requires = REQS,
version = "1.6.2",
author = "Robin Wilson",
author_email = "robin@rtwilson.com",
description = SHORT_DESCRIPTION,
license = "GPL",
test_suite = 'nose.collector',
url = "http://py6s.rtwilson.com/",
long_description = LONG_DESCRIPTION,
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Atmospheric Science",
"Topic :: Scientific/Engineering :: Physics",
"Topic :: Software Development :: Libraries :: Python Modules",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 2"
],
) | # along with Py6S. If not, see <http://www.gnu.org/licenses/>.
import os
from setuptools import setup
| random_line_split |
setup.py | #!/usr/bin/env python
# This file is part of Py6S.
#
# Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file.
#
# Py6S is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Py6S is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Py6S. If not, see <http://www.gnu.org/licenses/>.
import os
from setuptools import setup
PROJECT_ROOT = os.path.dirname(__file__)
def read_file(filepath, root=PROJECT_ROOT):
|
LONG_DESCRIPTION = read_file("README.rst")
SHORT_DESCRIPTION = "A wrapper for the 6S Radiative Transfer Model to make it easy to run simulations with a variety of input parameters, and to produce outputs in an easily processable form."
REQS = [
'pysolar==0.6',
'matplotlib',
'scipy'
]
setup(
name = "Py6S",
packages = ['Py6S', 'Py6S.Params', 'Py6S.SixSHelpers'],
install_requires = REQS,
version = "1.6.2",
author = "Robin Wilson",
author_email = "robin@rtwilson.com",
description = SHORT_DESCRIPTION,
license = "GPL",
test_suite = 'nose.collector',
url = "http://py6s.rtwilson.com/",
long_description = LONG_DESCRIPTION,
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Atmospheric Science",
"Topic :: Scientific/Engineering :: Physics",
"Topic :: Software Development :: Libraries :: Python Modules",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 2"
],
)
| """
Return the contents of the specified `filepath`.
* `root` is the base path and it defaults to the `PROJECT_ROOT` directory.
* `filepath` should be a relative path, starting from `root`.
"""
with open(os.path.join(root, filepath)) as fd:
text = fd.read()
return text | identifier_body |
setup.py | #!/usr/bin/env python
# This file is part of Py6S.
#
# Copyright 2012 Robin Wilson and contributors listed in the CONTRIBUTORS file.
#
# Py6S is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Py6S is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Py6S. If not, see <http://www.gnu.org/licenses/>.
import os
from setuptools import setup
PROJECT_ROOT = os.path.dirname(__file__)
def | (filepath, root=PROJECT_ROOT):
"""
Return the contents of the specified `filepath`.
* `root` is the base path and it defaults to the `PROJECT_ROOT` directory.
* `filepath` should be a relative path, starting from `root`.
"""
with open(os.path.join(root, filepath)) as fd:
text = fd.read()
return text
LONG_DESCRIPTION = read_file("README.rst")
SHORT_DESCRIPTION = "A wrapper for the 6S Radiative Transfer Model to make it easy to run simulations with a variety of input parameters, and to produce outputs in an easily processable form."
REQS = [
'pysolar==0.6',
'matplotlib',
'scipy'
]
setup(
name = "Py6S",
packages = ['Py6S', 'Py6S.Params', 'Py6S.SixSHelpers'],
install_requires = REQS,
version = "1.6.2",
author = "Robin Wilson",
author_email = "robin@rtwilson.com",
description = SHORT_DESCRIPTION,
license = "GPL",
test_suite = 'nose.collector',
url = "http://py6s.rtwilson.com/",
long_description = LONG_DESCRIPTION,
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Science/Research",
"Topic :: Scientific/Engineering :: Atmospheric Science",
"Topic :: Scientific/Engineering :: Physics",
"Topic :: Software Development :: Libraries :: Python Modules",
"License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 2"
],
)
| read_file | identifier_name |
elem.js | module.exports = {
dom(element,type){
let DOM = document.createElement(element);
if(type){
for(let key in type){
DOM.setAttribute(key,type[key])
}
}
return DOM
},
// 添加类
addClass(element,newclass){
if(element.className){
var oldClass=element.className;
element.className=oldClass+" "+newclass;
}else{
| ,
removeClass(element, a_class){
var obj_class = ' '+element.className+' ';//获取 class 内容, 并在首尾各加一个空格. ex) 'abc bcd' -> ' abc bcd '
obj_class = obj_class.replace(/(\s+)/gi, ' ');//将多余的空字符替换成一个空格. ex) ' abc bcd ' -> ' abc bcd '
var removed = obj_class.replace(' '+a_class+' ', ' ');//在原来的 class 替换掉首尾加了空格的 class. ex) ' abc bcd ' -> 'bcd '
removed = removed.replace(/(^\s+)|(\s+$)/g, '');//去掉首尾空格. ex) 'bcd ' -> 'bcd'
if(removed){
element.className = removed;//替换原来的 class.
}else{
element.removeAttribute('class')
}
}
}
| element.className=newclass;
}
} | conditional_block |
elem.js | module.exports = {
dom(element,type){
let DOM = document.createElement(element);
if(type){
for(let key in type){
DOM.setAttribute(key,type[key])
}
}
return DOM
},
// 添加类 | }else{
element.className=newclass;
}
},
removeClass(element, a_class){
var obj_class = ' '+element.className+' ';//获取 class 内容, 并在首尾各加一个空格. ex) 'abc bcd' -> ' abc bcd '
obj_class = obj_class.replace(/(\s+)/gi, ' ');//将多余的空字符替换成一个空格. ex) ' abc bcd ' -> ' abc bcd '
var removed = obj_class.replace(' '+a_class+' ', ' ');//在原来的 class 替换掉首尾加了空格的 class. ex) ' abc bcd ' -> 'bcd '
removed = removed.replace(/(^\s+)|(\s+$)/g, '');//去掉首尾空格. ex) 'bcd ' -> 'bcd'
if(removed){
element.className = removed;//替换原来的 class.
}else{
element.removeAttribute('class')
}
}
} | addClass(element,newclass){
if(element.className){
var oldClass=element.className;
element.className=oldClass+" "+newclass; | random_line_split |
elem.js | module.exports = {
dom(element,type){
let DOM = document.createElement(element);
if(type){
for(let key in type){
DOM.setAttribute(key,type[key])
}
}
return DOM
},
// 添加类
addCla | nt,newclass){
if(element.className){
var oldClass=element.className;
element.className=oldClass+" "+newclass;
}else{
element.className=newclass;
}
},
removeClass(element, a_class){
var obj_class = ' '+element.className+' ';//获取 class 内容, 并在首尾各加一个空格. ex) 'abc bcd' -> ' abc bcd '
obj_class = obj_class.replace(/(\s+)/gi, ' ');//将多余的空字符替换成一个空格. ex) ' abc bcd ' -> ' abc bcd '
var removed = obj_class.replace(' '+a_class+' ', ' ');//在原来的 class 替换掉首尾加了空格的 class. ex) ' abc bcd ' -> 'bcd '
removed = removed.replace(/(^\s+)|(\s+$)/g, '');//去掉首尾空格. ex) 'bcd ' -> 'bcd'
if(removed){
element.className = removed;//替换原来的 class.
}else{
element.removeAttribute('class')
}
}
}
| ss(eleme | identifier_name |
elem.js | module.exports = {
dom(element,type){
let DOM = document.createElement(element);
if(type){
for(let key in type){
DOM.setAttribute(key,type[key])
}
}
return DOM
},
// 添加类
addClass(element,newclass){
| removeClass(element, a_class){
var obj_class = ' '+element.className+' ';//获取 class 内容, 并在首尾各加一个空格. ex) 'abc bcd' -> ' abc bcd '
obj_class = obj_class.replace(/(\s+)/gi, ' ');//将多余的空字符替换成一个空格. ex) ' abc bcd ' -> ' abc bcd '
var removed = obj_class.replace(' '+a_class+' ', ' ');//在原来的 class 替换掉首尾加了空格的 class. ex) ' abc bcd ' -> 'bcd '
removed = removed.replace(/(^\s+)|(\s+$)/g, '');//去掉首尾空格. ex) 'bcd ' -> 'bcd'
if(removed){
element.className = removed;//替换原来的 class.
}else{
element.removeAttribute('class')
}
}
}
| if(element.className){
var oldClass=element.className;
element.className=oldClass+" "+newclass;
}else{
element.className=newclass;
}
},
| identifier_body |
index.js | /**
* Return an array of valid extensions, eg. ['.js','.json','.node']
*
* @api public
*/
function require_extensions()
{
return Object.keys(require.extensions);
}
module.exports = require_extensions;
/**
* return a glob pattern for `require.extensions`
*
* @api public
*/
function glob()
{
return '.{'+
require_extensions()
.map(function(ext) {
return ext.substr(1)
})
.join(',')
+'}';
}
module.exports.glob = glob;
/**
* return a new `RegExp` object that matches `require.extensions`
*
* @api public
*/
function | (group)
{
return new RegExp(regexp_string(group)+'$');
}
module.exports.regexp = regexp;
/**
* return a new `String` regular expression that matches `require.extensions`
*
* @api public
*/
function regexp_string(group)
{
return '(' + (group ? '' : '?:') + (require_extensions()
.map(function(ext){ return '\\'+ext; })
.join('|')) +
')'
}
module.exports.regexp.string = regexp_string;
Object.defineProperty(require.extensions,'glob',{
enumerable: false,
get: module.exports.glob
});
Object.defineProperty(require.extensions,'regexp',{
enumerable: false,
get: module.exports.regexp
});
| regexp | identifier_name |
index.js | /**
* Return an array of valid extensions, eg. ['.js','.json','.node']
*
* @api public
*/
function require_extensions()
|
module.exports = require_extensions;
/**
* return a glob pattern for `require.extensions`
*
* @api public
*/
function glob()
{
return '.{'+
require_extensions()
.map(function(ext) {
return ext.substr(1)
})
.join(',')
+'}';
}
module.exports.glob = glob;
/**
* return a new `RegExp` object that matches `require.extensions`
*
* @api public
*/
function regexp(group)
{
return new RegExp(regexp_string(group)+'$');
}
module.exports.regexp = regexp;
/**
* return a new `String` regular expression that matches `require.extensions`
*
* @api public
*/
function regexp_string(group)
{
return '(' + (group ? '' : '?:') + (require_extensions()
.map(function(ext){ return '\\'+ext; })
.join('|')) +
')'
}
module.exports.regexp.string = regexp_string;
Object.defineProperty(require.extensions,'glob',{
enumerable: false,
get: module.exports.glob
});
Object.defineProperty(require.extensions,'regexp',{
enumerable: false,
get: module.exports.regexp
});
| {
return Object.keys(require.extensions);
} | identifier_body |
index.js | /**
* Return an array of valid extensions, eg. ['.js','.json','.node']
*
* @api public
*/
function require_extensions()
{
return Object.keys(require.extensions);
}
module.exports = require_extensions;
/**
* return a glob pattern for `require.extensions`
*
* @api public
*/
function glob()
{
return '.{'+
require_extensions()
.map(function(ext) {
return ext.substr(1)
})
.join(',')
+'}';
}
module.exports.glob = glob;
/**
* return a new `RegExp` object that matches `require.extensions` | * @api public
*/
function regexp(group)
{
return new RegExp(regexp_string(group)+'$');
}
module.exports.regexp = regexp;
/**
* return a new `String` regular expression that matches `require.extensions`
*
* @api public
*/
function regexp_string(group)
{
return '(' + (group ? '' : '?:') + (require_extensions()
.map(function(ext){ return '\\'+ext; })
.join('|')) +
')'
}
module.exports.regexp.string = regexp_string;
Object.defineProperty(require.extensions,'glob',{
enumerable: false,
get: module.exports.glob
});
Object.defineProperty(require.extensions,'regexp',{
enumerable: false,
get: module.exports.regexp
}); | * | random_line_split |
lib.rs | /*
* Exopticon - A free video surveillance system.
* Copyright (C) 2020 David Matthew Mattli <dmm@mattli.us>
*
* This file is part of Exopticon.
*
* Exopticon is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Exopticon is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Exopticon. If not, see <http://www.gnu.org/licenses/>.
*/
use std::convert::TryFrom;
use std::ffi::CStr;
use std::io::{self, Write};
use std::slice;
//
use bincode::serialize;
use libc::c_char;
use crate::models::{CaptureMessage, FrameMessage};
pub mod models;
pub fn print_message(message: CaptureMessage) {
let serialized = serialize(&message).expect("Unable to serialize message!");
let stdout = io::stdout();
let mut handle = stdout.lock();
// write length of message as big-endian u32 for framing
let message_length = u32::try_from(serialized.len()).expect("Framed message too large!");
let message_length_be = message_length.to_be_bytes();
handle
.write_all(&message_length_be)
.expect("unable to write frame length!");
// Write message
handle
.write_all(serialized.as_slice())
.expect("unable to write frame!");
}
/// Take FrameMessage struct and write a framed message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_frame_message(frame: *const FrameMessage) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::Frame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Take FrameMessage struct and write a framed scaled, message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_scaled_frame_message(frame: *const FrameMessage, _height: i32) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::ScaledFrame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Send a message signaling a new file was created.
///
/// # Safety
///
/// filename and iso_begin_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_new_file_message(
filename: *const c_char,
iso_begin_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null()); | let iso_begin_time = {
assert!(!iso_begin_time.is_null());
CStr::from_ptr(iso_begin_time)
.to_string_lossy()
.into_owned()
};
let message = CaptureMessage::NewFile {
filename,
begin_time: iso_begin_time,
};
print_message(message);
}
/// Send a message signaling the closing of a file.
///
/// # Safety
///
/// filename and iso_end_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_end_file_message(
filename: *const c_char,
iso_end_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_end_time = {
assert!(!iso_end_time.is_null());
CStr::from_ptr(iso_end_time).to_string_lossy().into_owned()
};
let message = CaptureMessage::EndFile {
filename,
end_time: iso_end_time,
};
print_message(message);
}
/// Send a log message
///
/// # Safety
///
/// message must be a null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_log_message(_level: i32, message: *const c_char) {
let message = {
assert!(!message.is_null());
CStr::from_ptr(message).to_string_lossy().into_owned()
};
let capture_message = CaptureMessage::Log { message };
print_message(capture_message);
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
} |
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
| random_line_split |
lib.rs | /*
* Exopticon - A free video surveillance system.
* Copyright (C) 2020 David Matthew Mattli <dmm@mattli.us>
*
* This file is part of Exopticon.
*
* Exopticon is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Exopticon is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Exopticon. If not, see <http://www.gnu.org/licenses/>.
*/
use std::convert::TryFrom;
use std::ffi::CStr;
use std::io::{self, Write};
use std::slice;
//
use bincode::serialize;
use libc::c_char;
use crate::models::{CaptureMessage, FrameMessage};
pub mod models;
pub fn print_message(message: CaptureMessage) {
let serialized = serialize(&message).expect("Unable to serialize message!");
let stdout = io::stdout();
let mut handle = stdout.lock();
// write length of message as big-endian u32 for framing
let message_length = u32::try_from(serialized.len()).expect("Framed message too large!");
let message_length_be = message_length.to_be_bytes();
handle
.write_all(&message_length_be)
.expect("unable to write frame length!");
// Write message
handle
.write_all(serialized.as_slice())
.expect("unable to write frame!");
}
/// Take FrameMessage struct and write a framed message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_frame_message(frame: *const FrameMessage) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::Frame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Take FrameMessage struct and write a framed scaled, message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_scaled_frame_message(frame: *const FrameMessage, _height: i32) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::ScaledFrame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Send a message signaling a new file was created.
///
/// # Safety
///
/// filename and iso_begin_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_new_file_message(
filename: *const c_char,
iso_begin_time: *const c_char,
) |
/// Send a message signaling the closing of a file.
///
/// # Safety
///
/// filename and iso_end_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_end_file_message(
filename: *const c_char,
iso_end_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_end_time = {
assert!(!iso_end_time.is_null());
CStr::from_ptr(iso_end_time).to_string_lossy().into_owned()
};
let message = CaptureMessage::EndFile {
filename,
end_time: iso_end_time,
};
print_message(message);
}
/// Send a log message
///
/// # Safety
///
/// message must be a null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_log_message(_level: i32, message: *const c_char) {
let message = {
assert!(!message.is_null());
CStr::from_ptr(message).to_string_lossy().into_owned()
};
let capture_message = CaptureMessage::Log { message };
print_message(capture_message);
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
| {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_begin_time = {
assert!(!iso_begin_time.is_null());
CStr::from_ptr(iso_begin_time)
.to_string_lossy()
.into_owned()
};
let message = CaptureMessage::NewFile {
filename,
begin_time: iso_begin_time,
};
print_message(message);
} | identifier_body |
lib.rs | /*
* Exopticon - A free video surveillance system.
* Copyright (C) 2020 David Matthew Mattli <dmm@mattli.us>
*
* This file is part of Exopticon.
*
* Exopticon is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Exopticon is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Exopticon. If not, see <http://www.gnu.org/licenses/>.
*/
use std::convert::TryFrom;
use std::ffi::CStr;
use std::io::{self, Write};
use std::slice;
//
use bincode::serialize;
use libc::c_char;
use crate::models::{CaptureMessage, FrameMessage};
pub mod models;
pub fn print_message(message: CaptureMessage) {
let serialized = serialize(&message).expect("Unable to serialize message!");
let stdout = io::stdout();
let mut handle = stdout.lock();
// write length of message as big-endian u32 for framing
let message_length = u32::try_from(serialized.len()).expect("Framed message too large!");
let message_length_be = message_length.to_be_bytes();
handle
.write_all(&message_length_be)
.expect("unable to write frame length!");
// Write message
handle
.write_all(serialized.as_slice())
.expect("unable to write frame!");
}
/// Take FrameMessage struct and write a framed message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_frame_message(frame: *const FrameMessage) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::Frame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Take FrameMessage struct and write a framed scaled, message to stdout
///
/// # Safety
///
/// frame pointer must be to a valid, aligned FrameMessage.
///
#[no_mangle]
pub unsafe extern "C" fn send_scaled_frame_message(frame: *const FrameMessage, _height: i32) {
let frame = {
assert!(!frame.is_null());
&*frame
};
let jpeg = {
assert!(!frame.jpeg.is_null());
slice::from_raw_parts(frame.jpeg, frame.jpeg_size as usize)
};
let frame = CaptureMessage::ScaledFrame {
jpeg: jpeg.to_vec(),
offset: frame.offset,
unscaled_height: frame.unscaled_height,
unscaled_width: frame.unscaled_width,
};
print_message(frame);
}
/// Send a message signaling a new file was created.
///
/// # Safety
///
/// filename and iso_begin_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_new_file_message(
filename: *const c_char,
iso_begin_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_begin_time = {
assert!(!iso_begin_time.is_null());
CStr::from_ptr(iso_begin_time)
.to_string_lossy()
.into_owned()
};
let message = CaptureMessage::NewFile {
filename,
begin_time: iso_begin_time,
};
print_message(message);
}
/// Send a message signaling the closing of a file.
///
/// # Safety
///
/// filename and iso_end_time must be null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn send_end_file_message(
filename: *const c_char,
iso_end_time: *const c_char,
) {
let filename = {
assert!(!filename.is_null());
CStr::from_ptr(filename).to_string_lossy().into_owned()
};
let iso_end_time = {
assert!(!iso_end_time.is_null());
CStr::from_ptr(iso_end_time).to_string_lossy().into_owned()
};
let message = CaptureMessage::EndFile {
filename,
end_time: iso_end_time,
};
print_message(message);
}
/// Send a log message
///
/// # Safety
///
/// message must be a null-terminated character arrays.
///
#[no_mangle]
pub unsafe extern "C" fn | (_level: i32, message: *const c_char) {
let message = {
assert!(!message.is_null());
CStr::from_ptr(message).to_string_lossy().into_owned()
};
let capture_message = CaptureMessage::Log { message };
print_message(capture_message);
}
#[cfg(test)]
mod tests {
#[test]
fn it_works() {
assert_eq!(2 + 2, 4);
}
}
| send_log_message | identifier_name |
module.ts | import {AnimationAnnotation, registerAnimation} from "./animation";
import {ComponentAnnotation, publishComponent} from "./component";
import {ConstantWrapper, publishConstant} from "./constant";
import {DecoratorAnnotation, publishDecorator} from "./decorator";
import {DirectiveAnnotation, publishDirective} from "./directive";
import {FilterAnnotation, registerFilter} from "./filter";
import {ServiceAnnotation, publishService} from "./service";
import {TFunctionReturningNothing, setIfInterface} from "./utils";
import {ValueWrapper, publishValue} from "./value";
import {create, isArray, isFunction, isString} from "./utils";
import {getAnnotations, hasAnnotation, makeDecorator, mergeAnnotations} from "./reflection";
// TODO debug only?
// import * as angular from "angular";
import {assert} from "./assert";
import {safeBind} from "./di";
const PUBLISHED_ANNOTATION_KEY = "tng:module-published-as";
export type Dependency = string|Function|ConstantWrapper<any>|ValueWrapper<any>;
export type DependenciesArray = (Dependency|Dependency[])[];
/**
* Options available when decorating a class as a module
* TODO document
*/
export interface ModuleOptions {
name?: string;
dependencies?: DependenciesArray;
config?: Function|Function[];
run?: Function|Function[];
// modules?: (string|Function)[];
// components?: Function[];
// services?: Function[];
// filters?: Function[];
// decorators?: Function[];
// animations?: Function[];
// values?: Function[];
// constants?: Function[];
}
/**
* @internal
*/
export class ModuleAnnotation {
name: string = void 0;
dependencies: DependenciesArray = void 0;
config: Function|Function[] = void 0;
run: Function|Function[] = void 0;
// modules: (string|Function)[] = void 0;
// components: Function[] = void 0;
// services: Function[] = void 0;
// filters: Function[] = void 0;
// decorators: Function[] = void 0;
// animations: Function[] = void 0;
// values: Function[] = void 0;
// constants: Function[] = void 0;
constructor(options?: ModuleOptions) {
setIfInterface(this, options);
}
}
/**
* Interface modules MAY implement
* TODO document
*/
export interface Module {
onConfig?: TFunctionReturningNothing;
onRun?: TFunctionReturningNothing;
}
/**
* @internal
*/
export interface ModuleConstructor extends Function {
new (): Module;
new (ngModule: ng.IModule): Module;
}
type ModuleSignature = (options?: ModuleOptions) => ClassDecorator;
/**
* A decorator to annotate a class as being a module
*/
export var Module = <ModuleSignature> makeDecorator(ModuleAnnotation);
let moduleCount = 0;
function getNewModuleName() {
return `tng_generated_module#${++moduleCount}`;
}
/**
* @internal
*/
export function publishModule(moduleClass: ModuleConstructor, name?: string,
dependencies?: DependenciesArray,
constructorParameters?: any[]): ng.IModule {
let aux: ModuleAnnotation[] = getAnnotations(moduleClass, ModuleAnnotation);
// TODO debug only?
assert.notEmpty(aux, "Missing @Module decoration");
// Has this module already been published?
let publishedAs = Reflect.getOwnMetadata(PUBLISHED_ANNOTATION_KEY, moduleClass);
if (publishedAs) {
return angular.module(publishedAs);
}
// special merging for dependencies, run and config
if (aux.length > 1) {
let mergedArrays = new ModuleAnnotation({
dependencies: [],
run: [],
config: [],
});
for (let module of aux) {
if (module.dependencies) {
for (let dependency of module.dependencies) {
// We don't repeat dependencies
if (mergedArrays.dependencies.indexOf(dependency) === -1) {
mergedArrays.dependencies.push(dependency);
}
}
}
if (module.run) {
let _run = isArray(module.run) ? module.run : [module.run];
for (let run of _run) {
(<Function[]> mergedArrays.run).push(run);
}
}
if (module.config) {
let _config = isArray(module.config) ? module.config : [module.config];
for (let config of _config) {
(<Function[]> mergedArrays.config).push(config);
}
}
}
aux.push(mergedArrays);
}
let annotation = mergeAnnotations<ModuleAnnotation>(Object.create(null), ...aux);
let constants: any[] = [];
let values: any[] = [];
let services: any[] = [];
let decorators: any[] = [];
let filters: any[] = [];
let animations: any[] = [];
let components: any[] = [];
let directives: any[] = [];
let modules: any[] = [];
// TODO optimize this.. too much reflection queries
function processDependency(dep: Dependency|Dependency[]): void {
// Regular angular module
if (isString(dep)) {
modules.push(dep);
}
else if (isArray(dep)) {
for (let _dep of <Dependency[]> dep) {
processDependency(_dep);
}
}
else if (hasAnnotation(dep, ModuleAnnotation)) {
modules.push(publishModule(<ModuleConstructor> dep).name);
}
else if (dep instanceof ConstantWrapper) {
constants.push(dep);
}
else if (dep instanceof ValueWrapper) {
values.push(dep);
}
else if (hasAnnotation(dep, ServiceAnnotation)) |
else if (hasAnnotation(dep, DecoratorAnnotation)) {
decorators.push(dep);
}
else if (hasAnnotation(dep, FilterAnnotation)) {
filters.push(dep);
}
else if (hasAnnotation(dep, AnimationAnnotation)) {
animations.push(dep);
}
else if (hasAnnotation(dep, ComponentAnnotation)) {
components.push(dep);
}
else if (hasAnnotation(dep, DirectiveAnnotation)) {
directives.push(dep);
}
else {
// TODO WTF?
throw new Error(`I don't recognize what kind of dependency this is: ${dep}`);
}
}
let allDeps = [].concat(
(annotation.dependencies || []),
(dependencies || [])
);
allDeps.forEach((dep) => processDependency(dep));
name = name || annotation.name || getNewModuleName();
// Register the module on Angular
let ngModule = angular.module(name, modules);
// Instantiate the module
// var module = new moduleClass(ngModule);
let module = Object.create(moduleClass.prototype);
moduleClass.apply(module, [ngModule].concat(constructorParameters || []));
// Register config functions
let configFns: Function[] = [];
if (isFunction(module.onConfig)) configFns.push(safeBind(module.onConfig, module));
if (annotation.config) {
if (isFunction(annotation.config)) configFns.push(<Function> annotation.config);
else if (isArray(annotation.config)) configFns = configFns.concat(<Function[]> annotation.config);
}
for (let fn of configFns) ngModule.config(fn);
// Register initialization functions
let runFns: Function[] = [];
if (isFunction(module.onRun)) runFns.push(safeBind(module.onRun, module));
if (annotation.run) {
if (isFunction(annotation.run)) runFns.push(<Function> annotation.run);
else if (isArray(annotation.run)) runFns = runFns.concat(<Function[]> annotation.run);
}
for (let fn of runFns) ngModule.run(fn);
/* tslint:disable rule:curly */
for (let item of values) publishValue(item, ngModule);
for (let item of constants) publishConstant(item, ngModule);
for (let item of filters) registerFilter(item, ngModule);
for (let item of animations) registerAnimation(item, ngModule);
for (let item of services) publishService(item, ngModule);
for (let item of decorators) publishDecorator(item, ngModule);
for (let item of components) publishComponent(item, ngModule);
for (let item of directives) publishDirective(item, ngModule);
/* tslint:enable */
Reflect.defineMetadata(PUBLISHED_ANNOTATION_KEY, name, moduleClass);
return ngModule;
} | {
services.push(dep);
} | conditional_block |
module.ts | import {AnimationAnnotation, registerAnimation} from "./animation";
import {ComponentAnnotation, publishComponent} from "./component";
import {ConstantWrapper, publishConstant} from "./constant";
import {DecoratorAnnotation, publishDecorator} from "./decorator";
import {DirectiveAnnotation, publishDirective} from "./directive";
import {FilterAnnotation, registerFilter} from "./filter";
import {ServiceAnnotation, publishService} from "./service";
import {TFunctionReturningNothing, setIfInterface} from "./utils";
import {ValueWrapper, publishValue} from "./value";
import {create, isArray, isFunction, isString} from "./utils";
import {getAnnotations, hasAnnotation, makeDecorator, mergeAnnotations} from "./reflection";
// TODO debug only?
// import * as angular from "angular";
import {assert} from "./assert";
import {safeBind} from "./di";
const PUBLISHED_ANNOTATION_KEY = "tng:module-published-as";
export type Dependency = string|Function|ConstantWrapper<any>|ValueWrapper<any>;
export type DependenciesArray = (Dependency|Dependency[])[];
/**
* Options available when decorating a class as a module
* TODO document
*/
export interface ModuleOptions {
name?: string;
dependencies?: DependenciesArray;
config?: Function|Function[];
run?: Function|Function[];
// modules?: (string|Function)[];
// components?: Function[];
// services?: Function[];
// filters?: Function[];
// decorators?: Function[];
// animations?: Function[];
// values?: Function[];
// constants?: Function[];
}
/**
* @internal
*/
export class | {
name: string = void 0;
dependencies: DependenciesArray = void 0;
config: Function|Function[] = void 0;
run: Function|Function[] = void 0;
// modules: (string|Function)[] = void 0;
// components: Function[] = void 0;
// services: Function[] = void 0;
// filters: Function[] = void 0;
// decorators: Function[] = void 0;
// animations: Function[] = void 0;
// values: Function[] = void 0;
// constants: Function[] = void 0;
constructor(options?: ModuleOptions) {
setIfInterface(this, options);
}
}
/**
* Interface modules MAY implement
* TODO document
*/
export interface Module {
onConfig?: TFunctionReturningNothing;
onRun?: TFunctionReturningNothing;
}
/**
* @internal
*/
export interface ModuleConstructor extends Function {
new (): Module;
new (ngModule: ng.IModule): Module;
}
type ModuleSignature = (options?: ModuleOptions) => ClassDecorator;
/**
* A decorator to annotate a class as being a module
*/
export var Module = <ModuleSignature> makeDecorator(ModuleAnnotation);
let moduleCount = 0;
function getNewModuleName() {
return `tng_generated_module#${++moduleCount}`;
}
/**
* @internal
*/
export function publishModule(moduleClass: ModuleConstructor, name?: string,
dependencies?: DependenciesArray,
constructorParameters?: any[]): ng.IModule {
let aux: ModuleAnnotation[] = getAnnotations(moduleClass, ModuleAnnotation);
// TODO debug only?
assert.notEmpty(aux, "Missing @Module decoration");
// Has this module already been published?
let publishedAs = Reflect.getOwnMetadata(PUBLISHED_ANNOTATION_KEY, moduleClass);
if (publishedAs) {
return angular.module(publishedAs);
}
// special merging for dependencies, run and config
if (aux.length > 1) {
let mergedArrays = new ModuleAnnotation({
dependencies: [],
run: [],
config: [],
});
for (let module of aux) {
if (module.dependencies) {
for (let dependency of module.dependencies) {
// We don't repeat dependencies
if (mergedArrays.dependencies.indexOf(dependency) === -1) {
mergedArrays.dependencies.push(dependency);
}
}
}
if (module.run) {
let _run = isArray(module.run) ? module.run : [module.run];
for (let run of _run) {
(<Function[]> mergedArrays.run).push(run);
}
}
if (module.config) {
let _config = isArray(module.config) ? module.config : [module.config];
for (let config of _config) {
(<Function[]> mergedArrays.config).push(config);
}
}
}
aux.push(mergedArrays);
}
let annotation = mergeAnnotations<ModuleAnnotation>(Object.create(null), ...aux);
let constants: any[] = [];
let values: any[] = [];
let services: any[] = [];
let decorators: any[] = [];
let filters: any[] = [];
let animations: any[] = [];
let components: any[] = [];
let directives: any[] = [];
let modules: any[] = [];
// TODO optimize this.. too much reflection queries
function processDependency(dep: Dependency|Dependency[]): void {
// Regular angular module
if (isString(dep)) {
modules.push(dep);
}
else if (isArray(dep)) {
for (let _dep of <Dependency[]> dep) {
processDependency(_dep);
}
}
else if (hasAnnotation(dep, ModuleAnnotation)) {
modules.push(publishModule(<ModuleConstructor> dep).name);
}
else if (dep instanceof ConstantWrapper) {
constants.push(dep);
}
else if (dep instanceof ValueWrapper) {
values.push(dep);
}
else if (hasAnnotation(dep, ServiceAnnotation)) {
services.push(dep);
}
else if (hasAnnotation(dep, DecoratorAnnotation)) {
decorators.push(dep);
}
else if (hasAnnotation(dep, FilterAnnotation)) {
filters.push(dep);
}
else if (hasAnnotation(dep, AnimationAnnotation)) {
animations.push(dep);
}
else if (hasAnnotation(dep, ComponentAnnotation)) {
components.push(dep);
}
else if (hasAnnotation(dep, DirectiveAnnotation)) {
directives.push(dep);
}
else {
// TODO WTF?
throw new Error(`I don't recognize what kind of dependency this is: ${dep}`);
}
}
let allDeps = [].concat(
(annotation.dependencies || []),
(dependencies || [])
);
allDeps.forEach((dep) => processDependency(dep));
name = name || annotation.name || getNewModuleName();
// Register the module on Angular
let ngModule = angular.module(name, modules);
// Instantiate the module
// var module = new moduleClass(ngModule);
let module = Object.create(moduleClass.prototype);
moduleClass.apply(module, [ngModule].concat(constructorParameters || []));
// Register config functions
let configFns: Function[] = [];
if (isFunction(module.onConfig)) configFns.push(safeBind(module.onConfig, module));
if (annotation.config) {
if (isFunction(annotation.config)) configFns.push(<Function> annotation.config);
else if (isArray(annotation.config)) configFns = configFns.concat(<Function[]> annotation.config);
}
for (let fn of configFns) ngModule.config(fn);
// Register initialization functions
let runFns: Function[] = [];
if (isFunction(module.onRun)) runFns.push(safeBind(module.onRun, module));
if (annotation.run) {
if (isFunction(annotation.run)) runFns.push(<Function> annotation.run);
else if (isArray(annotation.run)) runFns = runFns.concat(<Function[]> annotation.run);
}
for (let fn of runFns) ngModule.run(fn);
/* tslint:disable rule:curly */
for (let item of values) publishValue(item, ngModule);
for (let item of constants) publishConstant(item, ngModule);
for (let item of filters) registerFilter(item, ngModule);
for (let item of animations) registerAnimation(item, ngModule);
for (let item of services) publishService(item, ngModule);
for (let item of decorators) publishDecorator(item, ngModule);
for (let item of components) publishComponent(item, ngModule);
for (let item of directives) publishDirective(item, ngModule);
/* tslint:enable */
Reflect.defineMetadata(PUBLISHED_ANNOTATION_KEY, name, moduleClass);
return ngModule;
} | ModuleAnnotation | identifier_name |
module.ts | import {AnimationAnnotation, registerAnimation} from "./animation";
import {ComponentAnnotation, publishComponent} from "./component";
import {ConstantWrapper, publishConstant} from "./constant";
import {DecoratorAnnotation, publishDecorator} from "./decorator";
import {DirectiveAnnotation, publishDirective} from "./directive";
import {FilterAnnotation, registerFilter} from "./filter";
import {ServiceAnnotation, publishService} from "./service";
import {TFunctionReturningNothing, setIfInterface} from "./utils";
import {ValueWrapper, publishValue} from "./value";
import {create, isArray, isFunction, isString} from "./utils";
import {getAnnotations, hasAnnotation, makeDecorator, mergeAnnotations} from "./reflection";
// TODO debug only?
// import * as angular from "angular";
import {assert} from "./assert";
import {safeBind} from "./di";
const PUBLISHED_ANNOTATION_KEY = "tng:module-published-as";
export type Dependency = string|Function|ConstantWrapper<any>|ValueWrapper<any>;
export type DependenciesArray = (Dependency|Dependency[])[];
/**
* Options available when decorating a class as a module
* TODO document
*/
export interface ModuleOptions {
name?: string;
dependencies?: DependenciesArray;
config?: Function|Function[];
run?: Function|Function[];
// modules?: (string|Function)[];
// components?: Function[];
// services?: Function[];
// filters?: Function[];
// decorators?: Function[];
// animations?: Function[];
// values?: Function[];
// constants?: Function[];
}
/**
* @internal
*/
export class ModuleAnnotation {
name: string = void 0;
dependencies: DependenciesArray = void 0;
config: Function|Function[] = void 0;
run: Function|Function[] = void 0;
// modules: (string|Function)[] = void 0;
// components: Function[] = void 0;
// services: Function[] = void 0;
// filters: Function[] = void 0;
// decorators: Function[] = void 0;
// animations: Function[] = void 0;
// values: Function[] = void 0;
// constants: Function[] = void 0;
constructor(options?: ModuleOptions) {
setIfInterface(this, options);
}
}
/**
* Interface modules MAY implement
* TODO document
*/
export interface Module {
onConfig?: TFunctionReturningNothing;
onRun?: TFunctionReturningNothing;
}
/**
* @internal
*/
export interface ModuleConstructor extends Function {
new (): Module;
new (ngModule: ng.IModule): Module;
}
type ModuleSignature = (options?: ModuleOptions) => ClassDecorator;
/**
* A decorator to annotate a class as being a module
*/
export var Module = <ModuleSignature> makeDecorator(ModuleAnnotation);
let moduleCount = 0;
function getNewModuleName() {
return `tng_generated_module#${++moduleCount}`;
}
/**
* @internal
*/
export function publishModule(moduleClass: ModuleConstructor, name?: string,
dependencies?: DependenciesArray,
constructorParameters?: any[]): ng.IModule {
let aux: ModuleAnnotation[] = getAnnotations(moduleClass, ModuleAnnotation);
// TODO debug only?
assert.notEmpty(aux, "Missing @Module decoration");
// Has this module already been published?
let publishedAs = Reflect.getOwnMetadata(PUBLISHED_ANNOTATION_KEY, moduleClass);
if (publishedAs) {
return angular.module(publishedAs);
}
// special merging for dependencies, run and config
if (aux.length > 1) {
let mergedArrays = new ModuleAnnotation({
dependencies: [],
run: [],
config: [],
});
for (let module of aux) {
if (module.dependencies) {
for (let dependency of module.dependencies) {
// We don't repeat dependencies
if (mergedArrays.dependencies.indexOf(dependency) === -1) {
mergedArrays.dependencies.push(dependency);
}
}
}
if (module.run) {
let _run = isArray(module.run) ? module.run : [module.run];
for (let run of _run) {
(<Function[]> mergedArrays.run).push(run);
}
}
if (module.config) { | let _config = isArray(module.config) ? module.config : [module.config];
for (let config of _config) {
(<Function[]> mergedArrays.config).push(config);
}
}
}
aux.push(mergedArrays);
}
let annotation = mergeAnnotations<ModuleAnnotation>(Object.create(null), ...aux);
let constants: any[] = [];
let values: any[] = [];
let services: any[] = [];
let decorators: any[] = [];
let filters: any[] = [];
let animations: any[] = [];
let components: any[] = [];
let directives: any[] = [];
let modules: any[] = [];
// TODO optimize this.. too much reflection queries
function processDependency(dep: Dependency|Dependency[]): void {
// Regular angular module
if (isString(dep)) {
modules.push(dep);
}
else if (isArray(dep)) {
for (let _dep of <Dependency[]> dep) {
processDependency(_dep);
}
}
else if (hasAnnotation(dep, ModuleAnnotation)) {
modules.push(publishModule(<ModuleConstructor> dep).name);
}
else if (dep instanceof ConstantWrapper) {
constants.push(dep);
}
else if (dep instanceof ValueWrapper) {
values.push(dep);
}
else if (hasAnnotation(dep, ServiceAnnotation)) {
services.push(dep);
}
else if (hasAnnotation(dep, DecoratorAnnotation)) {
decorators.push(dep);
}
else if (hasAnnotation(dep, FilterAnnotation)) {
filters.push(dep);
}
else if (hasAnnotation(dep, AnimationAnnotation)) {
animations.push(dep);
}
else if (hasAnnotation(dep, ComponentAnnotation)) {
components.push(dep);
}
else if (hasAnnotation(dep, DirectiveAnnotation)) {
directives.push(dep);
}
else {
// TODO WTF?
throw new Error(`I don't recognize what kind of dependency this is: ${dep}`);
}
}
let allDeps = [].concat(
(annotation.dependencies || []),
(dependencies || [])
);
allDeps.forEach((dep) => processDependency(dep));
name = name || annotation.name || getNewModuleName();
// Register the module on Angular
let ngModule = angular.module(name, modules);
// Instantiate the module
// var module = new moduleClass(ngModule);
let module = Object.create(moduleClass.prototype);
moduleClass.apply(module, [ngModule].concat(constructorParameters || []));
// Register config functions
let configFns: Function[] = [];
if (isFunction(module.onConfig)) configFns.push(safeBind(module.onConfig, module));
if (annotation.config) {
if (isFunction(annotation.config)) configFns.push(<Function> annotation.config);
else if (isArray(annotation.config)) configFns = configFns.concat(<Function[]> annotation.config);
}
for (let fn of configFns) ngModule.config(fn);
// Register initialization functions
let runFns: Function[] = [];
if (isFunction(module.onRun)) runFns.push(safeBind(module.onRun, module));
if (annotation.run) {
if (isFunction(annotation.run)) runFns.push(<Function> annotation.run);
else if (isArray(annotation.run)) runFns = runFns.concat(<Function[]> annotation.run);
}
for (let fn of runFns) ngModule.run(fn);
/* tslint:disable rule:curly */
for (let item of values) publishValue(item, ngModule);
for (let item of constants) publishConstant(item, ngModule);
for (let item of filters) registerFilter(item, ngModule);
for (let item of animations) registerAnimation(item, ngModule);
for (let item of services) publishService(item, ngModule);
for (let item of decorators) publishDecorator(item, ngModule);
for (let item of components) publishComponent(item, ngModule);
for (let item of directives) publishDirective(item, ngModule);
/* tslint:enable */
Reflect.defineMetadata(PUBLISHED_ANNOTATION_KEY, name, moduleClass);
return ngModule;
} | random_line_split | |
module.ts | import {AnimationAnnotation, registerAnimation} from "./animation";
import {ComponentAnnotation, publishComponent} from "./component";
import {ConstantWrapper, publishConstant} from "./constant";
import {DecoratorAnnotation, publishDecorator} from "./decorator";
import {DirectiveAnnotation, publishDirective} from "./directive";
import {FilterAnnotation, registerFilter} from "./filter";
import {ServiceAnnotation, publishService} from "./service";
import {TFunctionReturningNothing, setIfInterface} from "./utils";
import {ValueWrapper, publishValue} from "./value";
import {create, isArray, isFunction, isString} from "./utils";
import {getAnnotations, hasAnnotation, makeDecorator, mergeAnnotations} from "./reflection";
// TODO debug only?
// import * as angular from "angular";
import {assert} from "./assert";
import {safeBind} from "./di";
const PUBLISHED_ANNOTATION_KEY = "tng:module-published-as";
export type Dependency = string|Function|ConstantWrapper<any>|ValueWrapper<any>;
export type DependenciesArray = (Dependency|Dependency[])[];
/**
* Options available when decorating a class as a module
* TODO document
*/
export interface ModuleOptions {
name?: string;
dependencies?: DependenciesArray;
config?: Function|Function[];
run?: Function|Function[];
// modules?: (string|Function)[];
// components?: Function[];
// services?: Function[];
// filters?: Function[];
// decorators?: Function[];
// animations?: Function[];
// values?: Function[];
// constants?: Function[];
}
/**
* @internal
*/
export class ModuleAnnotation {
name: string = void 0;
dependencies: DependenciesArray = void 0;
config: Function|Function[] = void 0;
run: Function|Function[] = void 0;
// modules: (string|Function)[] = void 0;
// components: Function[] = void 0;
// services: Function[] = void 0;
// filters: Function[] = void 0;
// decorators: Function[] = void 0;
// animations: Function[] = void 0;
// values: Function[] = void 0;
// constants: Function[] = void 0;
constructor(options?: ModuleOptions) {
setIfInterface(this, options);
}
}
/**
* Interface modules MAY implement
* TODO document
*/
export interface Module {
onConfig?: TFunctionReturningNothing;
onRun?: TFunctionReturningNothing;
}
/**
* @internal
*/
export interface ModuleConstructor extends Function {
new (): Module;
new (ngModule: ng.IModule): Module;
}
type ModuleSignature = (options?: ModuleOptions) => ClassDecorator;
/**
* A decorator to annotate a class as being a module
*/
export var Module = <ModuleSignature> makeDecorator(ModuleAnnotation);
let moduleCount = 0;
function getNewModuleName() |
/**
* @internal
*/
export function publishModule(moduleClass: ModuleConstructor, name?: string,
dependencies?: DependenciesArray,
constructorParameters?: any[]): ng.IModule {
let aux: ModuleAnnotation[] = getAnnotations(moduleClass, ModuleAnnotation);
// TODO debug only?
assert.notEmpty(aux, "Missing @Module decoration");
// Has this module already been published?
let publishedAs = Reflect.getOwnMetadata(PUBLISHED_ANNOTATION_KEY, moduleClass);
if (publishedAs) {
return angular.module(publishedAs);
}
// special merging for dependencies, run and config
if (aux.length > 1) {
let mergedArrays = new ModuleAnnotation({
dependencies: [],
run: [],
config: [],
});
for (let module of aux) {
if (module.dependencies) {
for (let dependency of module.dependencies) {
// We don't repeat dependencies
if (mergedArrays.dependencies.indexOf(dependency) === -1) {
mergedArrays.dependencies.push(dependency);
}
}
}
if (module.run) {
let _run = isArray(module.run) ? module.run : [module.run];
for (let run of _run) {
(<Function[]> mergedArrays.run).push(run);
}
}
if (module.config) {
let _config = isArray(module.config) ? module.config : [module.config];
for (let config of _config) {
(<Function[]> mergedArrays.config).push(config);
}
}
}
aux.push(mergedArrays);
}
let annotation = mergeAnnotations<ModuleAnnotation>(Object.create(null), ...aux);
let constants: any[] = [];
let values: any[] = [];
let services: any[] = [];
let decorators: any[] = [];
let filters: any[] = [];
let animations: any[] = [];
let components: any[] = [];
let directives: any[] = [];
let modules: any[] = [];
// TODO optimize this.. too much reflection queries
function processDependency(dep: Dependency|Dependency[]): void {
// Regular angular module
if (isString(dep)) {
modules.push(dep);
}
else if (isArray(dep)) {
for (let _dep of <Dependency[]> dep) {
processDependency(_dep);
}
}
else if (hasAnnotation(dep, ModuleAnnotation)) {
modules.push(publishModule(<ModuleConstructor> dep).name);
}
else if (dep instanceof ConstantWrapper) {
constants.push(dep);
}
else if (dep instanceof ValueWrapper) {
values.push(dep);
}
else if (hasAnnotation(dep, ServiceAnnotation)) {
services.push(dep);
}
else if (hasAnnotation(dep, DecoratorAnnotation)) {
decorators.push(dep);
}
else if (hasAnnotation(dep, FilterAnnotation)) {
filters.push(dep);
}
else if (hasAnnotation(dep, AnimationAnnotation)) {
animations.push(dep);
}
else if (hasAnnotation(dep, ComponentAnnotation)) {
components.push(dep);
}
else if (hasAnnotation(dep, DirectiveAnnotation)) {
directives.push(dep);
}
else {
// TODO WTF?
throw new Error(`I don't recognize what kind of dependency this is: ${dep}`);
}
}
let allDeps = [].concat(
(annotation.dependencies || []),
(dependencies || [])
);
allDeps.forEach((dep) => processDependency(dep));
name = name || annotation.name || getNewModuleName();
// Register the module on Angular
let ngModule = angular.module(name, modules);
// Instantiate the module
// var module = new moduleClass(ngModule);
let module = Object.create(moduleClass.prototype);
moduleClass.apply(module, [ngModule].concat(constructorParameters || []));
// Register config functions
let configFns: Function[] = [];
if (isFunction(module.onConfig)) configFns.push(safeBind(module.onConfig, module));
if (annotation.config) {
if (isFunction(annotation.config)) configFns.push(<Function> annotation.config);
else if (isArray(annotation.config)) configFns = configFns.concat(<Function[]> annotation.config);
}
for (let fn of configFns) ngModule.config(fn);
// Register initialization functions
let runFns: Function[] = [];
if (isFunction(module.onRun)) runFns.push(safeBind(module.onRun, module));
if (annotation.run) {
if (isFunction(annotation.run)) runFns.push(<Function> annotation.run);
else if (isArray(annotation.run)) runFns = runFns.concat(<Function[]> annotation.run);
}
for (let fn of runFns) ngModule.run(fn);
/* tslint:disable rule:curly */
for (let item of values) publishValue(item, ngModule);
for (let item of constants) publishConstant(item, ngModule);
for (let item of filters) registerFilter(item, ngModule);
for (let item of animations) registerAnimation(item, ngModule);
for (let item of services) publishService(item, ngModule);
for (let item of decorators) publishDecorator(item, ngModule);
for (let item of components) publishComponent(item, ngModule);
for (let item of directives) publishDirective(item, ngModule);
/* tslint:enable */
Reflect.defineMetadata(PUBLISHED_ANNOTATION_KEY, name, moduleClass);
return ngModule;
} | {
return `tng_generated_module#${++moduleCount}`;
} | identifier_body |
websocket.py | # versione 0.5
import socket
import threading
import hashlib
import base64
import json
class BadWSRequest(Exception):
pass
class BadWSFrame(Exception):
pass
class BadCmdCall(Exception):
pass
class BadCmdParam(Exception):
pass
class Client(threading.Thread):
_MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
_OPCODE_TEXT = 0x1
_OPCODE_CLOSE = 0x8
def __init__(self, Manager, socket, address):
super().__init__()
self.Manager = Manager
self.socket = socket
self.ip, self.port = address
self.invokedPath = None
self.sessionStarted = False
def _parseHeader(self):
self.socket.settimeout(2.0)
rcvBuffer = ''
toRead = True
while toRead:
rcvBuffer += self.socket.recv(128).decode('utf-8')
#Check for the termination sequence
if rcvBuffer[-4:] == '\r\n\r\n': toRead = False
#vedere di usare splitlines
headerLines = rcvBuffer.split('\r\n')
requestLineElements = headerLines[0].split(' ')
if requestLineElements[0] == 'GET' and requestLineElements[-1] == 'HTTP/1.1':
self.invokedPath = requestLineElements[2]
else:
raise BadWSRequest
self.headerDict = {}
#Cut off rubbish (first line and termination sequence)
for header in headerLines[1:-2]:
headerKey, headerVal = header.split(':', 1)
self.headerDict.update({ headerKey: headerVal.strip() })
if (
'upgrade' not in self.headerDict['Connection'].lower().split(', ') or
self.headerDict['Upgrade'].lower() != 'websocket' or
'Sec-WebSocket-Key' not in self.headerDict
#Very weak part
):
raise BadWSRequest
#Operative mode needs more time
self.socket.settimeout(3600.0)
def _initComunication(self):
payload = 'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'
payload += 'Upgrade: WebSocket\r\n'
payload += 'Connection: Upgrade\r\n'
#Generate the security key
acceptKey = self.headerDict['Sec-WebSocket-Key'] + self._MAGIC_STRING
acceptKey = hashlib.sha1( acceptKey.encode('ascii') ).digest()
acceptKey = base64.b64encode(acceptKey)
payload += 'Sec-WebSocket-Accept: ' + acceptKey.decode('utf-8') + '\r\n\r\n'
self.socket.send( payload.encode('utf-8') )
def _rcvRequest(self):
#1st byte: FIN, RUBBISH1, RUBBISH2, RUBBISH3, OPCODE (4 bit)
#2nd byte: MASKED, PAYLOAD_LENGTH (7 bit)
rcvBuffer = self.socket.recv(2)
print('FIN: ' + str( rcvBuffer[0] >> 7 ))
#0x0f is 00001111 binary sequence
opcode = rcvBuffer[0] & 0x0f
print('opcode: ' + hex( opcode ))
maskBit = rcvBuffer[1] >> 7
print('mask: ' + str( maskBit ))
if maskBit != 1:
raise BadWSFrame('Unmasked data')
#0x7f is 01111111 binary sequence
length = rcvBuffer[1] & 0x7f
if length == 126:
#A long length is stored in more space
rcvBuffer = self.socket.recv(2)
length = int.from_bytes(rcvBuffer, 'big')
elif length == 127:
#un carico maggiore di 65kb a thread mi fa collassare il tutto..
#Ma poi.. perche' un utente dovrebbe caricare cosi' tanti dati? :O
raise BadWSFrame('Too big payload')
print('length: ' + str(length))
#Read the mask applied to data
maskKey = self.socket.recv(4)
#valutare di bufferizzare per rendere il thread piu' parsionioso
rcvBuffer = self.socket.recv(length)
message = b''
for i in range(length):
#Unmask the original message
message += bytes([ rcvBuffer[i] ^ maskKey[i % 4] ])
print(message)
if opcode == self._OPCODE_TEXT:
return json.loads( message.decode('utf-8') )
elif opcode == self._OPCODE_CLOSE:
return None
else:
raise BadWSFrame('Unknown OpCode')
def _sndResponse(self, data):
data = json.dumps(data).encode('utf-8')
length = len(data)
#FIN bit and opcode 0x1 (0x81 is 10000001 binary sequence)
payload = b'\x81'
if length >= 65535:
#Over the maximum length allowed by 16bit addressing
raise BadWSFrame('Too big payload')
elif length <= 125:
payload += bytes([length])
else:
payload += bytes([126])
payload += length.to_bytes(2, 'big')
#si potrebbe bufferizzare l'invio
self.socket.send(payload + data)
#Chiudere inviando un codice di errore e usando l'opcode globale
def | (self):
#FIN bit and opcode 0x8 (0x88 is 10001000 binary sequence)
#Mask and length bits are zero
self.socket.send(b'\x88\x00')
#Empty the remote buffer
self.socket.recv(100)
def run(self):
print('[+] Connection established with ' + self.ip + ':' + str(self.port), "[%s]" % str(len(self.Manager)))
try:
self._parseHeader()
self._initComunication()
self.sessionStarted = True
#socket non bloccanti potrebbero essere di aiuto per smaltire prima i dati
while True:
request = self._rcvRequest()
if not request: break
response = self.Manager.executeAction(self, request)
if response == None:
raise UnknownCommand
self._sndResponse(response)
except BadWSRequest:
print('[!] Bad-formed request from ' + self.ip + ':' + str(self.port))
except BadWSFrame as err:
print('[!] Bad-formed frame from ' + self.ip + ':' + str(self.port), str(err))
#valutare se lasciare il messaggio o meno
except BadCmdCall as err:
print('[!] Unknown command received from ' + self.ip + ':' + str(self.port), str(err))
except BadCmdParam as err:
print('[!] Invalid parameters from ' + self.ip + ':' + str(self.port), str(err))
except socket.timeout:
print('[!] Timeout occurred for ' + self.ip + ':' + str(self.port))
finally:
if self.sessionStarted:
self._sndClose()
self.socket.close()
self.Manager.rmvClient(self)
print('[-] Connection closed with ' + self.ip + ':' + str(self.port), "[%s]" % str(len(self.Manager)))
class ClientManager:
def __init__(self):
self.clientList = []
self.actionDict = {}
def __len__(self):
return len(self.clientList)
def addClient(self, clientSocket, address):
newClient = Client(self, clientSocket, address)
newClient.start()
self.clientList.append(newClient)
def rmvClient(self, clientInstance):
self.clientList.remove(clientInstance)
def registerAction(self, functionName, function):
self.actionDict.update({ functionName: function })
def executeAction(self, clientInstance, request):
#Array of two element is expected
function, parameters = request
if function in self.actionDict:
try:
return self.actionDict[function](*parameters)
except TypeError:
raise BadCmdParam(request)
else:
raise BadCmdCall(function)
def shutdown(self):
for client in self.clientList:
client.join()
class WebSocketServer:
def __init__(self, ip = '0.0.0.0', port = 8888, conns = 9999):
self.ip = ip
self.port = port
self.CM = ClientManager()
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind( (self.ip, self.port) )
self.socket.listen(conns)
print('[#] Waiting for connections on ' + self.ip + ':' + str(self.port) + '...')
except socket.error as err:
print('[!] Error opening the socket: ' + str(err))
def register(self, functionName, function):
self.CM.registerAction(functionName, function)
def start(self):
try:
while True:
clientSocket, address = self.socket.accept()
self.CM.addClient(clientSocket, address)
except:
print('[#] Shutting down the server...')
self.stop()
def stop(self):
self.CM.shutdown()
self.socket.close()
| _sndClose | identifier_name |
websocket.py | # versione 0.5
import socket
import threading
import hashlib
import base64
import json
class BadWSRequest(Exception):
pass
class BadWSFrame(Exception):
pass
class BadCmdCall(Exception):
pass
class BadCmdParam(Exception):
pass
class Client(threading.Thread):
_MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
_OPCODE_TEXT = 0x1
_OPCODE_CLOSE = 0x8
def __init__(self, Manager, socket, address):
super().__init__()
self.Manager = Manager
self.socket = socket
self.ip, self.port = address
self.invokedPath = None
self.sessionStarted = False
def _parseHeader(self):
self.socket.settimeout(2.0)
rcvBuffer = ''
toRead = True
while toRead:
rcvBuffer += self.socket.recv(128).decode('utf-8')
#Check for the termination sequence
if rcvBuffer[-4:] == '\r\n\r\n': toRead = False
#vedere di usare splitlines
headerLines = rcvBuffer.split('\r\n')
requestLineElements = headerLines[0].split(' ')
if requestLineElements[0] == 'GET' and requestLineElements[-1] == 'HTTP/1.1':
self.invokedPath = requestLineElements[2]
else:
raise BadWSRequest
self.headerDict = {}
#Cut off rubbish (first line and termination sequence)
for header in headerLines[1:-2]:
headerKey, headerVal = header.split(':', 1)
self.headerDict.update({ headerKey: headerVal.strip() })
if (
'upgrade' not in self.headerDict['Connection'].lower().split(', ') or
self.headerDict['Upgrade'].lower() != 'websocket' or
'Sec-WebSocket-Key' not in self.headerDict
#Very weak part
):
raise BadWSRequest
#Operative mode needs more time
self.socket.settimeout(3600.0)
def _initComunication(self):
payload = 'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'
payload += 'Upgrade: WebSocket\r\n'
payload += 'Connection: Upgrade\r\n'
#Generate the security key
acceptKey = self.headerDict['Sec-WebSocket-Key'] + self._MAGIC_STRING
acceptKey = hashlib.sha1( acceptKey.encode('ascii') ).digest()
acceptKey = base64.b64encode(acceptKey)
payload += 'Sec-WebSocket-Accept: ' + acceptKey.decode('utf-8') + '\r\n\r\n'
self.socket.send( payload.encode('utf-8') )
def _rcvRequest(self):
#1st byte: FIN, RUBBISH1, RUBBISH2, RUBBISH3, OPCODE (4 bit)
#2nd byte: MASKED, PAYLOAD_LENGTH (7 bit)
rcvBuffer = self.socket.recv(2)
print('FIN: ' + str( rcvBuffer[0] >> 7 ))
#0x0f is 00001111 binary sequence
opcode = rcvBuffer[0] & 0x0f
print('opcode: ' + hex( opcode ))
maskBit = rcvBuffer[1] >> 7
print('mask: ' + str( maskBit ))
if maskBit != 1:
raise BadWSFrame('Unmasked data')
#0x7f is 01111111 binary sequence
length = rcvBuffer[1] & 0x7f
if length == 126:
#A long length is stored in more space
rcvBuffer = self.socket.recv(2)
length = int.from_bytes(rcvBuffer, 'big')
elif length == 127:
#un carico maggiore di 65kb a thread mi fa collassare il tutto..
#Ma poi.. perche' un utente dovrebbe caricare cosi' tanti dati? :O
raise BadWSFrame('Too big payload')
print('length: ' + str(length))
#Read the mask applied to data
maskKey = self.socket.recv(4)
#valutare di bufferizzare per rendere il thread piu' parsionioso
rcvBuffer = self.socket.recv(length)
message = b''
for i in range(length):
#Unmask the original message
message += bytes([ rcvBuffer[i] ^ maskKey[i % 4] ])
print(message)
if opcode == self._OPCODE_TEXT:
return json.loads( message.decode('utf-8') )
elif opcode == self._OPCODE_CLOSE:
return None
else:
|
def _sndResponse(self, data):
data = json.dumps(data).encode('utf-8')
length = len(data)
#FIN bit and opcode 0x1 (0x81 is 10000001 binary sequence)
payload = b'\x81'
if length >= 65535:
#Over the maximum length allowed by 16bit addressing
raise BadWSFrame('Too big payload')
elif length <= 125:
payload += bytes([length])
else:
payload += bytes([126])
payload += length.to_bytes(2, 'big')
#si potrebbe bufferizzare l'invio
self.socket.send(payload + data)
#Chiudere inviando un codice di errore e usando l'opcode globale
def _sndClose(self):
#FIN bit and opcode 0x8 (0x88 is 10001000 binary sequence)
#Mask and length bits are zero
self.socket.send(b'\x88\x00')
#Empty the remote buffer
self.socket.recv(100)
def run(self):
print('[+] Connection established with ' + self.ip + ':' + str(self.port), "[%s]" % str(len(self.Manager)))
try:
self._parseHeader()
self._initComunication()
self.sessionStarted = True
#socket non bloccanti potrebbero essere di aiuto per smaltire prima i dati
while True:
request = self._rcvRequest()
if not request: break
response = self.Manager.executeAction(self, request)
if response == None:
raise UnknownCommand
self._sndResponse(response)
except BadWSRequest:
print('[!] Bad-formed request from ' + self.ip + ':' + str(self.port))
except BadWSFrame as err:
print('[!] Bad-formed frame from ' + self.ip + ':' + str(self.port), str(err))
#valutare se lasciare il messaggio o meno
except BadCmdCall as err:
print('[!] Unknown command received from ' + self.ip + ':' + str(self.port), str(err))
except BadCmdParam as err:
print('[!] Invalid parameters from ' + self.ip + ':' + str(self.port), str(err))
except socket.timeout:
print('[!] Timeout occurred for ' + self.ip + ':' + str(self.port))
finally:
if self.sessionStarted:
self._sndClose()
self.socket.close()
self.Manager.rmvClient(self)
print('[-] Connection closed with ' + self.ip + ':' + str(self.port), "[%s]" % str(len(self.Manager)))
class ClientManager:
def __init__(self):
self.clientList = []
self.actionDict = {}
def __len__(self):
return len(self.clientList)
def addClient(self, clientSocket, address):
newClient = Client(self, clientSocket, address)
newClient.start()
self.clientList.append(newClient)
def rmvClient(self, clientInstance):
self.clientList.remove(clientInstance)
def registerAction(self, functionName, function):
self.actionDict.update({ functionName: function })
def executeAction(self, clientInstance, request):
#Array of two element is expected
function, parameters = request
if function in self.actionDict:
try:
return self.actionDict[function](*parameters)
except TypeError:
raise BadCmdParam(request)
else:
raise BadCmdCall(function)
def shutdown(self):
for client in self.clientList:
client.join()
class WebSocketServer:
def __init__(self, ip = '0.0.0.0', port = 8888, conns = 9999):
self.ip = ip
self.port = port
self.CM = ClientManager()
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind( (self.ip, self.port) )
self.socket.listen(conns)
print('[#] Waiting for connections on ' + self.ip + ':' + str(self.port) + '...')
except socket.error as err:
print('[!] Error opening the socket: ' + str(err))
def register(self, functionName, function):
self.CM.registerAction(functionName, function)
def start(self):
try:
while True:
clientSocket, address = self.socket.accept()
self.CM.addClient(clientSocket, address)
except:
print('[#] Shutting down the server...')
self.stop()
def stop(self):
self.CM.shutdown()
self.socket.close()
| raise BadWSFrame('Unknown OpCode') | conditional_block |
websocket.py | # versione 0.5
import socket
import threading
import hashlib
import base64
import json
class BadWSRequest(Exception):
pass
class BadWSFrame(Exception):
pass
class BadCmdCall(Exception):
pass
class BadCmdParam(Exception):
pass
class Client(threading.Thread):
_MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
_OPCODE_TEXT = 0x1
_OPCODE_CLOSE = 0x8
def __init__(self, Manager, socket, address):
super().__init__()
self.Manager = Manager
self.socket = socket
self.ip, self.port = address
self.invokedPath = None
self.sessionStarted = False
def _parseHeader(self):
self.socket.settimeout(2.0)
rcvBuffer = ''
toRead = True
while toRead:
rcvBuffer += self.socket.recv(128).decode('utf-8')
#Check for the termination sequence
if rcvBuffer[-4:] == '\r\n\r\n': toRead = False
#vedere di usare splitlines
headerLines = rcvBuffer.split('\r\n')
requestLineElements = headerLines[0].split(' ')
if requestLineElements[0] == 'GET' and requestLineElements[-1] == 'HTTP/1.1':
self.invokedPath = requestLineElements[2]
else:
raise BadWSRequest
self.headerDict = {}
#Cut off rubbish (first line and termination sequence)
for header in headerLines[1:-2]:
headerKey, headerVal = header.split(':', 1)
self.headerDict.update({ headerKey: headerVal.strip() })
if (
'upgrade' not in self.headerDict['Connection'].lower().split(', ') or
self.headerDict['Upgrade'].lower() != 'websocket' or
'Sec-WebSocket-Key' not in self.headerDict
#Very weak part
):
raise BadWSRequest
#Operative mode needs more time
self.socket.settimeout(3600.0)
def _initComunication(self):
payload = 'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'
payload += 'Upgrade: WebSocket\r\n'
payload += 'Connection: Upgrade\r\n'
#Generate the security key
acceptKey = self.headerDict['Sec-WebSocket-Key'] + self._MAGIC_STRING
acceptKey = hashlib.sha1( acceptKey.encode('ascii') ).digest()
acceptKey = base64.b64encode(acceptKey)
payload += 'Sec-WebSocket-Accept: ' + acceptKey.decode('utf-8') + '\r\n\r\n'
self.socket.send( payload.encode('utf-8') )
def _rcvRequest(self):
#1st byte: FIN, RUBBISH1, RUBBISH2, RUBBISH3, OPCODE (4 bit) | print('FIN: ' + str( rcvBuffer[0] >> 7 ))
#0x0f is 00001111 binary sequence
opcode = rcvBuffer[0] & 0x0f
print('opcode: ' + hex( opcode ))
maskBit = rcvBuffer[1] >> 7
print('mask: ' + str( maskBit ))
if maskBit != 1:
raise BadWSFrame('Unmasked data')
#0x7f is 01111111 binary sequence
length = rcvBuffer[1] & 0x7f
if length == 126:
#A long length is stored in more space
rcvBuffer = self.socket.recv(2)
length = int.from_bytes(rcvBuffer, 'big')
elif length == 127:
#un carico maggiore di 65kb a thread mi fa collassare il tutto..
#Ma poi.. perche' un utente dovrebbe caricare cosi' tanti dati? :O
raise BadWSFrame('Too big payload')
print('length: ' + str(length))
#Read the mask applied to data
maskKey = self.socket.recv(4)
#valutare di bufferizzare per rendere il thread piu' parsionioso
rcvBuffer = self.socket.recv(length)
message = b''
for i in range(length):
#Unmask the original message
message += bytes([ rcvBuffer[i] ^ maskKey[i % 4] ])
print(message)
if opcode == self._OPCODE_TEXT:
return json.loads( message.decode('utf-8') )
elif opcode == self._OPCODE_CLOSE:
return None
else:
raise BadWSFrame('Unknown OpCode')
def _sndResponse(self, data):
data = json.dumps(data).encode('utf-8')
length = len(data)
#FIN bit and opcode 0x1 (0x81 is 10000001 binary sequence)
payload = b'\x81'
if length >= 65535:
#Over the maximum length allowed by 16bit addressing
raise BadWSFrame('Too big payload')
elif length <= 125:
payload += bytes([length])
else:
payload += bytes([126])
payload += length.to_bytes(2, 'big')
#si potrebbe bufferizzare l'invio
self.socket.send(payload + data)
#Chiudere inviando un codice di errore e usando l'opcode globale
def _sndClose(self):
#FIN bit and opcode 0x8 (0x88 is 10001000 binary sequence)
#Mask and length bits are zero
self.socket.send(b'\x88\x00')
#Empty the remote buffer
self.socket.recv(100)
def run(self):
print('[+] Connection established with ' + self.ip + ':' + str(self.port), "[%s]" % str(len(self.Manager)))
try:
self._parseHeader()
self._initComunication()
self.sessionStarted = True
#socket non bloccanti potrebbero essere di aiuto per smaltire prima i dati
while True:
request = self._rcvRequest()
if not request: break
response = self.Manager.executeAction(self, request)
if response == None:
raise UnknownCommand
self._sndResponse(response)
except BadWSRequest:
print('[!] Bad-formed request from ' + self.ip + ':' + str(self.port))
except BadWSFrame as err:
print('[!] Bad-formed frame from ' + self.ip + ':' + str(self.port), str(err))
#valutare se lasciare il messaggio o meno
except BadCmdCall as err:
print('[!] Unknown command received from ' + self.ip + ':' + str(self.port), str(err))
except BadCmdParam as err:
print('[!] Invalid parameters from ' + self.ip + ':' + str(self.port), str(err))
except socket.timeout:
print('[!] Timeout occurred for ' + self.ip + ':' + str(self.port))
finally:
if self.sessionStarted:
self._sndClose()
self.socket.close()
self.Manager.rmvClient(self)
print('[-] Connection closed with ' + self.ip + ':' + str(self.port), "[%s]" % str(len(self.Manager)))
class ClientManager:
def __init__(self):
self.clientList = []
self.actionDict = {}
def __len__(self):
return len(self.clientList)
def addClient(self, clientSocket, address):
newClient = Client(self, clientSocket, address)
newClient.start()
self.clientList.append(newClient)
def rmvClient(self, clientInstance):
self.clientList.remove(clientInstance)
def registerAction(self, functionName, function):
self.actionDict.update({ functionName: function })
def executeAction(self, clientInstance, request):
#Array of two element is expected
function, parameters = request
if function in self.actionDict:
try:
return self.actionDict[function](*parameters)
except TypeError:
raise BadCmdParam(request)
else:
raise BadCmdCall(function)
def shutdown(self):
for client in self.clientList:
client.join()
class WebSocketServer:
def __init__(self, ip = '0.0.0.0', port = 8888, conns = 9999):
self.ip = ip
self.port = port
self.CM = ClientManager()
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind( (self.ip, self.port) )
self.socket.listen(conns)
print('[#] Waiting for connections on ' + self.ip + ':' + str(self.port) + '...')
except socket.error as err:
print('[!] Error opening the socket: ' + str(err))
def register(self, functionName, function):
self.CM.registerAction(functionName, function)
def start(self):
try:
while True:
clientSocket, address = self.socket.accept()
self.CM.addClient(clientSocket, address)
except:
print('[#] Shutting down the server...')
self.stop()
def stop(self):
self.CM.shutdown()
self.socket.close() | #2nd byte: MASKED, PAYLOAD_LENGTH (7 bit)
rcvBuffer = self.socket.recv(2) | random_line_split |
websocket.py | # versione 0.5
import socket
import threading
import hashlib
import base64
import json
class BadWSRequest(Exception):
pass
class BadWSFrame(Exception):
pass
class BadCmdCall(Exception):
pass
class BadCmdParam(Exception):
pass
class Client(threading.Thread):
_MAGIC_STRING = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
_OPCODE_TEXT = 0x1
_OPCODE_CLOSE = 0x8
def __init__(self, Manager, socket, address):
super().__init__()
self.Manager = Manager
self.socket = socket
self.ip, self.port = address
self.invokedPath = None
self.sessionStarted = False
def _parseHeader(self):
self.socket.settimeout(2.0)
rcvBuffer = ''
toRead = True
while toRead:
rcvBuffer += self.socket.recv(128).decode('utf-8')
#Check for the termination sequence
if rcvBuffer[-4:] == '\r\n\r\n': toRead = False
#vedere di usare splitlines
headerLines = rcvBuffer.split('\r\n')
requestLineElements = headerLines[0].split(' ')
if requestLineElements[0] == 'GET' and requestLineElements[-1] == 'HTTP/1.1':
self.invokedPath = requestLineElements[2]
else:
raise BadWSRequest
self.headerDict = {}
#Cut off rubbish (first line and termination sequence)
for header in headerLines[1:-2]:
headerKey, headerVal = header.split(':', 1)
self.headerDict.update({ headerKey: headerVal.strip() })
if (
'upgrade' not in self.headerDict['Connection'].lower().split(', ') or
self.headerDict['Upgrade'].lower() != 'websocket' or
'Sec-WebSocket-Key' not in self.headerDict
#Very weak part
):
raise BadWSRequest
#Operative mode needs more time
self.socket.settimeout(3600.0)
def _initComunication(self):
payload = 'HTTP/1.1 101 Web Socket Protocol Handshake\r\n'
payload += 'Upgrade: WebSocket\r\n'
payload += 'Connection: Upgrade\r\n'
#Generate the security key
acceptKey = self.headerDict['Sec-WebSocket-Key'] + self._MAGIC_STRING
acceptKey = hashlib.sha1( acceptKey.encode('ascii') ).digest()
acceptKey = base64.b64encode(acceptKey)
payload += 'Sec-WebSocket-Accept: ' + acceptKey.decode('utf-8') + '\r\n\r\n'
self.socket.send( payload.encode('utf-8') )
def _rcvRequest(self):
#1st byte: FIN, RUBBISH1, RUBBISH2, RUBBISH3, OPCODE (4 bit)
#2nd byte: MASKED, PAYLOAD_LENGTH (7 bit)
rcvBuffer = self.socket.recv(2)
print('FIN: ' + str( rcvBuffer[0] >> 7 ))
#0x0f is 00001111 binary sequence
opcode = rcvBuffer[0] & 0x0f
print('opcode: ' + hex( opcode ))
maskBit = rcvBuffer[1] >> 7
print('mask: ' + str( maskBit ))
if maskBit != 1:
raise BadWSFrame('Unmasked data')
#0x7f is 01111111 binary sequence
length = rcvBuffer[1] & 0x7f
if length == 126:
#A long length is stored in more space
rcvBuffer = self.socket.recv(2)
length = int.from_bytes(rcvBuffer, 'big')
elif length == 127:
#un carico maggiore di 65kb a thread mi fa collassare il tutto..
#Ma poi.. perche' un utente dovrebbe caricare cosi' tanti dati? :O
raise BadWSFrame('Too big payload')
print('length: ' + str(length))
#Read the mask applied to data
maskKey = self.socket.recv(4)
#valutare di bufferizzare per rendere il thread piu' parsionioso
rcvBuffer = self.socket.recv(length)
message = b''
for i in range(length):
#Unmask the original message
message += bytes([ rcvBuffer[i] ^ maskKey[i % 4] ])
print(message)
if opcode == self._OPCODE_TEXT:
return json.loads( message.decode('utf-8') )
elif opcode == self._OPCODE_CLOSE:
return None
else:
raise BadWSFrame('Unknown OpCode')
def _sndResponse(self, data):
data = json.dumps(data).encode('utf-8')
length = len(data)
#FIN bit and opcode 0x1 (0x81 is 10000001 binary sequence)
payload = b'\x81'
if length >= 65535:
#Over the maximum length allowed by 16bit addressing
raise BadWSFrame('Too big payload')
elif length <= 125:
payload += bytes([length])
else:
payload += bytes([126])
payload += length.to_bytes(2, 'big')
#si potrebbe bufferizzare l'invio
self.socket.send(payload + data)
#Chiudere inviando un codice di errore e usando l'opcode globale
def _sndClose(self):
#FIN bit and opcode 0x8 (0x88 is 10001000 binary sequence)
#Mask and length bits are zero
self.socket.send(b'\x88\x00')
#Empty the remote buffer
self.socket.recv(100)
def run(self):
print('[+] Connection established with ' + self.ip + ':' + str(self.port), "[%s]" % str(len(self.Manager)))
try:
self._parseHeader()
self._initComunication()
self.sessionStarted = True
#socket non bloccanti potrebbero essere di aiuto per smaltire prima i dati
while True:
request = self._rcvRequest()
if not request: break
response = self.Manager.executeAction(self, request)
if response == None:
raise UnknownCommand
self._sndResponse(response)
except BadWSRequest:
print('[!] Bad-formed request from ' + self.ip + ':' + str(self.port))
except BadWSFrame as err:
print('[!] Bad-formed frame from ' + self.ip + ':' + str(self.port), str(err))
#valutare se lasciare il messaggio o meno
except BadCmdCall as err:
print('[!] Unknown command received from ' + self.ip + ':' + str(self.port), str(err))
except BadCmdParam as err:
print('[!] Invalid parameters from ' + self.ip + ':' + str(self.port), str(err))
except socket.timeout:
print('[!] Timeout occurred for ' + self.ip + ':' + str(self.port))
finally:
if self.sessionStarted:
self._sndClose()
self.socket.close()
self.Manager.rmvClient(self)
print('[-] Connection closed with ' + self.ip + ':' + str(self.port), "[%s]" % str(len(self.Manager)))
class ClientManager:
def __init__(self):
self.clientList = []
self.actionDict = {}
def __len__(self):
return len(self.clientList)
def addClient(self, clientSocket, address):
newClient = Client(self, clientSocket, address)
newClient.start()
self.clientList.append(newClient)
def rmvClient(self, clientInstance):
self.clientList.remove(clientInstance)
def registerAction(self, functionName, function):
|
def executeAction(self, clientInstance, request):
#Array of two element is expected
function, parameters = request
if function in self.actionDict:
try:
return self.actionDict[function](*parameters)
except TypeError:
raise BadCmdParam(request)
else:
raise BadCmdCall(function)
def shutdown(self):
for client in self.clientList:
client.join()
class WebSocketServer:
def __init__(self, ip = '0.0.0.0', port = 8888, conns = 9999):
self.ip = ip
self.port = port
self.CM = ClientManager()
try:
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.bind( (self.ip, self.port) )
self.socket.listen(conns)
print('[#] Waiting for connections on ' + self.ip + ':' + str(self.port) + '...')
except socket.error as err:
print('[!] Error opening the socket: ' + str(err))
def register(self, functionName, function):
self.CM.registerAction(functionName, function)
def start(self):
try:
while True:
clientSocket, address = self.socket.accept()
self.CM.addClient(clientSocket, address)
except:
print('[#] Shutting down the server...')
self.stop()
def stop(self):
self.CM.shutdown()
self.socket.close()
| self.actionDict.update({ functionName: function }) | identifier_body |
gruntfile.js | var $path = require('path');
module.exports = function(grunt) {
grunt.initConfig({
localBase : $path.resolve(__dirname),
pkg: grunt.file.readJSON('package.json'),
litheConcat : {
options : {
cwd: '<%=localBase%>'
},
publish : {
src : 'public/js/',
dest : 'public/js/dist/',
walk : true,
alias : 'config.js',
global : 'conf/global.js',
withoutGlobal : [
| litheCompress : {
options : {
cwd: '<%=localBase%>'
},
publish : {
src : 'public/js/dist/',
dest : 'public/js/dist/'
}
}
});
grunt.loadTasks('tasks/lithe');
grunt.registerTask(
'publish',
'[COMMON] pack and compress files, then distribute',
[
'litheConcat:publish',
'litheCompress:publish'
]
);
grunt.registerTask(
'default',
'the default task is publish',
[
'publish'
]
);
}; | ],
target : 'conf/'
}
},
| random_line_split |
setup.py | Overlays on map tiles in Python.
"""
from setuptools import setup
setup(
name='pymapplot',
version='0.0.1',
url='https://github.com/HengfengLi/pymapplot',
license='MIT',
author='Hengfeng Li',
author_email='hengf.li@gmail.com',
description=('Overlays on map tiles in Python. '),
long_description=__doc__,
packages=['pymapplot'],
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[],
test_suite="tests",
classifiers=[
'Environment :: Web Environment', 'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent', 'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Software Development :: Libraries :: Python Modules'
]) | """
PyMapPlot
-------------- | random_line_split | |
lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn | (bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| deflate_bytes_internal | identifier_name |
lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() | else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} | conditional_block |
lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal" | fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, 0)
}
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
} | static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
| random_line_split |
lib.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
Simple [DEFLATE][def]-based compression. This is a wrapper around the
[`miniz`][mz] library, which is a one-file pure-C implementation of zlib.
[def]: https://en.wikipedia.org/wiki/DEFLATE
[mz]: https://code.google.com/p/miniz/
*/
#![crate_id = "flate#0.11.0-pre"]
#![crate_type = "rlib"]
#![crate_type = "dylib"]
#![license = "MIT/ASL2"]
#![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
html_favicon_url = "http://www.rust-lang.org/favicon.ico",
html_root_url = "http://doc.rust-lang.org/")]
#![feature(phase)]
#![deny(deprecated_owned_vector)]
#[cfg(test)] #[phase(syntax, link)] extern crate log;
extern crate libc;
use std::c_vec::CVec;
use libc::{c_void, size_t, c_int};
#[link(name = "miniz", kind = "static")]
extern {
/// Raw miniz compression function.
fn tdefl_compress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
/// Raw miniz decompression function.
fn tinfl_decompress_mem_to_heap(psrc_buf: *c_void,
src_buf_len: size_t,
pout_len: *mut size_t,
flags: c_int)
-> *mut c_void;
}
static LZ_NORM : c_int = 0x80; // LZ with 128 probes, "normal"
static TINFL_FLAG_PARSE_ZLIB_HEADER : c_int = 0x1; // parse zlib header and adler32 checksum
static TDEFL_WRITE_ZLIB_HEADER : c_int = 0x01000; // write zlib header and adler32 checksum
fn deflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tdefl_compress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Compress a buffer, without writing any sort of header on the output.
pub fn deflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM)
}
/// Compress a buffer, using a header that zlib can understand.
pub fn deflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
deflate_bytes_internal(bytes, LZ_NORM | TDEFL_WRITE_ZLIB_HEADER)
}
fn inflate_bytes_internal(bytes: &[u8], flags: c_int) -> Option<CVec<u8>> {
unsafe {
let mut outsz : size_t = 0;
let res = tinfl_decompress_mem_to_heap(bytes.as_ptr() as *c_void,
bytes.len() as size_t,
&mut outsz,
flags);
if !res.is_null() {
Some(CVec::new_with_dtor(res as *mut u8, outsz as uint, proc() libc::free(res)))
} else {
None
}
}
}
/// Decompress a buffer, without parsing any sort of header on the input.
pub fn inflate_bytes(bytes: &[u8]) -> Option<CVec<u8>> |
/// Decompress a buffer that starts with a zlib header.
pub fn inflate_bytes_zlib(bytes: &[u8]) -> Option<CVec<u8>> {
inflate_bytes_internal(bytes, TINFL_FLAG_PARSE_ZLIB_HEADER)
}
#[cfg(test)]
mod tests {
use super::{inflate_bytes, deflate_bytes};
use std::rand;
use std::rand::Rng;
#[test]
#[allow(deprecated_owned_vector)]
fn test_flate_round_trip() {
let mut r = rand::task_rng();
let mut words = vec!();
for _ in range(0, 20) {
let range = r.gen_range(1u, 10);
let v = r.gen_iter::<u8>().take(range).collect::<Vec<u8>>();
words.push(v);
}
for _ in range(0, 20) {
let mut input = vec![];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()).unwrap().as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());
let cmp = deflate_bytes(input.as_slice()).expect("deflation failed");
let out = inflate_bytes(cmp.as_slice()).expect("inflation failed");
debug!("{} bytes deflated to {} ({:.1f}% size)",
input.len(), cmp.len(),
100.0 * ((cmp.len() as f64) / (input.len() as f64)));
assert_eq!(input.as_slice(), out.as_slice());
}
}
#[test]
fn test_zlib_flate() {
let bytes = vec!(1, 2, 3, 4, 5);
let deflated = deflate_bytes(bytes.as_slice()).expect("deflation failed");
let inflated = inflate_bytes(deflated.as_slice()).expect("inflation failed");
assert_eq!(inflated.as_slice(), bytes.as_slice());
}
}
| {
inflate_bytes_internal(bytes, 0)
} | identifier_body |
PracticeQuestions.py | """Chapter 22 Practice Questions
Answers Chapter 22 Practice Questions via Python code. |
def main():
# 1. How many prime numbers are there?
# Hint: Check page 322
message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 2. What are integers that are not prime called?
# Hint: Check page 323
message = "Vbmggpcw wlvx njr bhv pctqh emi psyzxf czxtrwdxr fhaugrd." # Encrypted with key "NOTCALLEDEVENS"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 3. What are two algorithms for finding prime numbers?
# Hint: Check page 323
# Encrypted with key "ALGORITHMS"
message = "Tsk hyzxl mdgzxwkpfz gkeo ob kpbz ngov gfv: bkpmd dtbwjqhu, eaegk cw Mkhfgsenseml, hzv Rlhwe-Ubsxwr."
#print(decryptMessage(blank, blank)) # Fill in the blanks
# If PracticeQuestions.py is run (instead of imported as a module), call
# the main() function:
if __name__ == '__main__':
main() | """
from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage
| random_line_split |
PracticeQuestions.py | """Chapter 22 Practice Questions
Answers Chapter 22 Practice Questions via Python code.
"""
from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage
def main():
# 1. How many prime numbers are there?
# Hint: Check page 322
|
# If PracticeQuestions.py is run (instead of imported as a module), call
# the main() function:
if __name__ == '__main__':
main()
| message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 2. What are integers that are not prime called?
# Hint: Check page 323
message = "Vbmggpcw wlvx njr bhv pctqh emi psyzxf czxtrwdxr fhaugrd." # Encrypted with key "NOTCALLEDEVENS"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 3. What are two algorithms for finding prime numbers?
# Hint: Check page 323
# Encrypted with key "ALGORITHMS"
message = "Tsk hyzxl mdgzxwkpfz gkeo ob kpbz ngov gfv: bkpmd dtbwjqhu, eaegk cw Mkhfgsenseml, hzv Rlhwe-Ubsxwr."
#print(decryptMessage(blank, blank)) # Fill in the blanks | identifier_body |
PracticeQuestions.py | """Chapter 22 Practice Questions
Answers Chapter 22 Practice Questions via Python code.
"""
from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage
def main():
# 1. How many prime numbers are there?
# Hint: Check page 322
message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 2. What are integers that are not prime called?
# Hint: Check page 323
message = "Vbmggpcw wlvx njr bhv pctqh emi psyzxf czxtrwdxr fhaugrd." # Encrypted with key "NOTCALLEDEVENS"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 3. What are two algorithms for finding prime numbers?
# Hint: Check page 323
# Encrypted with key "ALGORITHMS"
message = "Tsk hyzxl mdgzxwkpfz gkeo ob kpbz ngov gfv: bkpmd dtbwjqhu, eaegk cw Mkhfgsenseml, hzv Rlhwe-Ubsxwr."
#print(decryptMessage(blank, blank)) # Fill in the blanks
# If PracticeQuestions.py is run (instead of imported as a module), call
# the main() function:
if __name__ == '__main__':
| main() | conditional_block | |
PracticeQuestions.py | """Chapter 22 Practice Questions
Answers Chapter 22 Practice Questions via Python code.
"""
from pythontutorials.books.CrackingCodes.Ch18.vigenereCipher import decryptMessage
def | ():
# 1. How many prime numbers are there?
# Hint: Check page 322
message = "Iymdi ah rv urxxeqfi fjdjqv gu gzuqw clunijh." # Encrypted with key "PRIMES"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 2. What are integers that are not prime called?
# Hint: Check page 323
message = "Vbmggpcw wlvx njr bhv pctqh emi psyzxf czxtrwdxr fhaugrd." # Encrypted with key "NOTCALLEDEVENS"
#print(decryptMessage(blank, blank)) # Fill in the blanks
# 3. What are two algorithms for finding prime numbers?
# Hint: Check page 323
# Encrypted with key "ALGORITHMS"
message = "Tsk hyzxl mdgzxwkpfz gkeo ob kpbz ngov gfv: bkpmd dtbwjqhu, eaegk cw Mkhfgsenseml, hzv Rlhwe-Ubsxwr."
#print(decryptMessage(blank, blank)) # Fill in the blanks
# If PracticeQuestions.py is run (instead of imported as a module), call
# the main() function:
if __name__ == '__main__':
main()
| main | identifier_name |
mutable.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::*;
pub trait SyncMutable {
fn put(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>;
fn delete(&self, key: &[u8]) -> Result<()>;
fn delete_cf(&self, cf: &str, key: &[u8]) -> Result<()>;
fn delete_range_cf(&self, cf: &str, begin_key: &[u8], end_key: &[u8]) -> Result<()>;
fn put_msg<M: protobuf::Message>(&self, key: &[u8], m: &M) -> Result<()> {
self.put(key, &m.write_to_bytes()?)
}
fn put_msg_cf<M: protobuf::Message>(&self, cf: &str, key: &[u8], m: &M) -> Result<()> |
}
| {
self.put_cf(cf, key, &m.write_to_bytes()?)
} | identifier_body |
mutable.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::*;
pub trait SyncMutable {
fn put(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>;
fn delete(&self, key: &[u8]) -> Result<()>;
fn delete_cf(&self, cf: &str, key: &[u8]) -> Result<()>;
fn delete_range_cf(&self, cf: &str, begin_key: &[u8], end_key: &[u8]) -> Result<()>;
fn | <M: protobuf::Message>(&self, key: &[u8], m: &M) -> Result<()> {
self.put(key, &m.write_to_bytes()?)
}
fn put_msg_cf<M: protobuf::Message>(&self, cf: &str, key: &[u8], m: &M) -> Result<()> {
self.put_cf(cf, key, &m.write_to_bytes()?)
}
}
| put_msg | identifier_name |
mutable.rs | // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
use crate::*;
pub trait SyncMutable {
fn put(&self, key: &[u8], value: &[u8]) -> Result<()>;
fn put_cf(&self, cf: &str, key: &[u8], value: &[u8]) -> Result<()>;
fn delete(&self, key: &[u8]) -> Result<()>;
fn delete_cf(&self, cf: &str, key: &[u8]) -> Result<()>;
fn delete_range_cf(&self, cf: &str, begin_key: &[u8], end_key: &[u8]) -> Result<()>;
| }
fn put_msg_cf<M: protobuf::Message>(&self, cf: &str, key: &[u8], m: &M) -> Result<()> {
self.put_cf(cf, key, &m.write_to_bytes()?)
}
} | fn put_msg<M: protobuf::Message>(&self, key: &[u8], m: &M) -> Result<()> {
self.put(key, &m.write_to_bytes()?) | random_line_split |
wsgi.py | """
WSGI config for server project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setting.
Usually you will have the standard Django WSGI application here, but it also | middleware here, or combine a Django application with an application of another
framework.
"""
import os
# We defer to a DJANGO_SETTINGS_MODULE already in the environment. This breaks
# if running multiple sites in the same mod_wsgi process. To fix this, use
# mod_wsgi daemon mode with each site in its own daemon process, or use
# os.environ["DJANGO_SETTINGS_MODULE"] = "server.settings"
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings")
# This application object is used by any WSGI server configured to use this
# file. This includes Django's development server, if the WSGI_APPLICATION
# setting points here.
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
# Apply WSGI middleware here.
# from helloworld.wsgi import HelloWorldApplication
# application = HelloWorldApplication(application) | might make sense to replace the whole Django WSGI application with a custom one
that later delegates to the Django one. For example, you could introduce WSGI | random_line_split |
elf_arch-i386.rs | pub const ELF_CLASS: u8 = 1;
pub type ElfAddr = u32;
pub type ElfHalf = u16;
pub type ElfOff = u32;
pub type ElfWord = u32;
/// An ELF header
#[repr(packed)]
pub struct ElfHeader {
/// The "magic number" (4 bytes)
pub magic: [u8; 4],
/// 64 or 32 bit?
pub class: u8,
/// Little (1) or big endianness (2)?
pub endian: u8,
/// The ELF version (set to 1 for default)
pub ver: u8,
/// Operating system ABI (0x03 for Linux)
pub abi: [u8; 2],
/// Unused
pub pad: [u8; 7],
/// Specify whether the object is relocatable, executable, shared, or core (in order).
pub _type: ElfHalf,
/// Instruction set archcitecture
pub machine: ElfHalf, | pub ver_2: ElfWord,
/// The ELF entry
pub entry: ElfAddr,
/// The program header table offset
pub ph_off: ElfOff,
/// The section header table offset
pub sh_off: ElfOff,
/// The flags set
pub flags: ElfWord,
/// The header table length
pub h_len: ElfHalf,
/// The program header table entry length
pub ph_ent_len: ElfHalf,
/// The program head table length
pub ph_len: ElfHalf,
/// The section header table entry length
pub sh_ent_len: ElfHalf,
/// The section header table length
pub sh_len: ElfHalf,
/// The section header table string index
pub sh_str_index: ElfHalf,
}
/// An ELF segment
#[repr(packed)]
pub struct ElfSegment {
pub _type: ElfWord,
pub off: ElfOff,
pub vaddr: ElfAddr,
pub paddr: ElfAddr,
pub file_len: ElfWord,
pub mem_len: ElfWord,
pub flags: ElfWord,
pub align: ElfWord,
}
/// An ELF section
#[repr(packed)]
pub struct ElfSection {
pub name: ElfWord,
pub _type: ElfWord,
pub flags: ElfWord,
pub addr: ElfAddr,
pub off: ElfOff,
pub len: ElfWord,
pub link: ElfWord,
pub info: ElfWord,
pub addr_align: ElfWord,
pub ent_len: ElfWord,
}
/// An ELF symbol
#[repr(packed)]
pub struct ElfSymbol {
pub name: ElfWord,
pub value: ElfAddr,
pub size: ElfWord,
pub info: u8,
pub other: u8,
pub sh_index: ElfHalf,
} | /// Second version | random_line_split |
elf_arch-i386.rs | pub const ELF_CLASS: u8 = 1;
pub type ElfAddr = u32;
pub type ElfHalf = u16;
pub type ElfOff = u32;
pub type ElfWord = u32;
/// An ELF header
#[repr(packed)]
pub struct ElfHeader {
/// The "magic number" (4 bytes)
pub magic: [u8; 4],
/// 64 or 32 bit?
pub class: u8,
/// Little (1) or big endianness (2)?
pub endian: u8,
/// The ELF version (set to 1 for default)
pub ver: u8,
/// Operating system ABI (0x03 for Linux)
pub abi: [u8; 2],
/// Unused
pub pad: [u8; 7],
/// Specify whether the object is relocatable, executable, shared, or core (in order).
pub _type: ElfHalf,
/// Instruction set archcitecture
pub machine: ElfHalf,
/// Second version
pub ver_2: ElfWord,
/// The ELF entry
pub entry: ElfAddr,
/// The program header table offset
pub ph_off: ElfOff,
/// The section header table offset
pub sh_off: ElfOff,
/// The flags set
pub flags: ElfWord,
/// The header table length
pub h_len: ElfHalf,
/// The program header table entry length
pub ph_ent_len: ElfHalf,
/// The program head table length
pub ph_len: ElfHalf,
/// The section header table entry length
pub sh_ent_len: ElfHalf,
/// The section header table length
pub sh_len: ElfHalf,
/// The section header table string index
pub sh_str_index: ElfHalf,
}
/// An ELF segment
#[repr(packed)]
pub struct | {
pub _type: ElfWord,
pub off: ElfOff,
pub vaddr: ElfAddr,
pub paddr: ElfAddr,
pub file_len: ElfWord,
pub mem_len: ElfWord,
pub flags: ElfWord,
pub align: ElfWord,
}
/// An ELF section
#[repr(packed)]
pub struct ElfSection {
pub name: ElfWord,
pub _type: ElfWord,
pub flags: ElfWord,
pub addr: ElfAddr,
pub off: ElfOff,
pub len: ElfWord,
pub link: ElfWord,
pub info: ElfWord,
pub addr_align: ElfWord,
pub ent_len: ElfWord,
}
/// An ELF symbol
#[repr(packed)]
pub struct ElfSymbol {
pub name: ElfWord,
pub value: ElfAddr,
pub size: ElfWord,
pub info: u8,
pub other: u8,
pub sh_index: ElfHalf,
}
| ElfSegment | identifier_name |
test_despike.py | import numpy as np
from apvisitproc import despike
import pytest
import os
DATAPATH = os.path.dirname(__file__)
FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt')
FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt')
@pytest.fixture
def wave_spec_generate():
'''
Read in three small chunks of spectra for testing purposes
'wavelist_speclist_generate' can be used as input to any other test function
that needs access to the variables it returns!
wave1, spec1 are a single chunk of 1d spectrum
wavelist, speclist are lists of three chunks of 1d spectrum
'''
wave1, spec1 = np.loadtxt(os.path.join(DATAPATH, 'spec1test.txt'), unpack=True)
wave2, spec2 = np.loadtxt(os.path.join(DATAPATH, 'spec2test.txt'), unpack=True)
wave3, spec3 = np.loadtxt(os.path.join(DATAPATH, 'spec3test.txt'), unpack=True)
wavelist = [wave1, wave2, wave3]
speclist = [spec1, spec2, spec3]
return wave1, spec1, wavelist, speclist
@pytest.mark.parametrize('filelist, cond', [
(FILELIST1, False),
(FILELIST2, True),
])
def test_read_infiles(filelist, cond):
'''
Test reading in both text and fits files
Each resulting wavelength array should be sorted in ascending order
'''
infilelist, wavelist, speclist = despike.read_infiles(DATAPATH, filelist, cond)
assert len(infilelist) > 0
assert len(infilelist) == len(wavelist)
assert len(wavelist) == len(speclist)
for wave in wavelist:
|
def test_simpledespike(wave_spec_generate):
'''
spike condition is met at pixels 15, 16, 17 and 18
so indices 9 through 24, inclusive, should be removed
'''
wave, spec = wave_spec_generate[0], wave_spec_generate[1]
newwave, newspec = despike.simpledespike(wave, spec, delwindow=6,
stdfactorup=0.7, stdfactordown=3,
plot=False)
assert len(newwave) == len(newspec)
assert len(newwave) <= len(wave)
assert len(newspec) <= len(spec)
assert all(np.equal(np.hstack((wave[0:9], wave[25:])), newwave))
assert all(np.equal(np.hstack((spec[0:9], spec[25:])), newspec))
def test_despike_spectra(wave_spec_generate):
'''
Test that new spectra are shorter than the original because the outliers are gone
'''
wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3]
newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False)
assert len(newwavelist) == len(wavelist)
assert len(newspeclist) == len(speclist)
| assert all(value >= 0 for value in wave)
assert list(np.sort(wave)) == list(wave)
assert all(np.equal(np.sort(wave), wave)) | conditional_block |
test_despike.py | import numpy as np
from apvisitproc import despike
import pytest
import os
DATAPATH = os.path.dirname(__file__)
FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt')
FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt')
@pytest.fixture
def wave_spec_generate():
'''
Read in three small chunks of spectra for testing purposes
'wavelist_speclist_generate' can be used as input to any other test function
that needs access to the variables it returns!
wave1, spec1 are a single chunk of 1d spectrum
wavelist, speclist are lists of three chunks of 1d spectrum
'''
wave1, spec1 = np.loadtxt(os.path.join(DATAPATH, 'spec1test.txt'), unpack=True)
wave2, spec2 = np.loadtxt(os.path.join(DATAPATH, 'spec2test.txt'), unpack=True)
wave3, spec3 = np.loadtxt(os.path.join(DATAPATH, 'spec3test.txt'), unpack=True)
wavelist = [wave1, wave2, wave3]
speclist = [spec1, spec2, spec3]
return wave1, spec1, wavelist, speclist
@pytest.mark.parametrize('filelist, cond', [
(FILELIST1, False),
(FILELIST2, True),
])
def test_read_infiles(filelist, cond):
'''
Test reading in both text and fits files
Each resulting wavelength array should be sorted in ascending order
'''
infilelist, wavelist, speclist = despike.read_infiles(DATAPATH, filelist, cond)
assert len(infilelist) > 0
assert len(infilelist) == len(wavelist)
assert len(wavelist) == len(speclist)
for wave in wavelist:
assert all(value >= 0 for value in wave)
assert list(np.sort(wave)) == list(wave)
assert all(np.equal(np.sort(wave), wave))
def test_simpledespike(wave_spec_generate):
'''
spike condition is met at pixels 15, 16, 17 and 18
so indices 9 through 24, inclusive, should be removed
'''
wave, spec = wave_spec_generate[0], wave_spec_generate[1]
newwave, newspec = despike.simpledespike(wave, spec, delwindow=6,
stdfactorup=0.7, stdfactordown=3,
plot=False)
assert len(newwave) == len(newspec)
assert len(newwave) <= len(wave)
assert len(newspec) <= len(spec)
assert all(np.equal(np.hstack((wave[0:9], wave[25:])), newwave))
assert all(np.equal(np.hstack((spec[0:9], spec[25:])), newspec))
def test_despike_spectra(wave_spec_generate):
''' | '''
wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3]
newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False)
assert len(newwavelist) == len(wavelist)
assert len(newspeclist) == len(speclist) | Test that new spectra are shorter than the original because the outliers are gone | random_line_split |
test_despike.py | import numpy as np
from apvisitproc import despike
import pytest
import os
DATAPATH = os.path.dirname(__file__)
FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt')
FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt')
@pytest.fixture
def wave_spec_generate():
'''
Read in three small chunks of spectra for testing purposes
'wavelist_speclist_generate' can be used as input to any other test function
that needs access to the variables it returns!
wave1, spec1 are a single chunk of 1d spectrum
wavelist, speclist are lists of three chunks of 1d spectrum
'''
wave1, spec1 = np.loadtxt(os.path.join(DATAPATH, 'spec1test.txt'), unpack=True)
wave2, spec2 = np.loadtxt(os.path.join(DATAPATH, 'spec2test.txt'), unpack=True)
wave3, spec3 = np.loadtxt(os.path.join(DATAPATH, 'spec3test.txt'), unpack=True)
wavelist = [wave1, wave2, wave3]
speclist = [spec1, spec2, spec3]
return wave1, spec1, wavelist, speclist
@pytest.mark.parametrize('filelist, cond', [
(FILELIST1, False),
(FILELIST2, True),
])
def test_read_infiles(filelist, cond):
'''
Test reading in both text and fits files
Each resulting wavelength array should be sorted in ascending order
'''
infilelist, wavelist, speclist = despike.read_infiles(DATAPATH, filelist, cond)
assert len(infilelist) > 0
assert len(infilelist) == len(wavelist)
assert len(wavelist) == len(speclist)
for wave in wavelist:
assert all(value >= 0 for value in wave)
assert list(np.sort(wave)) == list(wave)
assert all(np.equal(np.sort(wave), wave))
def test_simpledespike(wave_spec_generate):
'''
spike condition is met at pixels 15, 16, 17 and 18
so indices 9 through 24, inclusive, should be removed
'''
wave, spec = wave_spec_generate[0], wave_spec_generate[1]
newwave, newspec = despike.simpledespike(wave, spec, delwindow=6,
stdfactorup=0.7, stdfactordown=3,
plot=False)
assert len(newwave) == len(newspec)
assert len(newwave) <= len(wave)
assert len(newspec) <= len(spec)
assert all(np.equal(np.hstack((wave[0:9], wave[25:])), newwave))
assert all(np.equal(np.hstack((spec[0:9], spec[25:])), newspec))
def test_despike_spectra(wave_spec_generate):
| '''
Test that new spectra are shorter than the original because the outliers are gone
'''
wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3]
newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False)
assert len(newwavelist) == len(wavelist)
assert len(newspeclist) == len(speclist) | identifier_body | |
test_despike.py | import numpy as np
from apvisitproc import despike
import pytest
import os
DATAPATH = os.path.dirname(__file__)
FILELIST1 = os.path.join(DATAPATH, 'list_of_txt_spectra.txt')
FILELIST2 = os.path.join(DATAPATH, 'list_of_fits_spectra.txt')
@pytest.fixture
def wave_spec_generate():
'''
Read in three small chunks of spectra for testing purposes
'wavelist_speclist_generate' can be used as input to any other test function
that needs access to the variables it returns!
wave1, spec1 are a single chunk of 1d spectrum
wavelist, speclist are lists of three chunks of 1d spectrum
'''
wave1, spec1 = np.loadtxt(os.path.join(DATAPATH, 'spec1test.txt'), unpack=True)
wave2, spec2 = np.loadtxt(os.path.join(DATAPATH, 'spec2test.txt'), unpack=True)
wave3, spec3 = np.loadtxt(os.path.join(DATAPATH, 'spec3test.txt'), unpack=True)
wavelist = [wave1, wave2, wave3]
speclist = [spec1, spec2, spec3]
return wave1, spec1, wavelist, speclist
@pytest.mark.parametrize('filelist, cond', [
(FILELIST1, False),
(FILELIST2, True),
])
def test_read_infiles(filelist, cond):
'''
Test reading in both text and fits files
Each resulting wavelength array should be sorted in ascending order
'''
infilelist, wavelist, speclist = despike.read_infiles(DATAPATH, filelist, cond)
assert len(infilelist) > 0
assert len(infilelist) == len(wavelist)
assert len(wavelist) == len(speclist)
for wave in wavelist:
assert all(value >= 0 for value in wave)
assert list(np.sort(wave)) == list(wave)
assert all(np.equal(np.sort(wave), wave))
def test_simpledespike(wave_spec_generate):
'''
spike condition is met at pixels 15, 16, 17 and 18
so indices 9 through 24, inclusive, should be removed
'''
wave, spec = wave_spec_generate[0], wave_spec_generate[1]
newwave, newspec = despike.simpledespike(wave, spec, delwindow=6,
stdfactorup=0.7, stdfactordown=3,
plot=False)
assert len(newwave) == len(newspec)
assert len(newwave) <= len(wave)
assert len(newspec) <= len(spec)
assert all(np.equal(np.hstack((wave[0:9], wave[25:])), newwave))
assert all(np.equal(np.hstack((spec[0:9], spec[25:])), newspec))
def | (wave_spec_generate):
'''
Test that new spectra are shorter than the original because the outliers are gone
'''
wavelist, speclist = wave_spec_generate[2], wave_spec_generate[3]
newwavelist, newspeclist = despike.despike_spectra(wavelist, speclist, type='simple', plot=False)
assert len(newwavelist) == len(wavelist)
assert len(newspeclist) == len(speclist)
| test_despike_spectra | identifier_name |
cp861.py | """ Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py.
|
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_map)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00d0, # LATIN CAPITAL LETTER ETH
0x008c: 0x00f0, # LATIN SMALL LETTER ETH
0x008d: 0x00de, # LATIN CAPITAL LETTER THORN
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00fe, # LATIN SMALL LETTER THORN
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE
0x0098: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE
0x00a5: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE
0x00a6: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE
0x00a7: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Encoding Map
encoding_map = {}
for k,v in decoding_map.items():
encoding_map[v] = k | Written by Marc-Andre Lemburg (mal@lemburg.com). | random_line_split |
cp861.py | """ Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_map)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def | ():
return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00d0, # LATIN CAPITAL LETTER ETH
0x008c: 0x00f0, # LATIN SMALL LETTER ETH
0x008d: 0x00de, # LATIN CAPITAL LETTER THORN
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00fe, # LATIN SMALL LETTER THORN
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE
0x0098: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE
0x00a5: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE
0x00a6: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE
0x00a7: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Encoding Map
encoding_map = {}
for k,v in decoding_map.items():
encoding_map[v] = k
| getregentry | identifier_name |
cp861.py | """ Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_map)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return (Codec().encode,Codec().decode,StreamReader,StreamWriter)
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00d0, # LATIN CAPITAL LETTER ETH
0x008c: 0x00f0, # LATIN SMALL LETTER ETH
0x008d: 0x00de, # LATIN CAPITAL LETTER THORN
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00fe, # LATIN SMALL LETTER THORN
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE
0x0098: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE
0x00a5: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE
0x00a6: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE
0x00a7: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Encoding Map
encoding_map = {}
for k,v in decoding_map.items():
| encoding_map[v] = k | conditional_block | |
cp861.py | """ Python Character Mapping Codec generated from 'CP861.TXT' with gencodec.py.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
(c) Copyright 2000 Guido van Rossum.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_map)
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
|
### Decoding Map
decoding_map = codecs.make_identity_dict(range(256))
decoding_map.update({
0x0080: 0x00c7, # LATIN CAPITAL LETTER C WITH CEDILLA
0x0081: 0x00fc, # LATIN SMALL LETTER U WITH DIAERESIS
0x0082: 0x00e9, # LATIN SMALL LETTER E WITH ACUTE
0x0083: 0x00e2, # LATIN SMALL LETTER A WITH CIRCUMFLEX
0x0084: 0x00e4, # LATIN SMALL LETTER A WITH DIAERESIS
0x0085: 0x00e0, # LATIN SMALL LETTER A WITH GRAVE
0x0086: 0x00e5, # LATIN SMALL LETTER A WITH RING ABOVE
0x0087: 0x00e7, # LATIN SMALL LETTER C WITH CEDILLA
0x0088: 0x00ea, # LATIN SMALL LETTER E WITH CIRCUMFLEX
0x0089: 0x00eb, # LATIN SMALL LETTER E WITH DIAERESIS
0x008a: 0x00e8, # LATIN SMALL LETTER E WITH GRAVE
0x008b: 0x00d0, # LATIN CAPITAL LETTER ETH
0x008c: 0x00f0, # LATIN SMALL LETTER ETH
0x008d: 0x00de, # LATIN CAPITAL LETTER THORN
0x008e: 0x00c4, # LATIN CAPITAL LETTER A WITH DIAERESIS
0x008f: 0x00c5, # LATIN CAPITAL LETTER A WITH RING ABOVE
0x0090: 0x00c9, # LATIN CAPITAL LETTER E WITH ACUTE
0x0091: 0x00e6, # LATIN SMALL LIGATURE AE
0x0092: 0x00c6, # LATIN CAPITAL LIGATURE AE
0x0093: 0x00f4, # LATIN SMALL LETTER O WITH CIRCUMFLEX
0x0094: 0x00f6, # LATIN SMALL LETTER O WITH DIAERESIS
0x0095: 0x00fe, # LATIN SMALL LETTER THORN
0x0096: 0x00fb, # LATIN SMALL LETTER U WITH CIRCUMFLEX
0x0097: 0x00dd, # LATIN CAPITAL LETTER Y WITH ACUTE
0x0098: 0x00fd, # LATIN SMALL LETTER Y WITH ACUTE
0x0099: 0x00d6, # LATIN CAPITAL LETTER O WITH DIAERESIS
0x009a: 0x00dc, # LATIN CAPITAL LETTER U WITH DIAERESIS
0x009b: 0x00f8, # LATIN SMALL LETTER O WITH STROKE
0x009c: 0x00a3, # POUND SIGN
0x009d: 0x00d8, # LATIN CAPITAL LETTER O WITH STROKE
0x009e: 0x20a7, # PESETA SIGN
0x009f: 0x0192, # LATIN SMALL LETTER F WITH HOOK
0x00a0: 0x00e1, # LATIN SMALL LETTER A WITH ACUTE
0x00a1: 0x00ed, # LATIN SMALL LETTER I WITH ACUTE
0x00a2: 0x00f3, # LATIN SMALL LETTER O WITH ACUTE
0x00a3: 0x00fa, # LATIN SMALL LETTER U WITH ACUTE
0x00a4: 0x00c1, # LATIN CAPITAL LETTER A WITH ACUTE
0x00a5: 0x00cd, # LATIN CAPITAL LETTER I WITH ACUTE
0x00a6: 0x00d3, # LATIN CAPITAL LETTER O WITH ACUTE
0x00a7: 0x00da, # LATIN CAPITAL LETTER U WITH ACUTE
0x00a8: 0x00bf, # INVERTED QUESTION MARK
0x00a9: 0x2310, # REVERSED NOT SIGN
0x00aa: 0x00ac, # NOT SIGN
0x00ab: 0x00bd, # VULGAR FRACTION ONE HALF
0x00ac: 0x00bc, # VULGAR FRACTION ONE QUARTER
0x00ad: 0x00a1, # INVERTED EXCLAMATION MARK
0x00ae: 0x00ab, # LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00af: 0x00bb, # RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
0x00b0: 0x2591, # LIGHT SHADE
0x00b1: 0x2592, # MEDIUM SHADE
0x00b2: 0x2593, # DARK SHADE
0x00b3: 0x2502, # BOX DRAWINGS LIGHT VERTICAL
0x00b4: 0x2524, # BOX DRAWINGS LIGHT VERTICAL AND LEFT
0x00b5: 0x2561, # BOX DRAWINGS VERTICAL SINGLE AND LEFT DOUBLE
0x00b6: 0x2562, # BOX DRAWINGS VERTICAL DOUBLE AND LEFT SINGLE
0x00b7: 0x2556, # BOX DRAWINGS DOWN DOUBLE AND LEFT SINGLE
0x00b8: 0x2555, # BOX DRAWINGS DOWN SINGLE AND LEFT DOUBLE
0x00b9: 0x2563, # BOX DRAWINGS DOUBLE VERTICAL AND LEFT
0x00ba: 0x2551, # BOX DRAWINGS DOUBLE VERTICAL
0x00bb: 0x2557, # BOX DRAWINGS DOUBLE DOWN AND LEFT
0x00bc: 0x255d, # BOX DRAWINGS DOUBLE UP AND LEFT
0x00bd: 0x255c, # BOX DRAWINGS UP DOUBLE AND LEFT SINGLE
0x00be: 0x255b, # BOX DRAWINGS UP SINGLE AND LEFT DOUBLE
0x00bf: 0x2510, # BOX DRAWINGS LIGHT DOWN AND LEFT
0x00c0: 0x2514, # BOX DRAWINGS LIGHT UP AND RIGHT
0x00c1: 0x2534, # BOX DRAWINGS LIGHT UP AND HORIZONTAL
0x00c2: 0x252c, # BOX DRAWINGS LIGHT DOWN AND HORIZONTAL
0x00c3: 0x251c, # BOX DRAWINGS LIGHT VERTICAL AND RIGHT
0x00c4: 0x2500, # BOX DRAWINGS LIGHT HORIZONTAL
0x00c5: 0x253c, # BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL
0x00c6: 0x255e, # BOX DRAWINGS VERTICAL SINGLE AND RIGHT DOUBLE
0x00c7: 0x255f, # BOX DRAWINGS VERTICAL DOUBLE AND RIGHT SINGLE
0x00c8: 0x255a, # BOX DRAWINGS DOUBLE UP AND RIGHT
0x00c9: 0x2554, # BOX DRAWINGS DOUBLE DOWN AND RIGHT
0x00ca: 0x2569, # BOX DRAWINGS DOUBLE UP AND HORIZONTAL
0x00cb: 0x2566, # BOX DRAWINGS DOUBLE DOWN AND HORIZONTAL
0x00cc: 0x2560, # BOX DRAWINGS DOUBLE VERTICAL AND RIGHT
0x00cd: 0x2550, # BOX DRAWINGS DOUBLE HORIZONTAL
0x00ce: 0x256c, # BOX DRAWINGS DOUBLE VERTICAL AND HORIZONTAL
0x00cf: 0x2567, # BOX DRAWINGS UP SINGLE AND HORIZONTAL DOUBLE
0x00d0: 0x2568, # BOX DRAWINGS UP DOUBLE AND HORIZONTAL SINGLE
0x00d1: 0x2564, # BOX DRAWINGS DOWN SINGLE AND HORIZONTAL DOUBLE
0x00d2: 0x2565, # BOX DRAWINGS DOWN DOUBLE AND HORIZONTAL SINGLE
0x00d3: 0x2559, # BOX DRAWINGS UP DOUBLE AND RIGHT SINGLE
0x00d4: 0x2558, # BOX DRAWINGS UP SINGLE AND RIGHT DOUBLE
0x00d5: 0x2552, # BOX DRAWINGS DOWN SINGLE AND RIGHT DOUBLE
0x00d6: 0x2553, # BOX DRAWINGS DOWN DOUBLE AND RIGHT SINGLE
0x00d7: 0x256b, # BOX DRAWINGS VERTICAL DOUBLE AND HORIZONTAL SINGLE
0x00d8: 0x256a, # BOX DRAWINGS VERTICAL SINGLE AND HORIZONTAL DOUBLE
0x00d9: 0x2518, # BOX DRAWINGS LIGHT UP AND LEFT
0x00da: 0x250c, # BOX DRAWINGS LIGHT DOWN AND RIGHT
0x00db: 0x2588, # FULL BLOCK
0x00dc: 0x2584, # LOWER HALF BLOCK
0x00dd: 0x258c, # LEFT HALF BLOCK
0x00de: 0x2590, # RIGHT HALF BLOCK
0x00df: 0x2580, # UPPER HALF BLOCK
0x00e0: 0x03b1, # GREEK SMALL LETTER ALPHA
0x00e1: 0x00df, # LATIN SMALL LETTER SHARP S
0x00e2: 0x0393, # GREEK CAPITAL LETTER GAMMA
0x00e3: 0x03c0, # GREEK SMALL LETTER PI
0x00e4: 0x03a3, # GREEK CAPITAL LETTER SIGMA
0x00e5: 0x03c3, # GREEK SMALL LETTER SIGMA
0x00e6: 0x00b5, # MICRO SIGN
0x00e7: 0x03c4, # GREEK SMALL LETTER TAU
0x00e8: 0x03a6, # GREEK CAPITAL LETTER PHI
0x00e9: 0x0398, # GREEK CAPITAL LETTER THETA
0x00ea: 0x03a9, # GREEK CAPITAL LETTER OMEGA
0x00eb: 0x03b4, # GREEK SMALL LETTER DELTA
0x00ec: 0x221e, # INFINITY
0x00ed: 0x03c6, # GREEK SMALL LETTER PHI
0x00ee: 0x03b5, # GREEK SMALL LETTER EPSILON
0x00ef: 0x2229, # INTERSECTION
0x00f0: 0x2261, # IDENTICAL TO
0x00f1: 0x00b1, # PLUS-MINUS SIGN
0x00f2: 0x2265, # GREATER-THAN OR EQUAL TO
0x00f3: 0x2264, # LESS-THAN OR EQUAL TO
0x00f4: 0x2320, # TOP HALF INTEGRAL
0x00f5: 0x2321, # BOTTOM HALF INTEGRAL
0x00f6: 0x00f7, # DIVISION SIGN
0x00f7: 0x2248, # ALMOST EQUAL TO
0x00f8: 0x00b0, # DEGREE SIGN
0x00f9: 0x2219, # BULLET OPERATOR
0x00fa: 0x00b7, # MIDDLE DOT
0x00fb: 0x221a, # SQUARE ROOT
0x00fc: 0x207f, # SUPERSCRIPT LATIN SMALL LETTER N
0x00fd: 0x00b2, # SUPERSCRIPT TWO
0x00fe: 0x25a0, # BLACK SQUARE
0x00ff: 0x00a0, # NO-BREAK SPACE
})
### Encoding Map
encoding_map = {}
for k,v in decoding_map.items():
encoding_map[v] = k
| return (Codec().encode,Codec().decode,StreamReader,StreamWriter) | identifier_body |
sleeptimer.py | #!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
from Cheetah.Template import Template
from Cheetah.DummyTransaction import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion | import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '2.4.4'
__CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0)
__CHEETAH_genTime__ = 1364979192.582168
__CHEETAH_genTimestamp__ = 'Wed Apr 3 17:53:12 2013'
__CHEETAH_src__ = '/home/fermi/Work/Model/tmsingle/openpli3.0/build-tmsingle/tmp/work/mips32el-oe-linux/enigma2-plugin-extensions-openwebif-0.1+git1+279a2577c3bc6defebd4bf9e61a046dcf7f37c01-r0.72/git/plugin/controllers/views/web/sleeptimer.tmpl'
__CHEETAH_srcLastModified__ = 'Wed Apr 3 17:10:17 2013'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'
if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
raise AssertionError(
'This template was compiled with Cheetah version'
' %s. Templates compiled before version %s must be recompiled.'%(
__CHEETAH_version__, RequiredCheetahVersion))
##################################################
## CLASSES
class sleeptimer(Template):
##################################################
## CHEETAH GENERATED METHODS
def __init__(self, *args, **KWs):
super(sleeptimer, self).__init__(*args, **KWs)
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
for k,v in KWs.items():
if k in allowedKWs: cheetahKWArgs[k] = v
self._initCheetahInstance(**cheetahKWArgs)
def respond(self, trans=None):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
_dummyTrans = True
else: _dummyTrans = False
write = trans.response().write
SL = self._CHEETAH__searchList
_filter = self._CHEETAH__currentFilter
########################################
## START - generated method body
_orig_filter_51193055 = _filter
filterName = u'WebSafe'
if self._CHEETAH__filters.has_key("WebSafe"):
_filter = self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName]
else:
_filter = self._CHEETAH__currentFilter = \
self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter
write(u'''<?xml version="1.0" encoding="UTF-8"?>
<e2sleeptimer>
\t<e2enabled>''')
_v = VFFSL(SL,"enabled",True) # u'$enabled' on line 4, col 13
if _v is not None: write(_filter(_v, rawExpr=u'$enabled')) # from line 4, col 13.
write(u'''</e2enabled>
\t<e2minutes>''')
_v = VFFSL(SL,"minutes",True) # u'$minutes' on line 5, col 13
if _v is not None: write(_filter(_v, rawExpr=u'$minutes')) # from line 5, col 13.
write(u'''</e2minutes>
\t<e2action>''')
_v = VFFSL(SL,"action",True) # u'$action' on line 6, col 12
if _v is not None: write(_filter(_v, rawExpr=u'$action')) # from line 6, col 12.
write(u'''</e2action>
\t<e2text>''')
_v = VFFSL(SL,"message",True) # u'$message' on line 7, col 10
if _v is not None: write(_filter(_v, rawExpr=u'$message')) # from line 7, col 10.
write(u'''</e2text>
</e2sleeptimer>
''')
_filter = self._CHEETAH__currentFilter = _orig_filter_51193055
########################################
## END - generated method body
return _dummyTrans and trans.response().getvalue() or ""
##################################################
## CHEETAH GENERATED ATTRIBUTES
_CHEETAH__instanceInitialized = False
_CHEETAH_version = __CHEETAH_version__
_CHEETAH_versionTuple = __CHEETAH_versionTuple__
_CHEETAH_genTime = __CHEETAH_genTime__
_CHEETAH_genTimestamp = __CHEETAH_genTimestamp__
_CHEETAH_src = __CHEETAH_src__
_CHEETAH_srcLastModified = __CHEETAH_srcLastModified__
_mainCheetahMethod_for_sleeptimer= 'respond'
## END CLASS DEFINITION
if not hasattr(sleeptimer, '_initCheetahAttributes'):
templateAPIClass = getattr(sleeptimer, '_CHEETAH_templateClass', Template)
templateAPIClass._addCheetahPlumbingCodeToClass(sleeptimer)
# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://www.CheetahTemplate.org/
##################################################
## if run from command line:
if __name__ == '__main__':
from Cheetah.TemplateCmdLineIface import CmdLineIface
CmdLineIface(templateObj=sleeptimer()).run() | random_line_split | |
sleeptimer.py | #!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
from Cheetah.Template import Template
from Cheetah.DummyTransaction import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion
import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '2.4.4'
__CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0)
__CHEETAH_genTime__ = 1364979192.582168
__CHEETAH_genTimestamp__ = 'Wed Apr 3 17:53:12 2013'
__CHEETAH_src__ = '/home/fermi/Work/Model/tmsingle/openpli3.0/build-tmsingle/tmp/work/mips32el-oe-linux/enigma2-plugin-extensions-openwebif-0.1+git1+279a2577c3bc6defebd4bf9e61a046dcf7f37c01-r0.72/git/plugin/controllers/views/web/sleeptimer.tmpl'
__CHEETAH_srcLastModified__ = 'Wed Apr 3 17:10:17 2013'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'
if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
raise AssertionError(
'This template was compiled with Cheetah version'
' %s. Templates compiled before version %s must be recompiled.'%(
__CHEETAH_version__, RequiredCheetahVersion))
##################################################
## CLASSES
class sleeptimer(Template):
##################################################
## CHEETAH GENERATED METHODS
def __init__(self, *args, **KWs):
super(sleeptimer, self).__init__(*args, **KWs)
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
for k,v in KWs.items():
if k in allowedKWs: cheetahKWArgs[k] = v
self._initCheetahInstance(**cheetahKWArgs)
def respond(self, trans=None):
## CHEETAH: main method generated for this template
|
##################################################
## CHEETAH GENERATED ATTRIBUTES
_CHEETAH__instanceInitialized = False
_CHEETAH_version = __CHEETAH_version__
_CHEETAH_versionTuple = __CHEETAH_versionTuple__
_CHEETAH_genTime = __CHEETAH_genTime__
_CHEETAH_genTimestamp = __CHEETAH_genTimestamp__
_CHEETAH_src = __CHEETAH_src__
_CHEETAH_srcLastModified = __CHEETAH_srcLastModified__
_mainCheetahMethod_for_sleeptimer= 'respond'
## END CLASS DEFINITION
if not hasattr(sleeptimer, '_initCheetahAttributes'):
templateAPIClass = getattr(sleeptimer, '_CHEETAH_templateClass', Template)
templateAPIClass._addCheetahPlumbingCodeToClass(sleeptimer)
# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://www.CheetahTemplate.org/
##################################################
## if run from command line:
if __name__ == '__main__':
from Cheetah.TemplateCmdLineIface import CmdLineIface
CmdLineIface(templateObj=sleeptimer()).run()
| if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
_dummyTrans = True
else: _dummyTrans = False
write = trans.response().write
SL = self._CHEETAH__searchList
_filter = self._CHEETAH__currentFilter
########################################
## START - generated method body
_orig_filter_51193055 = _filter
filterName = u'WebSafe'
if self._CHEETAH__filters.has_key("WebSafe"):
_filter = self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName]
else:
_filter = self._CHEETAH__currentFilter = \
self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter
write(u'''<?xml version="1.0" encoding="UTF-8"?>
<e2sleeptimer>
\t<e2enabled>''')
_v = VFFSL(SL,"enabled",True) # u'$enabled' on line 4, col 13
if _v is not None: write(_filter(_v, rawExpr=u'$enabled')) # from line 4, col 13.
write(u'''</e2enabled>
\t<e2minutes>''')
_v = VFFSL(SL,"minutes",True) # u'$minutes' on line 5, col 13
if _v is not None: write(_filter(_v, rawExpr=u'$minutes')) # from line 5, col 13.
write(u'''</e2minutes>
\t<e2action>''')
_v = VFFSL(SL,"action",True) # u'$action' on line 6, col 12
if _v is not None: write(_filter(_v, rawExpr=u'$action')) # from line 6, col 12.
write(u'''</e2action>
\t<e2text>''')
_v = VFFSL(SL,"message",True) # u'$message' on line 7, col 10
if _v is not None: write(_filter(_v, rawExpr=u'$message')) # from line 7, col 10.
write(u'''</e2text>
</e2sleeptimer>
''')
_filter = self._CHEETAH__currentFilter = _orig_filter_51193055
########################################
## END - generated method body
return _dummyTrans and trans.response().getvalue() or "" | identifier_body |
sleeptimer.py | #!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
from Cheetah.Template import Template
from Cheetah.DummyTransaction import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion
import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '2.4.4'
__CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0)
__CHEETAH_genTime__ = 1364979192.582168
__CHEETAH_genTimestamp__ = 'Wed Apr 3 17:53:12 2013'
__CHEETAH_src__ = '/home/fermi/Work/Model/tmsingle/openpli3.0/build-tmsingle/tmp/work/mips32el-oe-linux/enigma2-plugin-extensions-openwebif-0.1+git1+279a2577c3bc6defebd4bf9e61a046dcf7f37c01-r0.72/git/plugin/controllers/views/web/sleeptimer.tmpl'
__CHEETAH_srcLastModified__ = 'Wed Apr 3 17:10:17 2013'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'
if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
raise AssertionError(
'This template was compiled with Cheetah version'
' %s. Templates compiled before version %s must be recompiled.'%(
__CHEETAH_version__, RequiredCheetahVersion))
##################################################
## CLASSES
class sleeptimer(Template):
##################################################
## CHEETAH GENERATED METHODS
def __init__(self, *args, **KWs):
super(sleeptimer, self).__init__(*args, **KWs)
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
for k,v in KWs.items():
if k in allowedKWs: cheetahKWArgs[k] = v
self._initCheetahInstance(**cheetahKWArgs)
def respond(self, trans=None):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
_dummyTrans = True
else: |
write = trans.response().write
SL = self._CHEETAH__searchList
_filter = self._CHEETAH__currentFilter
########################################
## START - generated method body
_orig_filter_51193055 = _filter
filterName = u'WebSafe'
if self._CHEETAH__filters.has_key("WebSafe"):
_filter = self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName]
else:
_filter = self._CHEETAH__currentFilter = \
self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter
write(u'''<?xml version="1.0" encoding="UTF-8"?>
<e2sleeptimer>
\t<e2enabled>''')
_v = VFFSL(SL,"enabled",True) # u'$enabled' on line 4, col 13
if _v is not None: write(_filter(_v, rawExpr=u'$enabled')) # from line 4, col 13.
write(u'''</e2enabled>
\t<e2minutes>''')
_v = VFFSL(SL,"minutes",True) # u'$minutes' on line 5, col 13
if _v is not None: write(_filter(_v, rawExpr=u'$minutes')) # from line 5, col 13.
write(u'''</e2minutes>
\t<e2action>''')
_v = VFFSL(SL,"action",True) # u'$action' on line 6, col 12
if _v is not None: write(_filter(_v, rawExpr=u'$action')) # from line 6, col 12.
write(u'''</e2action>
\t<e2text>''')
_v = VFFSL(SL,"message",True) # u'$message' on line 7, col 10
if _v is not None: write(_filter(_v, rawExpr=u'$message')) # from line 7, col 10.
write(u'''</e2text>
</e2sleeptimer>
''')
_filter = self._CHEETAH__currentFilter = _orig_filter_51193055
########################################
## END - generated method body
return _dummyTrans and trans.response().getvalue() or ""
##################################################
## CHEETAH GENERATED ATTRIBUTES
_CHEETAH__instanceInitialized = False
_CHEETAH_version = __CHEETAH_version__
_CHEETAH_versionTuple = __CHEETAH_versionTuple__
_CHEETAH_genTime = __CHEETAH_genTime__
_CHEETAH_genTimestamp = __CHEETAH_genTimestamp__
_CHEETAH_src = __CHEETAH_src__
_CHEETAH_srcLastModified = __CHEETAH_srcLastModified__
_mainCheetahMethod_for_sleeptimer= 'respond'
## END CLASS DEFINITION
if not hasattr(sleeptimer, '_initCheetahAttributes'):
templateAPIClass = getattr(sleeptimer, '_CHEETAH_templateClass', Template)
templateAPIClass._addCheetahPlumbingCodeToClass(sleeptimer)
# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://www.CheetahTemplate.org/
##################################################
## if run from command line:
if __name__ == '__main__':
from Cheetah.TemplateCmdLineIface import CmdLineIface
CmdLineIface(templateObj=sleeptimer()).run()
| _dummyTrans = False | conditional_block |
sleeptimer.py | #!/usr/bin/env python
##################################################
## DEPENDENCIES
import sys
import os
import os.path
try:
import builtins as builtin
except ImportError:
import __builtin__ as builtin
from os.path import getmtime, exists
import time
import types
from Cheetah.Version import MinCompatibleVersion as RequiredCheetahVersion
from Cheetah.Version import MinCompatibleVersionTuple as RequiredCheetahVersionTuple
from Cheetah.Template import Template
from Cheetah.DummyTransaction import *
from Cheetah.NameMapper import NotFound, valueForName, valueFromSearchList, valueFromFrameOrSearchList
from Cheetah.CacheRegion import CacheRegion
import Cheetah.Filters as Filters
import Cheetah.ErrorCatchers as ErrorCatchers
##################################################
## MODULE CONSTANTS
VFFSL=valueFromFrameOrSearchList
VFSL=valueFromSearchList
VFN=valueForName
currentTime=time.time
__CHEETAH_version__ = '2.4.4'
__CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0)
__CHEETAH_genTime__ = 1364979192.582168
__CHEETAH_genTimestamp__ = 'Wed Apr 3 17:53:12 2013'
__CHEETAH_src__ = '/home/fermi/Work/Model/tmsingle/openpli3.0/build-tmsingle/tmp/work/mips32el-oe-linux/enigma2-plugin-extensions-openwebif-0.1+git1+279a2577c3bc6defebd4bf9e61a046dcf7f37c01-r0.72/git/plugin/controllers/views/web/sleeptimer.tmpl'
__CHEETAH_srcLastModified__ = 'Wed Apr 3 17:10:17 2013'
__CHEETAH_docstring__ = 'Autogenerated by Cheetah: The Python-Powered Template Engine'
if __CHEETAH_versionTuple__ < RequiredCheetahVersionTuple:
raise AssertionError(
'This template was compiled with Cheetah version'
' %s. Templates compiled before version %s must be recompiled.'%(
__CHEETAH_version__, RequiredCheetahVersion))
##################################################
## CLASSES
class | (Template):
##################################################
## CHEETAH GENERATED METHODS
def __init__(self, *args, **KWs):
super(sleeptimer, self).__init__(*args, **KWs)
if not self._CHEETAH__instanceInitialized:
cheetahKWArgs = {}
allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split()
for k,v in KWs.items():
if k in allowedKWs: cheetahKWArgs[k] = v
self._initCheetahInstance(**cheetahKWArgs)
def respond(self, trans=None):
## CHEETAH: main method generated for this template
if (not trans and not self._CHEETAH__isBuffering and not callable(self.transaction)):
trans = self.transaction # is None unless self.awake() was called
if not trans:
trans = DummyTransaction()
_dummyTrans = True
else: _dummyTrans = False
write = trans.response().write
SL = self._CHEETAH__searchList
_filter = self._CHEETAH__currentFilter
########################################
## START - generated method body
_orig_filter_51193055 = _filter
filterName = u'WebSafe'
if self._CHEETAH__filters.has_key("WebSafe"):
_filter = self._CHEETAH__currentFilter = self._CHEETAH__filters[filterName]
else:
_filter = self._CHEETAH__currentFilter = \
self._CHEETAH__filters[filterName] = getattr(self._CHEETAH__filtersLib, filterName)(self).filter
write(u'''<?xml version="1.0" encoding="UTF-8"?>
<e2sleeptimer>
\t<e2enabled>''')
_v = VFFSL(SL,"enabled",True) # u'$enabled' on line 4, col 13
if _v is not None: write(_filter(_v, rawExpr=u'$enabled')) # from line 4, col 13.
write(u'''</e2enabled>
\t<e2minutes>''')
_v = VFFSL(SL,"minutes",True) # u'$minutes' on line 5, col 13
if _v is not None: write(_filter(_v, rawExpr=u'$minutes')) # from line 5, col 13.
write(u'''</e2minutes>
\t<e2action>''')
_v = VFFSL(SL,"action",True) # u'$action' on line 6, col 12
if _v is not None: write(_filter(_v, rawExpr=u'$action')) # from line 6, col 12.
write(u'''</e2action>
\t<e2text>''')
_v = VFFSL(SL,"message",True) # u'$message' on line 7, col 10
if _v is not None: write(_filter(_v, rawExpr=u'$message')) # from line 7, col 10.
write(u'''</e2text>
</e2sleeptimer>
''')
_filter = self._CHEETAH__currentFilter = _orig_filter_51193055
########################################
## END - generated method body
return _dummyTrans and trans.response().getvalue() or ""
##################################################
## CHEETAH GENERATED ATTRIBUTES
_CHEETAH__instanceInitialized = False
_CHEETAH_version = __CHEETAH_version__
_CHEETAH_versionTuple = __CHEETAH_versionTuple__
_CHEETAH_genTime = __CHEETAH_genTime__
_CHEETAH_genTimestamp = __CHEETAH_genTimestamp__
_CHEETAH_src = __CHEETAH_src__
_CHEETAH_srcLastModified = __CHEETAH_srcLastModified__
_mainCheetahMethod_for_sleeptimer= 'respond'
## END CLASS DEFINITION
if not hasattr(sleeptimer, '_initCheetahAttributes'):
templateAPIClass = getattr(sleeptimer, '_CHEETAH_templateClass', Template)
templateAPIClass._addCheetahPlumbingCodeToClass(sleeptimer)
# CHEETAH was developed by Tavis Rudd and Mike Orr
# with code, advice and input from many other volunteers.
# For more information visit http://www.CheetahTemplate.org/
##################################################
## if run from command line:
if __name__ == '__main__':
from Cheetah.TemplateCmdLineIface import CmdLineIface
CmdLineIface(templateObj=sleeptimer()).run()
| sleeptimer | identifier_name |
Affix.test.tsx | import React from 'react';
import { mount, ReactWrapper, HTMLAttributes } from 'enzyme';
import ResizeObserverImpl from 'rc-resize-observer';
import Affix, { AffixProps, AffixState } from '..';
import { getObserverEntities } from '../utils';
import Button from '../../button';
import rtlTest from '../../../tests/shared/rtlTest';
import { sleep } from '../../../tests/utils';
const events: Partial<Record<keyof HTMLElementEventMap, (ev: Partial<Event>) => void>> = {};
class AffixMounter extends React.Component<{
offsetBottom?: number;
offsetTop?: number;
onTestUpdatePosition?(): void;
onChange?: () => void;
}> {
private container: HTMLDivElement;
public affix: Affix;
componentDidMount() {
this.container.addEventListener = jest
.fn()
.mockImplementation((event: keyof HTMLElementEventMap, cb: (ev: Partial<Event>) => void) => {
events[event] = cb;
});
}
getTarget = () => this.container;
render() {
return (
<div
ref={node => {
this.container = node!;
}}
className="container"
>
<Affix
className="fixed"
target={this.getTarget}
ref={ele => {
this.affix = ele!;
}}
{...this.props}
>
<Button type="primary">Fixed at the top of container</Button>
</Affix>
</div>
);
}
}
describe('Affix Render', () => {
rtlTest(Affix);
const domMock = jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect');
let affixMounterWrapper: ReactWrapper<unknown, unknown, AffixMounter>;
let affixWrapper: ReactWrapper<AffixProps, AffixState, Affix>;
const classRect: Record<string, DOMRect> = {
container: {
top: 0,
bottom: 100,
} as DOMRect,
};
beforeAll(() => {
domMock.mockImplementation(function fn(this: HTMLElement) {
return (
classRect[this.className] || {
top: 0,
bottom: 0,
}
);
});
});
afterAll(() => {
domMock.mockRestore();
});
const movePlaceholder = async (top: number) => {
classRect.fixed = {
top,
bottom: top,
} as DOMRect;
if (events.scroll == null) {
throw new Error('scroll should be set');
}
events.scroll({
type: 'scroll',
});
await sleep(20);
};
it('Anchor render perfectly', async () => {
document.body.innerHTML = '<div id="mounter" />';
affixMounterWrapper = mount(<AffixMounter />, { attachTo: document.getElementById('mounter') });
await sleep(20);
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
await movePlaceholder(-100);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
});
it('support offsetBottom', async () => {
document.body.innerHTML = '<div id="mounter" />';
affixMounterWrapper = mount(<AffixMounter offsetBottom={0} />, {
attachTo: document.getElementById('mounter'),
});
await sleep(20);
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
});
it('updatePosition when offsetTop changed', async () => {
document.body.innerHTML = '<div id="mounter" />';
const onChange = jest.fn();
affixMounterWrapper = mount(<AffixMounter offsetTop={0} onChange={onChange} />, {
attachTo: document.getElementById('mounter'),
});
await sleep(20);
| await movePlaceholder(-100);
expect(onChange).toHaveBeenLastCalledWith(true);
expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(0);
affixMounterWrapper.setProps({
offsetTop: 10,
});
await sleep(20);
expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(10);
});
describe('updatePosition when target changed', () => {
it('function change', () => {
document.body.innerHTML = '<div id="mounter" />';
const container = document.querySelector('#id') as HTMLDivElement;
const getTarget = () => container;
affixWrapper = mount(<Affix target={getTarget}>{null}</Affix>);
affixWrapper.setProps({ target: () => null });
expect(affixWrapper.instance().state.status).toBe(0);
expect(affixWrapper.instance().state.affixStyle).toBe(undefined);
expect(affixWrapper.instance().state.placeholderStyle).toBe(undefined);
});
it('instance change', async () => {
const getObserverLength = () => Object.keys(getObserverEntities()).length;
const container = document.createElement('div');
document.body.appendChild(container);
let target: HTMLDivElement | null = container;
const originLength = getObserverLength();
const getTarget = () => target;
affixWrapper = mount(<Affix target={getTarget}>{null}</Affix>);
await sleep(50);
expect(getObserverLength()).toBe(originLength + 1);
target = null;
affixWrapper.setProps({});
affixWrapper.update();
await sleep(50);
expect(getObserverLength()).toBe(originLength);
});
});
describe('updatePosition when size changed', () => {
it.each([
{ name: 'inner', index: 0 },
{ name: 'outer', index: 1 },
])('inner or outer', async ({ index }) => {
document.body.innerHTML = '<div id="mounter" />';
const updateCalled = jest.fn();
affixMounterWrapper = mount(
<AffixMounter offsetBottom={0} onTestUpdatePosition={updateCalled} />,
{
attachTo: document.getElementById('mounter'),
},
);
await sleep(20);
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await sleep(20);
affixMounterWrapper.update();
// Mock trigger resize
updateCalled.mockReset();
const resizeObserverInstance: ReactWrapper<
HTMLAttributes,
unknown,
ResizeObserverImpl
> = affixMounterWrapper.find('ResizeObserver') as any;
resizeObserverInstance
.at(index)
.instance()
.onResize(
[
{
target: {
getBoundingClientRect: () => ({ width: 99, height: 99 }),
} as Element,
contentRect: {} as DOMRect,
},
],
({} as unknown) as ResizeObserver,
);
await sleep(20);
expect(updateCalled).toHaveBeenCalled();
});
});
}); | random_line_split | |
Affix.test.tsx | import React from 'react';
import { mount, ReactWrapper, HTMLAttributes } from 'enzyme';
import ResizeObserverImpl from 'rc-resize-observer';
import Affix, { AffixProps, AffixState } from '..';
import { getObserverEntities } from '../utils';
import Button from '../../button';
import rtlTest from '../../../tests/shared/rtlTest';
import { sleep } from '../../../tests/utils';
const events: Partial<Record<keyof HTMLElementEventMap, (ev: Partial<Event>) => void>> = {};
class AffixMounter extends React.Component<{
offsetBottom?: number;
offsetTop?: number;
onTestUpdatePosition?(): void;
onChange?: () => void;
}> {
private container: HTMLDivElement;
public affix: Affix;
componentDidMount() {
this.container.addEventListener = jest
.fn()
.mockImplementation((event: keyof HTMLElementEventMap, cb: (ev: Partial<Event>) => void) => {
events[event] = cb;
});
}
getTarget = () => this.container;
render() {
return (
<div
ref={node => {
this.container = node!;
}}
className="container"
>
<Affix
className="fixed"
target={this.getTarget}
ref={ele => {
this.affix = ele!;
}}
{...this.props}
>
<Button type="primary">Fixed at the top of container</Button>
</Affix>
</div>
);
}
}
describe('Affix Render', () => {
rtlTest(Affix);
const domMock = jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect');
let affixMounterWrapper: ReactWrapper<unknown, unknown, AffixMounter>;
let affixWrapper: ReactWrapper<AffixProps, AffixState, Affix>;
const classRect: Record<string, DOMRect> = {
container: {
top: 0,
bottom: 100,
} as DOMRect,
};
beforeAll(() => {
domMock.mockImplementation(function fn(this: HTMLElement) {
return (
classRect[this.className] || {
top: 0,
bottom: 0,
}
);
});
});
afterAll(() => {
domMock.mockRestore();
});
const movePlaceholder = async (top: number) => {
classRect.fixed = {
top,
bottom: top,
} as DOMRect;
if (events.scroll == null) |
events.scroll({
type: 'scroll',
});
await sleep(20);
};
it('Anchor render perfectly', async () => {
document.body.innerHTML = '<div id="mounter" />';
affixMounterWrapper = mount(<AffixMounter />, { attachTo: document.getElementById('mounter') });
await sleep(20);
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
await movePlaceholder(-100);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
});
it('support offsetBottom', async () => {
document.body.innerHTML = '<div id="mounter" />';
affixMounterWrapper = mount(<AffixMounter offsetBottom={0} />, {
attachTo: document.getElementById('mounter'),
});
await sleep(20);
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
});
it('updatePosition when offsetTop changed', async () => {
document.body.innerHTML = '<div id="mounter" />';
const onChange = jest.fn();
affixMounterWrapper = mount(<AffixMounter offsetTop={0} onChange={onChange} />, {
attachTo: document.getElementById('mounter'),
});
await sleep(20);
await movePlaceholder(-100);
expect(onChange).toHaveBeenLastCalledWith(true);
expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(0);
affixMounterWrapper.setProps({
offsetTop: 10,
});
await sleep(20);
expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(10);
});
describe('updatePosition when target changed', () => {
it('function change', () => {
document.body.innerHTML = '<div id="mounter" />';
const container = document.querySelector('#id') as HTMLDivElement;
const getTarget = () => container;
affixWrapper = mount(<Affix target={getTarget}>{null}</Affix>);
affixWrapper.setProps({ target: () => null });
expect(affixWrapper.instance().state.status).toBe(0);
expect(affixWrapper.instance().state.affixStyle).toBe(undefined);
expect(affixWrapper.instance().state.placeholderStyle).toBe(undefined);
});
it('instance change', async () => {
const getObserverLength = () => Object.keys(getObserverEntities()).length;
const container = document.createElement('div');
document.body.appendChild(container);
let target: HTMLDivElement | null = container;
const originLength = getObserverLength();
const getTarget = () => target;
affixWrapper = mount(<Affix target={getTarget}>{null}</Affix>);
await sleep(50);
expect(getObserverLength()).toBe(originLength + 1);
target = null;
affixWrapper.setProps({});
affixWrapper.update();
await sleep(50);
expect(getObserverLength()).toBe(originLength);
});
});
describe('updatePosition when size changed', () => {
it.each([
{ name: 'inner', index: 0 },
{ name: 'outer', index: 1 },
])('inner or outer', async ({ index }) => {
document.body.innerHTML = '<div id="mounter" />';
const updateCalled = jest.fn();
affixMounterWrapper = mount(
<AffixMounter offsetBottom={0} onTestUpdatePosition={updateCalled} />,
{
attachTo: document.getElementById('mounter'),
},
);
await sleep(20);
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await sleep(20);
affixMounterWrapper.update();
// Mock trigger resize
updateCalled.mockReset();
const resizeObserverInstance: ReactWrapper<
HTMLAttributes,
unknown,
ResizeObserverImpl
> = affixMounterWrapper.find('ResizeObserver') as any;
resizeObserverInstance
.at(index)
.instance()
.onResize(
[
{
target: {
getBoundingClientRect: () => ({ width: 99, height: 99 }),
} as Element,
contentRect: {} as DOMRect,
},
],
({} as unknown) as ResizeObserver,
);
await sleep(20);
expect(updateCalled).toHaveBeenCalled();
});
});
});
| {
throw new Error('scroll should be set');
} | conditional_block |
Affix.test.tsx | import React from 'react';
import { mount, ReactWrapper, HTMLAttributes } from 'enzyme';
import ResizeObserverImpl from 'rc-resize-observer';
import Affix, { AffixProps, AffixState } from '..';
import { getObserverEntities } from '../utils';
import Button from '../../button';
import rtlTest from '../../../tests/shared/rtlTest';
import { sleep } from '../../../tests/utils';
const events: Partial<Record<keyof HTMLElementEventMap, (ev: Partial<Event>) => void>> = {};
class AffixMounter extends React.Component<{
offsetBottom?: number;
offsetTop?: number;
onTestUpdatePosition?(): void;
onChange?: () => void;
}> {
private container: HTMLDivElement;
public affix: Affix;
| () {
this.container.addEventListener = jest
.fn()
.mockImplementation((event: keyof HTMLElementEventMap, cb: (ev: Partial<Event>) => void) => {
events[event] = cb;
});
}
getTarget = () => this.container;
render() {
return (
<div
ref={node => {
this.container = node!;
}}
className="container"
>
<Affix
className="fixed"
target={this.getTarget}
ref={ele => {
this.affix = ele!;
}}
{...this.props}
>
<Button type="primary">Fixed at the top of container</Button>
</Affix>
</div>
);
}
}
describe('Affix Render', () => {
rtlTest(Affix);
const domMock = jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect');
let affixMounterWrapper: ReactWrapper<unknown, unknown, AffixMounter>;
let affixWrapper: ReactWrapper<AffixProps, AffixState, Affix>;
const classRect: Record<string, DOMRect> = {
container: {
top: 0,
bottom: 100,
} as DOMRect,
};
beforeAll(() => {
domMock.mockImplementation(function fn(this: HTMLElement) {
return (
classRect[this.className] || {
top: 0,
bottom: 0,
}
);
});
});
afterAll(() => {
domMock.mockRestore();
});
const movePlaceholder = async (top: number) => {
classRect.fixed = {
top,
bottom: top,
} as DOMRect;
if (events.scroll == null) {
throw new Error('scroll should be set');
}
events.scroll({
type: 'scroll',
});
await sleep(20);
};
it('Anchor render perfectly', async () => {
document.body.innerHTML = '<div id="mounter" />';
affixMounterWrapper = mount(<AffixMounter />, { attachTo: document.getElementById('mounter') });
await sleep(20);
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
await movePlaceholder(-100);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
});
it('support offsetBottom', async () => {
document.body.innerHTML = '<div id="mounter" />';
affixMounterWrapper = mount(<AffixMounter offsetBottom={0} />, {
attachTo: document.getElementById('mounter'),
});
await sleep(20);
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
});
it('updatePosition when offsetTop changed', async () => {
document.body.innerHTML = '<div id="mounter" />';
const onChange = jest.fn();
affixMounterWrapper = mount(<AffixMounter offsetTop={0} onChange={onChange} />, {
attachTo: document.getElementById('mounter'),
});
await sleep(20);
await movePlaceholder(-100);
expect(onChange).toHaveBeenLastCalledWith(true);
expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(0);
affixMounterWrapper.setProps({
offsetTop: 10,
});
await sleep(20);
expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(10);
});
describe('updatePosition when target changed', () => {
it('function change', () => {
document.body.innerHTML = '<div id="mounter" />';
const container = document.querySelector('#id') as HTMLDivElement;
const getTarget = () => container;
affixWrapper = mount(<Affix target={getTarget}>{null}</Affix>);
affixWrapper.setProps({ target: () => null });
expect(affixWrapper.instance().state.status).toBe(0);
expect(affixWrapper.instance().state.affixStyle).toBe(undefined);
expect(affixWrapper.instance().state.placeholderStyle).toBe(undefined);
});
it('instance change', async () => {
const getObserverLength = () => Object.keys(getObserverEntities()).length;
const container = document.createElement('div');
document.body.appendChild(container);
let target: HTMLDivElement | null = container;
const originLength = getObserverLength();
const getTarget = () => target;
affixWrapper = mount(<Affix target={getTarget}>{null}</Affix>);
await sleep(50);
expect(getObserverLength()).toBe(originLength + 1);
target = null;
affixWrapper.setProps({});
affixWrapper.update();
await sleep(50);
expect(getObserverLength()).toBe(originLength);
});
});
describe('updatePosition when size changed', () => {
it.each([
{ name: 'inner', index: 0 },
{ name: 'outer', index: 1 },
])('inner or outer', async ({ index }) => {
document.body.innerHTML = '<div id="mounter" />';
const updateCalled = jest.fn();
affixMounterWrapper = mount(
<AffixMounter offsetBottom={0} onTestUpdatePosition={updateCalled} />,
{
attachTo: document.getElementById('mounter'),
},
);
await sleep(20);
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await sleep(20);
affixMounterWrapper.update();
// Mock trigger resize
updateCalled.mockReset();
const resizeObserverInstance: ReactWrapper<
HTMLAttributes,
unknown,
ResizeObserverImpl
> = affixMounterWrapper.find('ResizeObserver') as any;
resizeObserverInstance
.at(index)
.instance()
.onResize(
[
{
target: {
getBoundingClientRect: () => ({ width: 99, height: 99 }),
} as Element,
contentRect: {} as DOMRect,
},
],
({} as unknown) as ResizeObserver,
);
await sleep(20);
expect(updateCalled).toHaveBeenCalled();
});
});
});
| componentDidMount | identifier_name |
Affix.test.tsx | import React from 'react';
import { mount, ReactWrapper, HTMLAttributes } from 'enzyme';
import ResizeObserverImpl from 'rc-resize-observer';
import Affix, { AffixProps, AffixState } from '..';
import { getObserverEntities } from '../utils';
import Button from '../../button';
import rtlTest from '../../../tests/shared/rtlTest';
import { sleep } from '../../../tests/utils';
const events: Partial<Record<keyof HTMLElementEventMap, (ev: Partial<Event>) => void>> = {};
class AffixMounter extends React.Component<{
offsetBottom?: number;
offsetTop?: number;
onTestUpdatePosition?(): void;
onChange?: () => void;
}> {
private container: HTMLDivElement;
public affix: Affix;
componentDidMount() {
this.container.addEventListener = jest
.fn()
.mockImplementation((event: keyof HTMLElementEventMap, cb: (ev: Partial<Event>) => void) => {
events[event] = cb;
});
}
getTarget = () => this.container;
render() | }
className="container"
>
<Affix
className="fixed"
target={this.getTarget}
ref={ele => {
this.affix = ele!;
}}
{...this.props}
>
<Button type="primary">Fixed at the top of container</Button>
</Affix>
</div>
);
}
}
describe('Affix Render', () => {
rtlTest(Affix);
const domMock = jest.spyOn(HTMLElement.prototype, 'getBoundingClientRect');
let affixMounterWrapper: ReactWrapper<unknown, unknown, AffixMounter>;
let affixWrapper: ReactWrapper<AffixProps, AffixState, Affix>;
const classRect: Record<string, DOMRect> = {
container: {
top: 0,
bottom: 100,
} as DOMRect,
};
beforeAll(() => {
domMock.mockImplementation(function fn(this: HTMLElement) {
return (
classRect[this.className] || {
top: 0,
bottom: 0,
}
);
});
});
afterAll(() => {
domMock.mockRestore();
});
const movePlaceholder = async (top: number) => {
classRect.fixed = {
top,
bottom: top,
} as DOMRect;
if (events.scroll == null) {
throw new Error('scroll should be set');
}
events.scroll({
type: 'scroll',
});
await sleep(20);
};
it('Anchor render perfectly', async () => {
document.body.innerHTML = '<div id="mounter" />';
affixMounterWrapper = mount(<AffixMounter />, { attachTo: document.getElementById('mounter') });
await sleep(20);
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
await movePlaceholder(-100);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
});
it('support offsetBottom', async () => {
document.body.innerHTML = '<div id="mounter" />';
affixMounterWrapper = mount(<AffixMounter offsetBottom={0} />, {
attachTo: document.getElementById('mounter'),
});
await sleep(20);
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await movePlaceholder(0);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeFalsy();
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
});
it('updatePosition when offsetTop changed', async () => {
document.body.innerHTML = '<div id="mounter" />';
const onChange = jest.fn();
affixMounterWrapper = mount(<AffixMounter offsetTop={0} onChange={onChange} />, {
attachTo: document.getElementById('mounter'),
});
await sleep(20);
await movePlaceholder(-100);
expect(onChange).toHaveBeenLastCalledWith(true);
expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(0);
affixMounterWrapper.setProps({
offsetTop: 10,
});
await sleep(20);
expect(affixMounterWrapper.instance().affix.state.affixStyle?.top).toBe(10);
});
describe('updatePosition when target changed', () => {
it('function change', () => {
document.body.innerHTML = '<div id="mounter" />';
const container = document.querySelector('#id') as HTMLDivElement;
const getTarget = () => container;
affixWrapper = mount(<Affix target={getTarget}>{null}</Affix>);
affixWrapper.setProps({ target: () => null });
expect(affixWrapper.instance().state.status).toBe(0);
expect(affixWrapper.instance().state.affixStyle).toBe(undefined);
expect(affixWrapper.instance().state.placeholderStyle).toBe(undefined);
});
it('instance change', async () => {
const getObserverLength = () => Object.keys(getObserverEntities()).length;
const container = document.createElement('div');
document.body.appendChild(container);
let target: HTMLDivElement | null = container;
const originLength = getObserverLength();
const getTarget = () => target;
affixWrapper = mount(<Affix target={getTarget}>{null}</Affix>);
await sleep(50);
expect(getObserverLength()).toBe(originLength + 1);
target = null;
affixWrapper.setProps({});
affixWrapper.update();
await sleep(50);
expect(getObserverLength()).toBe(originLength);
});
});
describe('updatePosition when size changed', () => {
it.each([
{ name: 'inner', index: 0 },
{ name: 'outer', index: 1 },
])('inner or outer', async ({ index }) => {
document.body.innerHTML = '<div id="mounter" />';
const updateCalled = jest.fn();
affixMounterWrapper = mount(
<AffixMounter offsetBottom={0} onTestUpdatePosition={updateCalled} />,
{
attachTo: document.getElementById('mounter'),
},
);
await sleep(20);
await movePlaceholder(300);
expect(affixMounterWrapper.instance().affix.state.affixStyle).toBeTruthy();
await sleep(20);
affixMounterWrapper.update();
// Mock trigger resize
updateCalled.mockReset();
const resizeObserverInstance: ReactWrapper<
HTMLAttributes,
unknown,
ResizeObserverImpl
> = affixMounterWrapper.find('ResizeObserver') as any;
resizeObserverInstance
.at(index)
.instance()
.onResize(
[
{
target: {
getBoundingClientRect: () => ({ width: 99, height: 99 }),
} as Element,
contentRect: {} as DOMRect,
},
],
({} as unknown) as ResizeObserver,
);
await sleep(20);
expect(updateCalled).toHaveBeenCalled();
});
});
});
| {
return (
<div
ref={node => {
this.container = node!;
} | identifier_body |
test_timeout2.js | var http = require("http");
var querystring = require("querystring"); // 核心模块
var SBuffer=require("../tools/SBuffer");
var common=require("../tools/common");
var zlib=require("zlib");
var redis_pool=require("../tools/connection_pool");
var events = require('events');
var util = require('util');
function ProxyAgent(preHeaders,preAnalysisFields,logName){
this. | 获取服务配置信息
* @param 服务名
* @return object
*/
ProxyAgent.prototype.getReqConfig = function(logName){
var _self=this;
var Obj={};
Obj=Config[logName];
Obj.logger=Analysis.getLogger(logName);
Obj.name=logName;
return Obj;
}
ProxyAgent.prototype.doRequest=function(_req,_res){
var _self=this;
_self.reqConf=_self.getReqConfig(this.logName);
logger.debug('进入'+_self.reqConf.desc+"服务");
var header_obj =this.packageHeaders(_req.headers,this.headNeeds);
var url_obj = url.parse(request.url, true);
var query_obj = url_obj.query;
var postData = request.body|| ""; // 获取请求参数
_res.setHeader("Content-Type", config.contentType);
_res.setHeader(config.headerkey, config.headerval);
var opts=_self.packData(header_obj,query_obj,postData);
logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]);
if(typeof(postData) =="object" && postData.redis_key.length>0){
this.getRedis(opts[0],opts[1]);
}
else{
this.httpProxy(opts[0],opts[1]);
}
}
/**
* 封装get post接口
* @param headers
* @param query
* @param body
* @return []
*/
ProxyAgent.prototype.packData=function(headers,query,body){
var _self=this;
//resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据
var type=_self.reqConf.resType || "";
body = body || "";
var len=0;
var query_str="";
var body_str="";
if(type==""){
query=common.extends(query,headers);
query_str = querystring.stringify(query, '&', '=');
}
else if(type=="body"){
body=common.extends(body,headers);
body_str = querystring.stringify(body, '&', '=');
len=body_str.length;
if(body.redis_key){
this.redis={};
this.redis.redis_key=body.redis_key;
}
}
else if(type=="json"){
query=common.extends(query,headers);
query_str = 'json='+querystring.stringify(query, '&', '=');
}
else if(type=="raw"){
len=body.length;
body_str=body;
}
var actionlocation = headers.actionlocation || "";
if(actionlocation==""){
actionlocation=query.actionlocation||"";
}
var opts=_self.getRequestOptions(len,actionlocation);
opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str;
return [opts,body_str];
}
/**
* 获取请求头信息
* @param len数据长度
* @param actiontion 通用访问地址
* @return object 头信息
*/
ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){
var _self=this;
var options = { //http请求参数设置
host: _self.reqConf.host, // 远端服务器域名
port: _self.reqConf.port, // 远端服务器端口号
path: _self.reqConf.path||"",
headers : {'Connection' : 'keep-alive'}
};
if(actionlocation.length>0){
options.path=actionlocation;
}
var rtype= _self.reqConf.reqType || "";
if(rtype.length>0){
options.headers['Content-Type']=rtype;
}
if(len>0){
options.headers['Content-Length']=len;
}
return options;
}
ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){
var obj={};
return obj;
}
/**
* 获取头部信息进行封装
* @param request.headers
* @param need fields ;split with ','
* @return object headers
*/
ProxyAgent.prototype.packageHeaders = function(headers) {
var fields=arguments[1]||"";
var query_obj = {};
var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址
var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源
var osversion = headers['osversion'] || '0';// 客户端系统
var devicemodel = headers['devicemodel'] || '0';// 客户端型号
var manufacturername = headers['manufacturername'] || '0';// 制造厂商
var actionlocation = headers['actionlocation']; // 请求后台地址
var dpi = headers['dpi'] || '2.0';// 密度
var imsi = headers['imsi'] || '0'; // 客户端imsi
var mobileid = headers['mobileid'] || '0'; // 客户端mibileid
var version = headers['version'] || '0';// 客户端版本version
var selflon = headers['selflon'] || '0';// 经度
var selflat = headers['selflat'] || '0';// 维度
var uid = headers['uid'] || '0'; // 犬号
var radius=headers['radius']||'0';//误差半径
var platform=headers['platform']||"";//平台 ios ,android
var gender= headers['gender'] || '0';
query_obj.gender = gender;
query_obj.reqip = reqip;
query_obj.forward = forward;
query_obj.osversion = osversion;
query_obj.devicemodel = devicemodel;
query_obj.manufacturername = manufacturername;
query_obj.actionlocation = actionlocation;
query_obj.dpi = dpi;
query_obj.imsi = imsi;
query_obj.mobileid = mobileid;
query_obj.version = version;
query_obj.selflon = selflon;
query_obj.selflat = selflat;
query_obj.uid = uid;
query_obj.radius=radius;
query_obj.platform=platform;
if(fields.length > 0){
var afields = fields.split(",");
var newObj = {};
for(var i = 0; i < afields.length ; i ++){
newObj[afields[i]] = query_obj[afields[i]] || "";
}
return newObj;
}
else{
return query_obj;
}
}
/**
* http 请求代理
* @param options 远程接口信息
* @param reqData 请求内容 req.method== get时一般为空
*/
ProxyAgent.prototype.httpProxy = function (options,reqData){
var _self=this;
var TongjiObj={};
var req = http.request(options, function(res) {
TongjiObj.statusCode = res.statusCode ||500;
var tmptime=Date.now();
TongjiObj.restime = tmptime;
TongjiObj.resEnd =tmptime;
TongjiObj.ends = tmptime;
TongjiObj.length = 0;
TongjiObj.last = tmptime;
var sbuffer=new SBuffer();
res.setEncoding("utf-8");
res.on('data', function (trunk) {
sbuffer.append(trunk);
});
res.on('end', function () {
TongjiObj.resEnd = Date.now();
//doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt);
_self.emmit("onDone",sbuffer,TongjiObj);
});
});
req.setTimeout(timeout,function(){
req.emit('timeOut',{message:'have been timeout...'});
});
req.on('error', function(e) {
TongjiObj.statusCode=500;
_self.emmit("onDone","",500,TongjiObj);
});
req.on('timeOut', function(e) {
req.abort();
TongjiObj.statusCode=500;
TongjiObj.last = Date.now();
_self.emmit("onDone","",500,TongjiObj);
});
req.end(reqData);
}
/**
* 设置缓存
* @param redis_key
* @param redis_time
* @param resultBuffer
*/
ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) {
redis_pool.acquire(function(err, client) {
if (!err) {
client.setex(redis_key, redis_time, resultBuffer, function(err,
repliy) {
redis_pool.release(client); // 链接使用完毕释放链接
});
logger.debug(redis_key + '设置缓存数据成功!');
} else {
writeLogs.logs(Analysis.getLogger('error'), 'error', {
msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常',
err : 14
});
logger.debug(redis_key + '设置缓存数据失败!');
}
});
}
/**
* 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存
* redis_key通过self变量中取
* @param options
* @param reqData
*/
ProxyAgent.prototype.getRedis = function ( options, reqData) {
var _self=this;
var redis_key=this.redis.redis_key || "";
redis_pool.acquire(function(err, client) {
if (!err) {
client.get(redis_key, function(err, date) {
redis_pool.release(client) // 用完之后释放链接
if (!err && date != null) {
var resultBuffer = new Buffer(date);
_self.response.statusCode = 200;
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
logger.debug(redis_key + '通用接口下行缓存数据:' + date);
} else {
_self.httpProxy(options, reqData);
}
});
} else {
_self.httpProxy(options, reqData);
}
});
}
/**
* 输出gzip数据
* response 内置
* @param resultBuffer
*/
ProxyAgent.prototype.gzipOutPut = function (resultBuffer){
var _self=this;
zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩
if (code != null) { // 如果正常结束
logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length);
_self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志
} else {
buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}');
_self.response.statusCode=500;
}
_self.response.setHeader("Content-Length", buffer.length);
_self.response.write(buffer);
_self.response.end();
});
}
/**
* 请求完毕处理
* @param buffer type buffer/string
* @param status 请求http状态
* @param tongji object统计对象
*/
ProxyAgent.prototype.onDone =function(buffer,status){
var tongji=arguments[2] ||"";
var _self=this;
var resultStr = typeof(buffer)=="object"?buffer.toString():buffer;
if(this.reqConf.isjson==1){
var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式
if (resultObj) { // 返回结果是json格式
resultStr = JSON.stringify(resultObj);
_self.response.statusCode = status;
} else {
resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}';
_self.response.statusCode = 500;
}
}
else{
_self.response.statusCode = status;
}
var resultBuffer = new Buffer(resultStr);
if(tongji!=""){
tongji.ends = Date.now();
tongji.length = resultBuffer.length;
}
if(resultBuffer.length > 500 ){
//压缩输出
_self.gzipOutPut(resultBuffer);
}else{
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
}
if(tongji!=""){
tongji.last= Date.now();
tongji=common.extends(tongji,_self.preAnalysisFields);
logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status);
writeLogs.logs(poiDetailServer,'poiDetailServer',obj);
}
});
ProxyAgent.prototype.onDones =function(buffer,status){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
ProxyAgent.prototype.dealDones =function(){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
//ProxyAgent 从event 集成
//utils.inherit(ProxyAgent,event);
exports.ProxyAgent=ProxyAgent;
| headNeeds = preHeaders||"";
this.preAnalysisFields = preAnalysisFields||"";
this.AnalysisFields = {};
this.logName=logName||"";
this.response=null;
this.reqConf={};
this.retData=[];
this.redis =null; // redis {} redis_key
events.EventEmitter.call(this);
}
/**
* | identifier_body |
test_timeout2.js | var http = require("http");
var querystring = require("querystring"); // 核心模块
var SBuffer=require("../tools/SBuffer");
var common=require("../tools/common");
var zlib=require("zlib");
var redis_pool=require("../tools/connection_pool");
var events = require('events');
var util = require('util');
function ProxyAge | ers,preAnalysisFields,logName){
this.headNeeds = preHeaders||"";
this.preAnalysisFields = preAnalysisFields||"";
this.AnalysisFields = {};
this.logName=logName||"";
this.response=null;
this.reqConf={};
this.retData=[];
this.redis =null; // redis {} redis_key
events.EventEmitter.call(this);
}
/**
* 获取服务配置信息
* @param 服务名
* @return object
*/
ProxyAgent.prototype.getReqConfig = function(logName){
var _self=this;
var Obj={};
Obj=Config[logName];
Obj.logger=Analysis.getLogger(logName);
Obj.name=logName;
return Obj;
}
ProxyAgent.prototype.doRequest=function(_req,_res){
var _self=this;
_self.reqConf=_self.getReqConfig(this.logName);
logger.debug('进入'+_self.reqConf.desc+"服务");
var header_obj =this.packageHeaders(_req.headers,this.headNeeds);
var url_obj = url.parse(request.url, true);
var query_obj = url_obj.query;
var postData = request.body|| ""; // 获取请求参数
_res.setHeader("Content-Type", config.contentType);
_res.setHeader(config.headerkey, config.headerval);
var opts=_self.packData(header_obj,query_obj,postData);
logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]);
if(typeof(postData) =="object" && postData.redis_key.length>0){
this.getRedis(opts[0],opts[1]);
}
else{
this.httpProxy(opts[0],opts[1]);
}
}
/**
* 封装get post接口
* @param headers
* @param query
* @param body
* @return []
*/
ProxyAgent.prototype.packData=function(headers,query,body){
var _self=this;
//resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据
var type=_self.reqConf.resType || "";
body = body || "";
var len=0;
var query_str="";
var body_str="";
if(type==""){
query=common.extends(query,headers);
query_str = querystring.stringify(query, '&', '=');
}
else if(type=="body"){
body=common.extends(body,headers);
body_str = querystring.stringify(body, '&', '=');
len=body_str.length;
if(body.redis_key){
this.redis={};
this.redis.redis_key=body.redis_key;
}
}
else if(type=="json"){
query=common.extends(query,headers);
query_str = 'json='+querystring.stringify(query, '&', '=');
}
else if(type=="raw"){
len=body.length;
body_str=body;
}
var actionlocation = headers.actionlocation || "";
if(actionlocation==""){
actionlocation=query.actionlocation||"";
}
var opts=_self.getRequestOptions(len,actionlocation);
opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str;
return [opts,body_str];
}
/**
* 获取请求头信息
* @param len数据长度
* @param actiontion 通用访问地址
* @return object 头信息
*/
ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){
var _self=this;
var options = { //http请求参数设置
host: _self.reqConf.host, // 远端服务器域名
port: _self.reqConf.port, // 远端服务器端口号
path: _self.reqConf.path||"",
headers : {'Connection' : 'keep-alive'}
};
if(actionlocation.length>0){
options.path=actionlocation;
}
var rtype= _self.reqConf.reqType || "";
if(rtype.length>0){
options.headers['Content-Type']=rtype;
}
if(len>0){
options.headers['Content-Length']=len;
}
return options;
}
ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){
var obj={};
return obj;
}
/**
* 获取头部信息进行封装
* @param request.headers
* @param need fields ;split with ','
* @return object headers
*/
ProxyAgent.prototype.packageHeaders = function(headers) {
var fields=arguments[1]||"";
var query_obj = {};
var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址
var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源
var osversion = headers['osversion'] || '0';// 客户端系统
var devicemodel = headers['devicemodel'] || '0';// 客户端型号
var manufacturername = headers['manufacturername'] || '0';// 制造厂商
var actionlocation = headers['actionlocation']; // 请求后台地址
var dpi = headers['dpi'] || '2.0';// 密度
var imsi = headers['imsi'] || '0'; // 客户端imsi
var mobileid = headers['mobileid'] || '0'; // 客户端mibileid
var version = headers['version'] || '0';// 客户端版本version
var selflon = headers['selflon'] || '0';// 经度
var selflat = headers['selflat'] || '0';// 维度
var uid = headers['uid'] || '0'; // 犬号
var radius=headers['radius']||'0';//误差半径
var platform=headers['platform']||"";//平台 ios ,android
var gender= headers['gender'] || '0';
query_obj.gender = gender;
query_obj.reqip = reqip;
query_obj.forward = forward;
query_obj.osversion = osversion;
query_obj.devicemodel = devicemodel;
query_obj.manufacturername = manufacturername;
query_obj.actionlocation = actionlocation;
query_obj.dpi = dpi;
query_obj.imsi = imsi;
query_obj.mobileid = mobileid;
query_obj.version = version;
query_obj.selflon = selflon;
query_obj.selflat = selflat;
query_obj.uid = uid;
query_obj.radius=radius;
query_obj.platform=platform;
if(fields.length > 0){
var afields = fields.split(",");
var newObj = {};
for(var i = 0; i < afields.length ; i ++){
newObj[afields[i]] = query_obj[afields[i]] || "";
}
return newObj;
}
else{
return query_obj;
}
}
/**
* http 请求代理
* @param options 远程接口信息
* @param reqData 请求内容 req.method== get时一般为空
*/
ProxyAgent.prototype.httpProxy = function (options,reqData){
var _self=this;
var TongjiObj={};
var req = http.request(options, function(res) {
TongjiObj.statusCode = res.statusCode ||500;
var tmptime=Date.now();
TongjiObj.restime = tmptime;
TongjiObj.resEnd =tmptime;
TongjiObj.ends = tmptime;
TongjiObj.length = 0;
TongjiObj.last = tmptime;
var sbuffer=new SBuffer();
res.setEncoding("utf-8");
res.on('data', function (trunk) {
sbuffer.append(trunk);
});
res.on('end', function () {
TongjiObj.resEnd = Date.now();
//doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt);
_self.emmit("onDone",sbuffer,TongjiObj);
});
});
req.setTimeout(timeout,function(){
req.emit('timeOut',{message:'have been timeout...'});
});
req.on('error', function(e) {
TongjiObj.statusCode=500;
_self.emmit("onDone","",500,TongjiObj);
});
req.on('timeOut', function(e) {
req.abort();
TongjiObj.statusCode=500;
TongjiObj.last = Date.now();
_self.emmit("onDone","",500,TongjiObj);
});
req.end(reqData);
}
/**
* 设置缓存
* @param redis_key
* @param redis_time
* @param resultBuffer
*/
ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) {
redis_pool.acquire(function(err, client) {
if (!err) {
client.setex(redis_key, redis_time, resultBuffer, function(err,
repliy) {
redis_pool.release(client); // 链接使用完毕释放链接
});
logger.debug(redis_key + '设置缓存数据成功!');
} else {
writeLogs.logs(Analysis.getLogger('error'), 'error', {
msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常',
err : 14
});
logger.debug(redis_key + '设置缓存数据失败!');
}
});
}
/**
* 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存
* redis_key通过self变量中取
* @param options
* @param reqData
*/
ProxyAgent.prototype.getRedis = function ( options, reqData) {
var _self=this;
var redis_key=this.redis.redis_key || "";
redis_pool.acquire(function(err, client) {
if (!err) {
client.get(redis_key, function(err, date) {
redis_pool.release(client) // 用完之后释放链接
if (!err && date != null) {
var resultBuffer = new Buffer(date);
_self.response.statusCode = 200;
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
logger.debug(redis_key + '通用接口下行缓存数据:' + date);
} else {
_self.httpProxy(options, reqData);
}
});
} else {
_self.httpProxy(options, reqData);
}
});
}
/**
* 输出gzip数据
* response 内置
* @param resultBuffer
*/
ProxyAgent.prototype.gzipOutPut = function (resultBuffer){
var _self=this;
zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩
if (code != null) { // 如果正常结束
logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length);
_self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志
} else {
buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}');
_self.response.statusCode=500;
}
_self.response.setHeader("Content-Length", buffer.length);
_self.response.write(buffer);
_self.response.end();
});
}
/**
* 请求完毕处理
* @param buffer type buffer/string
* @param status 请求http状态
* @param tongji object统计对象
*/
ProxyAgent.prototype.onDone =function(buffer,status){
var tongji=arguments[2] ||"";
var _self=this;
var resultStr = typeof(buffer)=="object"?buffer.toString():buffer;
if(this.reqConf.isjson==1){
var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式
if (resultObj) { // 返回结果是json格式
resultStr = JSON.stringify(resultObj);
_self.response.statusCode = status;
} else {
resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}';
_self.response.statusCode = 500;
}
}
else{
_self.response.statusCode = status;
}
var resultBuffer = new Buffer(resultStr);
if(tongji!=""){
tongji.ends = Date.now();
tongji.length = resultBuffer.length;
}
if(resultBuffer.length > 500 ){
//压缩输出
_self.gzipOutPut(resultBuffer);
}else{
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
}
if(tongji!=""){
tongji.last= Date.now();
tongji=common.extends(tongji,_self.preAnalysisFields);
logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status);
writeLogs.logs(poiDetailServer,'poiDetailServer',obj);
}
});
ProxyAgent.prototype.onDones =function(buffer,status){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
ProxyAgent.prototype.dealDones =function(){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
//ProxyAgent 从event 集成
//utils.inherit(ProxyAgent,event);
exports.ProxyAgent=ProxyAgent;
| nt(preHead | identifier_name |
test_timeout2.js | var http = require("http");
var querystring = require("querystring"); // 核心模块
var SBuffer=require("../tools/SBuffer");
var common=require("../tools/common");
var zlib=require("zlib");
var redis_pool=require("../tools/connection_pool");
var events = require('events');
var util = require('util');
function ProxyAgent(preHeaders,preAnalysisFields,logName){
this.headNeeds = preHeaders||"";
this.preAnalysisFields = preAnalysisFields||"";
this.AnalysisFields = {};
this.logName=logName||"";
this.response=null;
this.reqConf={};
this.retData=[];
this.redis =null; // redis {} redis_key
events.EventEmitter.call(this);
}
/**
* 获取服务配置信息
* @param 服务名
* @return object
*/
ProxyAgent.prototype.getReqConfig = function(logName){
var _self=this;
var Obj={};
Obj=Config[logName];
Obj.logger=Analysis.getLogger(logName);
Obj.name=logName;
return Obj;
}
ProxyAgent.prototype.doRequest=function(_req,_res){
var _self=this;
_self.reqConf=_self.getReqConfig(this.logName);
logger.debug('进入'+_self.reqConf.desc+"服务");
var header_obj =this.packageHeaders(_req.headers,this.headNeeds);
var url_obj = url.parse(request.url, true);
var query_obj = url_obj.query;
var postData = request.body|| ""; // 获取请求参数
_res.setHeader("Content-Type", config.contentType);
_res.setHeader(config.headerkey, config.headerval);
var opts=_self.packData(header_obj,query_obj,postData);
logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]);
if(typeof(postData) =="object" && postData.redis_key.length>0){
this.getRedis(opts[0],opts[1]);
}
else{
this.httpProxy(opts[0],opts[1]);
}
}
/**
* 封装get post接口
* @param headers
* @param query
* @param body
* @return []
*/
ProxyAgent.prototype.packData=function(headers,query,body){
var _self=this;
//resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据
var type=_self.reqConf.resType || "";
body = body || "";
var len=0;
var query_str="";
var body_str="";
if(type==""){
query=common.extends(query,headers);
query_str = querystring.stringify(query, '&', '=');
}
else if(type=="body"){
body=common.extends(body,headers);
body_str = querystring.stringify(body, '&', '=');
len=body_str.length;
if(body.redis_key){
this.redis={};
this.redis.redis_key=body.redis_key;
}
}
else if(type=="json"){
query=common.extends(query,headers);
query_str = 'json='+querystring.stringify(query, '&', '=');
}
else if(type=="raw"){
len=body.length;
body_str=body;
}
var actionlocation = headers.actionlocation || "";
if(actionlocation==""){
actionlocation=query.actionlocation||"";
}
var opts=_self.getRequestOptions(len,actionlocation);
opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str;
return [opts,body_str];
}
/**
* 获取请求头信息
* @param len数据长度
* @param actiontion 通用访问地址
* @return object 头信息
*/
ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){
var _self=this;
var options = { //http请求参数设置
host: _self.reqConf.host, // 远端服务器域名
port: _self.reqConf.port, // 远端服务器端口号
path: _self.reqConf.path||"",
headers : {'Connection' : 'keep-alive'}
};
if(actionlocation.length>0){
options.path=actionlocation;
}
var rtype= _self.reqConf.reqType || "";
if(rtype.length>0){
options.headers['Content-Type']=rtype;
}
if(len>0){
options.headers['Content-Length']=len;
}
return options;
}
ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){
var obj={};
return obj;
}
/**
* 获取头部信息进行封装
* @param request.headers
* @param need fields ;split with ','
* @return object headers
*/
ProxyAgent.prototype.packageHeaders = function(headers) {
var fields=arguments[1]||"";
var query_obj = {};
var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址
var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源
var osversion = headers['osversion'] || '0';// 客户端系统
var devicemodel = headers['devicemodel'] || '0';// 客户端型号
var manufacturername = headers['manufacturername'] || '0';// 制造厂商
var actionlocation = headers['actionlocation']; // 请求后台地址
var dpi = headers['dpi'] || '2.0';// 密度
var imsi = headers['imsi'] || '0'; // 客户端imsi
var mobileid = headers['mobileid'] || '0'; // 客户端mibileid
var version = headers['version'] || '0';// 客户端版本version
var selflon = headers['selflon'] || '0';// 经度
var selflat = headers['selflat'] || '0';// 维度
var uid = headers['uid'] || '0'; // 犬号
var radius=headers['radius']||'0';//误差半径
var platform=headers['platform']||"";//平台 ios ,android
var gender= headers['gender'] || '0';
query_obj.gender = gender;
query_obj.reqip = reqip;
query_obj.forward = forward;
query_obj.osversion = osversion;
query_obj.devicemodel = devicemodel;
query_obj.manufacturername = manufacturername;
query_obj.actionlocation = actionlocation;
query_obj.dpi = dpi;
query_obj.imsi = imsi;
query_obj.mobileid = mobileid;
query_obj.version = version;
query_obj.selflon = selflon;
query_obj.selflat = selflat;
query_obj.uid = uid;
query_obj.radius=radius;
query_obj.platform=platform;
if(fields.length > 0){
var afields = fields.split(",");
var newObj = {};
for(var i = 0; i < afields.length ; i ++){
newObj[afields[i]] = query_obj[afields[i]] || "";
}
return newObj;
}
else{
return query_obj;
}
}
/**
* http 请求代理
* @param options 远程接口信息
* @param reqData 请求内容 req.method== get时一般为空
*/
ProxyAgent.prototype.httpProxy = function (options,reqData){
var _self=this;
var TongjiObj={};
var req = http.request(options, function(res) {
TongjiObj.statusCode = res.statusCode ||500;
var tmptime=Date.now();
TongjiObj.restime = tmptime;
TongjiObj.resEnd =tmptime;
TongjiObj.ends = tmptime;
TongjiObj.length = 0;
TongjiObj.last = tmptime;
var sbuffer=new SBuffer();
res.setEncoding("utf-8");
res.on('data', function (trunk) {
sbuffer.append(trunk);
});
res.on('end', function () {
TongjiObj.resEnd = Date.now();
//doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt);
_self.emmit("onDone",sbuffer,TongjiObj);
});
});
req.setTimeout(timeout,function(){
req.emit('timeOut',{message:'have been timeout...'});
});
req.on('error', function(e) {
TongjiObj.statusCode=500;
_self.emmit("onDone","",500,TongjiObj);
});
req.on('timeOut', function(e) {
req.abort();
TongjiObj.statusCode=500;
TongjiObj.last = Date.now();
_self.emmit("onDone","",500,TongjiObj);
});
req.end(reqData);
}
/**
* 设置缓存
* @param redis_key
* @param redis_time
* @param resultBuffer
*/
ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) {
redis_pool.acquire(function(err, client) {
if (!err) {
client.setex(redis_key, redis_time, resultBuffer, function(err,
repliy) {
redis_pool.release(client); // 链接使用完毕释放链接
});
logger.debug(redis_key + '设置缓存数据成功!');
} else {
writeLogs.logs(Analysis.getLogger('error'), 'error', {
msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常',
err : 14
});
logger.debug(redis_key + '设置缓存数据失败!');
}
});
}
/**
* 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存
* redis_key通过self变量中取
* @param options
* @param reqData
*/
ProxyAgent.prototype.getRedis = function ( options, reqData) {
var _self=this;
var redis_key=this.redis.redis_key || "";
redis_pool.acquire(function(err, client) {
if (!err) {
client.get(redis_key, function(err, date) {
redis_pool.release(client) // 用完之后释放链接
if (!err && date != null) {
var resultBuffer = new Buffer(date);
_self.response.statusCode = 200;
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
logger.debug(redis_key + '通用接口下行缓存数据:' + date);
} else {
_self.httpProxy(options, reqData);
}
});
} else {
_self.httpProxy(options, reqData);
}
});
}
/**
* 输出gzip数据
* response 内置
* @param resultBuffer
*/
ProxyAgent.prototype.gzipOutPut = function (resultBuffer){
var _self=this;
zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩
if (code != null) { // 如果正常结束
logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length);
_self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志
} else {
buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}');
_self.response.statusCode=500;
}
_self.response.setHeader("Content-Length", buffer.length);
_self.response.write(buffer);
_self.response.end();
});
}
/**
* 请求完毕处理
* @param buffer type buffer/string
* @param status 请求http状态
* @param tongji object统计对象
*/
ProxyAgent.prototype.onDone =function(buffer,status){
var tongji=arguments[2] ||"";
var _self=this;
var resultStr = typeof(buffer)=="object"?buffer.toString():buffer;
if(this.reqConf.isjson==1){
var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式
if (resultObj) { // 返回结果是json格式
resultStr = JSON.stringify(resultObj);
_self.response.statusCode = status;
} else {
resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}';
_self.response.statusCode = 500;
}
}
else{
_self.response.statusCode = status;
}
var resultBuffer = new Buffer(resultStr);
if(tongji!=""){
tongji.ends = Date.now();
tongji.length = resultBuffer.length;
}
if(resultBuffer.length > 500 ){
//压缩输出
_self.gzipOutPut(resultBuffer);
}else{
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
}
if(tongji!=""){
tongji.last= Date.now();
tongji=common.extends(tongji,_self.preAnalysisFields);
logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status);
writeLogs.logs(poiDetailServer,'poiDetailServer',obj);
}
});
ProxyAgent.prototype.onDones =function(buffer,status){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
ProxyAgent.prototype.dealDones =function(){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
//ProxyAgent 从event 集成
//utils.inherit(ProxyAgent,event);
exports.ProxyAgent=ProxyAgent;
| conditional_block | ||
test_timeout2.js | var http = require("http");
var querystring = require("querystring"); // 核心模块
var SBuffer=require("../tools/SBuffer");
var common=require("../tools/common");
var zlib=require("zlib");
var redis_pool=require("../tools/connection_pool");
var events = require('events');
var util = require('util');
function ProxyAgent(preHeaders,preAnalysisFields,logName){
this.headNeeds = preHeaders||"";
this.preAnalysisFields = preAnalysisFields||"";
this.AnalysisFields = {};
this.logName=logName||"";
this.response=null;
this.reqConf={};
this.retData=[];
this.redis =null; // redis {} redis_key
events.EventEmitter.call(this);
}
/**
* 获取服务配置信息
* @param 服务名
* @return object
*/
ProxyAgent.prototype.getReqConfig = function(logName){
var _self=this;
var Obj={};
Obj=Config[logName];
Obj.logger=Analysis.getLogger(logName);
Obj.name=logName;
return Obj;
}
ProxyAgent.prototype.doRequest=function(_req,_res){
var _self=this;
_self.reqConf=_self.getReqConfig(this.logName);
logger.debug('进入'+_self.reqConf.desc+"服务");
var header_obj =this.packageHeaders(_req.headers,this.headNeeds);
var url_obj = url.parse(request.url, true);
var query_obj = url_obj.query;
var postData = request.body|| ""; // 获取请求参数
_res.setHeader("Content-Type", config.contentType);
_res.setHeader(config.headerkey, config.headerval);
var opts=_self.packData(header_obj,query_obj,postData);
logger.debug(header_obj.mobileid +_self.reqConf.desc+ '接口参数信息:'+opts[0].path +" data:"+ opts[1]);
if(typeof(postData) =="object" && postData.redis_key.length>0){
this.getRedis(opts[0],opts[1]);
}
else{
this.httpProxy(opts[0],opts[1]);
}
}
/**
* 封装get post接口
* @param headers
* @param query
* @param body
* @return []
*/
ProxyAgent.prototype.packData=function(headers,query,body){
var _self=this;
//resType 解释 ""==>GET,"body"==>POST,"json"==>特殊poi,"raw"==>原始数据
var type=_self.reqConf.resType || "";
body = body || "";
var len=0;
var query_str="";
var body_str="";
if(type==""){
query=common.extends(query,headers);
query_str = querystring.stringify(query, '&', '=');
}
else if(type=="body"){
body=common.extends(body,headers);
body_str = querystring.stringify(body, '&', '=');
len=body_str.length;
if(body.redis_key){
this.redis={};
this.redis.redis_key=body.redis_key;
}
}
else if(type=="json"){
query=common.extends(query,headers);
query_str = 'json='+querystring.stringify(query, '&', '=');
}
else if(type=="raw"){
len=body.length;
body_str=body;
}
var actionlocation = headers.actionlocation || "";
if(actionlocation==""){
actionlocation=query.actionlocation||"";
}
var opts=_self.getRequestOptions(len,actionlocation);
opts.path+=((opts.path.indexOf("?")>=0)?"&":"?")+query_str;
return [opts,body_str];
}
/**
* 获取请求头信息
* @param len数据长度
* @param actiontion 通用访问地址
* @return object 头信息
*/
ProxyAgent.prototype.getRequestOptions=function(len,actionlocation){
var _self=this;
var options = { //http请求参数设置
host: _self.reqConf.host, // 远端服务器域名
port: _self.reqConf.port, // 远端服务器端口号
path: _self.reqConf.path||"",
headers : {'Connection' : 'keep-alive'}
};
if(actionlocation.length>0){
options.path=actionlocation;
}
var rtype= _self.reqConf.reqType || "";
if(rtype.length>0){
options.headers['Content-Type']=rtype;
}
if(len>0){
options.headers['Content-Length']=len;
}
return options;
}
ProxyAgent.prototype.getRedisOptions=function(options,actionlocation){
var obj={};
return obj;
}
/**
* 获取头部信息进行封装
* @param request.headers
* @param need fields ;split with ','
* @return object headers
*/
ProxyAgent.prototype.packageHeaders = function(headers) {
var fields=arguments[1]||"";
var query_obj = {};
var reqip = headers['x-real-ip'] || '0'; // 客户端请求的真实ip地址
var forward = headers['x-forwarded-for'] || '0'; // 客户端请求来源
var osversion = headers['osversion'] || '0';// 客户端系统
var devicemodel = headers['devicemodel'] || '0';// 客户端型号
var manufacturername = headers['manufacturername'] || '0';// 制造厂商
var actionlocation = headers['actionlocation']; // 请求后台地址
var dpi = headers['dpi'] || '2.0';// 密度
var imsi = headers['imsi'] || '0'; // 客户端imsi
var mobileid = headers['mobileid'] || '0'; // 客户端mibileid
var version = headers['version'] || '0';// 客户端版本version
var selflon = headers['selflon'] || '0';// 经度
var selflat = headers['selflat'] || '0';// 维度
var uid = headers['uid'] || '0'; // 犬号
var radius=headers['radius']||'0';//误差半径
var platform=headers['platform']||"";//平台 ios ,android
var gender= headers['gender'] || '0';
query_obj.gender = gender;
query_obj.reqip = reqip;
query_obj.forward = forward;
query_obj.osversion = osversion;
query_obj.devicemodel = devicemodel;
query_obj.manufacturername = manufacturername;
query_obj.actionlocation = actionlocation;
query_obj.dpi = dpi;
query_obj.imsi = imsi;
query_obj.mobileid = mobileid;
query_obj.version = version;
query_obj.selflon = selflon;
query_obj.selflat = selflat;
query_obj.uid = uid;
query_obj.radius=radius;
query_obj.platform=platform;
if(fields.length > 0){
var afields = fields.split(",");
var newObj = {};
for(var i = 0; i < afields.length ; i ++){
newObj[afields[i]] = query_obj[afields[i]] || "";
}
return newObj;
}
else{
return query_obj;
}
}
/**
* http 请求代理
* @param options 远程接口信息
* @param reqData 请求内容 req.method== get时一般为空
*/
ProxyAgent.prototype.httpProxy = function (options,reqData){
var _self=this;
var TongjiObj={};
var req = http.request(options, function(res) {
TongjiObj.statusCode = res.statusCode ||500;
var tmptime=Date.now();
TongjiObj.restime = tmptime;
TongjiObj.resEnd =tmptime;
TongjiObj.ends = tmptime;
TongjiObj.length = 0;
TongjiObj.last = tmptime;
var sbuffer=new SBuffer();
res.setEncoding("utf-8");
res.on('data', function (trunk) {
sbuffer.append(trunk);
});
res.on('end', function () {
TongjiObj.resEnd = Date.now();
//doRequestCB(response, {"data":sbuffer.toString(),"status":res.statusCode},TongjiObj,redisOpt);
_self.emmit("onDone",sbuffer,TongjiObj);
});
});
req.setTimeout(timeout,function(){
req.emit('timeOut',{message:'have been timeout...'});
});
req.on('error', function(e) {
TongjiObj.statusCode=500;
_self.emmit("onDone","",500,TongjiObj);
});
req.on('timeOut', function(e) {
req.abort();
TongjiObj.statusCode=500;
TongjiObj.last = Date.now();
_self.emmit("onDone","",500,TongjiObj);
});
req.end(reqData);
}
/**
* 设置缓存
* @param redis_key
* @param redis_time | * @param resultBuffer
*/
ProxyAgent.prototype.setRedis = function (redis_key, redis_time, resultBuffer) {
redis_pool.acquire(function(err, client) {
if (!err) {
client.setex(redis_key, redis_time, resultBuffer, function(err,
repliy) {
redis_pool.release(client); // 链接使用完毕释放链接
});
logger.debug(redis_key + '设置缓存数据成功!');
} else {
writeLogs.logs(Analysis.getLogger('error'), 'error', {
msg : 'redis_general保存数据到redis缓存数据库时链接redis数据库异常',
err : 14
});
logger.debug(redis_key + '设置缓存数据失败!');
}
});
}
/**
* 从缓存中获取数据,如果获取不到,则请求后台返回的数据返回给客户端 并且将返回的数据设置到redis缓存
* redis_key通过self变量中取
* @param options
* @param reqData
*/
ProxyAgent.prototype.getRedis = function ( options, reqData) {
var _self=this;
var redis_key=this.redis.redis_key || "";
redis_pool.acquire(function(err, client) {
if (!err) {
client.get(redis_key, function(err, date) {
redis_pool.release(client) // 用完之后释放链接
if (!err && date != null) {
var resultBuffer = new Buffer(date);
_self.response.statusCode = 200;
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
logger.debug(redis_key + '通用接口下行缓存数据:' + date);
} else {
_self.httpProxy(options, reqData);
}
});
} else {
_self.httpProxy(options, reqData);
}
});
}
/**
* 输出gzip数据
* response 内置
* @param resultBuffer
*/
ProxyAgent.prototype.gzipOutPut = function (resultBuffer){
var _self=this;
zlib.gzip(resultBuffer, function(code, buffer){ // 对服务器返回的数据进行压缩
if (code != null) { // 如果正常结束
logger.debug('压缩成功,压缩前:'+resultBuffer.length+',压缩后:'+buffer.length);
_self.response.setHeader('Content-Encoding', 'gzip'); //压缩标志
} else {
buffer = new Buffer( '{"msg":["服务器返回数据非JSON格式"]}');
_self.response.statusCode=500;
}
_self.response.setHeader("Content-Length", buffer.length);
_self.response.write(buffer);
_self.response.end();
});
}
/**
* 请求完毕处理
* @param buffer type buffer/string
* @param status 请求http状态
* @param tongji object统计对象
*/
ProxyAgent.prototype.onDone =function(buffer,status){
var tongji=arguments[2] ||"";
var _self=this;
var resultStr = typeof(buffer)=="object"?buffer.toString():buffer;
if(this.reqConf.isjson==1){
var resultObj = common.isJson( resultStr, _self.reqConf.logName); // 判断返回结果是否是json格式
if (resultObj) { // 返回结果是json格式
resultStr = JSON.stringify(resultObj);
_self.response.statusCode = status;
} else {
resultStr = '{"msg":["gis服务器返回数据非JSON格式"]}';
_self.response.statusCode = 500;
}
}
else{
_self.response.statusCode = status;
}
var resultBuffer = new Buffer(resultStr);
if(tongji!=""){
tongji.ends = Date.now();
tongji.length = resultBuffer.length;
}
if(resultBuffer.length > 500 ){
//压缩输出
_self.gzipOutPut(resultBuffer);
}else{
_self.response.setHeader("Content-Length", resultBuffer.length);
_self.response.write(resultBuffer); // 以二进制流的方式输出数据
_self.response.end();
}
if(tongji!=""){
tongji.last= Date.now();
tongji=common.extends(tongji,_self.preAnalysisFields);
logger.debug('耗时:' + (tongji.last - tongji.start)+'ms statusCode='+status);
writeLogs.logs(poiDetailServer,'poiDetailServer',obj);
}
});
ProxyAgent.prototype.onDones =function(buffer,status){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
ProxyAgent.prototype.dealDones =function(){
var tongji=arguments[2] ||"";
this.retData.push([buffer,status,tongji];
});
//ProxyAgent 从event 集成
//utils.inherit(ProxyAgent,event);
exports.ProxyAgent=ProxyAgent; | random_line_split | |
char.js | import { Primitive } from './primitive.js';
/**
* A single Unicode character.
* Value type semantics, immutable and final.
*
* The parameter type signatures in this class and file are enforced
* by RacketScript when called from RacketScript.
*
* No checks are performed here, allowing us to use it internally
* without paying the cost of runtime type checking.
*
* @property {!number} codepoint
* @final
*/
export class Char extends Primitive /* implements Printable */ {
/**
* @param {!number} codepoint a non-negative integer.
* @param {(!string|null)} nativeString
* @private
*/
constructor(codepoint, nativeString) {
super();
this.codepoint = codepoint;
this._nativeString = nativeString;
}
/**
* @param {*} v
* @return {!boolean}
*/
equals(v) {
return check(v) && eq(this, v);
}
/**
* @return {true}
*/
isImmutable() {
return true;
}
/**
* @return {!number} this.codepoint.
* @override
*/
valueOf() {
return this.codepoint;
}
/**
* @return {!String}
* @override
*/
| () {
if (this._nativeString === null) {
this._nativeString = String.fromCodePoint(this.codepoint);
}
return this._nativeString;
}
/**
* @return {!number} a non-negative integer.
* @override
*/
hashForEqual() {
return this.codepoint;
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
displayNativeString(out) {
out.consume(this.toString());
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
writeNativeString(out) {
const c = this.codepoint;
switch (c) {
// Reference implementation:
// https://github.com/racket/racket/blob/cbfcc904ab621a338627e77d8f5a34f930ead0ab/racket/src/racket/src/print.c#L4089
case 0:
out.consume('#\\nul');
break;
case 8:
out.consume('#\\backspace');
break;
case 9:
out.consume('#\\tab');
break;
case 10:
out.consume('#\\newline');
break;
case 11:
out.consume('#\\vtab');
break;
case 12:
out.consume('#\\page');
break;
case 13:
out.consume('#\\return');
break;
case 32:
out.consume('#\\space');
break;
case 127:
out.consume('#\\rubout');
break;
default:
if (isGraphic(this)) {
out.consume(`#\\${this.toString()}`);
} else {
out.consume(c > 0xFFFF
? `#\\U${c.toString(16).toUpperCase().padStart(8, '0')}`
: `#\\u${c.toString(16).toUpperCase().padStart(4, '0')}`);
}
}
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
printNativeString(out) {
this.writeNativeString(out);
}
// displayUstring is defined in unicode_string.js to avoid a circular dependency.
/**
* @param {!Ports.UStringOutputPort} out
*/
printUString(out) {
this.writeUString(out);
}
}
const INTERN_CACHE_SIZE = 256;
/**
* @type {!Array<Char|undefined>} A cache for chars with small codepoints.
*/
const internedCache = new Array(INTERN_CACHE_SIZE);
/**
* @param {!number} codepoint a non-negative integer.
* @return {!Char}
*/
export function charFromCodepoint(codepoint) {
if (codepoint < INTERN_CACHE_SIZE) {
if (internedCache[codepoint] === undefined) {
internedCache[codepoint] = new Char(codepoint, null);
}
return internedCache[codepoint];
}
return new Char(codepoint, null);
}
/**
* @param {!string} s A native string exactly one Unicode codepoint long.
*/
export function charFromNativeString(s) {
const codepoint = s.codePointAt(0);
if (codepoint < INTERN_CACHE_SIZE) {
if (internedCache[codepoint] === undefined) {
internedCache[codepoint] = new Char(codepoint, s);
}
return internedCache[codepoint];
}
return new Char(codepoint, s);
}
/**
* @param {*} char
* @return {!boolean}
*/
export function check(char) {
// Because Char is final, we can compare the constructor directly
// instead of using the much slower `instanceof` operator.
return typeof char === 'object' && char !== null &&
char.constructor === Char;
}
// NOTE:
// "The Racket documentation only promises `eq?` for characters with
// scalar values in the range 0 to 255, but Chez Scheme characters
// are always `eq?` when they are `eqv?`."
// see: https://groups.google.com/g/racket-users/c/LFFV-xNq1SU/m/s6eoC35qAgAJ
// https://docs.racket-lang.org/reference/characters.html
/**
* @param {!Char} a
* @param {!Char} b
* @return {!boolean}
*/
export function eq(a, b) {
return a.codepoint === b.codepoint;
}
/**
* @param {!Char} c
* @return {!number} the given character's Unicode codepoint.
*/
export function charToInteger(c) {
return c.codepoint;
}
/**
* @param {!number} k a non-negative integer representing a Unicode codepoint.
* @return {!Char}
*/
export function integerToChar(k) {
return charFromCodepoint(k);
}
/**
* @param {!Char} c
* @return {!number} an integer between 1 and 6 (inclusive).
*/
export function charUtf8Length(c) {
const cp = c.codepoint;
if (cp < 0x80) {
return 1;
} else if (cp < 0x800) {
return 2;
} else if (cp < 0x10000) {
return 3;
} else if (cp < 0x200000) {
return 4;
} else if (cp < 0x4000000) {
return 5;
}
return 6;
}
/**
* @param {!string} str
* @return {!boolean}
*/
function isSingleCodePoint(str) {
return str.length === 1 || (str.length === 2 && str.codePointAt(0) > 0xFFFF);
}
/**
* @param {!Char} c
* @return {!Char}
*/
export function upcase(c) {
const upper = c.toString().toUpperCase();
if (!isSingleCodePoint(upper)) return c;
return charFromNativeString(upper);
}
/**
* @param {!Char} c
* @return {!Char}
*/
export function downcase(c) {
const lower = c.toString().toLowerCase();
if (!isSingleCodePoint(lower)) return c;
return charFromNativeString(lower);
}
// Unicode property testing regexps.
// TODO (Deprecated): We use `new RegExp` because traceur crashes on `/u` RegExp literals.
const IS_ALPHABETIC = new RegExp('\\p{Alphabetic}', 'u');
const IS_LOWER_CASE = new RegExp('\\p{Lowercase}', 'u');
const IS_UPPER_CASE = new RegExp('\\p{Uppercase}', 'u');
const IS_TITLE_CASE = new RegExp('\\p{Lt}', 'u');
// TODO: IS_NUMERIC should use \\p{Numeric_Value},
// but js regexp errs with "Invalid property name".
// Fix this when js regexps become more compliant with unicode standard
// see also:
// - https://stackoverflow.com/questions/5562835/split-and-replace-unicode-words-in-javascript-with-regex
// - https://github.com/vishesh/racketscript/issues/176
const IS_NUMERIC = new RegExp('[\\p{Nd}\\p{Nl}\\p{No}]', 'u');
const IS_SYMBOLIC = new RegExp('\\p{S}', 'u');
const IS_PUNCTUATION = new RegExp('\\p{P}', 'u');
const IS_GRAPHIC = new RegExp('[\\p{L}\\p{N}\\p{M}\\p{S}\\p{P}\\p{Alphabetic}]', 'u');
const IS_WHITESPACE = new RegExp('\\p{White_Space}', 'u');
const IS_BLANK = new RegExp('[\\p{Zs}\\t]', 'u');
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isAlphabetic(c) {
return IS_ALPHABETIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isLowerCase(c) {
return IS_LOWER_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isUpperCase(c) {
return IS_UPPER_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isTitleCase(c) {
return IS_TITLE_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isNumeric(c) {
return IS_NUMERIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isSymbolic(c) {
return IS_SYMBOLIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isPunctuation(c) {
return IS_PUNCTUATION.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isGraphic(c) {
return IS_GRAPHIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isWhitespace(c) {
return IS_WHITESPACE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isBlank(c) {
return IS_BLANK.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isIsoControl(c) {
const cp = c.codepoint;
return (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F);
}
| toString | identifier_name |
char.js | import { Primitive } from './primitive.js';
/**
* A single Unicode character.
* Value type semantics, immutable and final.
*
* The parameter type signatures in this class and file are enforced
* by RacketScript when called from RacketScript.
*
* No checks are performed here, allowing us to use it internally
* without paying the cost of runtime type checking.
*
* @property {!number} codepoint
* @final
*/
export class Char extends Primitive /* implements Printable */ {
/**
* @param {!number} codepoint a non-negative integer.
* @param {(!string|null)} nativeString
* @private
*/
constructor(codepoint, nativeString) {
super();
this.codepoint = codepoint;
this._nativeString = nativeString;
}
/**
* @param {*} v
* @return {!boolean}
*/
equals(v) {
return check(v) && eq(this, v);
}
/**
* @return {true}
*/
isImmutable() {
return true;
}
/**
* @return {!number} this.codepoint.
* @override
*/
valueOf() {
return this.codepoint;
}
/**
* @return {!String}
* @override
*/
toString() {
if (this._nativeString === null) {
this._nativeString = String.fromCodePoint(this.codepoint);
}
return this._nativeString;
}
/**
* @return {!number} a non-negative integer.
* @override
*/
hashForEqual() {
return this.codepoint;
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
displayNativeString(out) {
out.consume(this.toString());
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
writeNativeString(out) {
const c = this.codepoint;
switch (c) {
// Reference implementation:
// https://github.com/racket/racket/blob/cbfcc904ab621a338627e77d8f5a34f930ead0ab/racket/src/racket/src/print.c#L4089
case 0:
out.consume('#\\nul');
break;
case 8:
out.consume('#\\backspace');
break;
case 9:
out.consume('#\\tab');
break;
case 10:
out.consume('#\\newline');
break;
case 11:
out.consume('#\\vtab');
break;
case 12:
out.consume('#\\page');
break;
case 13:
out.consume('#\\return');
break;
case 32:
out.consume('#\\space');
break;
case 127:
out.consume('#\\rubout');
break;
default:
if (isGraphic(this)) {
out.consume(`#\\${this.toString()}`);
} else |
}
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
printNativeString(out) {
this.writeNativeString(out);
}
// displayUstring is defined in unicode_string.js to avoid a circular dependency.
/**
* @param {!Ports.UStringOutputPort} out
*/
printUString(out) {
this.writeUString(out);
}
}
const INTERN_CACHE_SIZE = 256;
/**
* @type {!Array<Char|undefined>} A cache for chars with small codepoints.
*/
const internedCache = new Array(INTERN_CACHE_SIZE);
/**
* @param {!number} codepoint a non-negative integer.
* @return {!Char}
*/
export function charFromCodepoint(codepoint) {
if (codepoint < INTERN_CACHE_SIZE) {
if (internedCache[codepoint] === undefined) {
internedCache[codepoint] = new Char(codepoint, null);
}
return internedCache[codepoint];
}
return new Char(codepoint, null);
}
/**
* @param {!string} s A native string exactly one Unicode codepoint long.
*/
export function charFromNativeString(s) {
const codepoint = s.codePointAt(0);
if (codepoint < INTERN_CACHE_SIZE) {
if (internedCache[codepoint] === undefined) {
internedCache[codepoint] = new Char(codepoint, s);
}
return internedCache[codepoint];
}
return new Char(codepoint, s);
}
/**
* @param {*} char
* @return {!boolean}
*/
export function check(char) {
// Because Char is final, we can compare the constructor directly
// instead of using the much slower `instanceof` operator.
return typeof char === 'object' && char !== null &&
char.constructor === Char;
}
// NOTE:
// "The Racket documentation only promises `eq?` for characters with
// scalar values in the range 0 to 255, but Chez Scheme characters
// are always `eq?` when they are `eqv?`."
// see: https://groups.google.com/g/racket-users/c/LFFV-xNq1SU/m/s6eoC35qAgAJ
// https://docs.racket-lang.org/reference/characters.html
/**
* @param {!Char} a
* @param {!Char} b
* @return {!boolean}
*/
export function eq(a, b) {
return a.codepoint === b.codepoint;
}
/**
* @param {!Char} c
* @return {!number} the given character's Unicode codepoint.
*/
export function charToInteger(c) {
return c.codepoint;
}
/**
* @param {!number} k a non-negative integer representing a Unicode codepoint.
* @return {!Char}
*/
export function integerToChar(k) {
return charFromCodepoint(k);
}
/**
* @param {!Char} c
* @return {!number} an integer between 1 and 6 (inclusive).
*/
export function charUtf8Length(c) {
const cp = c.codepoint;
if (cp < 0x80) {
return 1;
} else if (cp < 0x800) {
return 2;
} else if (cp < 0x10000) {
return 3;
} else if (cp < 0x200000) {
return 4;
} else if (cp < 0x4000000) {
return 5;
}
return 6;
}
/**
* @param {!string} str
* @return {!boolean}
*/
function isSingleCodePoint(str) {
return str.length === 1 || (str.length === 2 && str.codePointAt(0) > 0xFFFF);
}
/**
* @param {!Char} c
* @return {!Char}
*/
export function upcase(c) {
const upper = c.toString().toUpperCase();
if (!isSingleCodePoint(upper)) return c;
return charFromNativeString(upper);
}
/**
* @param {!Char} c
* @return {!Char}
*/
export function downcase(c) {
const lower = c.toString().toLowerCase();
if (!isSingleCodePoint(lower)) return c;
return charFromNativeString(lower);
}
// Unicode property testing regexps.
// TODO (Deprecated): We use `new RegExp` because traceur crashes on `/u` RegExp literals.
const IS_ALPHABETIC = new RegExp('\\p{Alphabetic}', 'u');
const IS_LOWER_CASE = new RegExp('\\p{Lowercase}', 'u');
const IS_UPPER_CASE = new RegExp('\\p{Uppercase}', 'u');
const IS_TITLE_CASE = new RegExp('\\p{Lt}', 'u');
// TODO: IS_NUMERIC should use \\p{Numeric_Value},
// but js regexp errs with "Invalid property name".
// Fix this when js regexps become more compliant with unicode standard
// see also:
// - https://stackoverflow.com/questions/5562835/split-and-replace-unicode-words-in-javascript-with-regex
// - https://github.com/vishesh/racketscript/issues/176
const IS_NUMERIC = new RegExp('[\\p{Nd}\\p{Nl}\\p{No}]', 'u');
const IS_SYMBOLIC = new RegExp('\\p{S}', 'u');
const IS_PUNCTUATION = new RegExp('\\p{P}', 'u');
const IS_GRAPHIC = new RegExp('[\\p{L}\\p{N}\\p{M}\\p{S}\\p{P}\\p{Alphabetic}]', 'u');
const IS_WHITESPACE = new RegExp('\\p{White_Space}', 'u');
const IS_BLANK = new RegExp('[\\p{Zs}\\t]', 'u');
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isAlphabetic(c) {
return IS_ALPHABETIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isLowerCase(c) {
return IS_LOWER_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isUpperCase(c) {
return IS_UPPER_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isTitleCase(c) {
return IS_TITLE_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isNumeric(c) {
return IS_NUMERIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isSymbolic(c) {
return IS_SYMBOLIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isPunctuation(c) {
return IS_PUNCTUATION.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isGraphic(c) {
return IS_GRAPHIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isWhitespace(c) {
return IS_WHITESPACE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isBlank(c) {
return IS_BLANK.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isIsoControl(c) {
const cp = c.codepoint;
return (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F);
}
| {
out.consume(c > 0xFFFF
? `#\\U${c.toString(16).toUpperCase().padStart(8, '0')}`
: `#\\u${c.toString(16).toUpperCase().padStart(4, '0')}`);
} | conditional_block |
char.js | import { Primitive } from './primitive.js';
/**
* A single Unicode character.
* Value type semantics, immutable and final.
*
* The parameter type signatures in this class and file are enforced
* by RacketScript when called from RacketScript.
*
* No checks are performed here, allowing us to use it internally
* without paying the cost of runtime type checking.
*
* @property {!number} codepoint
* @final
*/
export class Char extends Primitive /* implements Printable */ {
/**
* @param {!number} codepoint a non-negative integer.
* @param {(!string|null)} nativeString
* @private
*/
constructor(codepoint, nativeString) {
super();
this.codepoint = codepoint;
this._nativeString = nativeString;
}
/**
* @param {*} v
* @return {!boolean}
*/
equals(v) {
return check(v) && eq(this, v);
}
/**
* @return {true}
*/
isImmutable() {
return true;
}
/**
* @return {!number} this.codepoint.
* @override
*/
valueOf() {
return this.codepoint;
}
/**
* @return {!String}
* @override
*/
toString() {
if (this._nativeString === null) {
this._nativeString = String.fromCodePoint(this.codepoint);
}
return this._nativeString;
}
/**
* @return {!number} a non-negative integer.
* @override
*/
hashForEqual() {
return this.codepoint;
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
displayNativeString(out) {
out.consume(this.toString());
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
writeNativeString(out) {
const c = this.codepoint;
switch (c) {
// Reference implementation:
// https://github.com/racket/racket/blob/cbfcc904ab621a338627e77d8f5a34f930ead0ab/racket/src/racket/src/print.c#L4089
case 0:
out.consume('#\\nul');
break;
case 8:
out.consume('#\\backspace');
break;
case 9:
out.consume('#\\tab');
break;
case 10:
out.consume('#\\newline');
break;
case 11:
out.consume('#\\vtab');
break;
case 12:
out.consume('#\\page');
break;
case 13:
out.consume('#\\return');
break;
case 32:
out.consume('#\\space');
break;
case 127:
out.consume('#\\rubout');
break;
default:
if (isGraphic(this)) {
out.consume(`#\\${this.toString()}`);
} else {
out.consume(c > 0xFFFF
? `#\\U${c.toString(16).toUpperCase().padStart(8, '0')}`
: `#\\u${c.toString(16).toUpperCase().padStart(4, '0')}`);
}
}
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
printNativeString(out) {
this.writeNativeString(out);
}
// displayUstring is defined in unicode_string.js to avoid a circular dependency.
/**
* @param {!Ports.UStringOutputPort} out
*/
printUString(out) {
this.writeUString(out);
}
}
const INTERN_CACHE_SIZE = 256;
/**
* @type {!Array<Char|undefined>} A cache for chars with small codepoints.
*/
const internedCache = new Array(INTERN_CACHE_SIZE);
/**
* @param {!number} codepoint a non-negative integer.
* @return {!Char}
*/
export function charFromCodepoint(codepoint) {
if (codepoint < INTERN_CACHE_SIZE) {
if (internedCache[codepoint] === undefined) {
internedCache[codepoint] = new Char(codepoint, null);
}
return internedCache[codepoint];
}
return new Char(codepoint, null);
}
/**
* @param {!string} s A native string exactly one Unicode codepoint long.
*/
export function charFromNativeString(s) {
const codepoint = s.codePointAt(0);
if (codepoint < INTERN_CACHE_SIZE) {
if (internedCache[codepoint] === undefined) {
internedCache[codepoint] = new Char(codepoint, s);
}
return internedCache[codepoint];
}
return new Char(codepoint, s);
}
/**
* @param {*} char
* @return {!boolean}
*/
export function check(char) {
// Because Char is final, we can compare the constructor directly
// instead of using the much slower `instanceof` operator.
return typeof char === 'object' && char !== null &&
char.constructor === Char;
}
// NOTE:
// "The Racket documentation only promises `eq?` for characters with
// scalar values in the range 0 to 255, but Chez Scheme characters
// are always `eq?` when they are `eqv?`."
// see: https://groups.google.com/g/racket-users/c/LFFV-xNq1SU/m/s6eoC35qAgAJ
// https://docs.racket-lang.org/reference/characters.html
/**
* @param {!Char} a
* @param {!Char} b
* @return {!boolean}
*/
export function eq(a, b) {
return a.codepoint === b.codepoint;
}
/**
* @param {!Char} c
* @return {!number} the given character's Unicode codepoint.
*/
export function charToInteger(c) {
return c.codepoint;
}
/**
* @param {!number} k a non-negative integer representing a Unicode codepoint.
* @return {!Char}
*/
export function integerToChar(k) {
return charFromCodepoint(k);
}
/**
* @param {!Char} c
* @return {!number} an integer between 1 and 6 (inclusive).
*/
export function charUtf8Length(c) {
const cp = c.codepoint;
if (cp < 0x80) {
return 1;
} else if (cp < 0x800) {
return 2;
} else if (cp < 0x10000) {
return 3;
} else if (cp < 0x200000) {
return 4;
} else if (cp < 0x4000000) {
return 5;
}
return 6;
}
/**
* @param {!string} str
* @return {!boolean}
*/
function isSingleCodePoint(str) {
return str.length === 1 || (str.length === 2 && str.codePointAt(0) > 0xFFFF);
}
/**
* @param {!Char} c
* @return {!Char}
*/
export function upcase(c) {
const upper = c.toString().toUpperCase();
if (!isSingleCodePoint(upper)) return c;
return charFromNativeString(upper);
}
/**
* @param {!Char} c
* @return {!Char}
*/
export function downcase(c) {
const lower = c.toString().toLowerCase();
if (!isSingleCodePoint(lower)) return c;
return charFromNativeString(lower);
}
// Unicode property testing regexps.
// TODO (Deprecated): We use `new RegExp` because traceur crashes on `/u` RegExp literals.
const IS_ALPHABETIC = new RegExp('\\p{Alphabetic}', 'u');
const IS_LOWER_CASE = new RegExp('\\p{Lowercase}', 'u');
const IS_UPPER_CASE = new RegExp('\\p{Uppercase}', 'u');
const IS_TITLE_CASE = new RegExp('\\p{Lt}', 'u');
// TODO: IS_NUMERIC should use \\p{Numeric_Value},
// but js regexp errs with "Invalid property name".
// Fix this when js regexps become more compliant with unicode standard
// see also:
// - https://stackoverflow.com/questions/5562835/split-and-replace-unicode-words-in-javascript-with-regex
// - https://github.com/vishesh/racketscript/issues/176
const IS_NUMERIC = new RegExp('[\\p{Nd}\\p{Nl}\\p{No}]', 'u');
const IS_SYMBOLIC = new RegExp('\\p{S}', 'u');
const IS_PUNCTUATION = new RegExp('\\p{P}', 'u');
const IS_GRAPHIC = new RegExp('[\\p{L}\\p{N}\\p{M}\\p{S}\\p{P}\\p{Alphabetic}]', 'u');
const IS_WHITESPACE = new RegExp('\\p{White_Space}', 'u');
const IS_BLANK = new RegExp('[\\p{Zs}\\t]', 'u');
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isAlphabetic(c) {
return IS_ALPHABETIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isLowerCase(c) {
return IS_LOWER_CASE.test(c.toString());
}
/** | */
export function isUpperCase(c) {
return IS_UPPER_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isTitleCase(c) {
return IS_TITLE_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isNumeric(c) {
return IS_NUMERIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isSymbolic(c) {
return IS_SYMBOLIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isPunctuation(c) {
return IS_PUNCTUATION.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isGraphic(c) {
return IS_GRAPHIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isWhitespace(c) {
return IS_WHITESPACE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isBlank(c) {
return IS_BLANK.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isIsoControl(c) {
const cp = c.codepoint;
return (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F);
} | * @param {!Char} c
* @return {!boolean} | random_line_split |
char.js | import { Primitive } from './primitive.js';
/**
* A single Unicode character.
* Value type semantics, immutable and final.
*
* The parameter type signatures in this class and file are enforced
* by RacketScript when called from RacketScript.
*
* No checks are performed here, allowing us to use it internally
* without paying the cost of runtime type checking.
*
* @property {!number} codepoint
* @final
*/
export class Char extends Primitive /* implements Printable */ {
/**
* @param {!number} codepoint a non-negative integer.
* @param {(!string|null)} nativeString
* @private
*/
constructor(codepoint, nativeString) {
super();
this.codepoint = codepoint;
this._nativeString = nativeString;
}
/**
* @param {*} v
* @return {!boolean}
*/
equals(v) {
return check(v) && eq(this, v);
}
/**
* @return {true}
*/
isImmutable() {
return true;
}
/**
* @return {!number} this.codepoint.
* @override
*/
valueOf() {
return this.codepoint;
}
/**
* @return {!String}
* @override
*/
toString() {
if (this._nativeString === null) {
this._nativeString = String.fromCodePoint(this.codepoint);
}
return this._nativeString;
}
/**
* @return {!number} a non-negative integer.
* @override
*/
hashForEqual() {
return this.codepoint;
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
displayNativeString(out) {
out.consume(this.toString());
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
writeNativeString(out) {
const c = this.codepoint;
switch (c) {
// Reference implementation:
// https://github.com/racket/racket/blob/cbfcc904ab621a338627e77d8f5a34f930ead0ab/racket/src/racket/src/print.c#L4089
case 0:
out.consume('#\\nul');
break;
case 8:
out.consume('#\\backspace');
break;
case 9:
out.consume('#\\tab');
break;
case 10:
out.consume('#\\newline');
break;
case 11:
out.consume('#\\vtab');
break;
case 12:
out.consume('#\\page');
break;
case 13:
out.consume('#\\return');
break;
case 32:
out.consume('#\\space');
break;
case 127:
out.consume('#\\rubout');
break;
default:
if (isGraphic(this)) {
out.consume(`#\\${this.toString()}`);
} else {
out.consume(c > 0xFFFF
? `#\\U${c.toString(16).toUpperCase().padStart(8, '0')}`
: `#\\u${c.toString(16).toUpperCase().padStart(4, '0')}`);
}
}
}
/**
* @param {!Ports.NativeStringOutputPort} out
*/
printNativeString(out) {
this.writeNativeString(out);
}
// displayUstring is defined in unicode_string.js to avoid a circular dependency.
/**
* @param {!Ports.UStringOutputPort} out
*/
printUString(out) {
this.writeUString(out);
}
}
const INTERN_CACHE_SIZE = 256;
/**
* @type {!Array<Char|undefined>} A cache for chars with small codepoints.
*/
const internedCache = new Array(INTERN_CACHE_SIZE);
/**
* @param {!number} codepoint a non-negative integer.
* @return {!Char}
*/
export function charFromCodepoint(codepoint) {
if (codepoint < INTERN_CACHE_SIZE) {
if (internedCache[codepoint] === undefined) {
internedCache[codepoint] = new Char(codepoint, null);
}
return internedCache[codepoint];
}
return new Char(codepoint, null);
}
/**
* @param {!string} s A native string exactly one Unicode codepoint long.
*/
export function charFromNativeString(s) {
const codepoint = s.codePointAt(0);
if (codepoint < INTERN_CACHE_SIZE) {
if (internedCache[codepoint] === undefined) {
internedCache[codepoint] = new Char(codepoint, s);
}
return internedCache[codepoint];
}
return new Char(codepoint, s);
}
/**
* @param {*} char
* @return {!boolean}
*/
export function check(char) {
// Because Char is final, we can compare the constructor directly
// instead of using the much slower `instanceof` operator.
return typeof char === 'object' && char !== null &&
char.constructor === Char;
}
// NOTE:
// "The Racket documentation only promises `eq?` for characters with
// scalar values in the range 0 to 255, but Chez Scheme characters
// are always `eq?` when they are `eqv?`."
// see: https://groups.google.com/g/racket-users/c/LFFV-xNq1SU/m/s6eoC35qAgAJ
// https://docs.racket-lang.org/reference/characters.html
/**
* @param {!Char} a
* @param {!Char} b
* @return {!boolean}
*/
export function eq(a, b) {
return a.codepoint === b.codepoint;
}
/**
* @param {!Char} c
* @return {!number} the given character's Unicode codepoint.
*/
export function charToInteger(c) {
return c.codepoint;
}
/**
* @param {!number} k a non-negative integer representing a Unicode codepoint.
* @return {!Char}
*/
export function integerToChar(k) {
return charFromCodepoint(k);
}
/**
* @param {!Char} c
* @return {!number} an integer between 1 and 6 (inclusive).
*/
export function charUtf8Length(c) {
const cp = c.codepoint;
if (cp < 0x80) {
return 1;
} else if (cp < 0x800) {
return 2;
} else if (cp < 0x10000) {
return 3;
} else if (cp < 0x200000) {
return 4;
} else if (cp < 0x4000000) {
return 5;
}
return 6;
}
/**
* @param {!string} str
* @return {!boolean}
*/
function isSingleCodePoint(str) |
/**
* @param {!Char} c
* @return {!Char}
*/
export function upcase(c) {
const upper = c.toString().toUpperCase();
if (!isSingleCodePoint(upper)) return c;
return charFromNativeString(upper);
}
/**
* @param {!Char} c
* @return {!Char}
*/
export function downcase(c) {
const lower = c.toString().toLowerCase();
if (!isSingleCodePoint(lower)) return c;
return charFromNativeString(lower);
}
// Unicode property testing regexps.
// TODO (Deprecated): We use `new RegExp` because traceur crashes on `/u` RegExp literals.
const IS_ALPHABETIC = new RegExp('\\p{Alphabetic}', 'u');
const IS_LOWER_CASE = new RegExp('\\p{Lowercase}', 'u');
const IS_UPPER_CASE = new RegExp('\\p{Uppercase}', 'u');
const IS_TITLE_CASE = new RegExp('\\p{Lt}', 'u');
// TODO: IS_NUMERIC should use \\p{Numeric_Value},
// but js regexp errs with "Invalid property name".
// Fix this when js regexps become more compliant with unicode standard
// see also:
// - https://stackoverflow.com/questions/5562835/split-and-replace-unicode-words-in-javascript-with-regex
// - https://github.com/vishesh/racketscript/issues/176
const IS_NUMERIC = new RegExp('[\\p{Nd}\\p{Nl}\\p{No}]', 'u');
const IS_SYMBOLIC = new RegExp('\\p{S}', 'u');
const IS_PUNCTUATION = new RegExp('\\p{P}', 'u');
const IS_GRAPHIC = new RegExp('[\\p{L}\\p{N}\\p{M}\\p{S}\\p{P}\\p{Alphabetic}]', 'u');
const IS_WHITESPACE = new RegExp('\\p{White_Space}', 'u');
const IS_BLANK = new RegExp('[\\p{Zs}\\t]', 'u');
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isAlphabetic(c) {
return IS_ALPHABETIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isLowerCase(c) {
return IS_LOWER_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isUpperCase(c) {
return IS_UPPER_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isTitleCase(c) {
return IS_TITLE_CASE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isNumeric(c) {
return IS_NUMERIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isSymbolic(c) {
return IS_SYMBOLIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isPunctuation(c) {
return IS_PUNCTUATION.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isGraphic(c) {
return IS_GRAPHIC.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isWhitespace(c) {
return IS_WHITESPACE.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isBlank(c) {
return IS_BLANK.test(c.toString());
}
/**
* @param {!Char} c
* @return {!boolean}
*/
export function isIsoControl(c) {
const cp = c.codepoint;
return (cp >= 0 && cp <= 0x1F) || (cp >= 0x7F && cp <= 0x9F);
}
| {
return str.length === 1 || (str.length === 2 && str.codePointAt(0) > 0xFFFF);
} | identifier_body |
interrupt_pause_script.py | #!/usr/bin/python
from __future__ import print_function | #GPIO pins
Taster1 = 24
Taster2 = 27
# GPIO-Nummer als Pinreferenz waehlen
GPIO.setmode(GPIO.BCM)
# GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren
#PULL = GPIO.PUD_DOWN #GPIO -> GND
PULL = GPIO.PUD_UP #GPIO -> 3V3
GPIO.setup(Taster1, GPIO.IN, pull_up_down=PULL)
GPIO.setup(Taster2, GPIO.IN, pull_up_down=PULL)
# Dictionary definieren. http://www.tutorialspoint.com/python/python_dictionary.htm
dictionary = {}
dictionary['pause'] = False
queue = Queue.Queue()
# Script pausieren/blockieren/beschaeftigen
def Pause():
while dictionary['pause'] == True:
time.sleep(1)
# ISR
def interrupt_event(pin):
if pin == Taster1:
queue.put(pin)
if pin == Taster2:
print("Führe Script weiter aus")
dictionary['pause'] = False
try:
# Interrupt Event hinzufuegen. Auf steigende Flanke reagieren und ISR "Interrupt" deklarieren sowie Pin entprellen
GPIO.add_event_detect(Taster1, GPIO.RISING, callback=interrupt_event, bouncetime=200)
GPIO.add_event_detect(Taster2, GPIO.RISING, callback=interrupt_event, bouncetime=200)
# keep script running
while True:
time.sleep(0.5)
if not queue.empty():
job = queue.get()
if job == Taster1:
print("Pausiere Script")
dictionary['pause'] = True
Pause()
print("...puh... Im super heavy busy...")
except (KeyboardInterrupt, SystemExit):
GPIO.cleanup()
print("\nQuit\n") | import RPi.GPIO as GPIO
import time
import Queue # https://pymotw.com/2/Queue/
| random_line_split |
interrupt_pause_script.py | #!/usr/bin/python
from __future__ import print_function
import RPi.GPIO as GPIO
import time
import Queue # https://pymotw.com/2/Queue/
#GPIO pins
Taster1 = 24
Taster2 = 27
# GPIO-Nummer als Pinreferenz waehlen
GPIO.setmode(GPIO.BCM)
# GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren
#PULL = GPIO.PUD_DOWN #GPIO -> GND
PULL = GPIO.PUD_UP #GPIO -> 3V3
GPIO.setup(Taster1, GPIO.IN, pull_up_down=PULL)
GPIO.setup(Taster2, GPIO.IN, pull_up_down=PULL)
# Dictionary definieren. http://www.tutorialspoint.com/python/python_dictionary.htm
dictionary = {}
dictionary['pause'] = False
queue = Queue.Queue()
# Script pausieren/blockieren/beschaeftigen
def Pause():
|
# ISR
def interrupt_event(pin):
if pin == Taster1:
queue.put(pin)
if pin == Taster2:
print("Führe Script weiter aus")
dictionary['pause'] = False
try:
# Interrupt Event hinzufuegen. Auf steigende Flanke reagieren und ISR "Interrupt" deklarieren sowie Pin entprellen
GPIO.add_event_detect(Taster1, GPIO.RISING, callback=interrupt_event, bouncetime=200)
GPIO.add_event_detect(Taster2, GPIO.RISING, callback=interrupt_event, bouncetime=200)
# keep script running
while True:
time.sleep(0.5)
if not queue.empty():
job = queue.get()
if job == Taster1:
print("Pausiere Script")
dictionary['pause'] = True
Pause()
print("...puh... Im super heavy busy...")
except (KeyboardInterrupt, SystemExit):
GPIO.cleanup()
print("\nQuit\n") | while dictionary['pause'] == True:
time.sleep(1) | identifier_body |
interrupt_pause_script.py | #!/usr/bin/python
from __future__ import print_function
import RPi.GPIO as GPIO
import time
import Queue # https://pymotw.com/2/Queue/
#GPIO pins
Taster1 = 24
Taster2 = 27
# GPIO-Nummer als Pinreferenz waehlen
GPIO.setmode(GPIO.BCM)
# GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren
#PULL = GPIO.PUD_DOWN #GPIO -> GND
PULL = GPIO.PUD_UP #GPIO -> 3V3
GPIO.setup(Taster1, GPIO.IN, pull_up_down=PULL)
GPIO.setup(Taster2, GPIO.IN, pull_up_down=PULL)
# Dictionary definieren. http://www.tutorialspoint.com/python/python_dictionary.htm
dictionary = {}
dictionary['pause'] = False
queue = Queue.Queue()
# Script pausieren/blockieren/beschaeftigen
def Pause():
while dictionary['pause'] == True:
|
# ISR
def interrupt_event(pin):
if pin == Taster1:
queue.put(pin)
if pin == Taster2:
print("Führe Script weiter aus")
dictionary['pause'] = False
try:
# Interrupt Event hinzufuegen. Auf steigende Flanke reagieren und ISR "Interrupt" deklarieren sowie Pin entprellen
GPIO.add_event_detect(Taster1, GPIO.RISING, callback=interrupt_event, bouncetime=200)
GPIO.add_event_detect(Taster2, GPIO.RISING, callback=interrupt_event, bouncetime=200)
# keep script running
while True:
time.sleep(0.5)
if not queue.empty():
job = queue.get()
if job == Taster1:
print("Pausiere Script")
dictionary['pause'] = True
Pause()
print("...puh... Im super heavy busy...")
except (KeyboardInterrupt, SystemExit):
GPIO.cleanup()
print("\nQuit\n") | time.sleep(1) | conditional_block |
interrupt_pause_script.py | #!/usr/bin/python
from __future__ import print_function
import RPi.GPIO as GPIO
import time
import Queue # https://pymotw.com/2/Queue/
#GPIO pins
Taster1 = 24
Taster2 = 27
# GPIO-Nummer als Pinreferenz waehlen
GPIO.setmode(GPIO.BCM)
# GPIO vom SoC als Input deklarieren und Pull-Down Widerstand aktivieren
#PULL = GPIO.PUD_DOWN #GPIO -> GND
PULL = GPIO.PUD_UP #GPIO -> 3V3
GPIO.setup(Taster1, GPIO.IN, pull_up_down=PULL)
GPIO.setup(Taster2, GPIO.IN, pull_up_down=PULL)
# Dictionary definieren. http://www.tutorialspoint.com/python/python_dictionary.htm
dictionary = {}
dictionary['pause'] = False
queue = Queue.Queue()
# Script pausieren/blockieren/beschaeftigen
def Pause():
while dictionary['pause'] == True:
time.sleep(1)
# ISR
def | (pin):
if pin == Taster1:
queue.put(pin)
if pin == Taster2:
print("Führe Script weiter aus")
dictionary['pause'] = False
try:
# Interrupt Event hinzufuegen. Auf steigende Flanke reagieren und ISR "Interrupt" deklarieren sowie Pin entprellen
GPIO.add_event_detect(Taster1, GPIO.RISING, callback=interrupt_event, bouncetime=200)
GPIO.add_event_detect(Taster2, GPIO.RISING, callback=interrupt_event, bouncetime=200)
# keep script running
while True:
time.sleep(0.5)
if not queue.empty():
job = queue.get()
if job == Taster1:
print("Pausiere Script")
dictionary['pause'] = True
Pause()
print("...puh... Im super heavy busy...")
except (KeyboardInterrupt, SystemExit):
GPIO.cleanup()
print("\nQuit\n") | interrupt_event | identifier_name |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2019 The Stdlib Authors.
*
* 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.
*/
// TypeScript Version: 2.0
/**
* Returns an array of an object's own and inherited enumerable property names.
*
* ## Notes
*
* - Name order is not guaranteed, as object key enumeration is not specified according to the ECMAScript specification. In practice, however, most engines use insertion order to sort an object's keys, thus allowing for deterministic extraction.
*
* @param obj - input value
* @returns key array
*
* @example
* function Foo() {
* this.beep = 'boop';
* return this;
* }
*
* Foo.prototype.foo = 'bar';
*
* var obj = new Foo();
*
* var keys = keysIn( obj );
* // e.g., returns [ 'beep', 'foo' ]
*/
declare function keysIn( obj: any ): Array<string>;
|
// EXPORTS //
export = keysIn; | random_line_split | |
search-notifications.js | /*jslint browser */
/*globals window, settings, searchTerm, locales, pageLanguage, getQueryVariable */
// display a 'Searching' progress placeholder
function ebSearchShowSearchingNotice() {
'use strict';
var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder');
if (searchProgressPlaceholder) {
searchProgressPlaceholder.classList.remove('visuallyhidden');
} else {
searchProgressPlaceholder = document.createElement('div');
searchProgressPlaceholder.classList.add('search-progress-placeholder');
searchProgressPlaceholder.innerHTML = '<p>' + locales[pageLanguage].search['placeholder-searching'] + '</p>';
var searchForm = document.querySelector("form.search");
searchForm.insertAdjacentElement('afterend', searchProgressPlaceholder);
}
}
// Hide the search-progress placeholder
function ebSearchHideSearchingNotice() {
'use strict';
var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder');
if (searchProgressPlaceholder) |
}
// Load the search index and the script for showing results.
// We load these here so that they don't block the main thread.
// This does not seem to work in file:///'s, only on a webserver.
function ebSearchLoadIndexAndResults() {
'use strict';
[
'assets/js/search-index-' + settings.site.output + '.js',
'assets/js/search-results.js'
].forEach(function (src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.body.appendChild(script);
});
}
// Check whether the index has loaded
var ebSearchCheckForResultsLoad;
function ebSearchWaitingForResults() {
'use strict';
var results = document.getElementById('search-results');
if (results !== null) {
ebSearchHideSearchingNotice();
window.clearInterval(ebSearchCheckForResultsLoad);
} else {
ebSearchShowSearchingNotice();
}
}
function ebSearchResultsProcess() {
'use strict';
ebSearchCheckForResultsLoad = window.setInterval(ebSearchWaitingForResults, 500);
// Let notification show before loading index and results
window.setTimeout(
ebSearchLoadIndexAndResults,
500
);
}
function ebSearchCheckForSearchString() {
'use strict';
var query = getQueryVariable('query');
if (query && query !== '') {
ebSearchResultsProcess();
}
}
ebSearchCheckForSearchString();
| {
searchProgressPlaceholder.classList.add('visuallyhidden');
} | conditional_block |
search-notifications.js | /*jslint browser */
/*globals window, settings, searchTerm, locales, pageLanguage, getQueryVariable */
// display a 'Searching' progress placeholder
function ebSearchShowSearchingNotice() {
'use strict';
var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder');
if (searchProgressPlaceholder) {
searchProgressPlaceholder.classList.remove('visuallyhidden');
} else {
searchProgressPlaceholder = document.createElement('div');
searchProgressPlaceholder.classList.add('search-progress-placeholder');
searchProgressPlaceholder.innerHTML = '<p>' + locales[pageLanguage].search['placeholder-searching'] + '</p>';
var searchForm = document.querySelector("form.search");
searchForm.insertAdjacentElement('afterend', searchProgressPlaceholder);
}
}
// Hide the search-progress placeholder
function ebSearchHideSearchingNotice() {
'use strict';
var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder');
if (searchProgressPlaceholder) {
searchProgressPlaceholder.classList.add('visuallyhidden');
}
}
// Load the search index and the script for showing results.
// We load these here so that they don't block the main thread.
// This does not seem to work in file:///'s, only on a webserver.
function ebSearchLoadIndexAndResults() {
'use strict';
[
'assets/js/search-index-' + settings.site.output + '.js',
'assets/js/search-results.js'
].forEach(function (src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.body.appendChild(script);
});
}
// Check whether the index has loaded
var ebSearchCheckForResultsLoad;
function ebSearchWaitingForResults() {
'use strict';
var results = document.getElementById('search-results');
if (results !== null) {
ebSearchHideSearchingNotice();
window.clearInterval(ebSearchCheckForResultsLoad);
} else {
ebSearchShowSearchingNotice();
}
}
function ebSearchResultsProcess() {
'use strict';
ebSearchCheckForResultsLoad = window.setInterval(ebSearchWaitingForResults, 500);
// Let notification show before loading index and results
window.setTimeout(
ebSearchLoadIndexAndResults,
500
);
}
function | () {
'use strict';
var query = getQueryVariable('query');
if (query && query !== '') {
ebSearchResultsProcess();
}
}
ebSearchCheckForSearchString();
| ebSearchCheckForSearchString | identifier_name |
search-notifications.js | /*jslint browser */
/*globals window, settings, searchTerm, locales, pageLanguage, getQueryVariable */
// display a 'Searching' progress placeholder
function ebSearchShowSearchingNotice() {
'use strict';
var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder');
if (searchProgressPlaceholder) {
searchProgressPlaceholder.classList.remove('visuallyhidden');
} else {
searchProgressPlaceholder = document.createElement('div');
searchProgressPlaceholder.classList.add('search-progress-placeholder'); |
// Hide the search-progress placeholder
function ebSearchHideSearchingNotice() {
'use strict';
var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder');
if (searchProgressPlaceholder) {
searchProgressPlaceholder.classList.add('visuallyhidden');
}
}
// Load the search index and the script for showing results.
// We load these here so that they don't block the main thread.
// This does not seem to work in file:///'s, only on a webserver.
function ebSearchLoadIndexAndResults() {
'use strict';
[
'assets/js/search-index-' + settings.site.output + '.js',
'assets/js/search-results.js'
].forEach(function (src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.body.appendChild(script);
});
}
// Check whether the index has loaded
var ebSearchCheckForResultsLoad;
function ebSearchWaitingForResults() {
'use strict';
var results = document.getElementById('search-results');
if (results !== null) {
ebSearchHideSearchingNotice();
window.clearInterval(ebSearchCheckForResultsLoad);
} else {
ebSearchShowSearchingNotice();
}
}
function ebSearchResultsProcess() {
'use strict';
ebSearchCheckForResultsLoad = window.setInterval(ebSearchWaitingForResults, 500);
// Let notification show before loading index and results
window.setTimeout(
ebSearchLoadIndexAndResults,
500
);
}
function ebSearchCheckForSearchString() {
'use strict';
var query = getQueryVariable('query');
if (query && query !== '') {
ebSearchResultsProcess();
}
}
ebSearchCheckForSearchString(); | searchProgressPlaceholder.innerHTML = '<p>' + locales[pageLanguage].search['placeholder-searching'] + '</p>';
var searchForm = document.querySelector("form.search");
searchForm.insertAdjacentElement('afterend', searchProgressPlaceholder);
}
} | random_line_split |
search-notifications.js | /*jslint browser */
/*globals window, settings, searchTerm, locales, pageLanguage, getQueryVariable */
// display a 'Searching' progress placeholder
function ebSearchShowSearchingNotice() |
// Hide the search-progress placeholder
function ebSearchHideSearchingNotice() {
'use strict';
var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder');
if (searchProgressPlaceholder) {
searchProgressPlaceholder.classList.add('visuallyhidden');
}
}
// Load the search index and the script for showing results.
// We load these here so that they don't block the main thread.
// This does not seem to work in file:///'s, only on a webserver.
function ebSearchLoadIndexAndResults() {
'use strict';
[
'assets/js/search-index-' + settings.site.output + '.js',
'assets/js/search-results.js'
].forEach(function (src) {
var script = document.createElement('script');
script.src = src;
script.async = false;
document.body.appendChild(script);
});
}
// Check whether the index has loaded
var ebSearchCheckForResultsLoad;
function ebSearchWaitingForResults() {
'use strict';
var results = document.getElementById('search-results');
if (results !== null) {
ebSearchHideSearchingNotice();
window.clearInterval(ebSearchCheckForResultsLoad);
} else {
ebSearchShowSearchingNotice();
}
}
function ebSearchResultsProcess() {
'use strict';
ebSearchCheckForResultsLoad = window.setInterval(ebSearchWaitingForResults, 500);
// Let notification show before loading index and results
window.setTimeout(
ebSearchLoadIndexAndResults,
500
);
}
function ebSearchCheckForSearchString() {
'use strict';
var query = getQueryVariable('query');
if (query && query !== '') {
ebSearchResultsProcess();
}
}
ebSearchCheckForSearchString();
| {
'use strict';
var searchProgressPlaceholder = document.querySelector('.search-progress-placeholder');
if (searchProgressPlaceholder) {
searchProgressPlaceholder.classList.remove('visuallyhidden');
} else {
searchProgressPlaceholder = document.createElement('div');
searchProgressPlaceholder.classList.add('search-progress-placeholder');
searchProgressPlaceholder.innerHTML = '<p>' + locales[pageLanguage].search['placeholder-searching'] + '</p>';
var searchForm = document.querySelector("form.search");
searchForm.insertAdjacentElement('afterend', searchProgressPlaceholder);
}
} | identifier_body |
magnific.js | // Inline popups
$('#inline-popups').magnificPopup({
delegate: 'a',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
beforeOpen: function() {
this.st.mainClass = this.st.el.attr('data-effect');
}
},
midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
});
| // Image popups
$('.lightbox').magnificPopup({
// delegate: 'a',
type: 'image',
mainClass: 'mfp-3d-unfold',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
beforeOpen: function() {
// just a hack that adds mfp-anim class to markup
this.st.image.markup = this.st.image.markup.replace('mfp-figure', 'mfp-figure mfp-with-anim');
// this.st.mainClass = this.st.el.attr('data-effect');
}
},
closeOnContentClick: true,
midClick: true // allow opening popup on middle mouse click. Always set it to true if you don't provide alternative source.
});
// Hinge effect popup
$('a.hinge').magnificPopup({
mainClass: 'mfp-with-fade',
removalDelay: 1000, //delay removal by X to allow out-animation
callbacks: {
beforeClose: function() {
this.content.addClass('hinge');
},
close: function() {
this.content.removeClass('hinge');
}
},
midClick: true
});
//GALERY
$(document).ready(function() {
$('.popup-gallery').magnificPopup({
delegate: 'a',
type: 'image',
tLoading: 'Loading image #%curr%...',
mainClass: 'mfp-3d-unfold',
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
beforeOpen: function() {
// just a hack that adds mfp-anim class to markup
this.st.image.markup = this.st.image.markup.replace('mfp-figure', 'mfp-figure mfp-with-anim');
// this.st.mainClass = this.st.el.attr('data-effect');
}
},
gallery: {
enabled: true,
navigateByImgClick: true,
preload: [0,1] // Will preload 0 - before current, and 1 after the current image
},
image: {
tError: '<a href="%url%">The image #%curr%</a> could not be loaded.',
titleSrc: function(item) {
return item.el.attr('title') + '<small>by Marsel Van Oosten</small>';
}
}
});
});
// VIDEO GMAPS POPUP
$(document).ready(function() {
$('.popup-youtube, .popup-vimeo, .popup-gmaps').magnificPopup({
disableOn: 700,
type: 'iframe',
mainClass: 'mfp-fade',
removalDelay: 160,
preloader: false,
fixedContentPos: false
});
}); | random_line_split | |
webpack.config.js | /*
to package
"eslint": "^1.7.3",
"eslint-config-rackt": "^1.1.0",
"eslint-plugin-react": "^3.6.3",
*/
require('es6-promise').polyfill(); // old node 0.10
var path = require('path');
var webpack = require('webpack');
module.exports = {
externals: {
jquery: "jQuery",
autobahn: "autobahn"
},
plugins: [
// new webpack.optimize.UglifyJsPlugin({minimize: true}),
new webpack.optimize.CommonsChunkPlugin(
/* chunkName= */'vendor',
/* filename= */'vendor.js'
),
/* new webpack.ProvidePlugin({ // If you use "_", underscore is automatically required | "$": "jquery",
"_": "underscore",
}) */
],
resolve: {
alias: {
"lodash": path.resolve("./node_modules/lodash"),
"react": path.resolve("./node_modules/react/react.js"),
"react-dom": path.resolve("./node_modules/react/lib/ReactDOM.js"),
"react-router": path.resolve("./node_modules/react-router"),
"reflux": path.resolve("./node_modules/reflux/src/index.js"),
"object-assign":path.resolve("./node_modules/object-assign/index.js"),
}
},
entry: {
// demoshop: [
// './demoshop/app.js'
// ],
// employee: [
// 'employee/views/contact.js'
// ],
navbar: [
'./navbar/app.js'
],
vendor: [
'lodash',
'react',
'react-dom',
'reflux',
'object-assign'
]
},
output: {
path: 'www/app',
filename: '[name].js',
publicPath: '/app/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015', 'stage-0', 'react']
}
},
{ test: /\.css$/, loader: 'style!css' },
{ test: /\.jpg$/, loader: "file-loader" },
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }
]
},
// devtool: 'source-map',
devtool: 'inline-source-map',
// scripts: {
// watch: "webpack --watch -d --display-error-details"
// }
}; | random_line_split | |
Button.js | /**
* @file san-mui/Button
* @author leon <ludafa@outlook.com>
*/
import {create} from '../common/util/cx';
import {TouchRipple} from '../Ripple';
import BaseButton from './Base';
import {DataTypes} from 'san';
const cx = create('button');
export default class Button extends BaseButton {
static components = {
'san-touch-ripple': TouchRipple
};
static template = `
<button
on-click="click($event)"
type="{{type}}"
class="{{computedClassName}}"
disabled="{{disabled}}">
<slot />
<san-touch-ripple san-if="!disabled" />
</button>
`;
static computed = {
| () {
return cx(this).build();
}
};
static dataTypes = {
type: DataTypes.string,
disabled: DataTypes.bool
};
initData() {
return {
type: 'button',
disabled: false
};
};
attached() {
// save the original href into originalHref and change current href according to disabled
if (this.data.get('href')) {
this.data.set('originalHref', this.data.get('href'));
if (this.data.get('disabled')) {
this.setHref('javascript:void(0);');
}
}
this.watch('disabled', val => {
if (val) {
this.setHref('javascript:void(0);');
return;
}
this.setHref(this.data.get('originalHref'));
});
};
setHref(hrefVal) {
this.data.set('href', hrefVal);
}
click(e) {
if (!this.data.get('disabled')) {
this.fire('click', e);
}
}
}
| computedClassName | identifier_name |
Button.js | /**
* @file san-mui/Button
* @author leon <ludafa@outlook.com>
*/
import {create} from '../common/util/cx';
import {TouchRipple} from '../Ripple';
import BaseButton from './Base';
import {DataTypes} from 'san';
const cx = create('button');
export default class Button extends BaseButton {
static components = {
'san-touch-ripple': TouchRipple
};
static template = `
<button
on-click="click($event)"
type="{{type}}"
class="{{computedClassName}}"
disabled="{{disabled}}">
<slot />
<san-touch-ripple san-if="!disabled" />
</button>
`;
static computed = {
computedClassName() {
return cx(this).build();
}
};
static dataTypes = {
type: DataTypes.string,
disabled: DataTypes.bool
};
initData() {
return {
type: 'button',
disabled: false
};
};
attached() {
// save the original href into originalHref and change current href according to disabled
if (this.data.get('href')) {
this.data.set('originalHref', this.data.get('href'));
if (this.data.get('disabled')) {
this.setHref('javascript:void(0);');
}
}
this.watch('disabled', val => {
if (val) {
this.setHref('javascript:void(0);');
return;
}
this.setHref(this.data.get('originalHref'));
});
};
setHref(hrefVal) {
this.data.set('href', hrefVal);
}
click(e) |
}
| {
if (!this.data.get('disabled')) {
this.fire('click', e);
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.