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 |
|---|---|---|---|---|
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);
} | conditional_block |
Button.js | /**
* @file san-mui/Button
* @author leon <ludafa@outlook.com>
*/
| 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);
}
}
} | import {create} from '../common/util/cx';
import {TouchRipple} from '../Ripple'; | random_line_split |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2020 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
* | * 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
/**
* Interface describing `sfloor`.
*/
interface Routine {
/**
* Rounds each element in a single-precision floating-point strided array `x` toward negative infinity and assigns the results to elements in a single-precision floating-point strided array `y`.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param y - destination array
* @param strideY - `y` stride length
* @returns `y`
*
* @example
* var Float32Array = require( `@stdlib/array/float32` );
*
* var x = new Float32Array( [ -1.1, 1.1, 3.8, 4.5, 5.9 ] );
* var y = new Float32Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] );
*
* sfloor( x.length, x, 1, y, 1 );
* // y => <Float32Array>[ -2.0, 1.0, 3.0, 4.0, 5.0 ]
*/
( N: number, x: Float32Array, strideX: number, y: Float32Array, strideY: number ): Float32Array; // tslint:disable-line:max-line-length
/**
* Rounds each element in a single-precision floating-point strided array `x` toward negative infinity and assigns the results to elements in a single-precision floating-point strided array `y` using alternative indexing semantics.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param offsetX - starting index for `x`
* @param y - destination array
* @param strideY - `y` stride length
* @param offsetY - starting index for `y`
* @returns `y`
*
* @example
* var Float32Array = require( `@stdlib/array/float32` );
*
* var x = new Float32Array( [ -1.1, 1.1, 3.8, 4.5, 5.9 ] );
* var y = new Float32Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] );
*
* sfloor.ndarray( x.length, x, 1, 0, y, 1, 0 );
* // y => <Float32Array>[ -2.0, 1.0, 3.0, 4.0, 5.0 ]
*/
ndarray( N: number, x: Float32Array, strideX: number, offsetX: number, y: Float32Array, strideY: number, offsetY: number ): Float32Array; // tslint:disable-line:max-line-length
}
/**
* Rounds each element in a single-precision floating-point strided array `x` toward negative infinity and assigns the results to elements in a single-precision floating-point strided array `y`.
*
* @param N - number of indexed elements
* @param x - input array
* @param strideX - `x` stride length
* @param y - destination array
* @param strideY - `y` stride length
* @returns `y`
*
* @example
* var Float32Array = require( `@stdlib/array/float32` );
*
* var x = new Float32Array( [ -1.1, 1.1, 3.8, 4.5, 5.9 ] );
* var y = new Float32Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] );
*
* sfloor( x.length, x, 1, y, 1 );
* // y => <Float32Array>[ -2.0, 1.0, 3.0, 4.0, 5.0 ]
*
* @example
* var Float32Array = require( `@stdlib/array/float32` );
*
* var x = new Float32Array( [ -1.1, 1.1, 3.8, 4.5, 5.9 ] );
* var y = new Float32Array( [ 0.0, 0.0, 0.0, 0.0, 0.0 ] );
*
* sfloor.ndarray( x.length, x, 1, 0, y, 1, 0 );
* // y => <Float32Array>[ -2.0, 1.0, 3.0, 4.0, 5.0 ]
*/
declare var sfloor: Routine;
// EXPORTS //
export = sfloor; | * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, | random_line_split |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23' ... b'\x7e' | b'\x80' ... b'\xff' => (),
_ => { return false; }
}
}
true
}
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() || !slice.ends_with("\"") |
// The etag is weak if its first char is not a DQUOTE.
if slice.char_at(0) == '"' /* '"' */ {
// No need to check if the last char is a DQUOTE,
// we already did that above.
if check_slice_validity(slice.slice_chars(1, length-1)) {
return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_successes() {
// Expected successes
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
// Expected failures
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
}
| {
return Err(());
} | conditional_block |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23' ... b'\x7e' | b'\x80' ... b'\xff' => (),
_ => { return false; }
}
}
true
}
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() || !slice.ends_with("\"") {
return Err(());
}
// The etag is weak if its first char is not a DQUOTE.
if slice.char_at(0) == '"' /* '"' */ {
// No need to check if the last char is a DQUOTE,
// we already did that above.
if check_slice_validity(slice.slice_chars(1, length-1)) {
return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn | () {
// Expected successes
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
// Expected failures
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
}
| test_etag_successes | identifier_name |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool |
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() || !slice.ends_with("\"") {
return Err(());
}
// The etag is weak if its first char is not a DQUOTE.
if slice.char_at(0) == '"' /* '"' */ {
// No need to check if the last char is a DQUOTE,
// we already did that above.
if check_slice_validity(slice.slice_chars(1, length-1)) {
return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_successes() {
// Expected successes
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
// Expected failures
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
}
| {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23' ... b'\x7e' | b'\x80' ... b'\xff' => (),
_ => { return false; }
}
}
true
} | identifier_body |
entity.rs | use std::str::FromStr;
use std::fmt::{self, Display};
/// An entity tag
///
/// An Etag consists of a string enclosed by two literal double quotes.
/// Preceding the first double quote is an optional weakness indicator,
/// which always looks like this: W/
/// See also: https://tools.ietf.org/html/rfc7232#section-2.3
#[derive(Clone, PartialEq, Debug)]
pub struct EntityTag {
/// Weakness indicator for the tag
pub weak: bool,
/// The opaque string in between the DQUOTEs
pub tag: String
}
impl Display for EntityTag {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
if self.weak {
try!(write!(fmt, "{}", "W/"));
}
write!(fmt, "{}", self.tag)
}
}
// check that each char in the slice is either:
// 1. %x21, or
// 2. in the range %x23 to %x7E, or
// 3. in the range %x80 to %xFF
fn check_slice_validity(slice: &str) -> bool {
for c in slice.bytes() {
match c {
b'\x21' | b'\x23' ... b'\x7e' | b'\x80' ... b'\xff' => (),
_ => { return false; }
}
}
true
}
impl FromStr for EntityTag {
type Err = ();
fn from_str(s: &str) -> Result<EntityTag, ()> {
let length: usize = s.len();
let slice = &s[];
// Early exits:
// 1. The string is empty, or,
// 2. it doesn't terminate in a DQUOTE.
if slice.is_empty() || !slice.ends_with("\"") {
return Err(());
}
| return Ok(EntityTag {
weak: false,
tag: slice.slice_chars(1, length-1).to_string()
});
} else {
return Err(());
}
}
if slice.slice_chars(0, 3) == "W/\"" {
if check_slice_validity(slice.slice_chars(3, length-1)) {
return Ok(EntityTag {
weak: true,
tag: slice.slice_chars(3, length-1).to_string()
});
} else {
return Err(());
}
}
Err(())
}
}
#[cfg(test)]
mod tests {
use super::EntityTag;
#[test]
fn test_etag_successes() {
// Expected successes
let mut etag : EntityTag = "\"foobar\"".parse().unwrap();
assert_eq!(etag, (EntityTag {
weak: false,
tag: "foobar".to_string()
}));
etag = "\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: false,
tag: "".to_string()
});
etag = "W/\"weak-etag\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "weak-etag".to_string()
});
etag = "W/\"\x65\x62\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "\u{0065}\u{0062}".to_string()
});
etag = "W/\"\"".parse().unwrap();
assert_eq!(etag, EntityTag {
weak: true,
tag: "".to_string()
});
}
#[test]
fn test_etag_failures() {
// Expected failures
let mut etag: Result<EntityTag,()>;
etag = "no-dquotes".parse();
assert_eq!(etag, Err(()));
etag = "w/\"the-first-w-is-case-sensitive\"".parse();
assert_eq!(etag, Err(()));
etag = "".parse();
assert_eq!(etag, Err(()));
etag = "\"unmatched-dquotes1".parse();
assert_eq!(etag, Err(()));
etag = "unmatched-dquotes2\"".parse();
assert_eq!(etag, Err(()));
etag = "matched-\"dquotes\"".parse();
assert_eq!(etag, Err(()));
}
} | // The etag is weak if its first char is not a DQUOTE.
if slice.char_at(0) == '"' /* '"' */ {
// No need to check if the last char is a DQUOTE,
// we already did that above.
if check_slice_validity(slice.slice_chars(1, length-1)) { | random_line_split |
specHelper.ts | import * as uuid from "uuid";
import { Worker } from "node-resque";
import { api, config, task, Task, Action, Connection } from "./../index";
import { WebServer } from "../servers/web";
import { AsyncReturnType } from "type-fest";
import { TaskInputs } from "../classes/task";
export type SpecHelperConnection = Connection & {
actionCallbacks?: { [key: string]: Function };
};
export namespace specHelper {
/**
* Generate a connection to use in your tests
*/
export async function buildConnection() {
return api.specHelper.Connection.createAsync() as SpecHelperConnection;
}
/**
* Run an action via the specHelper server.
*/
export async function runAction<A extends Action | void = void>(
actionName: string,
input: Partial<SpecHelperConnection> | Record<string, any> = {}
) {
let connection: SpecHelperConnection;
if (input.id && input.type === "testServer") {
connection = input as SpecHelperConnection;
} else {
connection = await specHelper.buildConnection();
connection.params = input;
}
connection.params.action = actionName;
connection.messageId = connection.params.messageId || uuid.v4();
const response: (A extends Action
? AsyncReturnType<A["run"]>
: { [key: string]: any }) & {
messageId?: string;
error?: NodeJS.ErrnoException | string | any;
requesterInformation?: ReturnType<WebServer["buildRequesterInformation"]>;
serverInformation?: ReturnType<WebServer["buildServerInformation"]>;
} = await new Promise((resolve) => {
api.servers.servers.testServer.processAction(connection);
connection.actionCallbacks[connection.messageId] = resolve;
});
return response;
}
/**
* Mock a specHelper connection requesting a file from the server.
*/
export async function | (file: string): Promise<any> {
const connection = await specHelper.buildConnection();
connection.params.file = file;
const response = await new Promise((resolve) => {
api.servers.servers.testServer.processFile(connection);
connection.actionCallbacks[connection.messageId] = resolve;
});
return response;
}
/**
* Use the specHelper to run a task.
* Note: this only runs the task's `run()` method, and no middleware. This is faster than api.specHelper.runFullTask.
*/
export async function runTask<T extends Task | void = void>(
taskName: string,
params: object | Array<any>
) {
if (!api.tasks.tasks[taskName]) {
throw new Error(`task ${taskName} not found`);
}
const result: (T extends Task
? AsyncReturnType<T["run"]>
: { [key: string]: any }) & {
error?: NodeJS.ErrnoException | string;
} = await api.tasks.tasks[taskName].run(params, undefined);
return result;
}
/**
* Use the specHelper to run a task.
* Note: this will run a full Task worker, and will also include any middleware. This is slower than api.specHelper.runTask.
*/
export async function runFullTask<T extends Task | void = void>(
taskName: string,
params: object | Array<any>
) {
const worker = new Worker(
{
connection: {
redis: api.redis.clients.tasks,
pkg:
api.redis.clients.tasks?.constructor?.name === "RedisMock"
? "ioredis-mock"
: "ioredis",
},
queues: (Array.isArray(config.tasks.queues)
? config.tasks.queues
: await config.tasks.queues()) || ["default"],
},
api.tasks.jobs
);
try {
await worker.connect();
const result: (T extends Task
? AsyncReturnType<T["run"]>
: { [key: string]: any }) & {
error?: string;
} = await worker.performInline(
taskName,
Array.isArray(params) ? params : [params]
);
await worker.end();
return result;
} catch (error) {
try {
worker.end();
} catch (error) {}
throw error;
}
}
/**
* Use the specHelper to find enqueued instances of a task
* This will return an array of instances of the task which have been enqueued either in the normal queues or delayed queues
* If a task is enqueued in a delayed queue, it will have a 'timestamp' property
* i.e. [ { class: 'regularTask', queue: 'testQueue', args: [ [Object] ] } ]
*/
export async function findEnqueuedTasks(taskName: string) {
let found: TaskInputs[] = [];
// normal queues
const queues = await api.resque.queue.queues();
for (const i in queues) {
const q = queues[i];
const length = await api.resque.queue.length(q);
const batchFound = await task.queued(q, 0, length + 1);
let matches = batchFound.filter((t) => t.class === taskName);
matches = matches.map((m) => {
m.timestamp = null;
return m;
});
found = found.concat(matches);
}
// delayed queues
const allDelayed = await api.resque.queue.allDelayed();
for (const timestamp in allDelayed) {
let matches = allDelayed[timestamp].filter((t) => t.class === taskName);
matches = matches.map((m) => {
m.timestamp = parseInt(timestamp);
return m;
});
found = found.concat(matches);
}
return found;
}
/**
* Delete all enqueued instances of a task, both in all the normal queues and all of the delayed queues
*/
export async function deleteEnqueuedTasks(taskName: string, params: {}) {
const queues = await api.resque.queue.queues();
for (const i in queues) {
const q = queues[i];
await api.resque.queue.del(q, taskName, [params]);
await api.resque.queue.delDelayed(q, taskName, [params]);
}
}
}
| getStaticFile | identifier_name |
specHelper.ts | import * as uuid from "uuid";
import { Worker } from "node-resque";
import { api, config, task, Task, Action, Connection } from "./../index";
import { WebServer } from "../servers/web";
import { AsyncReturnType } from "type-fest";
import { TaskInputs } from "../classes/task";
export type SpecHelperConnection = Connection & {
actionCallbacks?: { [key: string]: Function };
};
export namespace specHelper {
/**
* Generate a connection to use in your tests
*/
export async function buildConnection() {
return api.specHelper.Connection.createAsync() as SpecHelperConnection;
}
/**
* Run an action via the specHelper server.
*/
export async function runAction<A extends Action | void = void>(
actionName: string,
input: Partial<SpecHelperConnection> | Record<string, any> = {}
) {
let connection: SpecHelperConnection;
if (input.id && input.type === "testServer") {
connection = input as SpecHelperConnection;
} else {
connection = await specHelper.buildConnection();
connection.params = input;
}
connection.params.action = actionName;
connection.messageId = connection.params.messageId || uuid.v4();
const response: (A extends Action
? AsyncReturnType<A["run"]>
: { [key: string]: any }) & {
messageId?: string;
error?: NodeJS.ErrnoException | string | any;
requesterInformation?: ReturnType<WebServer["buildRequesterInformation"]>;
serverInformation?: ReturnType<WebServer["buildServerInformation"]>;
} = await new Promise((resolve) => {
api.servers.servers.testServer.processAction(connection);
connection.actionCallbacks[connection.messageId] = resolve;
});
return response;
}
/**
* Mock a specHelper connection requesting a file from the server.
*/
export async function getStaticFile(file: string): Promise<any> {
const connection = await specHelper.buildConnection();
connection.params.file = file;
const response = await new Promise((resolve) => {
api.servers.servers.testServer.processFile(connection);
connection.actionCallbacks[connection.messageId] = resolve;
});
return response;
}
/**
* Use the specHelper to run a task.
* Note: this only runs the task's `run()` method, and no middleware. This is faster than api.specHelper.runFullTask.
*/
export async function runTask<T extends Task | void = void>(
taskName: string,
params: object | Array<any>
) {
if (!api.tasks.tasks[taskName]) {
throw new Error(`task ${taskName} not found`);
}
const result: (T extends Task
? AsyncReturnType<T["run"]>
: { [key: string]: any }) & {
error?: NodeJS.ErrnoException | string;
} = await api.tasks.tasks[taskName].run(params, undefined);
return result;
}
/**
* Use the specHelper to run a task.
* Note: this will run a full Task worker, and will also include any middleware. This is slower than api.specHelper.runTask.
*/
export async function runFullTask<T extends Task | void = void>(
taskName: string,
params: object | Array<any>
) {
const worker = new Worker(
{
connection: {
redis: api.redis.clients.tasks,
pkg:
api.redis.clients.tasks?.constructor?.name === "RedisMock"
? "ioredis-mock"
: "ioredis",
},
queues: (Array.isArray(config.tasks.queues)
? config.tasks.queues
: await config.tasks.queues()) || ["default"],
},
api.tasks.jobs
);
try {
await worker.connect();
const result: (T extends Task
? AsyncReturnType<T["run"]>
: { [key: string]: any }) & {
error?: string;
} = await worker.performInline(
taskName,
Array.isArray(params) ? params : [params]
);
await worker.end();
return result;
} catch (error) {
try {
worker.end();
} catch (error) {}
throw error;
}
}
/** | */
export async function findEnqueuedTasks(taskName: string) {
let found: TaskInputs[] = [];
// normal queues
const queues = await api.resque.queue.queues();
for (const i in queues) {
const q = queues[i];
const length = await api.resque.queue.length(q);
const batchFound = await task.queued(q, 0, length + 1);
let matches = batchFound.filter((t) => t.class === taskName);
matches = matches.map((m) => {
m.timestamp = null;
return m;
});
found = found.concat(matches);
}
// delayed queues
const allDelayed = await api.resque.queue.allDelayed();
for (const timestamp in allDelayed) {
let matches = allDelayed[timestamp].filter((t) => t.class === taskName);
matches = matches.map((m) => {
m.timestamp = parseInt(timestamp);
return m;
});
found = found.concat(matches);
}
return found;
}
/**
* Delete all enqueued instances of a task, both in all the normal queues and all of the delayed queues
*/
export async function deleteEnqueuedTasks(taskName: string, params: {}) {
const queues = await api.resque.queue.queues();
for (const i in queues) {
const q = queues[i];
await api.resque.queue.del(q, taskName, [params]);
await api.resque.queue.delDelayed(q, taskName, [params]);
}
}
} | * Use the specHelper to find enqueued instances of a task
* This will return an array of instances of the task which have been enqueued either in the normal queues or delayed queues
* If a task is enqueued in a delayed queue, it will have a 'timestamp' property
* i.e. [ { class: 'regularTask', queue: 'testQueue', args: [ [Object] ] } ] | random_line_split |
specHelper.ts | import * as uuid from "uuid";
import { Worker } from "node-resque";
import { api, config, task, Task, Action, Connection } from "./../index";
import { WebServer } from "../servers/web";
import { AsyncReturnType } from "type-fest";
import { TaskInputs } from "../classes/task";
export type SpecHelperConnection = Connection & {
actionCallbacks?: { [key: string]: Function };
};
export namespace specHelper {
/**
* Generate a connection to use in your tests
*/
export async function buildConnection() {
return api.specHelper.Connection.createAsync() as SpecHelperConnection;
}
/**
* Run an action via the specHelper server.
*/
export async function runAction<A extends Action | void = void>(
actionName: string,
input: Partial<SpecHelperConnection> | Record<string, any> = {}
) {
let connection: SpecHelperConnection;
if (input.id && input.type === "testServer") | else {
connection = await specHelper.buildConnection();
connection.params = input;
}
connection.params.action = actionName;
connection.messageId = connection.params.messageId || uuid.v4();
const response: (A extends Action
? AsyncReturnType<A["run"]>
: { [key: string]: any }) & {
messageId?: string;
error?: NodeJS.ErrnoException | string | any;
requesterInformation?: ReturnType<WebServer["buildRequesterInformation"]>;
serverInformation?: ReturnType<WebServer["buildServerInformation"]>;
} = await new Promise((resolve) => {
api.servers.servers.testServer.processAction(connection);
connection.actionCallbacks[connection.messageId] = resolve;
});
return response;
}
/**
* Mock a specHelper connection requesting a file from the server.
*/
export async function getStaticFile(file: string): Promise<any> {
const connection = await specHelper.buildConnection();
connection.params.file = file;
const response = await new Promise((resolve) => {
api.servers.servers.testServer.processFile(connection);
connection.actionCallbacks[connection.messageId] = resolve;
});
return response;
}
/**
* Use the specHelper to run a task.
* Note: this only runs the task's `run()` method, and no middleware. This is faster than api.specHelper.runFullTask.
*/
export async function runTask<T extends Task | void = void>(
taskName: string,
params: object | Array<any>
) {
if (!api.tasks.tasks[taskName]) {
throw new Error(`task ${taskName} not found`);
}
const result: (T extends Task
? AsyncReturnType<T["run"]>
: { [key: string]: any }) & {
error?: NodeJS.ErrnoException | string;
} = await api.tasks.tasks[taskName].run(params, undefined);
return result;
}
/**
* Use the specHelper to run a task.
* Note: this will run a full Task worker, and will also include any middleware. This is slower than api.specHelper.runTask.
*/
export async function runFullTask<T extends Task | void = void>(
taskName: string,
params: object | Array<any>
) {
const worker = new Worker(
{
connection: {
redis: api.redis.clients.tasks,
pkg:
api.redis.clients.tasks?.constructor?.name === "RedisMock"
? "ioredis-mock"
: "ioredis",
},
queues: (Array.isArray(config.tasks.queues)
? config.tasks.queues
: await config.tasks.queues()) || ["default"],
},
api.tasks.jobs
);
try {
await worker.connect();
const result: (T extends Task
? AsyncReturnType<T["run"]>
: { [key: string]: any }) & {
error?: string;
} = await worker.performInline(
taskName,
Array.isArray(params) ? params : [params]
);
await worker.end();
return result;
} catch (error) {
try {
worker.end();
} catch (error) {}
throw error;
}
}
/**
* Use the specHelper to find enqueued instances of a task
* This will return an array of instances of the task which have been enqueued either in the normal queues or delayed queues
* If a task is enqueued in a delayed queue, it will have a 'timestamp' property
* i.e. [ { class: 'regularTask', queue: 'testQueue', args: [ [Object] ] } ]
*/
export async function findEnqueuedTasks(taskName: string) {
let found: TaskInputs[] = [];
// normal queues
const queues = await api.resque.queue.queues();
for (const i in queues) {
const q = queues[i];
const length = await api.resque.queue.length(q);
const batchFound = await task.queued(q, 0, length + 1);
let matches = batchFound.filter((t) => t.class === taskName);
matches = matches.map((m) => {
m.timestamp = null;
return m;
});
found = found.concat(matches);
}
// delayed queues
const allDelayed = await api.resque.queue.allDelayed();
for (const timestamp in allDelayed) {
let matches = allDelayed[timestamp].filter((t) => t.class === taskName);
matches = matches.map((m) => {
m.timestamp = parseInt(timestamp);
return m;
});
found = found.concat(matches);
}
return found;
}
/**
* Delete all enqueued instances of a task, both in all the normal queues and all of the delayed queues
*/
export async function deleteEnqueuedTasks(taskName: string, params: {}) {
const queues = await api.resque.queue.queues();
for (const i in queues) {
const q = queues[i];
await api.resque.queue.del(q, taskName, [params]);
await api.resque.queue.delDelayed(q, taskName, [params]);
}
}
}
| {
connection = input as SpecHelperConnection;
} | conditional_block |
specHelper.ts | import * as uuid from "uuid";
import { Worker } from "node-resque";
import { api, config, task, Task, Action, Connection } from "./../index";
import { WebServer } from "../servers/web";
import { AsyncReturnType } from "type-fest";
import { TaskInputs } from "../classes/task";
export type SpecHelperConnection = Connection & {
actionCallbacks?: { [key: string]: Function };
};
export namespace specHelper {
/**
* Generate a connection to use in your tests
*/
export async function buildConnection() {
return api.specHelper.Connection.createAsync() as SpecHelperConnection;
}
/**
* Run an action via the specHelper server.
*/
export async function runAction<A extends Action | void = void>(
actionName: string,
input: Partial<SpecHelperConnection> | Record<string, any> = {}
) {
let connection: SpecHelperConnection;
if (input.id && input.type === "testServer") {
connection = input as SpecHelperConnection;
} else {
connection = await specHelper.buildConnection();
connection.params = input;
}
connection.params.action = actionName;
connection.messageId = connection.params.messageId || uuid.v4();
const response: (A extends Action
? AsyncReturnType<A["run"]>
: { [key: string]: any }) & {
messageId?: string;
error?: NodeJS.ErrnoException | string | any;
requesterInformation?: ReturnType<WebServer["buildRequesterInformation"]>;
serverInformation?: ReturnType<WebServer["buildServerInformation"]>;
} = await new Promise((resolve) => {
api.servers.servers.testServer.processAction(connection);
connection.actionCallbacks[connection.messageId] = resolve;
});
return response;
}
/**
* Mock a specHelper connection requesting a file from the server.
*/
export async function getStaticFile(file: string): Promise<any> {
const connection = await specHelper.buildConnection();
connection.params.file = file;
const response = await new Promise((resolve) => {
api.servers.servers.testServer.processFile(connection);
connection.actionCallbacks[connection.messageId] = resolve;
});
return response;
}
/**
* Use the specHelper to run a task.
* Note: this only runs the task's `run()` method, and no middleware. This is faster than api.specHelper.runFullTask.
*/
export async function runTask<T extends Task | void = void>(
taskName: string,
params: object | Array<any>
) {
if (!api.tasks.tasks[taskName]) {
throw new Error(`task ${taskName} not found`);
}
const result: (T extends Task
? AsyncReturnType<T["run"]>
: { [key: string]: any }) & {
error?: NodeJS.ErrnoException | string;
} = await api.tasks.tasks[taskName].run(params, undefined);
return result;
}
/**
* Use the specHelper to run a task.
* Note: this will run a full Task worker, and will also include any middleware. This is slower than api.specHelper.runTask.
*/
export async function runFullTask<T extends Task | void = void>(
taskName: string,
params: object | Array<any>
) {
const worker = new Worker(
{
connection: {
redis: api.redis.clients.tasks,
pkg:
api.redis.clients.tasks?.constructor?.name === "RedisMock"
? "ioredis-mock"
: "ioredis",
},
queues: (Array.isArray(config.tasks.queues)
? config.tasks.queues
: await config.tasks.queues()) || ["default"],
},
api.tasks.jobs
);
try {
await worker.connect();
const result: (T extends Task
? AsyncReturnType<T["run"]>
: { [key: string]: any }) & {
error?: string;
} = await worker.performInline(
taskName,
Array.isArray(params) ? params : [params]
);
await worker.end();
return result;
} catch (error) {
try {
worker.end();
} catch (error) {}
throw error;
}
}
/**
* Use the specHelper to find enqueued instances of a task
* This will return an array of instances of the task which have been enqueued either in the normal queues or delayed queues
* If a task is enqueued in a delayed queue, it will have a 'timestamp' property
* i.e. [ { class: 'regularTask', queue: 'testQueue', args: [ [Object] ] } ]
*/
export async function findEnqueuedTasks(taskName: string) {
let found: TaskInputs[] = [];
// normal queues
const queues = await api.resque.queue.queues();
for (const i in queues) {
const q = queues[i];
const length = await api.resque.queue.length(q);
const batchFound = await task.queued(q, 0, length + 1);
let matches = batchFound.filter((t) => t.class === taskName);
matches = matches.map((m) => {
m.timestamp = null;
return m;
});
found = found.concat(matches);
}
// delayed queues
const allDelayed = await api.resque.queue.allDelayed();
for (const timestamp in allDelayed) {
let matches = allDelayed[timestamp].filter((t) => t.class === taskName);
matches = matches.map((m) => {
m.timestamp = parseInt(timestamp);
return m;
});
found = found.concat(matches);
}
return found;
}
/**
* Delete all enqueued instances of a task, both in all the normal queues and all of the delayed queues
*/
export async function deleteEnqueuedTasks(taskName: string, params: {}) |
}
| {
const queues = await api.resque.queue.queues();
for (const i in queues) {
const q = queues[i];
await api.resque.queue.del(q, taskName, [params]);
await api.resque.queue.delDelayed(q, taskName, [params]);
}
} | identifier_body |
youtube.server-tests.js | YUI.add('youtube-model-yql-tests', function (Y, NAME) {
var suite = new YUITest.TestSuite(NAME),
model = null,
A = YUITest.Assert;
suite.add(new YUITest.TestCase({
name: "youtube-model-yql user tests",
setUp: function () {
model = Y.mojito.models["youtube-model-yql"];
},
tearDown: function () {
model = null;
},
'test mojit model': function () {
var called = false,
cfg = { color: 'red' };
A.isNotNull(model);
A.isFunction(model.init);
model.init(cfg);
A.areSame(cfg, model.config);
// check getData function is there
A.isFunction(model.getData); | /**
model.getData({},function (data) {
called = true;
//A.isTrue(!err);
//A.isObject(data);
//A.areSame('data', data.some);
});
A.isTrue(called);
**/
}
}));
YUITest.TestRunner.add(suite);
}, '0.0.1', {requires: ['mojito-test', 'youtube-model-yql']}); | random_line_split | |
dst-index.rs | // Copyright 2014 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.
// Test that overloaded index expressions with DST result types
// can't be used as rvalues
use std::ops::Index;
use std::fmt::Show;
struct S;
impl Index<uint, str> for S {
fn | <'a>(&'a self, _: &uint) -> &'a str {
"hello"
}
}
struct T;
impl Index<uint, Show + 'static> for T {
fn index<'a>(&'a self, idx: &uint) -> &'a (Show + 'static) {
static x: uint = 42;
&x
}
}
fn main() {
S[0];
//~^ ERROR E0161
T[0];
//~^ ERROR cannot move out of dereference
//~^^ ERROR E0161
}
| index | identifier_name |
dst-index.rs | // Copyright 2014 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.
// Test that overloaded index expressions with DST result types
// can't be used as rvalues |
struct S;
impl Index<uint, str> for S {
fn index<'a>(&'a self, _: &uint) -> &'a str {
"hello"
}
}
struct T;
impl Index<uint, Show + 'static> for T {
fn index<'a>(&'a self, idx: &uint) -> &'a (Show + 'static) {
static x: uint = 42;
&x
}
}
fn main() {
S[0];
//~^ ERROR E0161
T[0];
//~^ ERROR cannot move out of dereference
//~^^ ERROR E0161
} |
use std::ops::Index;
use std::fmt::Show; | random_line_split |
player_unit.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use error::*;
use identifier::*;
use io_tools::*;
use std::io::Read;
#[derive(Default, Debug)]
pub struct PlayerUnit {
pub position_x: f32,
pub position_y: f32,
pub position_z: f32,
pub spawn_id: Option<SpawnId>,
pub unit_id: UnitId,
pub state: u8,
pub rotation: f32,
}
impl PlayerUnit {
// TODO: Implement writing
pub fn | <S: Read>(stream: &mut S) -> Result<PlayerUnit> {
let mut data: PlayerUnit = Default::default();
data.position_x = try!(stream.read_f32());
data.position_y = try!(stream.read_f32());
data.position_z = try!(stream.read_f32());
data.spawn_id = optional_id!(try!(stream.read_i32()));
data.unit_id = required_id!(try!(stream.read_i16()));
data.state = try!(stream.read_u8());
data.rotation = try!(stream.read_f32());
Ok(data)
}
}
| read_from_stream | identifier_name |
player_unit.rs | // OpenAOE: An open source reimplementation of Age of Empires (1997)
// Copyright (c) 2016 Kevin Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
use error::*;
use identifier::*;
use io_tools::*;
use std::io::Read;
#[derive(Default, Debug)]
pub struct PlayerUnit {
pub position_x: f32,
pub position_y: f32,
pub position_z: f32,
pub spawn_id: Option<SpawnId>,
pub unit_id: UnitId,
pub state: u8,
pub rotation: f32,
}
impl PlayerUnit {
// TODO: Implement writing
pub fn read_from_stream<S: Read>(stream: &mut S) -> Result<PlayerUnit> {
let mut data: PlayerUnit = Default::default();
data.position_x = try!(stream.read_f32());
data.position_y = try!(stream.read_f32());
data.position_z = try!(stream.read_f32());
data.spawn_id = optional_id!(try!(stream.read_i32()));
data.unit_id = required_id!(try!(stream.read_i16()));
data.state = try!(stream.read_u8());
data.rotation = try!(stream.read_f32());
Ok(data)
}
} | // copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | random_line_split |
trait-with-bounds-default.rs | // Copyright 2013 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.
//
pub trait Clone2 {
/// Returns a copy of the value. The contents of boxes
/// are copied to maintain uniqueness, while the contents of
/// managed pointers are not copied.
fn clone(&self) -> Self;
}
trait Getter<T: Clone> {
fn do_get(&self) -> T;
fn do_get2(&self) -> (T, T) {
let x = self.do_get();
(x.clone(), x.clone())
}
}
impl Getter<isize> for isize {
fn do_get(&self) -> isize { *self }
}
impl<T: Clone> Getter<T> for Option<T> {
fn do_get(&self) -> T { self.as_ref().unwrap().clone() }
}
pub fn | () {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string()));
}
| main | identifier_name |
trait-with-bounds-default.rs | // Copyright 2013 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.
//
pub trait Clone2 {
/// Returns a copy of the value. The contents of boxes
/// are copied to maintain uniqueness, while the contents of
/// managed pointers are not copied.
fn clone(&self) -> Self;
}
trait Getter<T: Clone> {
fn do_get(&self) -> T;
fn do_get2(&self) -> (T, T) {
let x = self.do_get();
(x.clone(), x.clone())
}
}
impl Getter<isize> for isize {
fn do_get(&self) -> isize { *self }
}
impl<T: Clone> Getter<T> for Option<T> {
fn do_get(&self) -> T |
}
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string()));
}
| { self.as_ref().unwrap().clone() } | identifier_body |
trait-with-bounds-default.rs | // Copyright 2013 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.
//
pub trait Clone2 {
/// Returns a copy of the value. The contents of boxes
/// are copied to maintain uniqueness, while the contents of
/// managed pointers are not copied.
fn clone(&self) -> Self;
}
| fn do_get(&self) -> T;
fn do_get2(&self) -> (T, T) {
let x = self.do_get();
(x.clone(), x.clone())
}
}
impl Getter<isize> for isize {
fn do_get(&self) -> isize { *self }
}
impl<T: Clone> Getter<T> for Option<T> {
fn do_get(&self) -> T { self.as_ref().unwrap().clone() }
}
pub fn main() {
assert_eq!(3.do_get2(), (3, 3));
assert_eq!(Some("hi".to_string()).do_get2(), ("hi".to_string(), "hi".to_string()));
} | trait Getter<T: Clone> { | random_line_split |
views.py | from django.shortcuts import render
from rest_framework import viewsets
from basin.models import Task
from basin.serializers import TaskSerializer
def index(request):
context = {}
return render(request, 'index.html', context)
def display(request):
state = 'active'
if request.method == 'POST':
state = request.POST['state']
submit = request.POST['submit']
tid = request.POST['id']
if submit == 'check':
task = Task.objects.get(id=tid)
task.completed = not task.completed
task.save()
elif request.method == 'GET':
if 'state' in request.GET:
state = request.GET['state']
context = {
'task_list': Task.objects.state(state),
'state': state,
}
return render(request, 'display.html', context)
class ActiveViewSet(viewsets.ModelViewSet):
queryset = Task.objects.active()
serializer_class = TaskSerializer
class | (viewsets.ModelViewSet):
queryset = Task.objects.sleeping()
serializer_class = TaskSerializer
class BlockedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.blocked()
serializer_class = TaskSerializer
class DelegatedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.delegated()
serializer_class = TaskSerializer
class CompletedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.filter(completed=True, trashed=False)
serializer_class = TaskSerializer
class TaskViewSet(viewsets.ModelViewSet):
model = Task
serializer_class = TaskSerializer
def get_queryset(self):
if 'state' in self.request.QUERY_PARAMS:
state = self.request.QUERY_PARAMS['state']
return Task.objects.state(state)
return Task.objects.all()
| SleepingViewSet | identifier_name |
views.py | from django.shortcuts import render
from rest_framework import viewsets
from basin.models import Task
from basin.serializers import TaskSerializer
def index(request):
context = {}
return render(request, 'index.html', context)
def display(request):
state = 'active'
if request.method == 'POST':
state = request.POST['state']
submit = request.POST['submit']
tid = request.POST['id']
if submit == 'check':
task = Task.objects.get(id=tid)
task.completed = not task.completed
task.save()
elif request.method == 'GET':
if 'state' in request.GET:
state = request.GET['state']
context = {
'task_list': Task.objects.state(state),
'state': state,
}
return render(request, 'display.html', context)
class ActiveViewSet(viewsets.ModelViewSet):
queryset = Task.objects.active()
serializer_class = TaskSerializer
class SleepingViewSet(viewsets.ModelViewSet):
queryset = Task.objects.sleeping()
serializer_class = TaskSerializer
class BlockedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.blocked()
serializer_class = TaskSerializer
class DelegatedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.delegated()
serializer_class = TaskSerializer
class CompletedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.filter(completed=True, trashed=False)
serializer_class = TaskSerializer
class TaskViewSet(viewsets.ModelViewSet):
| model = Task
serializer_class = TaskSerializer
def get_queryset(self):
if 'state' in self.request.QUERY_PARAMS:
state = self.request.QUERY_PARAMS['state']
return Task.objects.state(state)
return Task.objects.all() | identifier_body | |
views.py | from django.shortcuts import render
from rest_framework import viewsets
from basin.models import Task
from basin.serializers import TaskSerializer
def index(request):
context = {}
return render(request, 'index.html', context)
def display(request):
state = 'active'
if request.method == 'POST':
state = request.POST['state']
submit = request.POST['submit']
tid = request.POST['id']
if submit == 'check':
task = Task.objects.get(id=tid)
task.completed = not task.completed
task.save()
elif request.method == 'GET':
if 'state' in request.GET:
|
context = {
'task_list': Task.objects.state(state),
'state': state,
}
return render(request, 'display.html', context)
class ActiveViewSet(viewsets.ModelViewSet):
queryset = Task.objects.active()
serializer_class = TaskSerializer
class SleepingViewSet(viewsets.ModelViewSet):
queryset = Task.objects.sleeping()
serializer_class = TaskSerializer
class BlockedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.blocked()
serializer_class = TaskSerializer
class DelegatedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.delegated()
serializer_class = TaskSerializer
class CompletedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.filter(completed=True, trashed=False)
serializer_class = TaskSerializer
class TaskViewSet(viewsets.ModelViewSet):
model = Task
serializer_class = TaskSerializer
def get_queryset(self):
if 'state' in self.request.QUERY_PARAMS:
state = self.request.QUERY_PARAMS['state']
return Task.objects.state(state)
return Task.objects.all()
| state = request.GET['state'] | conditional_block |
views.py | from django.shortcuts import render
from rest_framework import viewsets
from basin.models import Task
from basin.serializers import TaskSerializer
def index(request):
context = {}
return render(request, 'index.html', context)
def display(request):
state = 'active'
if request.method == 'POST':
state = request.POST['state']
submit = request.POST['submit']
tid = request.POST['id'] | elif request.method == 'GET':
if 'state' in request.GET:
state = request.GET['state']
context = {
'task_list': Task.objects.state(state),
'state': state,
}
return render(request, 'display.html', context)
class ActiveViewSet(viewsets.ModelViewSet):
queryset = Task.objects.active()
serializer_class = TaskSerializer
class SleepingViewSet(viewsets.ModelViewSet):
queryset = Task.objects.sleeping()
serializer_class = TaskSerializer
class BlockedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.blocked()
serializer_class = TaskSerializer
class DelegatedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.delegated()
serializer_class = TaskSerializer
class CompletedViewSet(viewsets.ModelViewSet):
queryset = Task.objects.filter(completed=True, trashed=False)
serializer_class = TaskSerializer
class TaskViewSet(viewsets.ModelViewSet):
model = Task
serializer_class = TaskSerializer
def get_queryset(self):
if 'state' in self.request.QUERY_PARAMS:
state = self.request.QUERY_PARAMS['state']
return Task.objects.state(state)
return Task.objects.all() | if submit == 'check':
task = Task.objects.get(id=tid)
task.completed = not task.completed
task.save() | random_line_split |
app.js |
/**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')
var index = require('./routes/index');
// Example route
// var user = require('./routes/user');
// below added by tommy
var login = require('./routes/login');
var messages = require('./routes/messages');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) |
// Add routes here
app.get('/', index.view);
// Example route
// app.get('/users', user.list);
//below added by tommy
app.get('/login', login.view);
app.get('/messages', messages.view);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
| {
app.use(express.errorHandler());
} | conditional_block |
app.js | /**
* Module dependencies.
*/
var express = require('express');
var http = require('http');
var path = require('path');
var handlebars = require('express3-handlebars')
var index = require('./routes/index');
// Example route
// var user = require('./routes/user');
|
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.engine('handlebars', handlebars());
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser('Intro HCI secret key'));
app.use(express.session());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
// Add routes here
app.get('/', index.view);
// Example route
// app.get('/users', user.list);
//below added by tommy
app.get('/login', login.view);
app.get('/messages', messages.view);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
}); | // below added by tommy
var login = require('./routes/login');
var messages = require('./routes/messages');
| random_line_split |
ifdef.py | #! /usr/bin/env python
# Selectively preprocess #ifdef / #ifndef statements.
# Usage:
# ifdef [-Dname] ... [-Uname] ... [file] ...
#
# This scans the file(s), looking for #ifdef and #ifndef preprocessor
# commands that test for one of the names mentioned in the -D and -U
# options. On standard output it writes a copy of the input file(s)
# minus those code sections that are suppressed by the selected
# combination of defined/undefined symbols. The #if(n)def/#else/#else
# lines themselfs (if the #if(n)def tests for one of the mentioned
# names) are removed as well.
# Features: Arbitrary nesting of recognized and unrecognized
# preprocesor statements works correctly. Unrecognized #if* commands
# are left in place, so it will never remove too much, only too
# little. It does accept whitespace around the '#' character.
# Restrictions: There should be no comments or other symbols on the
# #if(n)def lines. The effect of #define/#undef commands in the input
# file or in included files is not taken into account. Tests using
# #if and the defined() pseudo function are not recognized. The #elif
# command is not recognized. Improperly nesting is not detected.
# Lines that look like preprocessor commands but which are actually
# part of comments or string literals will be mistaken for
# preprocessor commands.
import sys
import getopt
defs = []
undefs = []
def main():
opts, args = getopt.getopt(sys.argv[1:], 'D:U:')
for o, a in opts:
if o == '-D':
defs.append(a)
if o == '-U':
undefs.append(a)
if not args:
args = ['-']
for filename in args:
if filename == '-':
process(sys.stdin, sys.stdout)
else:
f = open(filename, 'r')
process(f, sys.stdout)
f.close()
def process(fpi, fpo):
keywords = ('if', 'ifdef', 'ifndef', 'else', 'endif')
ok = 1
stack = []
while 1:
line = fpi.readline()
if not line: break
while line[-2:] == '\\\n':
nextline = fpi.readline()
if not nextline: break
line = line + nextline
tmp = line.strip()
if tmp[:1] != '#':
if ok: fpo.write(line)
continue
tmp = tmp[1:].strip()
words = tmp.split()
keyword = words[0]
if keyword not in keywords:
if ok: fpo.write(line)
continue
if keyword in ('ifdef', 'ifndef') and len(words) == 2:
if keyword == 'ifdef':
ko = 1
else:
ko = 0
word = words[1]
if word in defs:
stack.append((ok, ko, word))
if not ko: ok = 0
elif word in undefs:
stack.append((ok, not ko, word))
if ko: ok = 0
else:
stack.append((ok, -1, word))
if ok: fpo.write(line)
elif keyword == 'if':
stack.append((ok, -1, ''))
if ok: fpo.write(line)
elif keyword == 'else' and stack:
|
elif keyword == 'endif' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
del stack[-1]
ok = s_ok
else:
sys.stderr.write('Unknown keyword %s\n' % keyword)
if stack:
sys.stderr.write('stack: %s\n' % stack)
if __name__ == '__main__':
main()
| s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
else:
s_ko = not s_ko
ok = s_ok
if not s_ko: ok = 0
stack[-1] = s_ok, s_ko, s_word | conditional_block |
ifdef.py | #! /usr/bin/env python
# Selectively preprocess #ifdef / #ifndef statements.
# Usage:
# ifdef [-Dname] ... [-Uname] ... [file] ...
#
# This scans the file(s), looking for #ifdef and #ifndef preprocessor
# commands that test for one of the names mentioned in the -D and -U
# options. On standard output it writes a copy of the input file(s)
# minus those code sections that are suppressed by the selected
# combination of defined/undefined symbols. The #if(n)def/#else/#else
# lines themselfs (if the #if(n)def tests for one of the mentioned
# names) are removed as well.
# Features: Arbitrary nesting of recognized and unrecognized
# preprocesor statements works correctly. Unrecognized #if* commands
# are left in place, so it will never remove too much, only too
# little. It does accept whitespace around the '#' character.
# Restrictions: There should be no comments or other symbols on the
# #if(n)def lines. The effect of #define/#undef commands in the input
# file or in included files is not taken into account. Tests using
# #if and the defined() pseudo function are not recognized. The #elif
# command is not recognized. Improperly nesting is not detected.
# Lines that look like preprocessor commands but which are actually
# part of comments or string literals will be mistaken for
# preprocessor commands.
import sys
import getopt
defs = []
undefs = []
def main():
opts, args = getopt.getopt(sys.argv[1:], 'D:U:')
for o, a in opts:
if o == '-D':
defs.append(a)
if o == '-U':
undefs.append(a)
if not args:
args = ['-']
for filename in args:
if filename == '-':
process(sys.stdin, sys.stdout)
else:
f = open(filename, 'r')
process(f, sys.stdout)
f.close()
def process(fpi, fpo):
|
if __name__ == '__main__':
main()
| keywords = ('if', 'ifdef', 'ifndef', 'else', 'endif')
ok = 1
stack = []
while 1:
line = fpi.readline()
if not line: break
while line[-2:] == '\\\n':
nextline = fpi.readline()
if not nextline: break
line = line + nextline
tmp = line.strip()
if tmp[:1] != '#':
if ok: fpo.write(line)
continue
tmp = tmp[1:].strip()
words = tmp.split()
keyword = words[0]
if keyword not in keywords:
if ok: fpo.write(line)
continue
if keyword in ('ifdef', 'ifndef') and len(words) == 2:
if keyword == 'ifdef':
ko = 1
else:
ko = 0
word = words[1]
if word in defs:
stack.append((ok, ko, word))
if not ko: ok = 0
elif word in undefs:
stack.append((ok, not ko, word))
if ko: ok = 0
else:
stack.append((ok, -1, word))
if ok: fpo.write(line)
elif keyword == 'if':
stack.append((ok, -1, ''))
if ok: fpo.write(line)
elif keyword == 'else' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
else:
s_ko = not s_ko
ok = s_ok
if not s_ko: ok = 0
stack[-1] = s_ok, s_ko, s_word
elif keyword == 'endif' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
del stack[-1]
ok = s_ok
else:
sys.stderr.write('Unknown keyword %s\n' % keyword)
if stack:
sys.stderr.write('stack: %s\n' % stack) | identifier_body |
ifdef.py | #! /usr/bin/env python
# Selectively preprocess #ifdef / #ifndef statements.
# Usage:
# ifdef [-Dname] ... [-Uname] ... [file] ...
#
# This scans the file(s), looking for #ifdef and #ifndef preprocessor
# commands that test for one of the names mentioned in the -D and -U
# options. On standard output it writes a copy of the input file(s)
# minus those code sections that are suppressed by the selected
# combination of defined/undefined symbols. The #if(n)def/#else/#else
# lines themselfs (if the #if(n)def tests for one of the mentioned
# names) are removed as well.
# Features: Arbitrary nesting of recognized and unrecognized
# preprocesor statements works correctly. Unrecognized #if* commands
# are left in place, so it will never remove too much, only too
# little. It does accept whitespace around the '#' character.
# Restrictions: There should be no comments or other symbols on the
# #if(n)def lines. The effect of #define/#undef commands in the input
# file or in included files is not taken into account. Tests using
# #if and the defined() pseudo function are not recognized. The #elif
# command is not recognized. Improperly nesting is not detected.
# Lines that look like preprocessor commands but which are actually
# part of comments or string literals will be mistaken for
# preprocessor commands.
import sys
import getopt
defs = []
undefs = []
def | ():
opts, args = getopt.getopt(sys.argv[1:], 'D:U:')
for o, a in opts:
if o == '-D':
defs.append(a)
if o == '-U':
undefs.append(a)
if not args:
args = ['-']
for filename in args:
if filename == '-':
process(sys.stdin, sys.stdout)
else:
f = open(filename, 'r')
process(f, sys.stdout)
f.close()
def process(fpi, fpo):
keywords = ('if', 'ifdef', 'ifndef', 'else', 'endif')
ok = 1
stack = []
while 1:
line = fpi.readline()
if not line: break
while line[-2:] == '\\\n':
nextline = fpi.readline()
if not nextline: break
line = line + nextline
tmp = line.strip()
if tmp[:1] != '#':
if ok: fpo.write(line)
continue
tmp = tmp[1:].strip()
words = tmp.split()
keyword = words[0]
if keyword not in keywords:
if ok: fpo.write(line)
continue
if keyword in ('ifdef', 'ifndef') and len(words) == 2:
if keyword == 'ifdef':
ko = 1
else:
ko = 0
word = words[1]
if word in defs:
stack.append((ok, ko, word))
if not ko: ok = 0
elif word in undefs:
stack.append((ok, not ko, word))
if ko: ok = 0
else:
stack.append((ok, -1, word))
if ok: fpo.write(line)
elif keyword == 'if':
stack.append((ok, -1, ''))
if ok: fpo.write(line)
elif keyword == 'else' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
else:
s_ko = not s_ko
ok = s_ok
if not s_ko: ok = 0
stack[-1] = s_ok, s_ko, s_word
elif keyword == 'endif' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
del stack[-1]
ok = s_ok
else:
sys.stderr.write('Unknown keyword %s\n' % keyword)
if stack:
sys.stderr.write('stack: %s\n' % stack)
if __name__ == '__main__':
main()
| main | identifier_name |
ifdef.py | #! /usr/bin/env python
# Selectively preprocess #ifdef / #ifndef statements.
# Usage:
# ifdef [-Dname] ... [-Uname] ... [file] ...
#
# This scans the file(s), looking for #ifdef and #ifndef preprocessor
# commands that test for one of the names mentioned in the -D and -U
# options. On standard output it writes a copy of the input file(s)
# minus those code sections that are suppressed by the selected
# combination of defined/undefined symbols. The #if(n)def/#else/#else
# lines themselfs (if the #if(n)def tests for one of the mentioned
# names) are removed as well.
# Features: Arbitrary nesting of recognized and unrecognized
# preprocesor statements works correctly. Unrecognized #if* commands
# are left in place, so it will never remove too much, only too
# little. It does accept whitespace around the '#' character.
# Restrictions: There should be no comments or other symbols on the
# #if(n)def lines. The effect of #define/#undef commands in the input
# file or in included files is not taken into account. Tests using
# #if and the defined() pseudo function are not recognized. The #elif
# command is not recognized. Improperly nesting is not detected.
# Lines that look like preprocessor commands but which are actually
# part of comments or string literals will be mistaken for
# preprocessor commands.
import sys
import getopt
defs = []
undefs = []
def main():
opts, args = getopt.getopt(sys.argv[1:], 'D:U:')
for o, a in opts:
if o == '-D':
defs.append(a)
if o == '-U':
undefs.append(a)
if not args:
args = ['-']
for filename in args:
if filename == '-':
process(sys.stdin, sys.stdout)
else:
f = open(filename, 'r')
process(f, sys.stdout)
f.close()
def process(fpi, fpo):
keywords = ('if', 'ifdef', 'ifndef', 'else', 'endif')
ok = 1
stack = []
while 1:
line = fpi.readline()
if not line: break
while line[-2:] == '\\\n':
nextline = fpi.readline()
if not nextline: break
line = line + nextline
tmp = line.strip()
if tmp[:1] != '#':
if ok: fpo.write(line)
continue
tmp = tmp[1:].strip()
| words = tmp.split()
keyword = words[0]
if keyword not in keywords:
if ok: fpo.write(line)
continue
if keyword in ('ifdef', 'ifndef') and len(words) == 2:
if keyword == 'ifdef':
ko = 1
else:
ko = 0
word = words[1]
if word in defs:
stack.append((ok, ko, word))
if not ko: ok = 0
elif word in undefs:
stack.append((ok, not ko, word))
if ko: ok = 0
else:
stack.append((ok, -1, word))
if ok: fpo.write(line)
elif keyword == 'if':
stack.append((ok, -1, ''))
if ok: fpo.write(line)
elif keyword == 'else' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
else:
s_ko = not s_ko
ok = s_ok
if not s_ko: ok = 0
stack[-1] = s_ok, s_ko, s_word
elif keyword == 'endif' and stack:
s_ok, s_ko, s_word = stack[-1]
if s_ko < 0:
if ok: fpo.write(line)
del stack[-1]
ok = s_ok
else:
sys.stderr.write('Unknown keyword %s\n' % keyword)
if stack:
sys.stderr.write('stack: %s\n' % stack)
if __name__ == '__main__':
main() | random_line_split | |
urls.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
from PenBlog.admin import article,category,link,other
__author__ = 'lihaoquan'
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
# 文章
url(r'^$', article.show_articles),
url(r'^new-article/$', article.new),
url(r'^edit-article/(\d+)/$', article.edit),
url(r'^delete-article/(\d+)/$', article.delete), | url(r'^show-categories/$', category.show_all),
url(r'^new-category/$', category.new),
url(r'^edit-category/([0-9a-f]+)/$', category.edit),
url(r'^delete-category/([0-9a-f]+)/$', category.delete),
# 连接
url( r'^show-links/$', link.show_all),
url( r'^new-link/$', link.new),
url( r'^edit-link/([0-9a-f]+)/$', link.edit),
url( r'^delete-link/([0-9a-f]+)/$', link.delete),
# 设置
url( r'^blog-settings/$', other.show_settings),
url( r'^blog-plugins/$', other.show_plugins),
url( r'^upload-xml/$', other.upload_xml),
url( r'^import-xml/(.+?)/$', other.import_xml),
url( r'^import-and-export/$', other.import_and_export),
) | url(r'^show-hidden-article/(\d+)/$', article.show_hidden_article),
# 分类 | random_line_split |
appdirs.py | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Philipp Wolfer
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import os.path
from PyQt5.QtCore import (
QCoreApplication,
QStandardPaths,
)
from picard import (
PICARD_APP_NAME,
PICARD_ORG_NAME,
)
# Ensure the application is properly configured for the paths to work
QCoreApplication.setApplicationName(PICARD_APP_NAME)
QCoreApplication.setOrganizationName(PICARD_ORG_NAME)
def config_folder():
return os.path.normpath(os.environ.get('PICARD_CONFIG_DIR', QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation)))
def cache_folder():
|
def plugin_folder():
# FIXME: This really should be in QStandardPaths.AppDataLocation instead,
# but this is a breaking change that requires data migration
return os.path.normpath(os.environ.get('PICARD_PLUGIN_DIR', os.path.join(config_folder(), 'plugins')))
| return os.path.normpath(os.environ.get('PICARD_CACHE_DIR', QStandardPaths.writableLocation(QStandardPaths.CacheLocation))) | identifier_body |
appdirs.py | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Philipp Wolfer
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import os.path
from PyQt5.QtCore import (
QCoreApplication,
QStandardPaths,
)
from picard import (
PICARD_APP_NAME,
PICARD_ORG_NAME, | QCoreApplication.setOrganizationName(PICARD_ORG_NAME)
def config_folder():
return os.path.normpath(os.environ.get('PICARD_CONFIG_DIR', QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation)))
def cache_folder():
return os.path.normpath(os.environ.get('PICARD_CACHE_DIR', QStandardPaths.writableLocation(QStandardPaths.CacheLocation)))
def plugin_folder():
# FIXME: This really should be in QStandardPaths.AppDataLocation instead,
# but this is a breaking change that requires data migration
return os.path.normpath(os.environ.get('PICARD_PLUGIN_DIR', os.path.join(config_folder(), 'plugins'))) | )
# Ensure the application is properly configured for the paths to work
QCoreApplication.setApplicationName(PICARD_APP_NAME) | random_line_split |
appdirs.py | # -*- coding: utf-8 -*-
#
# Picard, the next-generation MusicBrainz tagger
#
# Copyright (C) 2021 Philipp Wolfer
#
# This program 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 2
# of the License, or (at your option) any later version.
#
# This program 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 this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import os
import os.path
from PyQt5.QtCore import (
QCoreApplication,
QStandardPaths,
)
from picard import (
PICARD_APP_NAME,
PICARD_ORG_NAME,
)
# Ensure the application is properly configured for the paths to work
QCoreApplication.setApplicationName(PICARD_APP_NAME)
QCoreApplication.setOrganizationName(PICARD_ORG_NAME)
def | ():
return os.path.normpath(os.environ.get('PICARD_CONFIG_DIR', QStandardPaths.writableLocation(QStandardPaths.AppConfigLocation)))
def cache_folder():
return os.path.normpath(os.environ.get('PICARD_CACHE_DIR', QStandardPaths.writableLocation(QStandardPaths.CacheLocation)))
def plugin_folder():
# FIXME: This really should be in QStandardPaths.AppDataLocation instead,
# but this is a breaking change that requires data migration
return os.path.normpath(os.environ.get('PICARD_PLUGIN_DIR', os.path.join(config_folder(), 'plugins')))
| config_folder | identifier_name |
position.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* A position in the editor. This interface is suitable for serialization.
*/
export interface IPosition {
/**
* line number (starts at 1)
*/
readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
readonly column: number;
}
/**
* A position in the editor.
*/
export class Position {
/**
* line number (starts at 1)
*/
public readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
public readonly column: number;
constructor(lineNumber: number, column: number) {
this.lineNumber = lineNumber;
this.column = column;
}
/**
* Create a new position from this position.
*
* @param newLineNumber new line number
* @param newColumn new column
*/
with(newLineNumber: number = this.lineNumber, newColumn: number = this.column): Position {
if (newLineNumber === this.lineNumber && newColumn === this.column) {
return this;
} else {
return new Position(newLineNumber, newColumn);
}
}
/**
* Derive a new position from this position.
*
* @param deltaLineNumber line number delta
* @param deltaColumn column delta
*/
delta(deltaLineNumber: number = 0, deltaColumn: number = 0): Position {
return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
}
/**
* Test if this position equals other position
*/
public equals(other: IPosition): boolean {
return Position.equals(this, other);
}
/**
* Test if position `a` equals position `b`
*/
public static equals(a: IPosition | null, b: IPosition | null): boolean {
if (!a && !b) {
return true;
}
return (
!!a &&
!!b &&
a.lineNumber === b.lineNumber &&
a.column === b.column
);
}
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be false.
*/
public isBefore(other: IPosition): boolean {
return Position.isBefore(this, other);
}
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be false.
*/
public static isBefore(a: IPosition, b: IPosition): boolean {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column < b.column;
}
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be true.
*/
public isBeforeOrEqual(other: IPosition): boolean {
return Position.isBeforeOrEqual(this, other);
}
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be true.
*/
public static isBeforeOrEqual(a: IPosition, b: IPosition): boolean {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) { | /**
* A function that compares positions, useful for sorting
*/
public static compare(a: IPosition, b: IPosition): number {
const aLineNumber = a.lineNumber | 0;
const bLineNumber = b.lineNumber | 0;
if (aLineNumber === bLineNumber) {
const aColumn = a.column | 0;
const bColumn = b.column | 0;
return aColumn - bColumn;
}
return aLineNumber - bLineNumber;
}
/**
* Clone this position.
*/
public clone(): Position {
return new Position(this.lineNumber, this.column);
}
/**
* Convert to a human-readable representation.
*/
public toString(): string {
return '(' + this.lineNumber + ',' + this.column + ')';
}
// ---
/**
* Create a `Position` from an `IPosition`.
*/
public static lift(pos: IPosition): Position {
return new Position(pos.lineNumber, pos.column);
}
/**
* Test if `obj` is an `IPosition`.
*/
public static isIPosition(obj: any): obj is IPosition {
return (
obj
&& (typeof obj.lineNumber === 'number')
&& (typeof obj.column === 'number')
);
}
} | return false;
}
return a.column <= b.column;
}
| random_line_split |
position.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* A position in the editor. This interface is suitable for serialization.
*/
export interface IPosition {
/**
* line number (starts at 1)
*/
readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
readonly column: number;
}
/**
* A position in the editor.
*/
export class Position {
/**
* line number (starts at 1)
*/
public readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
public readonly column: number;
constructor(lineNumber: number, column: number) {
this.lineNumber = lineNumber;
this.column = column;
}
/**
* Create a new position from this position.
*
* @param newLineNumber new line number
* @param newColumn new column
*/
with(newLineNumber: number = this.lineNumber, newColumn: number = this.column): Position {
if (newLineNumber === this.lineNumber && newColumn === this.column) {
return this;
} else {
return new Position(newLineNumber, newColumn);
}
}
/**
* Derive a new position from this position.
*
* @param deltaLineNumber line number delta
* @param deltaColumn column delta
*/
delta(deltaLineNumber: number = 0, deltaColumn: number = 0): Position {
return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
}
/**
* Test if this position equals other position
*/
public equals(other: IPosition): boolean {
return Position.equals(this, other);
}
/**
* Test if position `a` equals position `b`
*/
public static equals(a: IPosition | null, b: IPosition | null): boolean {
if (!a && !b) {
return true;
}
return (
!!a &&
!!b &&
a.lineNumber === b.lineNumber &&
a.column === b.column
);
}
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be false.
*/
public isBefore(other: IPosition): boolean {
return Position.isBefore(this, other);
}
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be false.
*/
public static isBefore(a: IPosition, b: IPosition): boolean {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column < b.column;
}
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be true.
*/
public isBeforeOrEqual(other: IPosition): boolean {
return Position.isBeforeOrEqual(this, other);
}
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be true.
*/
public static isBeforeOrEqual(a: IPosition, b: IPosition): boolean {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column <= b.column;
}
/**
* A function that compares positions, useful for sorting
*/
public static compare(a: IPosition, b: IPosition): number {
const aLineNumber = a.lineNumber | 0;
const bLineNumber = b.lineNumber | 0;
if (aLineNumber === bLineNumber) {
const aColumn = a.column | 0;
const bColumn = b.column | 0;
return aColumn - bColumn;
}
return aLineNumber - bLineNumber;
}
/**
* Clone this position.
*/
public clone(): Position |
/**
* Convert to a human-readable representation.
*/
public toString(): string {
return '(' + this.lineNumber + ',' + this.column + ')';
}
// ---
/**
* Create a `Position` from an `IPosition`.
*/
public static lift(pos: IPosition): Position {
return new Position(pos.lineNumber, pos.column);
}
/**
* Test if `obj` is an `IPosition`.
*/
public static isIPosition(obj: any): obj is IPosition {
return (
obj
&& (typeof obj.lineNumber === 'number')
&& (typeof obj.column === 'number')
);
}
}
| {
return new Position(this.lineNumber, this.column);
} | identifier_body |
position.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* A position in the editor. This interface is suitable for serialization.
*/
export interface IPosition {
/**
* line number (starts at 1)
*/
readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
readonly column: number;
}
/**
* A position in the editor.
*/
export class Position {
/**
* line number (starts at 1)
*/
public readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
public readonly column: number;
constructor(lineNumber: number, column: number) {
this.lineNumber = lineNumber;
this.column = column;
}
/**
* Create a new position from this position.
*
* @param newLineNumber new line number
* @param newColumn new column
*/
with(newLineNumber: number = this.lineNumber, newColumn: number = this.column): Position {
if (newLineNumber === this.lineNumber && newColumn === this.column) {
return this;
} else {
return new Position(newLineNumber, newColumn);
}
}
/**
* Derive a new position from this position.
*
* @param deltaLineNumber line number delta
* @param deltaColumn column delta
*/
delta(deltaLineNumber: number = 0, deltaColumn: number = 0): Position {
return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
}
/**
* Test if this position equals other position
*/
public equals(other: IPosition): boolean {
return Position.equals(this, other);
}
/**
* Test if position `a` equals position `b`
*/
public static equals(a: IPosition | null, b: IPosition | null): boolean {
if (!a && !b) {
return true;
}
return (
!!a &&
!!b &&
a.lineNumber === b.lineNumber &&
a.column === b.column
);
}
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be false.
*/
public isBefore(other: IPosition): boolean {
return Position.isBefore(this, other);
}
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be false.
*/
public static isBefore(a: IPosition, b: IPosition): boolean {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column < b.column;
}
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be true.
*/
public | (other: IPosition): boolean {
return Position.isBeforeOrEqual(this, other);
}
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be true.
*/
public static isBeforeOrEqual(a: IPosition, b: IPosition): boolean {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column <= b.column;
}
/**
* A function that compares positions, useful for sorting
*/
public static compare(a: IPosition, b: IPosition): number {
const aLineNumber = a.lineNumber | 0;
const bLineNumber = b.lineNumber | 0;
if (aLineNumber === bLineNumber) {
const aColumn = a.column | 0;
const bColumn = b.column | 0;
return aColumn - bColumn;
}
return aLineNumber - bLineNumber;
}
/**
* Clone this position.
*/
public clone(): Position {
return new Position(this.lineNumber, this.column);
}
/**
* Convert to a human-readable representation.
*/
public toString(): string {
return '(' + this.lineNumber + ',' + this.column + ')';
}
// ---
/**
* Create a `Position` from an `IPosition`.
*/
public static lift(pos: IPosition): Position {
return new Position(pos.lineNumber, pos.column);
}
/**
* Test if `obj` is an `IPosition`.
*/
public static isIPosition(obj: any): obj is IPosition {
return (
obj
&& (typeof obj.lineNumber === 'number')
&& (typeof obj.column === 'number')
);
}
}
| isBeforeOrEqual | identifier_name |
position.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
/**
* A position in the editor. This interface is suitable for serialization.
*/
export interface IPosition {
/**
* line number (starts at 1)
*/
readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
readonly column: number;
}
/**
* A position in the editor.
*/
export class Position {
/**
* line number (starts at 1)
*/
public readonly lineNumber: number;
/**
* column (the first character in a line is between column 1 and column 2)
*/
public readonly column: number;
constructor(lineNumber: number, column: number) {
this.lineNumber = lineNumber;
this.column = column;
}
/**
* Create a new position from this position.
*
* @param newLineNumber new line number
* @param newColumn new column
*/
with(newLineNumber: number = this.lineNumber, newColumn: number = this.column): Position {
if (newLineNumber === this.lineNumber && newColumn === this.column) {
return this;
} else {
return new Position(newLineNumber, newColumn);
}
}
/**
* Derive a new position from this position.
*
* @param deltaLineNumber line number delta
* @param deltaColumn column delta
*/
delta(deltaLineNumber: number = 0, deltaColumn: number = 0): Position {
return this.with(this.lineNumber + deltaLineNumber, this.column + deltaColumn);
}
/**
* Test if this position equals other position
*/
public equals(other: IPosition): boolean {
return Position.equals(this, other);
}
/**
* Test if position `a` equals position `b`
*/
public static equals(a: IPosition | null, b: IPosition | null): boolean {
if (!a && !b) {
return true;
}
return (
!!a &&
!!b &&
a.lineNumber === b.lineNumber &&
a.column === b.column
);
}
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be false.
*/
public isBefore(other: IPosition): boolean {
return Position.isBefore(this, other);
}
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be false.
*/
public static isBefore(a: IPosition, b: IPosition): boolean {
if (a.lineNumber < b.lineNumber) {
return true;
}
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column < b.column;
}
/**
* Test if this position is before other position.
* If the two positions are equal, the result will be true.
*/
public isBeforeOrEqual(other: IPosition): boolean {
return Position.isBeforeOrEqual(this, other);
}
/**
* Test if position `a` is before position `b`.
* If the two positions are equal, the result will be true.
*/
public static isBeforeOrEqual(a: IPosition, b: IPosition): boolean {
if (a.lineNumber < b.lineNumber) |
if (b.lineNumber < a.lineNumber) {
return false;
}
return a.column <= b.column;
}
/**
* A function that compares positions, useful for sorting
*/
public static compare(a: IPosition, b: IPosition): number {
const aLineNumber = a.lineNumber | 0;
const bLineNumber = b.lineNumber | 0;
if (aLineNumber === bLineNumber) {
const aColumn = a.column | 0;
const bColumn = b.column | 0;
return aColumn - bColumn;
}
return aLineNumber - bLineNumber;
}
/**
* Clone this position.
*/
public clone(): Position {
return new Position(this.lineNumber, this.column);
}
/**
* Convert to a human-readable representation.
*/
public toString(): string {
return '(' + this.lineNumber + ',' + this.column + ')';
}
// ---
/**
* Create a `Position` from an `IPosition`.
*/
public static lift(pos: IPosition): Position {
return new Position(pos.lineNumber, pos.column);
}
/**
* Test if `obj` is an `IPosition`.
*/
public static isIPosition(obj: any): obj is IPosition {
return (
obj
&& (typeof obj.lineNumber === 'number')
&& (typeof obj.column === 'number')
);
}
}
| {
return true;
} | conditional_block |
mod.rs | // Copyright 2014 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.
use core::cmp::PartialEq;
use core::fmt::Debug;
use core::ops::{Add, Sub, Mul, Div, Rem};
use core::marker::Copy;
#[macro_use]
mod int_macros;
mod i8;
mod i16;
mod i32;
mod i64;
#[macro_use]
mod uint_macros;
mod u8;
mod u16;
mod u32;
mod u64;
mod flt2dec;
/// Helper function for testing numeric operations
pub fn test_num<T>(ten: T, two: T) where
T: PartialEq
+ Add<Output=T> + Sub<Output=T>
+ Mul<Output=T> + Div<Output=T>
+ Rem<Output=T> + Debug
+ Copy
{
assert_eq!(ten.add(two), ten + two);
assert_eq!(ten.sub(two), ten - two);
assert_eq!(ten.mul(two), ten * two);
assert_eq!(ten.div(two), ten / two);
assert_eq!(ten.rem(two), ten % two);
}
#[cfg(test)]
mod tests {
use core::option::Option;
use core::option::Option::{Some, None};
use core::num::Float;
#[test]
fn from_str_issue7588() {
let u : Option<u8> = u8::from_str_radix("1000", 10).ok();
assert_eq!(u, None);
let s : Option<i16> = i16::from_str_radix("80000", 10).ok();
assert_eq!(s, None);
let s = "10000000000000000000000000000000000000000";
let f : Option<f32> = f32::from_str_radix(s, 10).ok();
assert_eq!(f, Some(Float::infinity()));
let fe : Option<f32> = f32::from_str_radix("1e40", 10).ok();
assert_eq!(fe, Some(Float::infinity()));
}
#[test]
fn test_from_str_radix_float() |
#[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127;
assert_eq!("127".parse::<i8>().ok(), Some(i8_val));
assert_eq!("128".parse::<i8>().ok(), None);
i8_val = i8_val.wrapping_add(1);
assert_eq!("-128".parse::<i8>().ok(), Some(i8_val));
assert_eq!("-129".parse::<i8>().ok(), None);
let mut i16_val: i16 = 32_767;
assert_eq!("32767".parse::<i16>().ok(), Some(i16_val));
assert_eq!("32768".parse::<i16>().ok(), None);
i16_val = i16_val.wrapping_add(1);
assert_eq!("-32768".parse::<i16>().ok(), Some(i16_val));
assert_eq!("-32769".parse::<i16>().ok(), None);
let mut i32_val: i32 = 2_147_483_647;
assert_eq!("2147483647".parse::<i32>().ok(), Some(i32_val));
assert_eq!("2147483648".parse::<i32>().ok(), None);
i32_val = i32_val.wrapping_add(1);
assert_eq!("-2147483648".parse::<i32>().ok(), Some(i32_val));
assert_eq!("-2147483649".parse::<i32>().ok(), None);
let mut i64_val: i64 = 9_223_372_036_854_775_807;
assert_eq!("9223372036854775807".parse::<i64>().ok(), Some(i64_val));
assert_eq!("9223372036854775808".parse::<i64>().ok(), None);
i64_val = i64_val.wrapping_add(1);
assert_eq!("-9223372036854775808".parse::<i64>().ok(), Some(i64_val));
assert_eq!("-9223372036854775809".parse::<i64>().ok(), None);
}
#[test]
fn test_invalid() {
assert_eq!("--129".parse::<i8>().ok(), None);
assert_eq!("Съешь".parse::<u8>().ok(), None);
}
#[test]
fn test_empty() {
assert_eq!("-".parse::<i8>().ok(), None);
assert_eq!("".parse::<u8>().ok(), None);
}
}
| {
let x1 : Option<f64> = f64::from_str_radix("-123.456", 10).ok();
assert_eq!(x1, Some(-123.456));
let x2 : Option<f32> = f32::from_str_radix("123.456", 10).ok();
assert_eq!(x2, Some(123.456));
let x3 : Option<f32> = f32::from_str_radix("-0.0", 10).ok();
assert_eq!(x3, Some(-0.0));
let x4 : Option<f32> = f32::from_str_radix("0.0", 10).ok();
assert_eq!(x4, Some(0.0));
let x4 : Option<f32> = f32::from_str_radix("1.0", 10).ok();
assert_eq!(x4, Some(1.0));
let x5 : Option<f32> = f32::from_str_radix("-1.0", 10).ok();
assert_eq!(x5, Some(-1.0));
} | identifier_body |
mod.rs | // Copyright 2014 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.
use core::cmp::PartialEq;
use core::fmt::Debug;
use core::ops::{Add, Sub, Mul, Div, Rem};
use core::marker::Copy;
#[macro_use]
mod int_macros;
mod i8;
mod i16;
mod i32;
mod i64;
#[macro_use]
mod uint_macros;
mod u8;
mod u16;
mod u32;
mod u64;
mod flt2dec;
/// Helper function for testing numeric operations
pub fn | <T>(ten: T, two: T) where
T: PartialEq
+ Add<Output=T> + Sub<Output=T>
+ Mul<Output=T> + Div<Output=T>
+ Rem<Output=T> + Debug
+ Copy
{
assert_eq!(ten.add(two), ten + two);
assert_eq!(ten.sub(two), ten - two);
assert_eq!(ten.mul(two), ten * two);
assert_eq!(ten.div(two), ten / two);
assert_eq!(ten.rem(two), ten % two);
}
#[cfg(test)]
mod tests {
use core::option::Option;
use core::option::Option::{Some, None};
use core::num::Float;
#[test]
fn from_str_issue7588() {
let u : Option<u8> = u8::from_str_radix("1000", 10).ok();
assert_eq!(u, None);
let s : Option<i16> = i16::from_str_radix("80000", 10).ok();
assert_eq!(s, None);
let s = "10000000000000000000000000000000000000000";
let f : Option<f32> = f32::from_str_radix(s, 10).ok();
assert_eq!(f, Some(Float::infinity()));
let fe : Option<f32> = f32::from_str_radix("1e40", 10).ok();
assert_eq!(fe, Some(Float::infinity()));
}
#[test]
fn test_from_str_radix_float() {
let x1 : Option<f64> = f64::from_str_radix("-123.456", 10).ok();
assert_eq!(x1, Some(-123.456));
let x2 : Option<f32> = f32::from_str_radix("123.456", 10).ok();
assert_eq!(x2, Some(123.456));
let x3 : Option<f32> = f32::from_str_radix("-0.0", 10).ok();
assert_eq!(x3, Some(-0.0));
let x4 : Option<f32> = f32::from_str_radix("0.0", 10).ok();
assert_eq!(x4, Some(0.0));
let x4 : Option<f32> = f32::from_str_radix("1.0", 10).ok();
assert_eq!(x4, Some(1.0));
let x5 : Option<f32> = f32::from_str_radix("-1.0", 10).ok();
assert_eq!(x5, Some(-1.0));
}
#[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127;
assert_eq!("127".parse::<i8>().ok(), Some(i8_val));
assert_eq!("128".parse::<i8>().ok(), None);
i8_val = i8_val.wrapping_add(1);
assert_eq!("-128".parse::<i8>().ok(), Some(i8_val));
assert_eq!("-129".parse::<i8>().ok(), None);
let mut i16_val: i16 = 32_767;
assert_eq!("32767".parse::<i16>().ok(), Some(i16_val));
assert_eq!("32768".parse::<i16>().ok(), None);
i16_val = i16_val.wrapping_add(1);
assert_eq!("-32768".parse::<i16>().ok(), Some(i16_val));
assert_eq!("-32769".parse::<i16>().ok(), None);
let mut i32_val: i32 = 2_147_483_647;
assert_eq!("2147483647".parse::<i32>().ok(), Some(i32_val));
assert_eq!("2147483648".parse::<i32>().ok(), None);
i32_val = i32_val.wrapping_add(1);
assert_eq!("-2147483648".parse::<i32>().ok(), Some(i32_val));
assert_eq!("-2147483649".parse::<i32>().ok(), None);
let mut i64_val: i64 = 9_223_372_036_854_775_807;
assert_eq!("9223372036854775807".parse::<i64>().ok(), Some(i64_val));
assert_eq!("9223372036854775808".parse::<i64>().ok(), None);
i64_val = i64_val.wrapping_add(1);
assert_eq!("-9223372036854775808".parse::<i64>().ok(), Some(i64_val));
assert_eq!("-9223372036854775809".parse::<i64>().ok(), None);
}
#[test]
fn test_invalid() {
assert_eq!("--129".parse::<i8>().ok(), None);
assert_eq!("Съешь".parse::<u8>().ok(), None);
}
#[test]
fn test_empty() {
assert_eq!("-".parse::<i8>().ok(), None);
assert_eq!("".parse::<u8>().ok(), None);
}
}
| test_num | identifier_name |
mod.rs | // Copyright 2014 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.
use core::cmp::PartialEq;
use core::fmt::Debug;
use core::ops::{Add, Sub, Mul, Div, Rem};
use core::marker::Copy;
#[macro_use]
mod int_macros;
mod i8;
mod i16;
mod i32;
mod i64;
#[macro_use]
mod uint_macros;
mod u8;
mod u16;
mod u32;
mod u64;
mod flt2dec;
/// Helper function for testing numeric operations
pub fn test_num<T>(ten: T, two: T) where
T: PartialEq
+ Add<Output=T> + Sub<Output=T>
+ Mul<Output=T> + Div<Output=T>
+ Rem<Output=T> + Debug
+ Copy
{
assert_eq!(ten.add(two), ten + two);
assert_eq!(ten.sub(two), ten - two);
assert_eq!(ten.mul(two), ten * two);
assert_eq!(ten.div(two), ten / two);
assert_eq!(ten.rem(two), ten % two);
}
#[cfg(test)]
mod tests {
use core::option::Option;
use core::option::Option::{Some, None};
use core::num::Float;
#[test]
fn from_str_issue7588() {
let u : Option<u8> = u8::from_str_radix("1000", 10).ok();
assert_eq!(u, None);
let s : Option<i16> = i16::from_str_radix("80000", 10).ok();
assert_eq!(s, None);
let s = "10000000000000000000000000000000000000000";
let f : Option<f32> = f32::from_str_radix(s, 10).ok();
assert_eq!(f, Some(Float::infinity()));
let fe : Option<f32> = f32::from_str_radix("1e40", 10).ok();
assert_eq!(fe, Some(Float::infinity()));
}
#[test]
fn test_from_str_radix_float() {
let x1 : Option<f64> = f64::from_str_radix("-123.456", 10).ok();
assert_eq!(x1, Some(-123.456));
let x2 : Option<f32> = f32::from_str_radix("123.456", 10).ok();
assert_eq!(x2, Some(123.456));
let x3 : Option<f32> = f32::from_str_radix("-0.0", 10).ok();
assert_eq!(x3, Some(-0.0));
let x4 : Option<f32> = f32::from_str_radix("0.0", 10).ok();
assert_eq!(x4, Some(0.0));
let x4 : Option<f32> = f32::from_str_radix("1.0", 10).ok(); | #[test]
fn test_int_from_str_overflow() {
let mut i8_val: i8 = 127;
assert_eq!("127".parse::<i8>().ok(), Some(i8_val));
assert_eq!("128".parse::<i8>().ok(), None);
i8_val = i8_val.wrapping_add(1);
assert_eq!("-128".parse::<i8>().ok(), Some(i8_val));
assert_eq!("-129".parse::<i8>().ok(), None);
let mut i16_val: i16 = 32_767;
assert_eq!("32767".parse::<i16>().ok(), Some(i16_val));
assert_eq!("32768".parse::<i16>().ok(), None);
i16_val = i16_val.wrapping_add(1);
assert_eq!("-32768".parse::<i16>().ok(), Some(i16_val));
assert_eq!("-32769".parse::<i16>().ok(), None);
let mut i32_val: i32 = 2_147_483_647;
assert_eq!("2147483647".parse::<i32>().ok(), Some(i32_val));
assert_eq!("2147483648".parse::<i32>().ok(), None);
i32_val = i32_val.wrapping_add(1);
assert_eq!("-2147483648".parse::<i32>().ok(), Some(i32_val));
assert_eq!("-2147483649".parse::<i32>().ok(), None);
let mut i64_val: i64 = 9_223_372_036_854_775_807;
assert_eq!("9223372036854775807".parse::<i64>().ok(), Some(i64_val));
assert_eq!("9223372036854775808".parse::<i64>().ok(), None);
i64_val = i64_val.wrapping_add(1);
assert_eq!("-9223372036854775808".parse::<i64>().ok(), Some(i64_val));
assert_eq!("-9223372036854775809".parse::<i64>().ok(), None);
}
#[test]
fn test_invalid() {
assert_eq!("--129".parse::<i8>().ok(), None);
assert_eq!("Съешь".parse::<u8>().ok(), None);
}
#[test]
fn test_empty() {
assert_eq!("-".parse::<i8>().ok(), None);
assert_eq!("".parse::<u8>().ok(), None);
}
} | assert_eq!(x4, Some(1.0));
let x5 : Option<f32> = f32::from_str_radix("-1.0", 10).ok();
assert_eq!(x5, Some(-1.0));
}
| random_line_split |
issue-34798.rs | // Copyright 2017 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.
// run-pass
#![forbid(improper_ctypes)]
#![allow(dead_code)]
#[repr(C)]
pub struct Foo {
size: u8,
__value: ::std::marker::PhantomData<i32>,
}
| pub struct ZeroSizeWithPhantomData<T>(::std::marker::PhantomData<T>);
#[repr(C)]
pub struct Bar {
size: u8,
baz: ZeroSizeWithPhantomData<i32>,
}
extern "C" {
pub fn bar(_: *mut Foo, _: *mut Bar);
}
fn main() {
} | #[repr(C)] | random_line_split |
issue-34798.rs | // Copyright 2017 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.
// run-pass
#![forbid(improper_ctypes)]
#![allow(dead_code)]
#[repr(C)]
pub struct Foo {
size: u8,
__value: ::std::marker::PhantomData<i32>,
}
#[repr(C)]
pub struct ZeroSizeWithPhantomData<T>(::std::marker::PhantomData<T>);
#[repr(C)]
pub struct | {
size: u8,
baz: ZeroSizeWithPhantomData<i32>,
}
extern "C" {
pub fn bar(_: *mut Foo, _: *mut Bar);
}
fn main() {
}
| Bar | identifier_name |
vec-res-add.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.
#[deriving(Show)]
struct r {
i:int
} |
impl Drop for r {
fn drop(&mut self) {}
}
fn main() {
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR binary operation `+` cannot be applied to type
println!("{}", j);
} |
fn r(i:int) -> r { r { i: i } } | random_line_split |
vec-res-add.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.
#[deriving(Show)]
struct r {
i:int
}
fn r(i:int) -> r { r { i: i } }
impl Drop for r {
fn | (&mut self) {}
}
fn main() {
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR binary operation `+` cannot be applied to type
println!("{}", j);
}
| drop | identifier_name |
vec-res-add.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.
#[deriving(Show)]
struct r {
i:int
}
fn r(i:int) -> r |
impl Drop for r {
fn drop(&mut self) {}
}
fn main() {
// This can't make sense as it would copy the classes
let i = vec!(r(0));
let j = vec!(r(1));
let k = i + j;
//~^ ERROR binary operation `+` cannot be applied to type
println!("{}", j);
}
| { r { i: i } } | identifier_body |
process.py | from .logging import debug, exception_log
from .typing import Any, List, Dict, Callable, Optional, IO
import os
import shutil
import subprocess
import threading
def add_extension_if_missing(server_binary_args: List[str]) -> List[str]:
if len(server_binary_args) > 0:
executable_arg = server_binary_args[0]
fname, ext = os.path.splitext(executable_arg)
if len(ext) < 1:
path_to_executable = shutil.which(executable_arg)
# what extensions should we append so CreateProcess can find it?
# node has .cmd
# dart has .bat
# python has .exe wrappers - not needed
for extension in ['.cmd', '.bat']:
if path_to_executable and path_to_executable.lower().endswith(extension):
executable_arg = executable_arg + extension
updated_args = [executable_arg]
updated_args.extend(server_binary_args[1:])
return updated_args
return server_binary_args
def start_server(
server_binary_args: List[str],
working_dir: Optional[str],
env: Dict[str, str],
on_stderr_log: Optional[Callable[[str], None]]
) -> Optional[subprocess.Popen]:
|
def attach_logger(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None:
threading.Thread(target=log_stream, args=(process, stream, log_callback)).start()
def log_stream(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None:
"""
Read lines from a stream and invoke the log_callback on the result
"""
running = True
while running:
running = process.poll() is None
try:
content = stream.readline()
if not content:
break
log_callback(content.decode('UTF-8', 'replace').strip())
except IOError as err:
exception_log("Failure reading stream", err)
return
debug("LSP stream logger stopped.")
| si = None
if os.name == "nt":
server_binary_args = add_extension_if_missing(server_binary_args)
si = subprocess.STARTUPINFO() # type: ignore
si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW # type: ignore
debug("starting " + str(server_binary_args))
stderr_destination = subprocess.PIPE if on_stderr_log else subprocess.DEVNULL
process = subprocess.Popen(
server_binary_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=stderr_destination,
cwd=working_dir,
env=env,
startupinfo=si)
if on_stderr_log is not None:
attach_logger(process, process.stderr, on_stderr_log) # type: ignore
return process | identifier_body |
process.py | from .logging import debug, exception_log
from .typing import Any, List, Dict, Callable, Optional, IO
import os
import shutil
import subprocess
import threading
def add_extension_if_missing(server_binary_args: List[str]) -> List[str]:
if len(server_binary_args) > 0:
executable_arg = server_binary_args[0]
fname, ext = os.path.splitext(executable_arg)
if len(ext) < 1:
path_to_executable = shutil.which(executable_arg)
# what extensions should we append so CreateProcess can find it?
# node has .cmd
# dart has .bat
# python has .exe wrappers - not needed
for extension in ['.cmd', '.bat']:
if path_to_executable and path_to_executable.lower().endswith(extension):
executable_arg = executable_arg + extension
updated_args = [executable_arg]
updated_args.extend(server_binary_args[1:])
return updated_args
return server_binary_args
def start_server(
server_binary_args: List[str],
working_dir: Optional[str],
env: Dict[str, str],
on_stderr_log: Optional[Callable[[str], None]]
) -> Optional[subprocess.Popen]:
si = None
if os.name == "nt":
server_binary_args = add_extension_if_missing(server_binary_args)
si = subprocess.STARTUPINFO() # type: ignore
si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW # type: ignore
debug("starting " + str(server_binary_args))
stderr_destination = subprocess.PIPE if on_stderr_log else subprocess.DEVNULL
process = subprocess.Popen(
server_binary_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=stderr_destination,
cwd=working_dir,
env=env,
startupinfo=si)
if on_stderr_log is not None:
attach_logger(process, process.stderr, on_stderr_log) # type: ignore
return process
def attach_logger(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None:
threading.Thread(target=log_stream, args=(process, stream, log_callback)).start()
def log_stream(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None:
"""
Read lines from a stream and invoke the log_callback on the result
"""
running = True
while running:
running = process.poll() is None
try:
content = stream.readline()
if not content:
|
log_callback(content.decode('UTF-8', 'replace').strip())
except IOError as err:
exception_log("Failure reading stream", err)
return
debug("LSP stream logger stopped.")
| break | conditional_block |
process.py | from .logging import debug, exception_log
from .typing import Any, List, Dict, Callable, Optional, IO
import os
import shutil
import subprocess
import threading
def add_extension_if_missing(server_binary_args: List[str]) -> List[str]:
if len(server_binary_args) > 0:
executable_arg = server_binary_args[0]
fname, ext = os.path.splitext(executable_arg)
if len(ext) < 1:
path_to_executable = shutil.which(executable_arg)
# what extensions should we append so CreateProcess can find it?
# node has .cmd
# dart has .bat
# python has .exe wrappers - not needed
for extension in ['.cmd', '.bat']:
if path_to_executable and path_to_executable.lower().endswith(extension):
executable_arg = executable_arg + extension
updated_args = [executable_arg]
updated_args.extend(server_binary_args[1:])
return updated_args
return server_binary_args
def start_server(
server_binary_args: List[str],
working_dir: Optional[str],
env: Dict[str, str],
on_stderr_log: Optional[Callable[[str], None]]
) -> Optional[subprocess.Popen]:
si = None
if os.name == "nt":
server_binary_args = add_extension_if_missing(server_binary_args)
si = subprocess.STARTUPINFO() # type: ignore
si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW # type: ignore
debug("starting " + str(server_binary_args))
stderr_destination = subprocess.PIPE if on_stderr_log else subprocess.DEVNULL
process = subprocess.Popen(
server_binary_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=stderr_destination,
cwd=working_dir,
env=env,
startupinfo=si)
if on_stderr_log is not None:
attach_logger(process, process.stderr, on_stderr_log) # type: ignore
return process
def attach_logger(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None:
threading.Thread(target=log_stream, args=(process, stream, log_callback)).start() | def log_stream(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None:
"""
Read lines from a stream and invoke the log_callback on the result
"""
running = True
while running:
running = process.poll() is None
try:
content = stream.readline()
if not content:
break
log_callback(content.decode('UTF-8', 'replace').strip())
except IOError as err:
exception_log("Failure reading stream", err)
return
debug("LSP stream logger stopped.") | random_line_split | |
process.py | from .logging import debug, exception_log
from .typing import Any, List, Dict, Callable, Optional, IO
import os
import shutil
import subprocess
import threading
def add_extension_if_missing(server_binary_args: List[str]) -> List[str]:
if len(server_binary_args) > 0:
executable_arg = server_binary_args[0]
fname, ext = os.path.splitext(executable_arg)
if len(ext) < 1:
path_to_executable = shutil.which(executable_arg)
# what extensions should we append so CreateProcess can find it?
# node has .cmd
# dart has .bat
# python has .exe wrappers - not needed
for extension in ['.cmd', '.bat']:
if path_to_executable and path_to_executable.lower().endswith(extension):
executable_arg = executable_arg + extension
updated_args = [executable_arg]
updated_args.extend(server_binary_args[1:])
return updated_args
return server_binary_args
def start_server(
server_binary_args: List[str],
working_dir: Optional[str],
env: Dict[str, str],
on_stderr_log: Optional[Callable[[str], None]]
) -> Optional[subprocess.Popen]:
si = None
if os.name == "nt":
server_binary_args = add_extension_if_missing(server_binary_args)
si = subprocess.STARTUPINFO() # type: ignore
si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW # type: ignore
debug("starting " + str(server_binary_args))
stderr_destination = subprocess.PIPE if on_stderr_log else subprocess.DEVNULL
process = subprocess.Popen(
server_binary_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=stderr_destination,
cwd=working_dir,
env=env,
startupinfo=si)
if on_stderr_log is not None:
attach_logger(process, process.stderr, on_stderr_log) # type: ignore
return process
def | (process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None:
threading.Thread(target=log_stream, args=(process, stream, log_callback)).start()
def log_stream(process: subprocess.Popen, stream: IO[Any], log_callback: Callable[[str], None]) -> None:
"""
Read lines from a stream and invoke the log_callback on the result
"""
running = True
while running:
running = process.poll() is None
try:
content = stream.readline()
if not content:
break
log_callback(content.decode('UTF-8', 'replace').strip())
except IOError as err:
exception_log("Failure reading stream", err)
return
debug("LSP stream logger stopped.")
| attach_logger | identifier_name |
FeedContent.d.ts | import * as React from 'react';
import { SemanticShorthandContent, SemanticShorthandItem } from '../..';
import { FeedDateProps } from './FeedDate';
import { FeedExtraProps } from './FeedExtra';
import { FeedMetaProps } from './FeedMeta';
import { FeedSummaryProps } from './FeedSummary';
export interface FeedContentProps {
[key: string]: any;
/** An element type to render as (string or function). */
as?: any;
/** Primary content. */
children?: React.ReactNode;
/** Additional classes. */
className?: string;
/** Shorthand for primary content. */
content?: SemanticShorthandContent;
/** An event can contain a date. */
date?: SemanticShorthandItem<FeedDateProps>;
/** Shorthand for FeedExtra with images. */
extraImages?: SemanticShorthandItem<FeedExtraProps>;
/** Shorthand for FeedExtra with text. */
extraText?: SemanticShorthandItem<FeedExtraProps>;
/** Shorthand for FeedMeta. */
meta?: SemanticShorthandItem<FeedMetaProps>;
/** Shorthand for FeedSummary. */
summary?: SemanticShorthandItem<FeedSummaryProps>;
}
| declare const FeedContent: React.StatelessComponent<FeedContentProps>;
export default FeedContent; | random_line_split | |
uconf.py | #!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
if attr == '_OrderedDict__root':
# Work around Python2's OrderedDict weirdness.
raise AttributeError("AttrDict has no attribute %r" % attr)
return self.__getitem__(attr)
def __setitem__(self, name, value):
d = self
if name in d:
otype = type(d[name])
ntype = type(value)
if otype is not ntype:
msg = "cannot set '%s' to '%s', expecting type: '%s', given '%s'" % \
(name, str(value), otype.__name__, ntype.__name__)
raise AttributeError(msg)
super().__setitem__(name, value)
def __setattr__(self, name, value):
self[name] = value
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m: | self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("uconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
def dump_int(i):
'''Stringize ``i``, append 'L' if ``i`` is exceeds the 32-bit int range'''
return str(i) + ('' if SMALL_INT_MIN <= i <= SMALL_INT_MAX else 'L')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' = ' + spaces
if isinstance(value, dict):
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif isinstance(value, tuple):
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif isinstance(value, list):
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif isstr(value):
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif isint(value):
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif isinstance(value, float):
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u'\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
def namespace(): return AttrDict()
def isnamespace(v): return isinstance(v, dict) | skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1 | random_line_split |
uconf.py | #!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
if attr == '_OrderedDict__root':
# Work around Python2's OrderedDict weirdness.
raise AttributeError("AttrDict has no attribute %r" % attr)
return self.__getitem__(attr)
def __setitem__(self, name, value):
d = self
if name in d:
otype = type(d[name])
ntype = type(value)
if otype is not ntype:
msg = "cannot set '%s' to '%s', expecting type: '%s', given '%s'" % \
(name, str(value), otype.__name__, ntype.__name__)
raise AttributeError(msg)
super().__setitem__(name, value)
def __setattr__(self, name, value):
self[name] = value
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def | (self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("uconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
def dump_int(i):
'''Stringize ``i``, append 'L' if ``i`` is exceeds the 32-bit int range'''
return str(i) + ('' if SMALL_INT_MIN <= i <= SMALL_INT_MAX else 'L')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' = ' + spaces
if isinstance(value, dict):
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif isinstance(value, tuple):
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif isinstance(value, list):
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif isstr(value):
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif isint(value):
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif isinstance(value, float):
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u'\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
def namespace(): return AttrDict()
def isnamespace(v): return isinstance(v, dict)
| __init__ | identifier_name |
uconf.py | #!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
if attr == '_OrderedDict__root':
# Work around Python2's OrderedDict weirdness.
raise AttributeError("AttrDict has no attribute %r" % attr)
return self.__getitem__(attr)
def __setitem__(self, name, value):
d = self
if name in d:
otype = type(d[name])
ntype = type(value)
if otype is not ntype:
msg = "cannot set '%s' to '%s', expecting type: '%s', given '%s'" % \
(name, str(value), otype.__name__, ntype.__name__)
raise AttributeError(msg)
super().__setitem__(name, value)
def __setattr__(self, name, value):
self[name] = value
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
lines.append(line)
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
|
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("uconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
def dump_int(i):
'''Stringize ``i``, append 'L' if ``i`` is exceeds the 32-bit int range'''
return str(i) + ('' if SMALL_INT_MIN <= i <= SMALL_INT_MAX else 'L')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' = ' + spaces
if isinstance(value, dict):
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif isinstance(value, tuple):
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif isinstance(value, list):
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif isstr(value):
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif isint(value):
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif isinstance(value, float):
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u'\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
def namespace(): return AttrDict()
def isnamespace(v): return isinstance(v, dict)
| if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result | identifier_body |
uconf.py | #!/usr/bin/python
from __future__ import absolute_import, division, print_function
import sys
import os
import codecs
import collections
import io
import re
# Define an isstr() and isint() that work on both Python2 and Python3.
# See http://stackoverflow.com/questions/11301138
try:
basestring # attempt to evaluate basestring
def isstr(s):
return isinstance(s, basestring)
def isint(i):
return isinstance(i, (int, long))
except NameError:
def isstr(s):
return isinstance(s, str)
def isint(i):
return isinstance(i, int)
# Bounds to determine when an "L" suffix should be used during dump().
SMALL_INT_MIN = -2**31
SMALL_INT_MAX = 2**31 - 1
ESCAPE_SEQUENCE_RE = re.compile(r'''
( \\x.. # 2-digit hex escapes
| \\[\\'"abfnrtv] # Single-character escapes
)''', re.UNICODE | re.VERBOSE)
SKIP_RE = re.compile(r'\s+|#.*$|//.*$|/\*(.|\n)*?\*/', re.MULTILINE)
UNPRINTABLE_CHARACTER_RE = re.compile(r'[\x00-\x1F\x7F]')
# load() logic
##############
def decode_escapes(s):
'''Unescape libconfig string literals'''
def decode_match(match):
return codecs.decode(match.group(0), 'unicode-escape')
return ESCAPE_SEQUENCE_RE.sub(decode_match, s)
class AttrDict(collections.OrderedDict):
'''OrderedDict subclass giving access to string keys via attribute access
This class derives from collections.OrderedDict. Thus, the original
order of the config entries in the input stream is maintained.
'''
def __getattr__(self, attr):
if attr == '_OrderedDict__root':
# Work around Python2's OrderedDict weirdness.
raise AttributeError("AttrDict has no attribute %r" % attr)
return self.__getitem__(attr)
def __setitem__(self, name, value):
d = self
if name in d:
otype = type(d[name])
ntype = type(value)
if otype is not ntype:
msg = "cannot set '%s' to '%s', expecting type: '%s', given '%s'" % \
(name, str(value), otype.__name__, ntype.__name__)
raise AttributeError(msg)
super().__setitem__(name, value)
def __setattr__(self, name, value):
self[name] = value
class ConfigParseError(RuntimeError):
'''Exception class raised on errors reading the libconfig input'''
pass
class ConfigSerializeError(TypeError):
'''Exception class raised on errors serializing a config object'''
pass
class Token(object):
'''Base class for all tokens produced by the libconf tokenizer'''
def __init__(self, type, text, filename, row, column):
self.type = type
self.text = text
self.filename = filename
self.row = row
self.column = column
def __str__(self):
return "%r in %r, row %d, column %d" % (
self.text, self.filename, self.row, self.column)
class FltToken(Token):
'''Token subclass for floating point values'''
def __init__(self, *args, **kwargs):
super(FltToken, self).__init__(*args, **kwargs)
self.value = float(self.text)
class IntToken(Token):
'''Token subclass for integral values'''
def __init__(self, *args, **kwargs):
super(IntToken, self).__init__(*args, **kwargs)
self.is_long = self.text.endswith('L')
self.is_hex = (self.text[1:2].lower() == 'x')
self.value = int(self.text.rstrip('L'), 0)
class BoolToken(Token):
'''Token subclass for booleans'''
def __init__(self, *args, **kwargs):
super(BoolToken, self).__init__(*args, **kwargs)
self.value = (self.text[0].lower() == 't')
class StrToken(Token):
'''Token subclass for strings'''
def __init__(self, *args, **kwargs):
super(StrToken, self).__init__(*args, **kwargs)
self.value = decode_escapes(self.text[1:-1])
def compile_regexes(token_map):
return [(cls, type, re.compile(regex))
for cls, type, regex in token_map]
class Tokenizer:
'''Tokenize an input string
Typical usage:
tokens = list(Tokenizer("<memory>").tokenize("""a = 7; b = ();"""))
The filename argument to the constructor is used only in error messages, no
data is loaded from the file. The input data is received as argument to the
tokenize function, which yields tokens or throws a ConfigParseError on
invalid input.
Include directives are not supported, they must be handled at a higher
level (cf. the TokenStream class).
'''
token_map = compile_regexes([
(FltToken, 'float', r'([-+]?(\d+)?\.\d*([eE][-+]?\d+)?)|'
r'([-+]?(\d+)(\.\d*)?[eE][-+]?\d+)'),
(IntToken, 'hex64', r'0[Xx][0-9A-Fa-f]+(L(L)?)'),
(IntToken, 'hex', r'0[Xx][0-9A-Fa-f]+'),
(IntToken, 'integer64', r'[-+]?[0-9]+L(L)?'),
(IntToken, 'integer', r'[-+]?[0-9]+'),
(BoolToken, 'boolean', r'(?i)(true|false)\b'),
(StrToken, 'string', r'"([^"\\]|\\.)*"'),
(Token, 'name', r'[A-Za-z\*][-A-Za-z0-9_\*]*'),
(Token, '}', r'\}'),
(Token, '{', r'\{'),
(Token, ')', r'\)'),
(Token, '(', r'\('),
(Token, ']', r'\]'),
(Token, '[', r'\['),
(Token, ',', r','),
(Token, ';', r';'),
(Token, '=', r'='),
(Token, ':', r':'),
])
def __init__(self, filename):
self.filename = filename
self.row = 1
self.column = 1
def tokenize(self, string):
'''Yield tokens from the input string or throw ConfigParseError'''
pos = 0
while pos < len(string):
m = SKIP_RE.match(string, pos=pos)
if m:
skip_lines = m.group(0).split('\n')
if len(skip_lines) > 1:
self.row += len(skip_lines) - 1
self.column = 1 + len(skip_lines[-1])
else:
self.column += len(skip_lines[0])
pos = m.end()
continue
for cls, type, regex in self.token_map:
m = regex.match(string, pos=pos)
if m:
yield cls(type, m.group(0),
self.filename, self.row, self.column)
self.column += len(m.group(0))
pos = m.end()
break
else:
raise ConfigParseError(
"Couldn't load config in %r row %d, column %d: %r" %
(self.filename, self.row, self.column,
string[pos:pos+20]))
class TokenStream:
'''Offer a parsing-oriented view on tokens
Provide several methods that are useful to parsers, like ``accept()``,
``expect()``, ...
The ``from_file()`` method is the preferred way to read input files, as
it handles include directives, which the ``Tokenizer`` class does not do.
'''
def __init__(self, tokens):
self.position = 0
self.tokens = list(tokens)
@classmethod
def from_file(cls, f, filename=None, includedir='', seenfiles=None):
'''Create a token stream by reading an input file
Read tokens from `f`. If an include directive ('@include "file.cfg"')
is found, read its contents as well.
The `filename` argument is used for error messages and to detect
circular imports. ``includedir`` sets the lookup directory for included
files. ``seenfiles`` is used internally to detect circular includes,
and should normally not be supplied by users of is function.
'''
if filename is None:
filename = getattr(f, 'name', '<unknown>')
if seenfiles is None:
seenfiles = set()
if filename in seenfiles:
raise ConfigParseError("Circular include: %r" % (filename,))
seenfiles = seenfiles | {filename} # Copy seenfiles, don't alter it.
tokenizer = Tokenizer(filename=filename)
lines = []
tokens = []
for line in f:
m = re.match(r'@include "(.*)"$', line.strip())
if m:
tokens.extend(tokenizer.tokenize(''.join(lines)))
lines = [re.sub(r'\S', ' ', line)]
includefilename = decode_escapes(m.group(1))
includefilename = os.path.join(includedir, includefilename)
try:
includefile = open(includefilename, "r")
except IOError:
raise ConfigParseError("Could not open include file %r" %
(includefilename,))
with includefile:
includestream = cls.from_file(includefile,
filename=includefilename,
includedir=includedir,
seenfiles=seenfiles)
tokens.extend(includestream.tokens)
else:
|
tokens.extend(tokenizer.tokenize(''.join(lines)))
return cls(tokens)
def peek(self):
'''Return (but do not consume) the next token
At the end of input, ``None`` is returned.
'''
if self.position >= len(self.tokens):
return None
return self.tokens[self.position]
def accept(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, return None.
'''
token = self.peek()
if token is None:
return None
for arg in args:
if token.type == arg:
self.position += 1
return token
return None
def expect(self, *args):
'''Consume and return the next token if it has the correct type
Multiple token types (as strings, e.g. 'integer64') can be given
as arguments. If the next token is one of them, consume and return it.
If the token type doesn't match, raise a ConfigParseError.
'''
t = self.accept(*args)
if t is not None:
return t
self.error("expected: %r" % (args,))
def error(self, msg):
'''Raise a ConfigParseError at the current input position'''
if self.finished():
raise ConfigParseError("Unexpected end of input; %s" % (msg,))
else:
t = self.peek()
raise ConfigParseError("Unexpected token %s; %s" % (t, msg))
def finished(self):
'''Return ``True`` if the end of the token stream is reached.'''
return self.position >= len(self.tokens)
class Parser:
'''Recursive descent parser for libconfig files
Takes a ``TokenStream`` as input, the ``parse()`` method then returns
the config file data in a ``json``-module-style format.
'''
def __init__(self, tokenstream):
self.tokens = tokenstream
def parse(self):
return self.configuration()
def configuration(self):
result = self.setting_list_or_empty()
if not self.tokens.finished():
raise ConfigParseError("Expected end of input but found %s" %
(self.tokens.peek(),))
return result
def setting_list_or_empty(self):
result = AttrDict()
while True:
s = self.setting()
if s is None:
return result
result[s[0]] = s[1]
def setting(self):
name = self.tokens.accept('name')
if name is None:
return None
self.tokens.expect(':', '=')
value = self.value()
if value is None:
self.tokens.error("expected a value")
self.tokens.accept(';', ',')
return (name.text, value)
def value(self):
acceptable = [self.scalar_value, self.array, self.list, self.group]
return self._parse_any_of(acceptable)
def scalar_value(self):
# This list is ordered so that more common tokens are checked first.
acceptable = [self.string, self.boolean, self.integer, self.float,
self.hex, self.integer64, self.hex64]
return self._parse_any_of(acceptable)
def value_list_or_empty(self):
return tuple(self._comma_separated_list_or_empty(self.value))
def scalar_value_list_or_empty(self):
return self._comma_separated_list_or_empty(self.scalar_value)
def array(self):
return self._enclosed_block('[', self.scalar_value_list_or_empty, ']')
def list(self):
return self._enclosed_block('(', self.value_list_or_empty, ')')
def group(self):
return self._enclosed_block('{', self.setting_list_or_empty, '}')
def boolean(self):
return self._create_value_node('boolean')
def integer(self):
return self._create_value_node('integer')
def integer64(self):
return self._create_value_node('integer64')
def hex(self):
return self._create_value_node('hex')
def hex64(self):
return self._create_value_node('hex64')
def float(self):
return self._create_value_node('float')
def string(self):
t_first = self.tokens.accept('string')
if t_first is None:
return None
values = [t_first.value]
while True:
t = self.tokens.accept('string')
if t is None:
break
values.append(t.value)
return ''.join(values)
def _create_value_node(self, tokentype):
t = self.tokens.accept(tokentype)
if t is None:
return None
return t.value
def _parse_any_of(self, nonterminals):
for fun in nonterminals:
result = fun()
if result is not None:
return result
return None
def _comma_separated_list_or_empty(self, nonterminal):
values = []
first = True
while True:
v = nonterminal()
if v is None:
if first:
return []
else:
self.tokens.error("expected value after ','")
values.append(v)
if not self.tokens.accept(','):
return values
first = False
def _enclosed_block(self, start, nonterminal, end):
if not self.tokens.accept(start):
return None
result = nonterminal()
self.tokens.expect(end)
return result
def load(f, filename=None, includedir=''):
'''Load the contents of ``f`` (a file-like object) to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> with open('test/example.cfg') as f:
... config = libconf.load(f)
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
if isinstance(f.read(0), bytes):
raise TypeError("uconf.load() input file must by unicode")
tokenstream = TokenStream.from_file(f,
filename=filename,
includedir=includedir)
return Parser(tokenstream).parse()
def loads(string, filename=None, includedir=''):
'''Load the contents of ``string`` to a Python object
The returned object is a subclass of ``dict`` that exposes string keys as
attributes as well.
Example:
>>> config = libconf.loads('window: { title: "libconfig example"; };')
>>> config['window']['title']
'libconfig example'
>>> config.window.title
'libconfig example'
'''
try:
f = io.StringIO(string)
except TypeError:
raise TypeError("libconf.loads() input string must by unicode")
return load(f, filename=filename, includedir=includedir)
# dump() logic
##############
def dump_int(i):
'''Stringize ``i``, append 'L' if ``i`` is exceeds the 32-bit int range'''
return str(i) + ('' if SMALL_INT_MIN <= i <= SMALL_INT_MAX else 'L')
def dump_string(s):
'''Stringize ``s``, adding double quotes and escaping as necessary
Backslash escape backslashes, double quotes, ``\f``, ``\n``, ``\r``, and
``\t``. Escape all remaining unprintable characters in ``\xFF``-style.
The returned string will be surrounded by double quotes.
'''
s = (s.replace('\\', '\\\\')
.replace('"', '\\"')
.replace('\f', r'\f')
.replace('\n', r'\n')
.replace('\r', r'\r')
.replace('\t', r'\t'))
s = UNPRINTABLE_CHARACTER_RE.sub(
lambda m: r'\x{:02x}'.format(ord(m.group(0))),
s)
return '"' + s + '"'
def dump_value(key, value, f, indent=0):
'''Save a value of any libconfig type
This function serializes takes ``key`` and ``value`` and serializes them
into ``f``. If ``key`` is ``None``, a list-style output is produced.
Otherwise, output has ``key = value`` format.
'''
spaces = ' ' * indent
if key is None:
key_prefix = ''
key_prefix_nl = ''
else:
key_prefix = key + ' = '
key_prefix_nl = key + ' = ' + spaces
if isinstance(value, dict):
f.write(u'{}{}{{\n'.format(spaces, key_prefix_nl))
dump_dict(value, f, indent + 4)
f.write(u'{}}}'.format(spaces))
elif isinstance(value, tuple):
f.write(u'{}{}(\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{})'.format(spaces))
elif isinstance(value, list):
f.write(u'{}{}[\n'.format(spaces, key_prefix_nl))
dump_collection(value, f, indent + 4)
f.write(u'\n{}]'.format(spaces))
elif isstr(value):
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_string(value)))
elif isint(value):
f.write(u'{}{}{}'.format(spaces, key_prefix, dump_int(value)))
elif isinstance(value, float):
f.write(u'{}{}{}'.format(spaces, key_prefix, value))
else:
raise ConfigSerializeError("Can not serialize object %r of type %s" %
(value, type(value)))
def dump_collection(cfg, f, indent=0):
'''Save a collection of attributes'''
for i, value in enumerate(cfg):
dump_value(None, value, f, indent)
if i < len(cfg) - 1:
f.write(u',\n')
def dump_dict(cfg, f, indent=0):
'''Save a dictionary of attributes'''
for key in cfg:
if not isstr(key):
raise ConfigSerializeError("Dict keys must be strings: %r" %
(key,))
dump_value(key, cfg[key], f, indent)
f.write(u'\n')
def dumps(cfg):
'''Serialize ``cfg`` into a libconfig-formatted ``str``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
Returns the formatted string.
'''
str_file = io.StringIO()
dump(cfg, str_file)
return str_file.getvalue()
def dump(cfg, f):
'''Serialize ``cfg`` as a libconfig-formatted stream into ``f``
``cfg`` must be a ``dict`` with ``str`` keys and libconf-supported values
(numbers, strings, booleans, possibly nested dicts, lists, and tuples).
``f`` must be a ``file``-like object with a ``write()`` method.
'''
if not isinstance(cfg, dict):
raise ConfigSerializeError(
'dump() requires a dict as input, not %r of type %r' %
(cfg, type(cfg)))
dump_dict(cfg, f, 0)
def namespace(): return AttrDict()
def isnamespace(v): return isinstance(v, dict)
| lines.append(line) | conditional_block |
utils.js | "use strict";
var assert = require('assert') | describe('Autocompleter widget', function () {
var Autocompleter = require('../utils/autocomplete_widget')
describe('instance', function () {
var testAutocompleter = new Autocompleter(null, 'egp', 'topics');
it('should query the correct url', function () {
assert.equal(testAutocompleter.url, '/api/projects/egp/topics/');
});
it('should build a query string from a term', function () {
var query = testAutocompleter.buildQuery('Alexander Berkman');
assert.deepEqual(query, { 'q': 'Alexander Berkman' });
});
it('should create its own input element when not passed one', function () {
assert.equal(testAutocompleter.$el.length, 1);
});
it('should be able to be enabled', function () {
var $el = testAutocompleter.$el;
assert.equal(_.isEmpty($el.data('ui-autocomplete')), false);
assert.equal($el.prop('placeholder'), 'Begin typing to search for topics.');
});
it('should be able to be disabled', function () {
var testAutocompleter = new Autocompleter(null, 'egp', 'topics');
testAutocompleter.disable();
assert.equal(_.isEmpty(testAutocompleter.$el.data('ui-autocomplete')), true);
assert.equal(testAutocompleter.$el.prop('placeholder'), '');
});
it('should be able to be enabled after being disabled', function () {
var testAutocompleter = new Autocompleter(null, 'egp', 'topics')
, $el = testAutocompleter.$el;
testAutocompleter.disable();
testAutocompleter.enable();
testAutocompleter.disable();
testAutocompleter.enable();
assert.equal(_.isEmpty($el.data('ui-autocomplete')), false);
assert.equal($el.prop('placeholder'), 'Begin typing to search for topics.');
});
});
describe('should throw an error when its constructor', function () {
it('is not passed a project', function () {
assert.throws(
function () { new Autocompleter() },
/Must pass project slug/
);
});
it('is passed an invalid model', function () {
assert.throws(
function () { new Autocompleter(null, 'blah', 'fakemodel') },
/Invalid model/
);
});
it('is passed an element other than a text input', function () {
var el = global.document.createElement('div');
assert.throws(
function () { new Autocompleter(el, 'blah', 'notes') },
/Element must be a text input/
);
});
});
});
describe('Text editor', function () {
var Editor = require('../utils/text_editor.js')
it('should fail without being passed an element', function () {
assert.throws(
function () { new Editor() },
/Must pass exactly one element/
);
});
it('should fail when passed a non-visible element', function () {
var el = global.document.createElement('div');
assert.throws(
function () { new Editor(el) },
/Can't edit text of element that is not visible/
);
});
describe('', function () {
var sandboxes = []
, sandbox
, testEl
beforeEach(function (done) {
sandbox = global.document.createElement('div');
testEl = global.document.createElement('p');
global.document.body.appendChild(sandbox);
testEl.innerHTML = 'Test content';
sandbox.appendChild(testEl);
sandboxes.push(sandbox);
done();
});
after(function (done) {
_.forEach(sandboxes, function (sandbox) {
global.document.body.removeChild(sandbox);
});
done();
});
it('should allow passing a non-jquery element', function () {
var editor = new Editor(testEl);
assert.equal(editor.$el[0], testEl);
});
it('should assign a unique ID to its element automatically', function () {
var editor = new Editor(testEl);
assert.notStrictEqual(editor.id, undefined);
});
it('should create its own textarea', function () {
var editor = new Editor(testEl);
assert.equal(editor.$textarea.length, 1);
assert.equal(editor.$textarea.is('textarea'), true);
});
it('should create its own toolbar', function () {
var editor = new Editor(testEl);
assert.equal(editor.$toolbar.is('div.wysihtml5-toolbar'), true);
});
it('should be able to get its own value', function (done) {
var editor = new Editor(testEl);
editor.editor.on('load', function () {
assert.equal(editor.value(), 'Test content');
done();
});
});
it('should clean up after itself', function (done) {
var editor = new Editor(testEl);
editor.editor.on('load', function () {
editor.value('<p>new value</p>');
editor.destroy();
});
editor.$el.on('editor:destroyed', function (e, val) {
assert.equal(val, '<p>new value</p>');
assert.equal(editor.$el.html(), '<p>new value</p>');
done();
});
});
});
});
describe('Citation generator', function () {
var CitationGenerator = require('../utils/citation_generator');
it('should be able to be created', function () {
var testGenerator = new CitationGenerator();
assert.notEqual(testGenerator.engine, undefined);
});
it('should be able to produce citations', function () {
var testGenerator = new CitationGenerator()
, testData = {
id: 'testing',
type: 'book',
title: 'Living My Life',
author: [{ family: 'Goldman', given: 'Emma' }],
issued: { raw: '1931' }
}
assert.equal(
testGenerator.makeCitation(testData),
'Emma Goldman, <em>Living My Life</em>, 1931.'
)
});
});
describe('Zotero => CSL converter', function () {
var converter = require('../utils/zotero_to_csl')
it('should give me a CSL object when passed a Zotero object', function () {
var testData
, expected
testData = {
itemType: 'book',
title: 'Living My Life',
creators: [{ creatorType: 'author', firstName: 'Emma', lastName: 'Goldman' }],
date: '1931'
}
expected = {
type: 'book',
title: 'Living My Life',
author: [{ family: 'Goldman', given: 'Emma' }],
issued: { raw: '1931' }
}
assert.deepEqual(converter(testData), expected);
});
}); | , _ = require('underscore')
| random_line_split |
generic_path.rs | use std::io::Write;
use std::ops::Deref;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};
#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
}
fn write_internal<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
with_default: bool,
) {
if !self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
if i != 0 {
out.write(", ");
}
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
}
}
out.write(">");
out.new_line();
}
}
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, true);
}
}
impl Deref for GenericParams {
type Target = [Path];
fn | (&self) -> &[Path] {
&self.0
}
}
impl Source for GenericParams {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, false);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
ctype: Option<DeclarationType>,
}
impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generics,
ctype: None,
}
}
pub fn self_path() -> Self {
Self::new(Path::new("Self"), vec![])
}
pub fn replace_self_with(&mut self, self_ty: &Path) {
if self.path.replace_self_with(self_ty) {
self.export_name = self_ty.name().to_owned();
}
// Caller deals with generics.
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn generics(&self) -> &[Type] {
&self.generics
}
pub fn generics_mut(&mut self) -> &mut [Type] {
&mut self.generics
}
pub fn ctype(&self) -> Option<&DeclarationType> {
self.ctype.as_ref()
}
pub fn name(&self) -> &str {
self.path.name()
}
pub fn export_name(&self) -> &str {
&self.export_name
}
pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if !generic_params.contains(&self.path) {
config.export.rename(&mut self.export_name);
}
}
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
self.ctype = resolver.type_for(&self.path);
}
pub fn load(path: &syn::Path) -> Result<Self, String> {
assert!(
!path.segments.is_empty(),
"{:?} doesn't have any segments",
path
);
let last_segment = path.segments.last().unwrap();
let name = last_segment.ident.unraw().to_string();
let path = Path::new(name);
let phantom_data_path = Path::new("PhantomData");
if path == phantom_data_path {
return Ok(Self::new(path, Vec::new()));
}
let generics = match last_segment.arguments {
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Lifetime(_) => Ok(None),
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
return Err("Path contains parentheses.".to_owned());
}
_ => Vec::new(),
};
Ok(Self::new(path, generics))
}
}
| deref | identifier_name |
generic_path.rs | use std::io::Write;
use std::ops::Deref;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};
#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
}
fn write_internal<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
with_default: bool,
) {
if !self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
if i != 0 {
out.write(", ");
}
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
}
}
out.write(">");
out.new_line();
}
}
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, true);
}
}
impl Deref for GenericParams {
type Target = [Path];
fn deref(&self) -> &[Path] {
&self.0
}
}
impl Source for GenericParams {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, false);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
ctype: Option<DeclarationType>,
}
impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generics,
ctype: None,
}
}
pub fn self_path() -> Self {
Self::new(Path::new("Self"), vec![])
}
pub fn replace_self_with(&mut self, self_ty: &Path) {
if self.path.replace_self_with(self_ty) {
self.export_name = self_ty.name().to_owned();
}
// Caller deals with generics.
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn generics(&self) -> &[Type] {
&self.generics
}
pub fn generics_mut(&mut self) -> &mut [Type] {
&mut self.generics
}
pub fn ctype(&self) -> Option<&DeclarationType> |
pub fn name(&self) -> &str {
self.path.name()
}
pub fn export_name(&self) -> &str {
&self.export_name
}
pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if !generic_params.contains(&self.path) {
config.export.rename(&mut self.export_name);
}
}
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
self.ctype = resolver.type_for(&self.path);
}
pub fn load(path: &syn::Path) -> Result<Self, String> {
assert!(
!path.segments.is_empty(),
"{:?} doesn't have any segments",
path
);
let last_segment = path.segments.last().unwrap();
let name = last_segment.ident.unraw().to_string();
let path = Path::new(name);
let phantom_data_path = Path::new("PhantomData");
if path == phantom_data_path {
return Ok(Self::new(path, Vec::new()));
}
let generics = match last_segment.arguments {
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Lifetime(_) => Ok(None),
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
return Err("Path contains parentheses.".to_owned());
}
_ => Vec::new(),
};
Ok(Self::new(path, generics))
}
}
| {
self.ctype.as_ref()
} | identifier_body |
generic_path.rs | use std::io::Write;
use std::ops::Deref;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};
#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
}
fn write_internal<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
with_default: bool,
) {
if !self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
if i != 0 {
out.write(", ");
}
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
}
}
out.write(">");
out.new_line();
}
} | }
impl Deref for GenericParams {
type Target = [Path];
fn deref(&self) -> &[Path] {
&self.0
}
}
impl Source for GenericParams {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, false);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
ctype: Option<DeclarationType>,
}
impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generics,
ctype: None,
}
}
pub fn self_path() -> Self {
Self::new(Path::new("Self"), vec![])
}
pub fn replace_self_with(&mut self, self_ty: &Path) {
if self.path.replace_self_with(self_ty) {
self.export_name = self_ty.name().to_owned();
}
// Caller deals with generics.
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn generics(&self) -> &[Type] {
&self.generics
}
pub fn generics_mut(&mut self) -> &mut [Type] {
&mut self.generics
}
pub fn ctype(&self) -> Option<&DeclarationType> {
self.ctype.as_ref()
}
pub fn name(&self) -> &str {
self.path.name()
}
pub fn export_name(&self) -> &str {
&self.export_name
}
pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if !generic_params.contains(&self.path) {
config.export.rename(&mut self.export_name);
}
}
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
self.ctype = resolver.type_for(&self.path);
}
pub fn load(path: &syn::Path) -> Result<Self, String> {
assert!(
!path.segments.is_empty(),
"{:?} doesn't have any segments",
path
);
let last_segment = path.segments.last().unwrap();
let name = last_segment.ident.unraw().to_string();
let path = Path::new(name);
let phantom_data_path = Path::new("PhantomData");
if path == phantom_data_path {
return Ok(Self::new(path, Vec::new()));
}
let generics = match last_segment.arguments {
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Lifetime(_) => Ok(None),
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
return Err("Path contains parentheses.".to_owned());
}
_ => Vec::new(),
};
Ok(Self::new(path, generics))
}
} |
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, true);
} | random_line_split |
generic_path.rs | use std::io::Write;
use std::ops::Deref;
use syn::ext::IdentExt;
use crate::bindgen::config::{Config, Language};
use crate::bindgen::declarationtyperesolver::{DeclarationType, DeclarationTypeResolver};
use crate::bindgen::ir::{Path, Type};
use crate::bindgen::utilities::IterHelpers;
use crate::bindgen::writer::{Source, SourceWriter};
#[derive(Default, Debug, Clone)]
pub struct GenericParams(pub Vec<Path>);
impl GenericParams {
pub fn new(generics: &syn::Generics) -> Self {
GenericParams(
generics
.params
.iter()
.filter_map(|x| match *x {
syn::GenericParam::Type(syn::TypeParam { ref ident, .. }) => {
Some(Path::new(ident.unraw().to_string()))
}
_ => None,
})
.collect(),
)
}
fn write_internal<F: Write>(
&self,
config: &Config,
out: &mut SourceWriter<F>,
with_default: bool,
) {
if !self.0.is_empty() && config.language == Language::Cxx {
out.write("template<");
for (i, item) in self.0.iter().enumerate() {
if i != 0 |
write!(out, "typename {}", item);
if with_default {
write!(out, " = void");
}
}
out.write(">");
out.new_line();
}
}
pub fn write_with_default<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, true);
}
}
impl Deref for GenericParams {
type Target = [Path];
fn deref(&self) -> &[Path] {
&self.0
}
}
impl Source for GenericParams {
fn write<F: Write>(&self, config: &Config, out: &mut SourceWriter<F>) {
self.write_internal(config, out, false);
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct GenericPath {
path: Path,
export_name: String,
generics: Vec<Type>,
ctype: Option<DeclarationType>,
}
impl GenericPath {
pub fn new(path: Path, generics: Vec<Type>) -> Self {
let export_name = path.name().to_owned();
Self {
path,
export_name,
generics,
ctype: None,
}
}
pub fn self_path() -> Self {
Self::new(Path::new("Self"), vec![])
}
pub fn replace_self_with(&mut self, self_ty: &Path) {
if self.path.replace_self_with(self_ty) {
self.export_name = self_ty.name().to_owned();
}
// Caller deals with generics.
}
pub fn path(&self) -> &Path {
&self.path
}
pub fn generics(&self) -> &[Type] {
&self.generics
}
pub fn generics_mut(&mut self) -> &mut [Type] {
&mut self.generics
}
pub fn ctype(&self) -> Option<&DeclarationType> {
self.ctype.as_ref()
}
pub fn name(&self) -> &str {
self.path.name()
}
pub fn export_name(&self) -> &str {
&self.export_name
}
pub fn rename_for_config(&mut self, config: &Config, generic_params: &GenericParams) {
for generic in &mut self.generics {
generic.rename_for_config(config, generic_params);
}
if !generic_params.contains(&self.path) {
config.export.rename(&mut self.export_name);
}
}
pub fn resolve_declaration_types(&mut self, resolver: &DeclarationTypeResolver) {
self.ctype = resolver.type_for(&self.path);
}
pub fn load(path: &syn::Path) -> Result<Self, String> {
assert!(
!path.segments.is_empty(),
"{:?} doesn't have any segments",
path
);
let last_segment = path.segments.last().unwrap();
let name = last_segment.ident.unraw().to_string();
let path = Path::new(name);
let phantom_data_path = Path::new("PhantomData");
if path == phantom_data_path {
return Ok(Self::new(path, Vec::new()));
}
let generics = match last_segment.arguments {
syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
ref args,
..
}) => args.iter().try_skip_map(|x| match *x {
syn::GenericArgument::Type(ref x) => Type::load(x),
syn::GenericArgument::Lifetime(_) => Ok(None),
_ => Err(format!("can't handle generic argument {:?}", x)),
})?,
syn::PathArguments::Parenthesized(_) => {
return Err("Path contains parentheses.".to_owned());
}
_ => Vec::new(),
};
Ok(Self::new(path, generics))
}
}
| {
out.write(", ");
} | conditional_block |
getClientErrorObject_spec.ts | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import { ErrorTypeEnum } from 'src/components/ErrorMessage/types';
import getClientErrorObject from 'src/utils/getClientErrorObject';
describe('getClientErrorObject()', () => {
it('Returns a Promise', () => {
const response = getClientErrorObject('error');
expect(response instanceof Promise).toBe(true);
});
it('Returns a Promise that resolves to an object with an error key', () => {
const error = 'error';
return getClientErrorObject(error).then(errorObj => {
expect(errorObj).toMatchObject({ error });
});
});
it('Handles Response that can be parsed as json', () => {
const jsonError = { something: 'something', error: 'Error message' };
const jsonErrorString = JSON.stringify(jsonError);
return getClientErrorObject(new Response(jsonErrorString)).then(
errorObj => {
expect(errorObj).toMatchObject(jsonError);
},
);
});
it('Handles backwards compatibility between old error messages and the new SIP-40 errors format', () => {
const jsonError = {
errors: [
{
error_type: ErrorTypeEnum.GENERIC_DB_ENGINE_ERROR,
extra: { engine: 'presto', link: 'https://www.google.com' },
level: 'error',
message: 'presto error: test error', | return getClientErrorObject(new Response(jsonErrorString)).then(
errorObj => {
expect(errorObj.error).toEqual(jsonError.errors[0].message);
expect(errorObj.link).toEqual(jsonError.errors[0].extra.link);
},
);
});
it('Handles Response that can be parsed as text', () => {
const textError = 'Hello I am a text error';
return getClientErrorObject(new Response(textError)).then(errorObj => {
expect(errorObj).toMatchObject({ error: textError });
});
});
it('Handles plain text as input', () => {
const error = 'error';
return getClientErrorObject(error).then(errorObj => {
expect(errorObj).toMatchObject({ error });
});
});
}); | },
],
};
const jsonErrorString = JSON.stringify(jsonError);
| random_line_split |
class_ClientMessage.py |
# _*_ coding:utf-8 _*_
# Filename:ClientUI.py
# Python在线聊天客户端
from socket import *
from ftplib import FTP
import ftplib
import socket
import thread
import time
import sys
import codecs
import os
reload(sys)
sys.setdefaultencoding( "utf-8" )
class ClientMessage():
#设置用户名密码
def setUsrANDPwd(self,usr,pwd):
self.usr=usr
self.pwd=pwd
#设置目标用户
def setToUsr(self,toUsr):
self.toUsr=toUsr
self.ChatFormTitle=toUsr
#设置ip地址和端口号
def setLocalANDPort(self,local,port):
self.local = local
self.port = port
def check_info(self):
self.buffer = 1024
self.ADDR=(self.local,self.port)
self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM)
self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR)
self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer)
s=self.serverMsg.split('##')
if s[0]=='Y':
return True
elif s[0]== 'N':
return False
#接收消息
def receiveMessage(self):
self.buffer = 1024
self.ADDR=(self.local,self.port)
self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM)
self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR)
while True:
#连接建立,接收服务器端消息
self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer)
s=self.serverMsg.split('##')
if s[0]=='Y':
#self.chatText.insert(Tkinter.END,'客户端已经与服务器端建立连接......')
return True
elif s[0]== 'N':
#self.chatText.insert(Tkinter.END,'客户端与服务器端建立连接失败......')
return False
elif s[0]=='CLOSE':
i=5
while i>0:
self.chatText.insert(Tkinter.END,'你的账号在另一端登录,该客户端'+str(i)+'秒后退出......')
time.sleep(1)
i=i-1
self.chatText.delete(Tkinter.END)
os._exit(0)
#好友列表
elif s[0]=='F':
for eachFriend in s[1:len(s)]:
print eachFriend
#好友上线
elif s[0]=='0':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'上线了')
#好友下线
elif s[0]=='1':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'下线了')
#好友传来消息
elif s[0]=='2':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +' '+s[1] +' 说:\n')
self.chatText.insert(Tkinter.END, ' ' + s[3])
#好友传来文件
elif s[0]=='3':
filename=s[2]
f=FTP('192.168.1.105')
f.login('Coder', 'xianjian')
f.cwd(self.usr)
filenameD=filename[:-1].encode("cp936")
try:
f.retrbinary('RETR '+filenameD,open('..\\'+self.usr+'\\'+filenameD,'wb').write)
except ftplib.error_perm:
print 'ERROR:cannot read file "%s"' %file
self.chatText.insert(Tkinter.END,filename[:-1]+' 传输完成')
elif s[0]=='4':
agreement=raw_input(s[1]+'请求加你为好友,验证消息:'+s[3]+'你愿意加'+s[1]+'为好友吗(Y/N)')
if agreement=='Y':
self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##Y',self.ADDR)
elif agreement=='N':
self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##N',self.ADDR)
elif s[0]=='5':
if s[3]=='Y':
print s[2]+'接受了你的好友请求'
elif s[3]=='N':
print s[2]+'拒绝了你的好友请求'
#发送消息
def sendMessage(self):
#得到用户在Text中输入的消息
message = self.inputText.get('1.0',Tkinter.END)
#格式化当前的时间
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +' 我 说:\n')
self.chatText.insert(Tkinter.END,' ' + message + '\n')
self.u | dpCliSock.sendto('2##'+self.usr+'##'+self.toUsr+'##'+message,self.ADDR);
#清空用户在Text中输入的消息
self.inputText.delete(0.0,message.__len__()-1.0)
#传文件
def sendFile(self):
filename = self.inputText.get('1.0',Tkinter.END)
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +'我' + ' 传文件:\n')
self.chatText.insert(Tkinter.END,' ' + filename[:-1] + '\n')
f=FTP('192.168.1.105')
f.login('Coder', 'xianjian')
f.cwd(self.toUsr)
filenameU=filename[:-1].encode("cp936")
try:
#f.retrbinary('RETR '+filename,open(filename,'wb').write)
#将文件上传到服务器对方文件夹中
f.storbinary('STOR ' + filenameU, open('..\\'+self.usr+'\\'+filenameU, 'rb'))
except ftplib.error_perm:
print 'ERROR:cannot read file "%s"' %file
self.udpCliSock.sendto('3##'+self.usr+'##'+self.toUsr+'##'+filename,self.ADDR);
#加好友
def addFriends(self):
message= self.inputText.get('1.0',Tkinter.END)
s=message.split('##')
self.udpCliSock.sendto('4##'+self.usr+'##'+s[0]+'##'+s[1],self.ADDR);
#关闭消息窗口并退出
def close(self):
self.udpCliSock.sendto('1##'+self.usr,self.ADDR);
sys.exit()
#启动线程接收服务器端的消息
def startNewThread(self):
thread.start_new_thread(self.receiveMessage,())
def main():
client = ClientMessage()
client.setLocalANDPort('192.168.1.105', 8808)
client.setUsrANDPwd('12073127', '12073127')
client.setToUsr('12073128')
client.startNewThread()
if __name__=='__main__':
main()
| conditional_block | |
class_ClientMessage.py | # _*_ coding:utf-8 _*_
# Filename:ClientUI.py
# Python在线聊天客户端
from socket import *
from ftplib import FTP
import ftplib
import socket
import thread
import time
import sys
import codecs
import os
reload(sys)
sys.setdefaultencoding( "utf-8" )
class ClientMessage():
#设置用户名密码
def setUsrANDPwd(self,usr,pwd):
self.usr=usr
self.pwd=pwd
#设置目标用户
def setToUsr(self,toUsr):
self.toUsr=toUsr
self.ChatFormTitle=toUsr
#设置ip地址和端口号
def setLocalANDPort(self,local,port):
self.local = local
self.port = port
def check_info(self):
self.buffer = 1024
self.ADDR=(self.local,self.port)
self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM)
self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR)
self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer)
s=self.serverMsg.split('##')
if s[0]=='Y':
return True
elif s[0]== 'N':
return False
#接收消息
def receiveMessage(self):
self.buffer = 1024
self.ADDR=(self.local,self.port)
self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM)
self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR)
while True:
#连接建立,接收服务器端消息
self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer)
s=self.serverMsg.split('##')
if s[0]=='Y':
#self.chatText.insert(Tkinter.END,'客户端已经与服务器端建立连接......') | return True
elif s[0]== 'N':
#self.chatText.insert(Tkinter.END,'客户端与服务器端建立连接失败......')
return False
elif s[0]=='CLOSE':
i=5
while i>0:
self.chatText.insert(Tkinter.END,'你的账号在另一端登录,该客户端'+str(i)+'秒后退出......')
time.sleep(1)
i=i-1
self.chatText.delete(Tkinter.END)
os._exit(0)
#好友列表
elif s[0]=='F':
for eachFriend in s[1:len(s)]:
print eachFriend
#好友上线
elif s[0]=='0':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'上线了')
#好友下线
elif s[0]=='1':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'下线了')
#好友传来消息
elif s[0]=='2':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +' '+s[1] +' 说:\n')
self.chatText.insert(Tkinter.END, ' ' + s[3])
#好友传来文件
elif s[0]=='3':
filename=s[2]
f=FTP('192.168.1.105')
f.login('Coder', 'xianjian')
f.cwd(self.usr)
filenameD=filename[:-1].encode("cp936")
try:
f.retrbinary('RETR '+filenameD,open('..\\'+self.usr+'\\'+filenameD,'wb').write)
except ftplib.error_perm:
print 'ERROR:cannot read file "%s"' %file
self.chatText.insert(Tkinter.END,filename[:-1]+' 传输完成')
elif s[0]=='4':
agreement=raw_input(s[1]+'请求加你为好友,验证消息:'+s[3]+'你愿意加'+s[1]+'为好友吗(Y/N)')
if agreement=='Y':
self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##Y',self.ADDR)
elif agreement=='N':
self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##N',self.ADDR)
elif s[0]=='5':
if s[3]=='Y':
print s[2]+'接受了你的好友请求'
elif s[3]=='N':
print s[2]+'拒绝了你的好友请求'
#发送消息
def sendMessage(self):
#得到用户在Text中输入的消息
message = self.inputText.get('1.0',Tkinter.END)
#格式化当前的时间
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +' 我 说:\n')
self.chatText.insert(Tkinter.END,' ' + message + '\n')
self.udpCliSock.sendto('2##'+self.usr+'##'+self.toUsr+'##'+message,self.ADDR);
#清空用户在Text中输入的消息
self.inputText.delete(0.0,message.__len__()-1.0)
#传文件
def sendFile(self):
filename = self.inputText.get('1.0',Tkinter.END)
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +'我' + ' 传文件:\n')
self.chatText.insert(Tkinter.END,' ' + filename[:-1] + '\n')
f=FTP('192.168.1.105')
f.login('Coder', 'xianjian')
f.cwd(self.toUsr)
filenameU=filename[:-1].encode("cp936")
try:
#f.retrbinary('RETR '+filename,open(filename,'wb').write)
#将文件上传到服务器对方文件夹中
f.storbinary('STOR ' + filenameU, open('..\\'+self.usr+'\\'+filenameU, 'rb'))
except ftplib.error_perm:
print 'ERROR:cannot read file "%s"' %file
self.udpCliSock.sendto('3##'+self.usr+'##'+self.toUsr+'##'+filename,self.ADDR);
#加好友
def addFriends(self):
message= self.inputText.get('1.0',Tkinter.END)
s=message.split('##')
self.udpCliSock.sendto('4##'+self.usr+'##'+s[0]+'##'+s[1],self.ADDR);
#关闭消息窗口并退出
def close(self):
self.udpCliSock.sendto('1##'+self.usr,self.ADDR);
sys.exit()
#启动线程接收服务器端的消息
def startNewThread(self):
thread.start_new_thread(self.receiveMessage,())
def main():
client = ClientMessage()
client.setLocalANDPort('192.168.1.105', 8808)
client.setUsrANDPwd('12073127', '12073127')
client.setToUsr('12073128')
client.startNewThread()
if __name__=='__main__':
main() | random_line_split | |
class_ClientMessage.py |
# _*_ coding:utf-8 _*_
# Filename:ClientUI.py
# Python在线聊天客户端
from socket import *
from ftplib import FTP
import ftplib
import socket
import thread
import time
import sys
import codecs
import os
reload(sys)
sys.setdefaultencoding( "utf-8" )
class ClientMessage():
#设置用户名密码
def setUsrANDPwd(self,usr,pwd):
self.usr=usr
self.pwd=pwd
#设置目标用户
def setToUsr(self,toUsr):
self.toUsr=toUsr
self.ChatFormTitle=toUsr
#设置ip地址和端口号
def setLocalANDPort(self,local,port):
self.local = l | lf.port = port
def check_info(self):
self.buffer = 1024
self.ADDR=(self.local,self.port)
self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM)
self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR)
self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer)
s=self.serverMsg.split('##')
if s[0]=='Y':
return True
elif s[0]== 'N':
return False
#接收消息
def receiveMessage(self):
self.buffer = 1024
self.ADDR=(self.local,self.port)
self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM)
self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR)
while True:
#连接建立,接收服务器端消息
self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer)
s=self.serverMsg.split('##')
if s[0]=='Y':
#self.chatText.insert(Tkinter.END,'客户端已经与服务器端建立连接......')
return True
elif s[0]== 'N':
#self.chatText.insert(Tkinter.END,'客户端与服务器端建立连接失败......')
return False
elif s[0]=='CLOSE':
i=5
while i>0:
self.chatText.insert(Tkinter.END,'你的账号在另一端登录,该客户端'+str(i)+'秒后退出......')
time.sleep(1)
i=i-1
self.chatText.delete(Tkinter.END)
os._exit(0)
#好友列表
elif s[0]=='F':
for eachFriend in s[1:len(s)]:
print eachFriend
#好友上线
elif s[0]=='0':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'上线了')
#好友下线
elif s[0]=='1':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'下线了')
#好友传来消息
elif s[0]=='2':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +' '+s[1] +' 说:\n')
self.chatText.insert(Tkinter.END, ' ' + s[3])
#好友传来文件
elif s[0]=='3':
filename=s[2]
f=FTP('192.168.1.105')
f.login('Coder', 'xianjian')
f.cwd(self.usr)
filenameD=filename[:-1].encode("cp936")
try:
f.retrbinary('RETR '+filenameD,open('..\\'+self.usr+'\\'+filenameD,'wb').write)
except ftplib.error_perm:
print 'ERROR:cannot read file "%s"' %file
self.chatText.insert(Tkinter.END,filename[:-1]+' 传输完成')
elif s[0]=='4':
agreement=raw_input(s[1]+'请求加你为好友,验证消息:'+s[3]+'你愿意加'+s[1]+'为好友吗(Y/N)')
if agreement=='Y':
self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##Y',self.ADDR)
elif agreement=='N':
self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##N',self.ADDR)
elif s[0]=='5':
if s[3]=='Y':
print s[2]+'接受了你的好友请求'
elif s[3]=='N':
print s[2]+'拒绝了你的好友请求'
#发送消息
def sendMessage(self):
#得到用户在Text中输入的消息
message = self.inputText.get('1.0',Tkinter.END)
#格式化当前的时间
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +' 我 说:\n')
self.chatText.insert(Tkinter.END,' ' + message + '\n')
self.udpCliSock.sendto('2##'+self.usr+'##'+self.toUsr+'##'+message,self.ADDR);
#清空用户在Text中输入的消息
self.inputText.delete(0.0,message.__len__()-1.0)
#传文件
def sendFile(self):
filename = self.inputText.get('1.0',Tkinter.END)
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +'我' + ' 传文件:\n')
self.chatText.insert(Tkinter.END,' ' + filename[:-1] + '\n')
f=FTP('192.168.1.105')
f.login('Coder', 'xianjian')
f.cwd(self.toUsr)
filenameU=filename[:-1].encode("cp936")
try:
#f.retrbinary('RETR '+filename,open(filename,'wb').write)
#将文件上传到服务器对方文件夹中
f.storbinary('STOR ' + filenameU, open('..\\'+self.usr+'\\'+filenameU, 'rb'))
except ftplib.error_perm:
print 'ERROR:cannot read file "%s"' %file
self.udpCliSock.sendto('3##'+self.usr+'##'+self.toUsr+'##'+filename,self.ADDR);
#加好友
def addFriends(self):
message= self.inputText.get('1.0',Tkinter.END)
s=message.split('##')
self.udpCliSock.sendto('4##'+self.usr+'##'+s[0]+'##'+s[1],self.ADDR);
#关闭消息窗口并退出
def close(self):
self.udpCliSock.sendto('1##'+self.usr,self.ADDR);
sys.exit()
#启动线程接收服务器端的消息
def startNewThread(self):
thread.start_new_thread(self.receiveMessage,())
def main():
client = ClientMessage()
client.setLocalANDPort('192.168.1.105', 8808)
client.setUsrANDPwd('12073127', '12073127')
client.setToUsr('12073128')
client.startNewThread()
if __name__=='__main__':
main()
| ocal
se | identifier_name |
class_ClientMessage.py |
# _*_ coding:utf-8 _*_
# Filename:ClientUI.py
# Python在线聊天客户端
from socket import *
from ftplib import FTP
import ftplib
import socket
import thread
import time
import sys
import codecs
import os
reload(sys)
sys.setdefaultencoding( "utf-8" )
class ClientMessage():
#设置用户名密码
def setUsrANDPwd(self,usr,pwd):
self.usr=usr
self.pwd=pwd
#设置目标用户
def setToUsr(self,toUsr):
self.toUsr=toUsr
self.ChatFormTitle=toUsr
#设置ip地址和端口号
def setLocalANDPort(self,local,port):
self.local = local
self.port = port
def check_info(self):
self.buffer = 1024
self.ADDR=(self.local,self.port)
self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM)
self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR)
self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer)
s=self.serverMsg.split('##')
if s[0]=='Y':
return True
elif s[0]== 'N':
return False
#接收消息
def receiveMessage(self):
self.buffer = 1024
self.ADDR=(self.local,self.port)
self.udpCliSock = socket.socket(AF_INET, SOCK_DGRAM)
self.udpCliSock.sendto('0##'+self.usr+'##'+self.pwd,self.ADDR)
while True:
#连接建立,接收服务器端消息
self.serverMsg ,self.ADDR = self.udpCliSock.recvfrom(self.buffer)
s=self.serverMsg.split('##')
if s[0]=='Y':
#self.chatText.insert(Tkinter.END,'客户端已经与服务器端建立连接......')
return True
elif s[0]== 'N':
#self.chatText.insert(Tkinter.END,'客户端与服务器端建立连接失败......')
return False
elif s[0]=='CLOSE':
i=5
while i>0:
self.chatText.insert(Tkinter.END,'你的账号在另一端登录,该客户端'+str(i)+'秒后退出......')
time.sleep(1)
i=i-1
self.chatText.delete(Tkinter.END)
os._exit(0)
#好友列表
elif s[0]=='F':
for eachFriend in s[1:len(s)]:
print eachFriend
#好友上线
elif s[0]=='0':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'上线了')
#好友下线
elif s[0]=='1':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime+' ' +'你的好友' + s[1]+'下线了')
#好友传来消息
elif s[0]=='2':
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +' '+s[1] +' 说:\n')
self.chatText.insert(Tkinter.END, ' ' + s[3])
#好友传来文件
elif s[0]=='3':
filename=s[2]
f=FTP('192.168.1.105')
f.login('Coder', 'xianjian')
f.cwd(self.usr)
filenameD=filename[:-1].encode("cp936")
try:
f.retrbinary('RETR '+filenameD,open('..\\'+self.usr+'\\'+filenameD,'wb').write)
except ftplib.error_perm:
print 'ERROR:cannot read file "%s"' %file
self.chatText.insert(Tkinter.END,filename[:-1]+' 传输完成')
elif s[0]=='4':
agreement=raw_input(s[1]+'请求加你为好友,验证消息:'+s[3]+'你愿意加'+s[1]+'为好友吗(Y/N)')
if agreement=='Y':
self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##Y',self.ADDR)
elif agreement=='N':
self.udpCliSock.sendto('5##'+s[1]+'##'+s[2]+'##N',self.ADDR)
elif s[0]=='5':
if s[3]=='Y':
print s[2]+'接受了你的好友请求'
elif s[3]=='N':
print s[2]+'拒绝了你的好友请求'
#发送消息
def sendMessage(self):
#得到用户在Text中输入的消息
message = self.inputText.get('1.0',Tkinter.END)
#格式化当前的时间
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +' 我 说:\n')
self.chatText.insert(Tkinter.END,' ' + message + '\n')
self.udpCliSock.sendto('2##'+self.usr+'##'+self.toUsr+'##'+message,self.ADDR);
#清空用户在Text中输入的消息
self.inputText.delete(0.0,message.__len__()-1.0)
#传文件
def sendFile(self):
filename = self.inputText.get('1.0',Tkinter.END)
theTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.chatText.insert(Tkinter.END, theTime +'我' + ' 传文件:\n')
self.chatText.insert(Tkinter.END,' ' + filename[:-1] + '\n')
f=FTP('192.168.1.105')
f.login('Coder', 'xianjian')
f.cwd(self.toUsr)
filenameU=filename[:-1].encode("cp936")
try:
#f.retrbinary('RETR '+filename,open(filename,'wb').write)
#将文件上传到服务器对方文件夹中
f.storbinary('STOR ' + filenameU, open('..\\'+self.usr+'\\'+filenameU, 'rb'))
except ftplib.error_perm:
print 'ERROR:cannot read file "%s"' %file
self.udpCliSock.sendto('3##'+self.usr+'##'+self.toUsr+'##'+filename,self.ADDR);
#加好友
def addFriends(self):
message= self.inputText.get('1.0',Tkinter.END)
s=message.split('##')
self.udpCliSock.sendto('4##'+self.usr+'##'+s[0]+'##'+s[1],self.ADDR);
#关闭消息窗口并退出
def close(self):
self.udpCliSock.sendto('1##'+self.usr,self.ADDR);
sys.exit()
#启动线程接收服务器端的消息
def startNewThread(self):
thread.start_new_thread(self.receiveMessage,())
def main():
client = ClientMessage()
client.setLocalANDPort('192.168.1.105', 8808)
cli | ent.setUsrANDPwd('12073127', '12073127')
client.setToUsr('12073128')
client.startNewThread()
if __name__=='__main__':
main()
| identifier_body | |
__init__.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Copyright 2011-2014, Nigel Small
#
# 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.
|
__all__ = ["LegacyResource", "LegacyNode", "Index", "LegacyReadBatch", "LegacyWriteBatch"] |
from py2neo.legacy.batch import *
from py2neo.legacy.core import *
from py2neo.legacy.index import *
| random_line_split |
test-install.py | #!/usr/bin/python2.7
#
# This file is part of drizzle-ci
#
# Copyright (c) 2013 Sharan Kumar M
#
# drizzle-ci 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.
#
# drizzle-ci 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 drizzle-ci. If not, see <http://www.gnu.org/licenses/>.
#
#
# ==========================
# Test script for drizzle-ci
# ==========================
# imports
import logging
import os
import re
import signal
import subprocess
import sys
# configuring paths
path = {}
path['root'] = os.getcwd()
path['state'] = '/srv/salt'
path['pillar'] = '/srv/pillar'
# configuring variables
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.INFO)
log = logging.getLogger(__name__)
copy = 'sudo cp -r {0} {1}'
top_file = '''base:
'*':
- {0}
'''
# functions
def process_command_line():
'''
A function to return the command line arguments as a dictionary of items
'''
opt = {}
argv = sys.argv[1:]
if len(argv) is 0:
opt['minion'] = ['*']
opt['state'] = ['drizzle-dbd','drizzle','jenkins','nova','salt','sysbench','users']
return opt
for arg in argv:
key = arg.split('=')[0][2:]
opt[key] = arg.split('=')[1].split(',')
return opt
def keyboard_interrupt(signal_type,handler):
'''
This function handles the keyboard interrupt
'''
log.info('\t\tPressed CTRL+C')
log.info('\t\texiting...')
exit(0)
# processing the command line and kick start!
opt = process_command_line()
signal.signal(signal.SIGINT,keyboard_interrupt)
log.info('\t\tsetting up the environment')
# setting up the environment
cmd = copy.format(path['state']+'/top.sls',path['state']+'/top.sls.bak')
os.system(cmd)
cmd = copy.format(path['root']+'/salt',path['state'])
os.system(cmd)
cmd = copy.format(path['root']+'/pillar', path['pillar'])
os.system(cmd)
# refreshing pillar data
log.info('\t\tsetting up pillar data')
for minion in opt['minion']:
subprocess.Popen(['sudo','salt',minion,'saltutil.refresh_pillar'],stdout=subprocess.PIPE)
# processing each state
log.info('\n\t\t==================================================') | for state in opt['state']:
top_data = top_file.format(state)
with open(path['state']+'/top.sls', 'w') as top_sls:
top_sls.write(top_data)
for minion in opt['minion']:
output = subprocess.Popen(['sudo', 'salt', minion, 'state.highstate'], stdout=subprocess.PIPE)
result, error = output.communicate()
if error is not None:
logging.info('ERROR')
logging.info(error)
failure = re.search(r'Result:\s+False',result)
if failure is not None:
status = 'FAILURE'
else:
status = 'OK'
log.info('\t\t'+state.ljust(20)+minion.ljust(20)+status.ljust(10))
# restoring the original top.sls and cleaning up..
log.info('\t\t==================================================')
log.info('\n\t\tcleaning up...')
cmd = 'sudo mv {0} {1}'.format(path['state']+'/top.sls.bak', path['state']+'/top.sls')
os.system(cmd)
log.info('\t\tsuccessfully executed') | log.info('\t\tstate minion status ')
log.info('\t\t==================================================') | random_line_split |
test-install.py | #!/usr/bin/python2.7
#
# This file is part of drizzle-ci
#
# Copyright (c) 2013 Sharan Kumar M
#
# drizzle-ci 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.
#
# drizzle-ci 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 drizzle-ci. If not, see <http://www.gnu.org/licenses/>.
#
#
# ==========================
# Test script for drizzle-ci
# ==========================
# imports
import logging
import os
import re
import signal
import subprocess
import sys
# configuring paths
path = {}
path['root'] = os.getcwd()
path['state'] = '/srv/salt'
path['pillar'] = '/srv/pillar'
# configuring variables
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.INFO)
log = logging.getLogger(__name__)
copy = 'sudo cp -r {0} {1}'
top_file = '''base:
'*':
- {0}
'''
# functions
def process_command_line():
'''
A function to return the command line arguments as a dictionary of items
'''
opt = {}
argv = sys.argv[1:]
if len(argv) is 0:
opt['minion'] = ['*']
opt['state'] = ['drizzle-dbd','drizzle','jenkins','nova','salt','sysbench','users']
return opt
for arg in argv:
key = arg.split('=')[0][2:]
opt[key] = arg.split('=')[1].split(',')
return opt
def | (signal_type,handler):
'''
This function handles the keyboard interrupt
'''
log.info('\t\tPressed CTRL+C')
log.info('\t\texiting...')
exit(0)
# processing the command line and kick start!
opt = process_command_line()
signal.signal(signal.SIGINT,keyboard_interrupt)
log.info('\t\tsetting up the environment')
# setting up the environment
cmd = copy.format(path['state']+'/top.sls',path['state']+'/top.sls.bak')
os.system(cmd)
cmd = copy.format(path['root']+'/salt',path['state'])
os.system(cmd)
cmd = copy.format(path['root']+'/pillar', path['pillar'])
os.system(cmd)
# refreshing pillar data
log.info('\t\tsetting up pillar data')
for minion in opt['minion']:
subprocess.Popen(['sudo','salt',minion,'saltutil.refresh_pillar'],stdout=subprocess.PIPE)
# processing each state
log.info('\n\t\t==================================================')
log.info('\t\tstate minion status ')
log.info('\t\t==================================================')
for state in opt['state']:
top_data = top_file.format(state)
with open(path['state']+'/top.sls', 'w') as top_sls:
top_sls.write(top_data)
for minion in opt['minion']:
output = subprocess.Popen(['sudo', 'salt', minion, 'state.highstate'], stdout=subprocess.PIPE)
result, error = output.communicate()
if error is not None:
logging.info('ERROR')
logging.info(error)
failure = re.search(r'Result:\s+False',result)
if failure is not None:
status = 'FAILURE'
else:
status = 'OK'
log.info('\t\t'+state.ljust(20)+minion.ljust(20)+status.ljust(10))
# restoring the original top.sls and cleaning up..
log.info('\t\t==================================================')
log.info('\n\t\tcleaning up...')
cmd = 'sudo mv {0} {1}'.format(path['state']+'/top.sls.bak', path['state']+'/top.sls')
os.system(cmd)
log.info('\t\tsuccessfully executed')
| keyboard_interrupt | identifier_name |
test-install.py | #!/usr/bin/python2.7
#
# This file is part of drizzle-ci
#
# Copyright (c) 2013 Sharan Kumar M
#
# drizzle-ci 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.
#
# drizzle-ci 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 drizzle-ci. If not, see <http://www.gnu.org/licenses/>.
#
#
# ==========================
# Test script for drizzle-ci
# ==========================
# imports
import logging
import os
import re
import signal
import subprocess
import sys
# configuring paths
path = {}
path['root'] = os.getcwd()
path['state'] = '/srv/salt'
path['pillar'] = '/srv/pillar'
# configuring variables
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.INFO)
log = logging.getLogger(__name__)
copy = 'sudo cp -r {0} {1}'
top_file = '''base:
'*':
- {0}
'''
# functions
def process_command_line():
'''
A function to return the command line arguments as a dictionary of items
'''
opt = {}
argv = sys.argv[1:]
if len(argv) is 0:
opt['minion'] = ['*']
opt['state'] = ['drizzle-dbd','drizzle','jenkins','nova','salt','sysbench','users']
return opt
for arg in argv:
key = arg.split('=')[0][2:]
opt[key] = arg.split('=')[1].split(',')
return opt
def keyboard_interrupt(signal_type,handler):
|
# processing the command line and kick start!
opt = process_command_line()
signal.signal(signal.SIGINT,keyboard_interrupt)
log.info('\t\tsetting up the environment')
# setting up the environment
cmd = copy.format(path['state']+'/top.sls',path['state']+'/top.sls.bak')
os.system(cmd)
cmd = copy.format(path['root']+'/salt',path['state'])
os.system(cmd)
cmd = copy.format(path['root']+'/pillar', path['pillar'])
os.system(cmd)
# refreshing pillar data
log.info('\t\tsetting up pillar data')
for minion in opt['minion']:
subprocess.Popen(['sudo','salt',minion,'saltutil.refresh_pillar'],stdout=subprocess.PIPE)
# processing each state
log.info('\n\t\t==================================================')
log.info('\t\tstate minion status ')
log.info('\t\t==================================================')
for state in opt['state']:
top_data = top_file.format(state)
with open(path['state']+'/top.sls', 'w') as top_sls:
top_sls.write(top_data)
for minion in opt['minion']:
output = subprocess.Popen(['sudo', 'salt', minion, 'state.highstate'], stdout=subprocess.PIPE)
result, error = output.communicate()
if error is not None:
logging.info('ERROR')
logging.info(error)
failure = re.search(r'Result:\s+False',result)
if failure is not None:
status = 'FAILURE'
else:
status = 'OK'
log.info('\t\t'+state.ljust(20)+minion.ljust(20)+status.ljust(10))
# restoring the original top.sls and cleaning up..
log.info('\t\t==================================================')
log.info('\n\t\tcleaning up...')
cmd = 'sudo mv {0} {1}'.format(path['state']+'/top.sls.bak', path['state']+'/top.sls')
os.system(cmd)
log.info('\t\tsuccessfully executed')
| '''
This function handles the keyboard interrupt
'''
log.info('\t\tPressed CTRL+C')
log.info('\t\texiting...')
exit(0) | identifier_body |
test-install.py | #!/usr/bin/python2.7
#
# This file is part of drizzle-ci
#
# Copyright (c) 2013 Sharan Kumar M
#
# drizzle-ci 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.
#
# drizzle-ci 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 drizzle-ci. If not, see <http://www.gnu.org/licenses/>.
#
#
# ==========================
# Test script for drizzle-ci
# ==========================
# imports
import logging
import os
import re
import signal
import subprocess
import sys
# configuring paths
path = {}
path['root'] = os.getcwd()
path['state'] = '/srv/salt'
path['pillar'] = '/srv/pillar'
# configuring variables
logging.basicConfig(format='%(levelname)s:%(message)s',level=logging.INFO)
log = logging.getLogger(__name__)
copy = 'sudo cp -r {0} {1}'
top_file = '''base:
'*':
- {0}
'''
# functions
def process_command_line():
'''
A function to return the command line arguments as a dictionary of items
'''
opt = {}
argv = sys.argv[1:]
if len(argv) is 0:
opt['minion'] = ['*']
opt['state'] = ['drizzle-dbd','drizzle','jenkins','nova','salt','sysbench','users']
return opt
for arg in argv:
key = arg.split('=')[0][2:]
opt[key] = arg.split('=')[1].split(',')
return opt
def keyboard_interrupt(signal_type,handler):
'''
This function handles the keyboard interrupt
'''
log.info('\t\tPressed CTRL+C')
log.info('\t\texiting...')
exit(0)
# processing the command line and kick start!
opt = process_command_line()
signal.signal(signal.SIGINT,keyboard_interrupt)
log.info('\t\tsetting up the environment')
# setting up the environment
cmd = copy.format(path['state']+'/top.sls',path['state']+'/top.sls.bak')
os.system(cmd)
cmd = copy.format(path['root']+'/salt',path['state'])
os.system(cmd)
cmd = copy.format(path['root']+'/pillar', path['pillar'])
os.system(cmd)
# refreshing pillar data
log.info('\t\tsetting up pillar data')
for minion in opt['minion']:
subprocess.Popen(['sudo','salt',minion,'saltutil.refresh_pillar'],stdout=subprocess.PIPE)
# processing each state
log.info('\n\t\t==================================================')
log.info('\t\tstate minion status ')
log.info('\t\t==================================================')
for state in opt['state']:
top_data = top_file.format(state)
with open(path['state']+'/top.sls', 'w') as top_sls:
top_sls.write(top_data)
for minion in opt['minion']:
output = subprocess.Popen(['sudo', 'salt', minion, 'state.highstate'], stdout=subprocess.PIPE)
result, error = output.communicate()
if error is not None:
logging.info('ERROR')
logging.info(error)
failure = re.search(r'Result:\s+False',result)
if failure is not None:
|
else:
status = 'OK'
log.info('\t\t'+state.ljust(20)+minion.ljust(20)+status.ljust(10))
# restoring the original top.sls and cleaning up..
log.info('\t\t==================================================')
log.info('\n\t\tcleaning up...')
cmd = 'sudo mv {0} {1}'.format(path['state']+'/top.sls.bak', path['state']+'/top.sls')
os.system(cmd)
log.info('\t\tsuccessfully executed')
| status = 'FAILURE' | conditional_block |
detect.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <chifflier@wzdftpd.net>
use crate::krb::krb5::KRB5Transaction;
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_msgtype(tx: &mut KRB5Transaction,
ptr: *mut u32)
{
*ptr = tx.msg_type.0;
}
/// Get error code, if present in transaction
/// Return 0 if error code was filled, else 1
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_errcode(tx: &mut KRB5Transaction,
ptr: *mut i32) -> u32
{
match tx.error_code {
Some(ref e) => {
*ptr = e.0;
0
},
None => 1
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.cname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.sname {
if (i as usize) < s.name_string.len() |
}
0
}
| {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
} | conditional_block |
detect.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <chifflier@wzdftpd.net>
use crate::krb::krb5::KRB5Transaction;
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_msgtype(tx: &mut KRB5Transaction,
ptr: *mut u32)
{
*ptr = tx.msg_type.0;
}
/// Get error code, if present in transaction
/// Return 0 if error code was filled, else 1
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_errcode(tx: &mut KRB5Transaction,
ptr: *mut i32) -> u32
{
match tx.error_code {
Some(ref e) => {
*ptr = e.0;
0
},
None => 1
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8, | -> u8
{
if let Some(ref s) = tx.cname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.sname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
} | buffer_len: *mut u32) | random_line_split |
detect.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <chifflier@wzdftpd.net>
use crate::krb::krb5::KRB5Transaction;
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_msgtype(tx: &mut KRB5Transaction,
ptr: *mut u32)
{
*ptr = tx.msg_type.0;
}
/// Get error code, if present in transaction
/// Return 0 if error code was filled, else 1
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_errcode(tx: &mut KRB5Transaction,
ptr: *mut i32) -> u32
{
match tx.error_code {
Some(ref e) => {
*ptr = e.0;
0
},
None => 1
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
|
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.sname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
| {
if let Some(ref s) = tx.cname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
} | identifier_body |
detect.rs | /* Copyright (C) 2018 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program 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
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
// written by Pierre Chifflier <chifflier@wzdftpd.net>
use crate::krb::krb5::KRB5Transaction;
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_msgtype(tx: &mut KRB5Transaction,
ptr: *mut u32)
{
*ptr = tx.msg_type.0;
}
/// Get error code, if present in transaction
/// Return 0 if error code was filled, else 1
#[no_mangle]
pub unsafe extern "C" fn | (tx: &mut KRB5Transaction,
ptr: *mut i32) -> u32
{
match tx.error_code {
Some(ref e) => {
*ptr = e.0;
0
},
None => 1
}
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_cname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.cname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
#[no_mangle]
pub unsafe extern "C" fn rs_krb5_tx_get_sname(tx: &mut KRB5Transaction,
i: u16,
buffer: *mut *const u8,
buffer_len: *mut u32)
-> u8
{
if let Some(ref s) = tx.sname {
if (i as usize) < s.name_string.len() {
let value = &s.name_string[i as usize];
*buffer = value.as_ptr();
*buffer_len = value.len() as u32;
return 1;
}
}
0
}
| rs_krb5_tx_get_errcode | identifier_name |
misc.py | import time
from os import system
import bot as cleanBot
def pp(message, mtype='INFO'):
mtype = mtype.upper()
print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message)
def ppi(channel, message, username):
print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, username.lower(), message)
def pbot(message, channel=''):
if channel:
msg = '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, 'BOT', message)
else:
msg = '[%s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), 'BOT', message)
print msg
def pbutton(message_buffer):
#system('clear')
if cleanBot.Bot().botOn == True:
|
else:
print '\n\n'
print '\n'.join('CHAT ENABLED ACTIONS ARE OFF')
print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer])
| print '\n\n'
print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer]) | conditional_block |
misc.py | import time
from os import system
import bot as cleanBot
def pp(message, mtype='INFO'):
mtype = mtype.upper()
print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message)
def ppi(channel, message, username):
print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, username.lower(), message)
def pbot(message, channel=''):
if channel:
msg = '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, 'BOT', message)
else:
msg = '[%s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), 'BOT', message)
print msg
def pbutton(message_buffer):
#system('clear')
if cleanBot.Bot().botOn == True: | print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer])
else:
print '\n\n'
print '\n'.join('CHAT ENABLED ACTIONS ARE OFF')
print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer]) | print '\n\n' | random_line_split |
misc.py | import time
from os import system
import bot as cleanBot
def pp(message, mtype='INFO'):
mtype = mtype.upper()
print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message)
def ppi(channel, message, username):
print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, username.lower(), message)
def pbot(message, channel=''):
if channel:
msg = '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, 'BOT', message)
else:
msg = '[%s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), 'BOT', message)
print msg
def pbutton(message_buffer):
#system('clear')
| if cleanBot.Bot().botOn == True:
print '\n\n'
print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer])
else:
print '\n\n'
print '\n'.join('CHAT ENABLED ACTIONS ARE OFF')
print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer]) | identifier_body | |
misc.py | import time
from os import system
import bot as cleanBot
def pp(message, mtype='INFO'):
mtype = mtype.upper()
print '[%s] [%s] %s' % (time.strftime('%H:%M:%S', time.gmtime()), mtype, message)
def ppi(channel, message, username):
print '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, username.lower(), message)
def pbot(message, channel=''):
if channel:
msg = '[%s %s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), channel, 'BOT', message)
else:
msg = '[%s] <%s> %s' % (time.strftime('%H:%M:%S', time.gmtime()), 'BOT', message)
print msg
def | (message_buffer):
#system('clear')
if cleanBot.Bot().botOn == True:
print '\n\n'
print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer])
else:
print '\n\n'
print '\n'.join('CHAT ENABLED ACTIONS ARE OFF')
print '\n'.join([' {0:<12s} {1:>6s}'.format(message['username'][:12].title(), message['button'].lower()) for message in message_buffer])
| pbutton | identifier_name |
cryptographer.py | from base64 import b64decode, b64encode
from hashlib import sha256
from Crypto import Random
from Crypto.Cipher import AES
from frontstage import app
class | :
"""Manage the encryption and decryption of random byte strings"""
def __init__(self):
"""
Set up the encryption key, this will come from an .ini file or from
an environment variable. Change the block size to suit the data supplied
or performance required.
:param key: The encryption key to use when encrypting the data
"""
key = app.config["SECRET_KEY"]
self._key = sha256(key.encode("utf-8")).digest()
def encrypt(self, raw_text):
"""
Encrypt the supplied text
:param raw_text: The data to encrypt, must be a string of type byte
:return: The encrypted text
"""
raw_text = self.pad(raw_text)
init_vector = Random.new().read(AES.block_size)
ons_cipher = AES.new(self._key, AES.MODE_CBC, init_vector)
return b64encode(init_vector + ons_cipher.encrypt(raw_text))
def decrypt(self, encrypted_text):
"""
Decrypt the supplied text
:param encrypted_text: The data to decrypt, must be a string of type byte
:return: The unencrypted text
"""
encrypted_text = b64decode(encrypted_text)
init_vector = encrypted_text[:16]
ons_cipher = AES.new(self._key, AES.MODE_CBC, init_vector)
return self.unpad(ons_cipher.decrypt(encrypted_text[16:]))
def pad(self, data):
"""
Pad the data out to the selected block size.
:param data: The data were trying to encrypt
:return: The data padded out to our given block size
"""
vector = AES.block_size - len(data) % AES.block_size
return data + ((bytes([vector])) * vector)
def unpad(self, data):
"""
Un-pad the selected data.
:param data: Our padded data
:return: The data 'un'padded
"""
return data[0 : -data[-1]]
| Cryptographer | identifier_name |
cryptographer.py | from base64 import b64decode, b64encode
from hashlib import sha256
from Crypto import Random
from Crypto.Cipher import AES
from frontstage import app
class Cryptographer:
"""Manage the encryption and decryption of random byte strings"""
def __init__(self):
"""
Set up the encryption key, this will come from an .ini file or from
an environment variable. Change the block size to suit the data supplied
or performance required.
:param key: The encryption key to use when encrypting the data
"""
key = app.config["SECRET_KEY"]
self._key = sha256(key.encode("utf-8")).digest()
def encrypt(self, raw_text):
"""
Encrypt the supplied text
:param raw_text: The data to encrypt, must be a string of type byte
:return: The encrypted text
"""
raw_text = self.pad(raw_text)
init_vector = Random.new().read(AES.block_size)
ons_cipher = AES.new(self._key, AES.MODE_CBC, init_vector)
return b64encode(init_vector + ons_cipher.encrypt(raw_text))
def decrypt(self, encrypted_text):
"""
Decrypt the supplied text
:param encrypted_text: The data to decrypt, must be a string of type byte
:return: The unencrypted text
"""
encrypted_text = b64decode(encrypted_text)
init_vector = encrypted_text[:16]
ons_cipher = AES.new(self._key, AES.MODE_CBC, init_vector)
return self.unpad(ons_cipher.decrypt(encrypted_text[16:]))
def pad(self, data):
"""
Pad the data out to the selected block size.
:param data: The data were trying to encrypt
:return: The data padded out to our given block size
""" | """
Un-pad the selected data.
:param data: Our padded data
:return: The data 'un'padded
"""
return data[0 : -data[-1]] | vector = AES.block_size - len(data) % AES.block_size
return data + ((bytes([vector])) * vector)
def unpad(self, data): | random_line_split |
cryptographer.py | from base64 import b64decode, b64encode
from hashlib import sha256
from Crypto import Random
from Crypto.Cipher import AES
from frontstage import app
class Cryptographer:
"""Manage the encryption and decryption of random byte strings"""
def __init__(self):
"""
Set up the encryption key, this will come from an .ini file or from
an environment variable. Change the block size to suit the data supplied
or performance required.
:param key: The encryption key to use when encrypting the data
"""
key = app.config["SECRET_KEY"]
self._key = sha256(key.encode("utf-8")).digest()
def encrypt(self, raw_text):
"""
Encrypt the supplied text
:param raw_text: The data to encrypt, must be a string of type byte
:return: The encrypted text
"""
raw_text = self.pad(raw_text)
init_vector = Random.new().read(AES.block_size)
ons_cipher = AES.new(self._key, AES.MODE_CBC, init_vector)
return b64encode(init_vector + ons_cipher.encrypt(raw_text))
def decrypt(self, encrypted_text):
"""
Decrypt the supplied text
:param encrypted_text: The data to decrypt, must be a string of type byte
:return: The unencrypted text
"""
encrypted_text = b64decode(encrypted_text)
init_vector = encrypted_text[:16]
ons_cipher = AES.new(self._key, AES.MODE_CBC, init_vector)
return self.unpad(ons_cipher.decrypt(encrypted_text[16:]))
def pad(self, data):
|
def unpad(self, data):
"""
Un-pad the selected data.
:param data: Our padded data
:return: The data 'un'padded
"""
return data[0 : -data[-1]]
| """
Pad the data out to the selected block size.
:param data: The data were trying to encrypt
:return: The data padded out to our given block size
"""
vector = AES.block_size - len(data) % AES.block_size
return data + ((bytes([vector])) * vector) | identifier_body |
fp.rs | // Copyright 2021 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{DecodeError, FieldInfo};
/// Decodes the ISS value for a floating-point exception.
pub fn decode_iss_fp(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
let res0a = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 24).check_res0()?;
let tfv =
FieldInfo::get_bit(iss, "TFV", Some("Trapped Fault Valid"), 23).describe_bit(describe_tfv);
let res0b = FieldInfo::get(iss, "RES0", Some("Reserved"), 11, 23).check_res0()?;
let vecitr = FieldInfo::get(iss, "VECITR", Some("RES1 or UNKNOWN"), 8, 11);
let idf = FieldInfo::get_bit(iss, "IDF", Some("Input Denormal"), 7).describe_bit(describe_idf);
let res0c = FieldInfo::get(iss, "RES0", Some("Reserved"), 5, 7).check_res0()?;
let ixf = FieldInfo::get_bit(iss, "IXF", Some("Inexact"), 4).describe_bit(describe_ixf);
let uff = FieldInfo::get_bit(iss, "UFF", Some("Underflow"), 3).describe_bit(describe_uff);
let off = FieldInfo::get_bit(iss, "OFF", Some("Overflow"), 2).describe_bit(describe_off);
let dzf = FieldInfo::get_bit(iss, "DZF", Some("Divide by Zero"), 1).describe_bit(describe_dzf);
let iof =
FieldInfo::get_bit(iss, "IOF", Some("Invalid Operation"), 0).describe_bit(describe_iof);
Ok(vec![
res0a, tfv, res0b, vecitr, idf, res0c, ixf, uff, off, dzf, iof,
])
}
fn describe_tfv(tfv: bool) -> &'static str {
if tfv {
"One or more floating-point exceptions occurred; IDF, IXF, UFF, OFF, DZF and IOF hold information about what."
} else {
"IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information."
}
}
fn | (idf: bool) -> &'static str {
if idf {
"Input denormal floating-point exception occurred."
} else {
"Input denormal floating-point exception did not occur."
}
}
fn describe_ixf(ixf: bool) -> &'static str {
if ixf {
"Inexact floating-point exception occurred."
} else {
"Inexact floating-point exception did not occur."
}
}
fn describe_uff(uff: bool) -> &'static str {
if uff {
"Underflow floating-point exception occurred."
} else {
"Underflow floating-point exception did not occur."
}
}
fn describe_off(off: bool) -> &'static str {
if off {
"Overflow floating-point exception occurred."
} else {
"Overflow floating-point exception did not occur."
}
}
fn describe_dzf(dzf: bool) -> &'static str {
if dzf {
"Divide by Zero floating-point exception occurred."
} else {
"Divide by Zero floating-point exception did not occur."
}
}
fn describe_iof(iof: bool) -> &'static str {
if iof {
"Invalid Operation floating-point exception occurred."
} else {
"Invalid Operation floating-point exception did not occur."
}
}
| describe_idf | identifier_name |
fp.rs | // Copyright 2021 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{DecodeError, FieldInfo};
/// Decodes the ISS value for a floating-point exception.
pub fn decode_iss_fp(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
let res0a = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 24).check_res0()?;
let tfv =
FieldInfo::get_bit(iss, "TFV", Some("Trapped Fault Valid"), 23).describe_bit(describe_tfv);
let res0b = FieldInfo::get(iss, "RES0", Some("Reserved"), 11, 23).check_res0()?;
let vecitr = FieldInfo::get(iss, "VECITR", Some("RES1 or UNKNOWN"), 8, 11);
let idf = FieldInfo::get_bit(iss, "IDF", Some("Input Denormal"), 7).describe_bit(describe_idf);
let res0c = FieldInfo::get(iss, "RES0", Some("Reserved"), 5, 7).check_res0()?;
let ixf = FieldInfo::get_bit(iss, "IXF", Some("Inexact"), 4).describe_bit(describe_ixf);
let uff = FieldInfo::get_bit(iss, "UFF", Some("Underflow"), 3).describe_bit(describe_uff);
let off = FieldInfo::get_bit(iss, "OFF", Some("Overflow"), 2).describe_bit(describe_off);
let dzf = FieldInfo::get_bit(iss, "DZF", Some("Divide by Zero"), 1).describe_bit(describe_dzf);
let iof =
FieldInfo::get_bit(iss, "IOF", Some("Invalid Operation"), 0).describe_bit(describe_iof);
Ok(vec![
res0a, tfv, res0b, vecitr, idf, res0c, ixf, uff, off, dzf, iof,
])
}
fn describe_tfv(tfv: bool) -> &'static str {
if tfv {
"One or more floating-point exceptions occurred; IDF, IXF, UFF, OFF, DZF and IOF hold information about what." | }
}
fn describe_idf(idf: bool) -> &'static str {
if idf {
"Input denormal floating-point exception occurred."
} else {
"Input denormal floating-point exception did not occur."
}
}
fn describe_ixf(ixf: bool) -> &'static str {
if ixf {
"Inexact floating-point exception occurred."
} else {
"Inexact floating-point exception did not occur."
}
}
fn describe_uff(uff: bool) -> &'static str {
if uff {
"Underflow floating-point exception occurred."
} else {
"Underflow floating-point exception did not occur."
}
}
fn describe_off(off: bool) -> &'static str {
if off {
"Overflow floating-point exception occurred."
} else {
"Overflow floating-point exception did not occur."
}
}
fn describe_dzf(dzf: bool) -> &'static str {
if dzf {
"Divide by Zero floating-point exception occurred."
} else {
"Divide by Zero floating-point exception did not occur."
}
}
fn describe_iof(iof: bool) -> &'static str {
if iof {
"Invalid Operation floating-point exception occurred."
} else {
"Invalid Operation floating-point exception did not occur."
}
} | } else {
"IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information." | random_line_split |
fp.rs | // Copyright 2021 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{DecodeError, FieldInfo};
/// Decodes the ISS value for a floating-point exception.
pub fn decode_iss_fp(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
let res0a = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 24).check_res0()?;
let tfv =
FieldInfo::get_bit(iss, "TFV", Some("Trapped Fault Valid"), 23).describe_bit(describe_tfv);
let res0b = FieldInfo::get(iss, "RES0", Some("Reserved"), 11, 23).check_res0()?;
let vecitr = FieldInfo::get(iss, "VECITR", Some("RES1 or UNKNOWN"), 8, 11);
let idf = FieldInfo::get_bit(iss, "IDF", Some("Input Denormal"), 7).describe_bit(describe_idf);
let res0c = FieldInfo::get(iss, "RES0", Some("Reserved"), 5, 7).check_res0()?;
let ixf = FieldInfo::get_bit(iss, "IXF", Some("Inexact"), 4).describe_bit(describe_ixf);
let uff = FieldInfo::get_bit(iss, "UFF", Some("Underflow"), 3).describe_bit(describe_uff);
let off = FieldInfo::get_bit(iss, "OFF", Some("Overflow"), 2).describe_bit(describe_off);
let dzf = FieldInfo::get_bit(iss, "DZF", Some("Divide by Zero"), 1).describe_bit(describe_dzf);
let iof =
FieldInfo::get_bit(iss, "IOF", Some("Invalid Operation"), 0).describe_bit(describe_iof);
Ok(vec![
res0a, tfv, res0b, vecitr, idf, res0c, ixf, uff, off, dzf, iof,
])
}
fn describe_tfv(tfv: bool) -> &'static str {
if tfv {
"One or more floating-point exceptions occurred; IDF, IXF, UFF, OFF, DZF and IOF hold information about what."
} else {
"IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information."
}
}
fn describe_idf(idf: bool) -> &'static str {
if idf {
"Input denormal floating-point exception occurred."
} else {
"Input denormal floating-point exception did not occur."
}
}
fn describe_ixf(ixf: bool) -> &'static str {
if ixf {
"Inexact floating-point exception occurred."
} else |
}
fn describe_uff(uff: bool) -> &'static str {
if uff {
"Underflow floating-point exception occurred."
} else {
"Underflow floating-point exception did not occur."
}
}
fn describe_off(off: bool) -> &'static str {
if off {
"Overflow floating-point exception occurred."
} else {
"Overflow floating-point exception did not occur."
}
}
fn describe_dzf(dzf: bool) -> &'static str {
if dzf {
"Divide by Zero floating-point exception occurred."
} else {
"Divide by Zero floating-point exception did not occur."
}
}
fn describe_iof(iof: bool) -> &'static str {
if iof {
"Invalid Operation floating-point exception occurred."
} else {
"Invalid Operation floating-point exception did not occur."
}
}
| {
"Inexact floating-point exception did not occur."
} | conditional_block |
fp.rs | // Copyright 2021 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use crate::{DecodeError, FieldInfo};
/// Decodes the ISS value for a floating-point exception.
pub fn decode_iss_fp(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> {
let res0a = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 24).check_res0()?;
let tfv =
FieldInfo::get_bit(iss, "TFV", Some("Trapped Fault Valid"), 23).describe_bit(describe_tfv);
let res0b = FieldInfo::get(iss, "RES0", Some("Reserved"), 11, 23).check_res0()?;
let vecitr = FieldInfo::get(iss, "VECITR", Some("RES1 or UNKNOWN"), 8, 11);
let idf = FieldInfo::get_bit(iss, "IDF", Some("Input Denormal"), 7).describe_bit(describe_idf);
let res0c = FieldInfo::get(iss, "RES0", Some("Reserved"), 5, 7).check_res0()?;
let ixf = FieldInfo::get_bit(iss, "IXF", Some("Inexact"), 4).describe_bit(describe_ixf);
let uff = FieldInfo::get_bit(iss, "UFF", Some("Underflow"), 3).describe_bit(describe_uff);
let off = FieldInfo::get_bit(iss, "OFF", Some("Overflow"), 2).describe_bit(describe_off);
let dzf = FieldInfo::get_bit(iss, "DZF", Some("Divide by Zero"), 1).describe_bit(describe_dzf);
let iof =
FieldInfo::get_bit(iss, "IOF", Some("Invalid Operation"), 0).describe_bit(describe_iof);
Ok(vec![
res0a, tfv, res0b, vecitr, idf, res0c, ixf, uff, off, dzf, iof,
])
}
fn describe_tfv(tfv: bool) -> &'static str {
if tfv {
"One or more floating-point exceptions occurred; IDF, IXF, UFF, OFF, DZF and IOF hold information about what."
} else {
"IDF, IXF, UFF, OFF, DZF and IOF do not hold valid information."
}
}
fn describe_idf(idf: bool) -> &'static str {
if idf {
"Input denormal floating-point exception occurred."
} else {
"Input denormal floating-point exception did not occur."
}
}
fn describe_ixf(ixf: bool) -> &'static str {
if ixf {
"Inexact floating-point exception occurred."
} else {
"Inexact floating-point exception did not occur."
}
}
fn describe_uff(uff: bool) -> &'static str {
if uff {
"Underflow floating-point exception occurred."
} else {
"Underflow floating-point exception did not occur."
}
}
fn describe_off(off: bool) -> &'static str {
if off {
"Overflow floating-point exception occurred."
} else {
"Overflow floating-point exception did not occur."
}
}
fn describe_dzf(dzf: bool) -> &'static str {
if dzf {
"Divide by Zero floating-point exception occurred."
} else {
"Divide by Zero floating-point exception did not occur."
}
}
fn describe_iof(iof: bool) -> &'static str | {
if iof {
"Invalid Operation floating-point exception occurred."
} else {
"Invalid Operation floating-point exception did not occur."
}
} | identifier_body | |
app.component.spec.ts | import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { OnChangesDemoComponent } from './on-changes-demo/on-changes-demo.component';
import { DoCheckDemoComponent } from './do-check-demo/do-check-demo.component';
import { OnInitDemoComponent } from './on-init-demo/on-init-demo.component';
import { AfterContentInitChildComponent } from './after-content-init-child/after-content-init-child.component';
import { AfterContentInitDemoComponent } from './after-content-init-demo/after-content-init-demo.component';
import { OnDestroyDemoComponent } from './on-destroy-demo/on-destroy-demo.component';
import { AfterViewInitDemoComponent } from './after-view-init-demo/after-view-init-demo.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [CommonModule, FormsModule],
declarations: [
AppComponent,
OnInitDemoComponent, | AfterContentInitChildComponent,
AfterContentInitDemoComponent,
OnDestroyDemoComponent,
AfterViewInitDemoComponent
]
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
}); | OnChangesDemoComponent,
DoCheckDemoComponent,
OnInitDemoComponent, | random_line_split |
dmc_colors.py | import csv
import os
import color
def _GetDataDirPath():
return os.path.join(os.path.dirname(__file__), 'data')
def _GetCsvPath():
return os.path.join(_GetDataDirPath(), 'dmccolors.csv')
def _GetCsvString():
with open(_GetCsvPath()) as f:
return f.read().strip()
def _CreateDmcColorFromRow(row):
number = int(row[0])
name = row[1]
hex_color = row[5]
rgb_color = color.RGBColorFromHexString(hex_color)
return DMCColor(number, name, rgb_color)
# DMC Colors singleton
_dmc_colors = None
def _CreateDMCColors():
|
def GetDMCColors():
global _dmc_colors
if not _dmc_colors:
_dmc_colors = frozenset(_CreateDMCColors())
return _dmc_colors
def GetClosestDMCColorsPairs(rgb_color):
pairs = list()
for dcolor in GetDMCColors():
pairs.append((dcolor, color.RGBColor.distance(rgb_color, dcolor.color)))
return sorted(pairs, key=lambda pair: pair[1])
def GetClosestDMCColors(rgb_color):
return [pair[0] for pair in GetClosestDMCColorsPairs(rgb_color)]
class DMCColor(object):
def __init__(self, number, name, color):
self.number = number
self.name = name
self.color = color
def __str__(self):
return super(DMCColor, self).__str__() + str((self.number, self.name, self.color))
def GetStringForDMCColor(dmc_color):
return "%s %s %s" % (dmc_color.number, dmc_color.name, dmc_color.color)
# Simple executable functionality for debugging.
def main():
for color in GetDMCColors():
print color
if __name__ == '__main__':
main()
| global _dmc_colors
csv_data = _GetCsvString()
lines = csv_data.splitlines()
# Skip first line
lines = lines[1:]
reader = csv.reader(lines, delimiter='\t')
dmc_colors = set()
for row in reader:
dmc_colors.add(_CreateDmcColorFromRow(row))
return dmc_colors | identifier_body |
dmc_colors.py | import csv
import os
import color
def _GetDataDirPath():
return os.path.join(os.path.dirname(__file__), 'data')
def _GetCsvPath():
return os.path.join(_GetDataDirPath(), 'dmccolors.csv')
def _GetCsvString():
with open(_GetCsvPath()) as f:
return f.read().strip()
def _CreateDmcColorFromRow(row):
number = int(row[0])
name = row[1]
hex_color = row[5]
rgb_color = color.RGBColorFromHexString(hex_color)
return DMCColor(number, name, rgb_color)
# DMC Colors singleton
_dmc_colors = None
def _CreateDMCColors():
global _dmc_colors
csv_data = _GetCsvString()
lines = csv_data.splitlines()
# Skip first line
lines = lines[1:]
reader = csv.reader(lines, delimiter='\t')
dmc_colors = set()
for row in reader:
dmc_colors.add(_CreateDmcColorFromRow(row))
return dmc_colors
def GetDMCColors():
global _dmc_colors
if not _dmc_colors:
_dmc_colors = frozenset(_CreateDMCColors())
return _dmc_colors
def GetClosestDMCColorsPairs(rgb_color):
pairs = list()
for dcolor in GetDMCColors():
pairs.append((dcolor, color.RGBColor.distance(rgb_color, dcolor.color)))
return sorted(pairs, key=lambda pair: pair[1])
def GetClosestDMCColors(rgb_color):
return [pair[0] for pair in GetClosestDMCColorsPairs(rgb_color)]
class DMCColor(object):
def __init__(self, number, name, color):
self.number = number
self.name = name
self.color = color
def __str__(self):
return super(DMCColor, self).__str__() + str((self.number, self.name, self.color))
def GetStringForDMCColor(dmc_color):
return "%s %s %s" % (dmc_color.number, dmc_color.name, dmc_color.color)
# Simple executable functionality for debugging.
def main():
for color in GetDMCColors():
print color | if __name__ == '__main__':
main() | random_line_split | |
dmc_colors.py | import csv
import os
import color
def _GetDataDirPath():
return os.path.join(os.path.dirname(__file__), 'data')
def _GetCsvPath():
return os.path.join(_GetDataDirPath(), 'dmccolors.csv')
def _GetCsvString():
with open(_GetCsvPath()) as f:
return f.read().strip()
def _CreateDmcColorFromRow(row):
number = int(row[0])
name = row[1]
hex_color = row[5]
rgb_color = color.RGBColorFromHexString(hex_color)
return DMCColor(number, name, rgb_color)
# DMC Colors singleton
_dmc_colors = None
def _CreateDMCColors():
global _dmc_colors
csv_data = _GetCsvString()
lines = csv_data.splitlines()
# Skip first line
lines = lines[1:]
reader = csv.reader(lines, delimiter='\t')
dmc_colors = set()
for row in reader:
|
return dmc_colors
def GetDMCColors():
global _dmc_colors
if not _dmc_colors:
_dmc_colors = frozenset(_CreateDMCColors())
return _dmc_colors
def GetClosestDMCColorsPairs(rgb_color):
pairs = list()
for dcolor in GetDMCColors():
pairs.append((dcolor, color.RGBColor.distance(rgb_color, dcolor.color)))
return sorted(pairs, key=lambda pair: pair[1])
def GetClosestDMCColors(rgb_color):
return [pair[0] for pair in GetClosestDMCColorsPairs(rgb_color)]
class DMCColor(object):
def __init__(self, number, name, color):
self.number = number
self.name = name
self.color = color
def __str__(self):
return super(DMCColor, self).__str__() + str((self.number, self.name, self.color))
def GetStringForDMCColor(dmc_color):
return "%s %s %s" % (dmc_color.number, dmc_color.name, dmc_color.color)
# Simple executable functionality for debugging.
def main():
for color in GetDMCColors():
print color
if __name__ == '__main__':
main()
| dmc_colors.add(_CreateDmcColorFromRow(row)) | conditional_block |
dmc_colors.py | import csv
import os
import color
def _GetDataDirPath():
return os.path.join(os.path.dirname(__file__), 'data')
def _GetCsvPath():
return os.path.join(_GetDataDirPath(), 'dmccolors.csv')
def _GetCsvString():
with open(_GetCsvPath()) as f:
return f.read().strip()
def _CreateDmcColorFromRow(row):
number = int(row[0])
name = row[1]
hex_color = row[5]
rgb_color = color.RGBColorFromHexString(hex_color)
return DMCColor(number, name, rgb_color)
# DMC Colors singleton
_dmc_colors = None
def _CreateDMCColors():
global _dmc_colors
csv_data = _GetCsvString()
lines = csv_data.splitlines()
# Skip first line
lines = lines[1:]
reader = csv.reader(lines, delimiter='\t')
dmc_colors = set()
for row in reader:
dmc_colors.add(_CreateDmcColorFromRow(row))
return dmc_colors
def GetDMCColors():
global _dmc_colors
if not _dmc_colors:
_dmc_colors = frozenset(_CreateDMCColors())
return _dmc_colors
def GetClosestDMCColorsPairs(rgb_color):
pairs = list()
for dcolor in GetDMCColors():
pairs.append((dcolor, color.RGBColor.distance(rgb_color, dcolor.color)))
return sorted(pairs, key=lambda pair: pair[1])
def GetClosestDMCColors(rgb_color):
return [pair[0] for pair in GetClosestDMCColorsPairs(rgb_color)]
class DMCColor(object):
def __init__(self, number, name, color):
self.number = number
self.name = name
self.color = color
def | (self):
return super(DMCColor, self).__str__() + str((self.number, self.name, self.color))
def GetStringForDMCColor(dmc_color):
return "%s %s %s" % (dmc_color.number, dmc_color.name, dmc_color.color)
# Simple executable functionality for debugging.
def main():
for color in GetDMCColors():
print color
if __name__ == '__main__':
main()
| __str__ | identifier_name |
const-vec-of-fns.rs | // Copyright 2013 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.
/*!
* Try to double-check that static fns have the right size (with or
* without dummy env ptr, as appropriate) by iterating a size-2 array.
* If the static size differs from the runtime size, the second element
* should be read as a null or otherwise wrong pointer and crash.
*/
fn | () { }
static bare_fns: &'static [fn()] = &[f, f];
struct S<F: FnOnce()>(F);
static mut closures: &'static mut [S<fn()>] = &mut [S(f as fn()), S(f as fn())];
pub fn main() {
unsafe {
for &bare_fn in bare_fns { bare_fn() }
for closure in &mut *closures {
let S(ref mut closure) = *closure;
(*closure)()
}
}
}
| f | identifier_name |
const-vec-of-fns.rs | // Copyright 2013 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.
/*!
* Try to double-check that static fns have the right size (with or
* without dummy env ptr, as appropriate) by iterating a size-2 array.
* If the static size differs from the runtime size, the second element
* should be read as a null or otherwise wrong pointer and crash.
*/
fn f() { }
static bare_fns: &'static [fn()] = &[f, f];
struct S<F: FnOnce()>(F);
static mut closures: &'static mut [S<fn()>] = &mut [S(f as fn()), S(f as fn())];
pub fn main() {
unsafe {
for &bare_fn in bare_fns { bare_fn() }
for closure in &mut *closures {
let S(ref mut closure) = *closure;
(*closure)()
}
}
} | random_line_split | |
output.py | # Copyright 1998-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $
import os
import sys
import re
havecolor = 1
dotitles = 1
spinpos = 0
spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|"
esc_seq = "\x1b["
g_attr = {}
g_attr["normal"] = 0
g_attr["bold"] = 1
g_attr["faint"] = 2
g_attr["standout"] = 3
g_attr["underline"] = 4
g_attr["blink"] = 5
g_attr["overline"] = 6 # Why is overline actually useful?
g_attr["reverse"] = 7
g_attr["invisible"] = 8
g_attr["no-attr"] = 22
g_attr["no-standout"] = 23
g_attr["no-underline"] = 24
g_attr["no-blink"] = 25
g_attr["no-overline"] = 26
g_attr["no-reverse"] = 27
# 28 isn't defined?
# 29 isn't defined?
g_attr["black"] = 30
g_attr["red"] = 31
g_attr["green"] = 32
g_attr["yellow"] = 33
g_attr["blue"] = 34
g_attr["magenta"] = 35
g_attr["cyan"] = 36
g_attr["white"] = 37
# 38 isn't defined?
g_attr["default"] = 39
g_attr["bg_black"] = 40
g_attr["bg_red"] = 41
g_attr["bg_green"] = 42
g_attr["bg_yellow"] = 43
g_attr["bg_blue"] = 44
g_attr["bg_magenta"] = 45
g_attr["bg_cyan"] = 46
g_attr["bg_white"] = 47
g_attr["bg_default"] = 49
# make_seq("blue", "black", "normal")
def color(fg, bg="default", attr=["normal"]):
mystr = esc_seq[:] + "%02d" % g_attr[fg]
for x in [bg] + attr:
mystr += ";%02d" % g_attr[x]
return mystr + "m"
codes = {}
codes["reset"] = esc_seq + "39;49;00m"
codes["bold"] = esc_seq + "01m"
codes["faint"] = esc_seq + "02m"
codes["standout"] = esc_seq + "03m"
codes["underline"] = esc_seq + "04m"
codes["blink"] = esc_seq + "05m"
codes["overline"] = esc_seq + "06m" # Who made this up? Seriously.
codes["teal"] = esc_seq + "36m"
codes["turquoise"] = esc_seq + "36;01m"
codes["fuchsia"] = esc_seq + "35;01m"
codes["purple"] = esc_seq + "35m"
codes["blue"] = esc_seq + "34;01m"
codes["darkblue"] = esc_seq + "34m"
codes["green"] = esc_seq + "32;01m"
codes["darkgreen"] = esc_seq + "32m"
codes["yellow"] = esc_seq + "33;01m"
codes["brown"] = esc_seq + "33m"
codes["red"] = esc_seq + "31;01m"
codes["darkred"] = esc_seq + "31m"
def | (mystr):
tmp = re.sub(esc_seq + "^m]+m", "", mystr)
return len(tmp)
def xtermTitle(mystr):
if havecolor and dotitles and "TERM" in os.environ and sys.stderr.isatty():
myt = os.environ["TERM"]
legal_terms = [
"xterm", "Eterm", "aterm", "rxvt", "screen", "kterm", "rxvt-unicode"]
for term in legal_terms:
if myt.startswith(term):
sys.stderr.write("\x1b]2;" + str(mystr) + "\x07")
sys.stderr.flush()
break
def xtermTitleReset():
if havecolor and dotitles and "TERM" in os.environ:
myt = os.environ["TERM"]
xtermTitle(os.environ["TERM"])
def notitles():
"turn off title setting"
dotitles = 0
def nocolor():
"turn off colorization"
havecolor = 0
for x in codes.keys():
codes[x] = ""
def resetColor():
return codes["reset"]
def ctext(color, text):
return codes[ctext] + text + codes["reset"]
def bold(text):
return codes["bold"] + text + codes["reset"]
def faint(text):
return codes["faint"] + text + codes["reset"]
def white(text):
return bold(text)
def teal(text):
return codes["teal"] + text + codes["reset"]
def turquoise(text):
return codes["turquoise"] + text + codes["reset"]
def darkteal(text):
return turquoise(text)
def fuscia(text): # Don't use this one. It's spelled wrong!
return codes["fuchsia"] + text + codes["reset"]
def fuchsia(text):
return codes["fuchsia"] + text + codes["reset"]
def purple(text):
return codes["purple"] + text + codes["reset"]
def blue(text):
return codes["blue"] + text + codes["reset"]
def darkblue(text):
return codes["darkblue"] + text + codes["reset"]
def green(text):
return codes["green"] + text + codes["reset"]
def darkgreen(text):
return codes["darkgreen"] + text + codes["reset"]
def yellow(text):
return codes["yellow"] + text + codes["reset"]
def brown(text):
return codes["brown"] + text + codes["reset"]
def darkyellow(text):
return brown(text)
def red(text):
return codes["red"] + text + codes["reset"]
def darkred(text):
return codes["darkred"] + text + codes["reset"]
def update_basic_spinner():
global spinner, spinpos
spinpos = (spinpos + 1) % 500
if (spinpos % 100) == 0:
if spinpos == 0:
sys.stdout.write(". ")
else:
sys.stdout.write(".")
sys.stdout.flush()
def update_scroll_spinner():
global spinner, spinpos
if(spinpos >= len(spinner)):
sys.stdout.write(
darkgreen(" \b\b\b" + spinner[len(spinner) - 1 - (spinpos % len(spinner))]))
else:
sys.stdout.write(green("\b " + spinner[spinpos]))
sys.stdout.flush()
spinpos = (spinpos + 1) % (2 * len(spinner))
def update_spinner():
global spinner, spinpos
spinpos = (spinpos + 1) % len(spinner)
sys.stdout.write("\b\b " + spinner[spinpos])
sys.stdout.flush()
| nc_len | identifier_name |
output.py | # Copyright 1998-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $
import os
import sys
import re
havecolor = 1
dotitles = 1
spinpos = 0
spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|"
esc_seq = "\x1b["
g_attr = {}
g_attr["normal"] = 0
g_attr["bold"] = 1
g_attr["faint"] = 2
g_attr["standout"] = 3
g_attr["underline"] = 4
g_attr["blink"] = 5
g_attr["overline"] = 6 # Why is overline actually useful?
g_attr["reverse"] = 7
g_attr["invisible"] = 8
g_attr["no-attr"] = 22
g_attr["no-standout"] = 23
g_attr["no-underline"] = 24
g_attr["no-blink"] = 25
g_attr["no-overline"] = 26
g_attr["no-reverse"] = 27
# 28 isn't defined?
# 29 isn't defined?
g_attr["black"] = 30
g_attr["red"] = 31
g_attr["green"] = 32
g_attr["yellow"] = 33
g_attr["blue"] = 34
g_attr["magenta"] = 35
g_attr["cyan"] = 36
g_attr["white"] = 37
# 38 isn't defined?
g_attr["default"] = 39
g_attr["bg_black"] = 40
g_attr["bg_red"] = 41
g_attr["bg_green"] = 42
g_attr["bg_yellow"] = 43
g_attr["bg_blue"] = 44
g_attr["bg_magenta"] = 45
g_attr["bg_cyan"] = 46
g_attr["bg_white"] = 47
g_attr["bg_default"] = 49
# make_seq("blue", "black", "normal")
def color(fg, bg="default", attr=["normal"]):
mystr = esc_seq[:] + "%02d" % g_attr[fg]
for x in [bg] + attr:
mystr += ";%02d" % g_attr[x]
return mystr + "m"
codes = {}
codes["reset"] = esc_seq + "39;49;00m"
codes["bold"] = esc_seq + "01m"
codes["faint"] = esc_seq + "02m"
codes["standout"] = esc_seq + "03m"
codes["underline"] = esc_seq + "04m"
codes["blink"] = esc_seq + "05m"
codes["overline"] = esc_seq + "06m" # Who made this up? Seriously.
codes["teal"] = esc_seq + "36m"
codes["turquoise"] = esc_seq + "36;01m"
codes["fuchsia"] = esc_seq + "35;01m"
codes["purple"] = esc_seq + "35m"
codes["blue"] = esc_seq + "34;01m"
codes["darkblue"] = esc_seq + "34m"
codes["green"] = esc_seq + "32;01m"
codes["darkgreen"] = esc_seq + "32m"
codes["yellow"] = esc_seq + "33;01m"
codes["brown"] = esc_seq + "33m"
codes["red"] = esc_seq + "31;01m"
codes["darkred"] = esc_seq + "31m"
def nc_len(mystr):
tmp = re.sub(esc_seq + "^m]+m", "", mystr)
return len(tmp)
def xtermTitle(mystr):
if havecolor and dotitles and "TERM" in os.environ and sys.stderr.isatty():
myt = os.environ["TERM"]
legal_terms = [
"xterm", "Eterm", "aterm", "rxvt", "screen", "kterm", "rxvt-unicode"]
for term in legal_terms:
if myt.startswith(term):
sys.stderr.write("\x1b]2;" + str(mystr) + "\x07")
sys.stderr.flush()
break
def xtermTitleReset():
if havecolor and dotitles and "TERM" in os.environ:
myt = os.environ["TERM"]
xtermTitle(os.environ["TERM"])
def notitles():
"turn off title setting"
dotitles = 0
def nocolor():
"turn off colorization"
havecolor = 0
for x in codes.keys():
|
def resetColor():
return codes["reset"]
def ctext(color, text):
return codes[ctext] + text + codes["reset"]
def bold(text):
return codes["bold"] + text + codes["reset"]
def faint(text):
return codes["faint"] + text + codes["reset"]
def white(text):
return bold(text)
def teal(text):
return codes["teal"] + text + codes["reset"]
def turquoise(text):
return codes["turquoise"] + text + codes["reset"]
def darkteal(text):
return turquoise(text)
def fuscia(text): # Don't use this one. It's spelled wrong!
return codes["fuchsia"] + text + codes["reset"]
def fuchsia(text):
return codes["fuchsia"] + text + codes["reset"]
def purple(text):
return codes["purple"] + text + codes["reset"]
def blue(text):
return codes["blue"] + text + codes["reset"]
def darkblue(text):
return codes["darkblue"] + text + codes["reset"]
def green(text):
return codes["green"] + text + codes["reset"]
def darkgreen(text):
return codes["darkgreen"] + text + codes["reset"]
def yellow(text):
return codes["yellow"] + text + codes["reset"]
def brown(text):
return codes["brown"] + text + codes["reset"]
def darkyellow(text):
return brown(text)
def red(text):
return codes["red"] + text + codes["reset"]
def darkred(text):
return codes["darkred"] + text + codes["reset"]
def update_basic_spinner():
global spinner, spinpos
spinpos = (spinpos + 1) % 500
if (spinpos % 100) == 0:
if spinpos == 0:
sys.stdout.write(". ")
else:
sys.stdout.write(".")
sys.stdout.flush()
def update_scroll_spinner():
global spinner, spinpos
if(spinpos >= len(spinner)):
sys.stdout.write(
darkgreen(" \b\b\b" + spinner[len(spinner) - 1 - (spinpos % len(spinner))]))
else:
sys.stdout.write(green("\b " + spinner[spinpos]))
sys.stdout.flush()
spinpos = (spinpos + 1) % (2 * len(spinner))
def update_spinner():
global spinner, spinpos
spinpos = (spinpos + 1) % len(spinner)
sys.stdout.write("\b\b " + spinner[spinpos])
sys.stdout.flush()
| codes[x] = "" | conditional_block |
output.py | # Copyright 1998-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $
import os
import sys
import re
havecolor = 1
dotitles = 1
spinpos = 0
spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|"
esc_seq = "\x1b["
g_attr = {}
g_attr["normal"] = 0
g_attr["bold"] = 1
g_attr["faint"] = 2
g_attr["standout"] = 3
g_attr["underline"] = 4
g_attr["blink"] = 5
g_attr["overline"] = 6 # Why is overline actually useful?
g_attr["reverse"] = 7
g_attr["invisible"] = 8
g_attr["no-attr"] = 22
g_attr["no-standout"] = 23
g_attr["no-underline"] = 24
g_attr["no-blink"] = 25
g_attr["no-overline"] = 26
g_attr["no-reverse"] = 27
# 28 isn't defined?
# 29 isn't defined?
g_attr["black"] = 30
g_attr["red"] = 31
g_attr["green"] = 32
g_attr["yellow"] = 33
g_attr["blue"] = 34
g_attr["magenta"] = 35
g_attr["cyan"] = 36
g_attr["white"] = 37
# 38 isn't defined?
g_attr["default"] = 39
g_attr["bg_black"] = 40
g_attr["bg_red"] = 41
g_attr["bg_green"] = 42
g_attr["bg_yellow"] = 43
g_attr["bg_blue"] = 44
g_attr["bg_magenta"] = 45
g_attr["bg_cyan"] = 46
g_attr["bg_white"] = 47
g_attr["bg_default"] = 49
# make_seq("blue", "black", "normal")
def color(fg, bg="default", attr=["normal"]):
mystr = esc_seq[:] + "%02d" % g_attr[fg]
for x in [bg] + attr:
mystr += ";%02d" % g_attr[x]
return mystr + "m"
codes = {}
codes["reset"] = esc_seq + "39;49;00m"
codes["bold"] = esc_seq + "01m"
codes["faint"] = esc_seq + "02m"
codes["standout"] = esc_seq + "03m"
codes["underline"] = esc_seq + "04m"
codes["blink"] = esc_seq + "05m"
codes["overline"] = esc_seq + "06m" # Who made this up? Seriously.
codes["teal"] = esc_seq + "36m"
codes["turquoise"] = esc_seq + "36;01m"
codes["fuchsia"] = esc_seq + "35;01m"
codes["purple"] = esc_seq + "35m"
codes["blue"] = esc_seq + "34;01m"
codes["darkblue"] = esc_seq + "34m"
codes["green"] = esc_seq + "32;01m"
codes["darkgreen"] = esc_seq + "32m"
codes["yellow"] = esc_seq + "33;01m"
codes["brown"] = esc_seq + "33m"
codes["red"] = esc_seq + "31;01m"
codes["darkred"] = esc_seq + "31m"
def nc_len(mystr):
tmp = re.sub(esc_seq + "^m]+m", "", mystr)
return len(tmp)
def xtermTitle(mystr):
if havecolor and dotitles and "TERM" in os.environ and sys.stderr.isatty():
myt = os.environ["TERM"]
legal_terms = [
"xterm", "Eterm", "aterm", "rxvt", "screen", "kterm", "rxvt-unicode"]
for term in legal_terms:
if myt.startswith(term):
sys.stderr.write("\x1b]2;" + str(mystr) + "\x07")
sys.stderr.flush()
break
def xtermTitleReset():
if havecolor and dotitles and "TERM" in os.environ:
myt = os.environ["TERM"]
xtermTitle(os.environ["TERM"])
def notitles():
"turn off title setting"
dotitles = 0
def nocolor():
"turn off colorization"
havecolor = 0
for x in codes.keys():
codes[x] = ""
def resetColor():
return codes["reset"]
def ctext(color, text):
return codes[ctext] + text + codes["reset"]
def bold(text):
return codes["bold"] + text + codes["reset"]
def faint(text):
return codes["faint"] + text + codes["reset"]
def white(text):
return bold(text)
def teal(text):
return codes["teal"] + text + codes["reset"]
def turquoise(text):
return codes["turquoise"] + text + codes["reset"]
def darkteal(text):
return turquoise(text)
def fuscia(text): # Don't use this one. It's spelled wrong!
return codes["fuchsia"] + text + codes["reset"]
def fuchsia(text):
return codes["fuchsia"] + text + codes["reset"]
def purple(text):
return codes["purple"] + text + codes["reset"]
def blue(text):
return codes["blue"] + text + codes["reset"]
|
def green(text):
return codes["green"] + text + codes["reset"]
def darkgreen(text):
return codes["darkgreen"] + text + codes["reset"]
def yellow(text):
return codes["yellow"] + text + codes["reset"]
def brown(text):
return codes["brown"] + text + codes["reset"]
def darkyellow(text):
return brown(text)
def red(text):
return codes["red"] + text + codes["reset"]
def darkred(text):
return codes["darkred"] + text + codes["reset"]
def update_basic_spinner():
global spinner, spinpos
spinpos = (spinpos + 1) % 500
if (spinpos % 100) == 0:
if spinpos == 0:
sys.stdout.write(". ")
else:
sys.stdout.write(".")
sys.stdout.flush()
def update_scroll_spinner():
global spinner, spinpos
if(spinpos >= len(spinner)):
sys.stdout.write(
darkgreen(" \b\b\b" + spinner[len(spinner) - 1 - (spinpos % len(spinner))]))
else:
sys.stdout.write(green("\b " + spinner[spinpos]))
sys.stdout.flush()
spinpos = (spinpos + 1) % (2 * len(spinner))
def update_spinner():
global spinner, spinpos
spinpos = (spinpos + 1) % len(spinner)
sys.stdout.write("\b\b " + spinner[spinpos])
sys.stdout.flush() |
def darkblue(text):
return codes["darkblue"] + text + codes["reset"] | random_line_split |
output.py | # Copyright 1998-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License v2
# $Id: output.py,v 1.1 2006/03/06 18:13:31 henrique Exp $
import os
import sys
import re
havecolor = 1
dotitles = 1
spinpos = 0
spinner = "/-\\|/-\\|/-\\|/-\\|\\-/|\\-/|\\-/|\\-/|"
esc_seq = "\x1b["
g_attr = {}
g_attr["normal"] = 0
g_attr["bold"] = 1
g_attr["faint"] = 2
g_attr["standout"] = 3
g_attr["underline"] = 4
g_attr["blink"] = 5
g_attr["overline"] = 6 # Why is overline actually useful?
g_attr["reverse"] = 7
g_attr["invisible"] = 8
g_attr["no-attr"] = 22
g_attr["no-standout"] = 23
g_attr["no-underline"] = 24
g_attr["no-blink"] = 25
g_attr["no-overline"] = 26
g_attr["no-reverse"] = 27
# 28 isn't defined?
# 29 isn't defined?
g_attr["black"] = 30
g_attr["red"] = 31
g_attr["green"] = 32
g_attr["yellow"] = 33
g_attr["blue"] = 34
g_attr["magenta"] = 35
g_attr["cyan"] = 36
g_attr["white"] = 37
# 38 isn't defined?
g_attr["default"] = 39
g_attr["bg_black"] = 40
g_attr["bg_red"] = 41
g_attr["bg_green"] = 42
g_attr["bg_yellow"] = 43
g_attr["bg_blue"] = 44
g_attr["bg_magenta"] = 45
g_attr["bg_cyan"] = 46
g_attr["bg_white"] = 47
g_attr["bg_default"] = 49
# make_seq("blue", "black", "normal")
def color(fg, bg="default", attr=["normal"]):
mystr = esc_seq[:] + "%02d" % g_attr[fg]
for x in [bg] + attr:
mystr += ";%02d" % g_attr[x]
return mystr + "m"
codes = {}
codes["reset"] = esc_seq + "39;49;00m"
codes["bold"] = esc_seq + "01m"
codes["faint"] = esc_seq + "02m"
codes["standout"] = esc_seq + "03m"
codes["underline"] = esc_seq + "04m"
codes["blink"] = esc_seq + "05m"
codes["overline"] = esc_seq + "06m" # Who made this up? Seriously.
codes["teal"] = esc_seq + "36m"
codes["turquoise"] = esc_seq + "36;01m"
codes["fuchsia"] = esc_seq + "35;01m"
codes["purple"] = esc_seq + "35m"
codes["blue"] = esc_seq + "34;01m"
codes["darkblue"] = esc_seq + "34m"
codes["green"] = esc_seq + "32;01m"
codes["darkgreen"] = esc_seq + "32m"
codes["yellow"] = esc_seq + "33;01m"
codes["brown"] = esc_seq + "33m"
codes["red"] = esc_seq + "31;01m"
codes["darkred"] = esc_seq + "31m"
def nc_len(mystr):
tmp = re.sub(esc_seq + "^m]+m", "", mystr)
return len(tmp)
def xtermTitle(mystr):
if havecolor and dotitles and "TERM" in os.environ and sys.stderr.isatty():
myt = os.environ["TERM"]
legal_terms = [
"xterm", "Eterm", "aterm", "rxvt", "screen", "kterm", "rxvt-unicode"]
for term in legal_terms:
if myt.startswith(term):
sys.stderr.write("\x1b]2;" + str(mystr) + "\x07")
sys.stderr.flush()
break
def xtermTitleReset():
if havecolor and dotitles and "TERM" in os.environ:
myt = os.environ["TERM"]
xtermTitle(os.environ["TERM"])
def notitles():
"turn off title setting"
dotitles = 0
def nocolor():
"turn off colorization"
havecolor = 0
for x in codes.keys():
codes[x] = ""
def resetColor():
|
def ctext(color, text):
return codes[ctext] + text + codes["reset"]
def bold(text):
return codes["bold"] + text + codes["reset"]
def faint(text):
return codes["faint"] + text + codes["reset"]
def white(text):
return bold(text)
def teal(text):
return codes["teal"] + text + codes["reset"]
def turquoise(text):
return codes["turquoise"] + text + codes["reset"]
def darkteal(text):
return turquoise(text)
def fuscia(text): # Don't use this one. It's spelled wrong!
return codes["fuchsia"] + text + codes["reset"]
def fuchsia(text):
return codes["fuchsia"] + text + codes["reset"]
def purple(text):
return codes["purple"] + text + codes["reset"]
def blue(text):
return codes["blue"] + text + codes["reset"]
def darkblue(text):
return codes["darkblue"] + text + codes["reset"]
def green(text):
return codes["green"] + text + codes["reset"]
def darkgreen(text):
return codes["darkgreen"] + text + codes["reset"]
def yellow(text):
return codes["yellow"] + text + codes["reset"]
def brown(text):
return codes["brown"] + text + codes["reset"]
def darkyellow(text):
return brown(text)
def red(text):
return codes["red"] + text + codes["reset"]
def darkred(text):
return codes["darkred"] + text + codes["reset"]
def update_basic_spinner():
global spinner, spinpos
spinpos = (spinpos + 1) % 500
if (spinpos % 100) == 0:
if spinpos == 0:
sys.stdout.write(". ")
else:
sys.stdout.write(".")
sys.stdout.flush()
def update_scroll_spinner():
global spinner, spinpos
if(spinpos >= len(spinner)):
sys.stdout.write(
darkgreen(" \b\b\b" + spinner[len(spinner) - 1 - (spinpos % len(spinner))]))
else:
sys.stdout.write(green("\b " + spinner[spinpos]))
sys.stdout.flush()
spinpos = (spinpos + 1) % (2 * len(spinner))
def update_spinner():
global spinner, spinpos
spinpos = (spinpos + 1) % len(spinner)
sys.stdout.write("\b\b " + spinner[spinpos])
sys.stdout.flush()
| return codes["reset"] | identifier_body |
CustomizedTables.tsx | import * as React from 'react';
import { styled } from '@mui/material/styles';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: theme.palette.common.black,
color: theme.palette.common.white,
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
},
}));
const StyledTableRow = styled(TableRow)(({ theme }) => ({
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
// hide last border
'&:last-child td, &:last-child th': {
border: 0,
},
}));
function createData(
name: string,
calories: number,
fat: number,
carbs: number,
protein: number,
) {
return { name, calories, fat, carbs, protein };
}
const rows = [
createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
createData('Eclair', 262, 16.0, 24, 6.0),
createData('Cupcake', 305, 3.7, 67, 4.3),
createData('Gingerbread', 356, 16.0, 49, 3.9),
];
export default function CustomizedTables() {
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<TableRow>
<StyledTableCell>Dessert (100g serving)</StyledTableCell>
<StyledTableCell align="right">Calories</StyledTableCell>
<StyledTableCell align="right">Fat (g)</StyledTableCell>
<StyledTableCell align="right">Carbs (g)</StyledTableCell>
<StyledTableCell align="right">Protein (g)</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row) => (
<StyledTableRow key={row.name}>
<StyledTableCell component="th" scope="row">
{row.name}
</StyledTableCell>
<StyledTableCell align="right">{row.calories}</StyledTableCell>
<StyledTableCell align="right">{row.fat}</StyledTableCell>
<StyledTableCell align="right">{row.carbs}</StyledTableCell>
<StyledTableCell align="right">{row.protein}</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer> | );
} | random_line_split | |
CustomizedTables.tsx | import * as React from 'react';
import { styled } from '@mui/material/styles';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: theme.palette.common.black,
color: theme.palette.common.white,
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
},
}));
const StyledTableRow = styled(TableRow)(({ theme }) => ({
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
// hide last border
'&:last-child td, &:last-child th': {
border: 0,
},
}));
function | (
name: string,
calories: number,
fat: number,
carbs: number,
protein: number,
) {
return { name, calories, fat, carbs, protein };
}
const rows = [
createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
createData('Eclair', 262, 16.0, 24, 6.0),
createData('Cupcake', 305, 3.7, 67, 4.3),
createData('Gingerbread', 356, 16.0, 49, 3.9),
];
export default function CustomizedTables() {
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<TableRow>
<StyledTableCell>Dessert (100g serving)</StyledTableCell>
<StyledTableCell align="right">Calories</StyledTableCell>
<StyledTableCell align="right">Fat (g)</StyledTableCell>
<StyledTableCell align="right">Carbs (g)</StyledTableCell>
<StyledTableCell align="right">Protein (g)</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row) => (
<StyledTableRow key={row.name}>
<StyledTableCell component="th" scope="row">
{row.name}
</StyledTableCell>
<StyledTableCell align="right">{row.calories}</StyledTableCell>
<StyledTableCell align="right">{row.fat}</StyledTableCell>
<StyledTableCell align="right">{row.carbs}</StyledTableCell>
<StyledTableCell align="right">{row.protein}</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
| createData | identifier_name |
CustomizedTables.tsx | import * as React from 'react';
import { styled } from '@mui/material/styles';
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell, { tableCellClasses } from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableHead from '@mui/material/TableHead';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
const StyledTableCell = styled(TableCell)(({ theme }) => ({
[`&.${tableCellClasses.head}`]: {
backgroundColor: theme.palette.common.black,
color: theme.palette.common.white,
},
[`&.${tableCellClasses.body}`]: {
fontSize: 14,
},
}));
const StyledTableRow = styled(TableRow)(({ theme }) => ({
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.action.hover,
},
// hide last border
'&:last-child td, &:last-child th': {
border: 0,
},
}));
function createData(
name: string,
calories: number,
fat: number,
carbs: number,
protein: number,
) |
const rows = [
createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
createData('Eclair', 262, 16.0, 24, 6.0),
createData('Cupcake', 305, 3.7, 67, 4.3),
createData('Gingerbread', 356, 16.0, 49, 3.9),
];
export default function CustomizedTables() {
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 700 }} aria-label="customized table">
<TableHead>
<TableRow>
<StyledTableCell>Dessert (100g serving)</StyledTableCell>
<StyledTableCell align="right">Calories</StyledTableCell>
<StyledTableCell align="right">Fat (g)</StyledTableCell>
<StyledTableCell align="right">Carbs (g)</StyledTableCell>
<StyledTableCell align="right">Protein (g)</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row) => (
<StyledTableRow key={row.name}>
<StyledTableCell component="th" scope="row">
{row.name}
</StyledTableCell>
<StyledTableCell align="right">{row.calories}</StyledTableCell>
<StyledTableCell align="right">{row.fat}</StyledTableCell>
<StyledTableCell align="right">{row.carbs}</StyledTableCell>
<StyledTableCell align="right">{row.protein}</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}
| {
return { name, calories, fat, carbs, protein };
} | identifier_body |
gulpfile.js | // ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename =require('gulp-rename');
var svgstore =require('gulp-svgstore');
var svgmin =require('gulp-svgmin');
var inject =require('gulp-inject');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
//maps: false,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
// .pipe(function() {
// return gulpif('*.less', less());
// })
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
//SVG fonts inject
gulp.task('svgicons', function () {
var svgs = gulp
.src('assets/icons/*.svg')
.pipe(rename({prefix: 'icon-'}))
.pipe(svgmin())
.pipe(svgstore({ inlineSvg: true }));
function fileContents (filePath, file) |
return gulp
.src('templates/svg-icons.php')
.pipe(inject(svgs, { transform: fileContents }))
.pipe(gulp.dest('templates'));
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
notify: {
styles: {
top: 'auto',
bottom: '0',
right: 'auto',
left: '0',
margin: '0px',
padding: '5px',
position: 'fixed',
fontSize: '10px',
zIndex: '9999',
borderRadius: '0px 5px 0px',
color: 'white',
textAlign: 'center',
display: 'block',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
}
},
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch([path.source + 'icons/**/*.svg'], ['svgicons']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images', 'svgicons'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
| {
return file.contents.toString();
} | identifier_body |
gulpfile.js | // ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var merge = require('merge-stream');
var cssNano = require('gulp-cssnano');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename =require('gulp-rename');
var svgstore =require('gulp-svgstore');
var svgmin =require('gulp-svgmin');
var inject =require('gulp-inject');
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
//maps: false,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
// .pipe(function() {
// return gulpif('*.less', less());
// })
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12'
]
})
.pipe(cssNano, {
safe: true
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: '/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
//SVG fonts inject
gulp.task('svgicons', function () {
var svgs = gulp
.src('assets/icons/*.svg')
.pipe(rename({prefix: 'icon-'}))
.pipe(svgmin())
.pipe(svgstore({ inlineSvg: true }));
function | (filePath, file) {
return file.contents.toString();
}
return gulp
.src('templates/svg-icons.php')
.pipe(inject(svgs, { transform: fileContents }))
.pipe(gulp.dest('templates'));
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates}/**/*.php', '*.php'],
proxy: config.devUrl,
notify: {
styles: {
top: 'auto',
bottom: '0',
right: 'auto',
left: '0',
margin: '0px',
padding: '5px',
position: 'fixed',
fontSize: '10px',
zIndex: '9999',
borderRadius: '0px 5px 0px',
color: 'white',
textAlign: 'center',
display: 'block',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
}
},
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch([path.source + 'icons/**/*.svg'], ['svgicons']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
runSequence('styles',
'scripts',
['fonts', 'images', 'svgicons'],
callback);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean'], function() {
gulp.start('build');
});
| fileContents | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.