file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
snack-bar.d.ts | import { ComponentType, Overlay, LiveAnnouncer } from '../core';
import { MdSnackBarConfig } from './snack-bar-config';
import { MdSnackBarRef } from './snack-bar-ref';
import { SimpleSnackBar } from './simple-snack-bar';
/**
* Service to dispatch Material Design snack bar messages.
*/
export declare class | {
private _overlay;
private _live;
private _parentSnackBar;
/**
* Reference to the current snack bar in the view *at this level* (in the Angular injector tree).
* If there is a parent snack-bar service, all operations should delegate to that parent
* via `_openedSnackBarRef`.
*/
... | MdSnackBar | identifier_name |
snack-bar.d.ts | import { ComponentType, Overlay, LiveAnnouncer } from '../core'; | */
export declare class MdSnackBar {
private _overlay;
private _live;
private _parentSnackBar;
/**
* Reference to the current snack bar in the view *at this level* (in the Angular injector tree).
* If there is a parent snack-bar service, all operations should delegate to that parent
* vi... | import { MdSnackBarConfig } from './snack-bar-config';
import { MdSnackBarRef } from './snack-bar-ref';
import { SimpleSnackBar } from './simple-snack-bar';
/**
* Service to dispatch Material Design snack bar messages. | random_line_split |
derive_object.rs | use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn build_derive_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::R... | }
if !attrs.is_internal && name.starts_with("__") {
error.no_double_underscore(if let Some(name) = attrs.name {
name.span_ident()
} else {
ident.span()
});
}
if fields.is_empty() {
error.not_empty(ast_span);
}
// Early abort after GraphQ... |
if let Some(duplicates) =
crate::util::duplicate::Duplicate::find_by_key(&fields, |field| field.name.as_str())
{
error.duplicate(duplicates.iter()); | random_line_split |
derive_object.rs | use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn build_derive_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::R... |
let field_name = &field.ident.unwrap();
let name = field_attrs
.name
.clone()
.map(SpanContainer::into_inner)
.unwrap_or_else(|| {
attrs
.rename
.unwrap_or(Rename... | {
return None;
} | conditional_block |
derive_object.rs | use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn | (ast: syn::DeriveInput, error: GraphQLScope) -> syn::Result<TokenStream> {
let ast_span = ast.span();
let struct_fields = match ast.data {
Data::Struct(data) => match data.fields {
Fields::Named(fields) => fields.named,
_ => return Err(error.custom_error(ast_span, "only named fie... | build_derive_object | identifier_name |
derive_object.rs | use crate::{
result::{GraphQLScope, UnsupportedAttribute},
util::{self, span_container::SpanContainer, RenameRule},
};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{self, ext::IdentExt, spanned::Spanned, Data, Fields};
pub fn build_derive_object(ast: syn::DeriveInput, error: GraphQLScope) -> syn::R... | let fields = struct_fields
.into_iter()
.filter_map(|field| {
let span = field.span();
let field_attrs = match util::FieldAttributes::from_attrs(
&field.attrs,
util::FieldAttributeParseMode::Object,
) {
Ok(attrs) => ... | {
let ast_span = ast.span();
let struct_fields = match ast.data {
Data::Struct(data) => match data.fields {
Fields::Named(fields) => fields.named,
_ => return Err(error.custom_error(ast_span, "only named fields are allowed")),
},
_ => return Err(error.custom_error... | identifier_body |
Query.js | import { Bullhorn } from './Bullhorn';
import { Deferred } from './Deferred';
import { QueryString } from './QueryString';
| export class Query {
constructor(endpoint) {
this.endpoint = endpoint;
this.records = [];
this._page = 0;
this.WHERE = 'where';
this.ORDER = 'orderBy';
this.parameters = {
fields: ['id'],
start: 0,
count: 10
};
}
fields(...args) {
this.parameters.fields =... | random_line_split | |
Query.js | import { Bullhorn } from './Bullhorn';
import { Deferred } from './Deferred';
import { QueryString } from './QueryString';
export class Query {
constructor(endpoint) {
this.endpoint = endpoint;
this.records = [];
this._page = 0;
this.WHERE = 'where';
this.ORDER = 'orderBy';
... | (add) {
let interceptor = new Deferred();
let request;
//BH-15325: Akamai has a query string limit.
let too_long = new QueryString('', this.parameters).toString().length > 8000;
if ( too_long ) {
request = Bullhorn.http().post(this.endpoint, this.parameters)
} else {
request = Bullhorn.http()... | run | identifier_name |
in-memory-data.service.ts | import { InMemoryDbService } from 'angular2-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() |
}
| {
let heroes = [
{id: 11, name: 'Mr. Nice',stock:5,price:560,image:"/assets/img/smile.png",featured:false,quantity:5},
{id: 12, name: 'Narco',stock:5,price:560,image:" /assets/img/smile.png",featured:false,quantity:5},
{id: 13, name: 'Bombasto',stock:5,price:560,image:" /assets/img/smile.png",feat... | identifier_body |
in-memory-data.service.ts | import { InMemoryDbService } from 'angular2-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
let heroes = [
{id: 11, name: 'Mr. Nice',stock:5,price:560,image:"/assets/img/smile.png",featured:false,quantity:5}, | {id: 12, name: 'Narco',stock:5,price:560,image:" /assets/img/smile.png",featured:false,quantity:5},
{id: 13, name: 'Bombasto',stock:5,price:560,image:" /assets/img/smile.png",featured:true,quantity:5},
{id: 14, name: 'Celeritas',stock:5,price:560,image:" /assets/img/smile.png",featured:false,quantity:... | random_line_split | |
in-memory-data.service.ts | import { InMemoryDbService } from 'angular2-in-memory-web-api';
export class | implements InMemoryDbService {
createDb() {
let heroes = [
{id: 11, name: 'Mr. Nice',stock:5,price:560,image:"/assets/img/smile.png",featured:false,quantity:5},
{id: 12, name: 'Narco',stock:5,price:560,image:" /assets/img/smile.png",featured:false,quantity:5},
{id: 13, name: 'Bombasto',stock:5,... | InMemoryDataService | identifier_name |
rscope.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 ... | _: Span,
count: uint)
-> Result<~[ty::Region], ()> {
let idx = *self.anon_bindings;
*self.anon_bindings += count;
Ok(vec::from_fn(count, |i| ty::ReLateBound(self.binder_id,
ty::BrAnon(i... | }
impl RegionScope for BindingRscope {
fn anon_regions(&self, | random_line_split |
rscope.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 ... | {
assert!(defs.iter().all(|def| def.def_id.crate == ast::LOCAL_CRATE));
defs.iter().enumerate().map(
|(i, def)| ty::ReEarlyBound(def.def_id.node, i, def.ident)).collect()
} | identifier_body | |
rscope.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 ... | ;
impl RegionScope for ExplicitRscope {
fn anon_regions(&self,
_span: Span,
_count: uint)
-> Result<~[ty::Region], ()> {
Err(())
}
}
/// A scope in which we generate anonymous, late-bound regions for
/// omitted regions. This occurs in functi... | ExplicitRscope | identifier_name |
vk_parser.py | import vk
import json
from sentiment_classifiers import SentimentClassifier, binary_dict, files
class VkFeatureProvider(object):
def | (self):
self._vk_api = vk.API(vk.Session())
self._vk_delay = 0.3
self._clf = SentimentClassifier(files['binary_goods'], binary_dict)
def _vk_grace(self):
import time
time.sleep(self._vk_delay)
def get_news(self, sources, amount=10):
# entry for Alex Anlysis tool... | __init__ | identifier_name |
vk_parser.py | import vk
import json
from sentiment_classifiers import SentimentClassifier, binary_dict, files
class VkFeatureProvider(object):
def __init__(self):
self._vk_api = vk.API(vk.Session())
self._vk_delay = 0.3
self._clf = SentimentClassifier(files['binary_goods'], binary_dict)
def _vk_grac... |
def get_news(self, sources, amount=10):
# entry for Alex Anlysis tool
result = []
for source in sources:
try:
data = self._vk_api.wall.get(domain=source, count=amount, extended=1, fields='name')
self._vk_grace()
except:
... | import time
time.sleep(self._vk_delay) | identifier_body |
vk_parser.py | import vk
import json
from sentiment_classifiers import SentimentClassifier, binary_dict, files
class VkFeatureProvider(object):
def __init__(self):
self._vk_api = vk.API(vk.Session())
self._vk_delay = 0.3
self._clf = SentimentClassifier(files['binary_goods'], binary_dict)
def _vk_grac... | self._vk_grace()
except:
pass
for i, uid in enumerate(uid_list[1:]):
try:
tmp = set(self._vk_api.friends.get(user_id=uid))
self._vk_grace()
except:
continue
if result is not None:
... | random_line_split | |
vk_parser.py | import vk
import json
from sentiment_classifiers import SentimentClassifier, binary_dict, files
class VkFeatureProvider(object):
def __init__(self):
self._vk_api = vk.API(vk.Session())
self._vk_delay = 0.3
self._clf = SentimentClassifier(files['binary_goods'], binary_dict)
def _vk_grac... |
return result
if __name__ == '__main__':
provider = VkFeatureProvider()
res = provider.get_news(['scientific.american'], 5)
print(res)
| try:
friend = self._vk_api.users.get(user_id=friend_uid, fields='sex,personal', name_case='nom')
self._vk_grace()
except:
continue
result.append(friend) | conditional_block |
model-generator.js | 'use strict'
const modelHelper = require('./model-helper')
const authHelper = require('./auth-helper')
const fs = require('fs')
const path = require('path')
/**
* This module reads in all the model files and generates the corresponding mongoose models.
* @param mongoose
* @param logger
* @param config
* @returns... | return
}
for (const file of files) {
// EXPL: Import all the model schemas
const ext = path.extname(file)
if (ext === '.js') {
const modelName = path.basename(file, '.js')
const schema = require(modelPath + '/' + modelName)(mongoose)
// EXPL: A... | )
)
} else {
reject(err)
} | random_line_split |
model-generator.js | 'use strict'
const modelHelper = require('./model-helper')
const authHelper = require('./auth-helper')
const fs = require('fs')
const path = require('path')
/**
* This module reads in all the model files and generates the corresponding mongoose models.
* @param mongoose
* @param logger
* @param config
* @returns... |
for (const file of files) {
// EXPL: Import all the model schemas
const ext = path.extname(file)
if (ext === '.js') {
const modelName = path.basename(file, '.js')
const schema = require(modelPath + '/' + modelName)(mongoose)
// EXPL: Add text index if enabl... | {
if (err.message.includes('no such file')) {
Log.error(err)
reject(
new Error(
'The model directory provided is either empty or does not exist. ' +
"Try setting the 'modelPath' property of the config file."
)
)
} else {... | conditional_block |
event_mail.py | # pylint: disable=api-one-deprecated
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, tools
_INTERVALS = {
"hours": lambda interval: relativedelta(hours=interval),
"days": lambda interval: relativedelta(days=interval),
"weeks": lambda in... | (models.Model):
_inherit = "event.mail.registration"
@api.one
@api.depends(
"registration_id", "scheduler_id.interval_unit", "scheduler_id.interval_type"
)
def _compute_scheduled_date(self):
# keep for-block event though it's api.one now (it was api.multi but it didn't work -- sched... | EventMailRegistration | identifier_name |
event_mail.py | # pylint: disable=api-one-deprecated
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, tools
_INTERVALS = {
"hours": lambda interval: relativedelta(hours=interval),
"days": lambda interval: relativedelta(days=interval),
"weeks": lambda in... | )
).execute()
return True
class EventMailRegistration(models.Model):
_inherit = "event.mail.registration"
@api.one
@api.depends(
"registration_id", "scheduler_id.interval_unit", "scheduler_id.interval_type"
)
def _compute_scheduled_date(self):
... | for rself in self:
if rself.interval_type not in [
"transferring_started",
"transferring_finished",
]:
return super(EventMailScheduler, rself).execute()
if registration:
rself.write(
{
... | identifier_body |
event_mail.py | # pylint: disable=api-one-deprecated
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, tools
_INTERVALS = {
"hours": lambda interval: relativedelta(hours=interval),
"days": lambda interval: relativedelta(days=interval),
"weeks": lambda in... |
if rself.registration_id:
# date_open is not corresponded to its meaining,
# but keep because it's copy-pasted code
date_open_datetime = fields.datetime.now()
rself.scheduled_date = date_open_datetime + _INTERVALS[
rself.sc... | if rself.scheduler_id.interval_type not in [
"transferring_started",
"transferring_finished",
]:
return super(EventMailRegistration, rself)._compute_scheduled_date() | random_line_split |
event_mail.py | # pylint: disable=api-one-deprecated
from datetime import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models, tools
_INTERVALS = {
"hours": lambda interval: relativedelta(hours=interval),
"days": lambda interval: relativedelta(days=interval),
"weeks": lambda in... |
if rself.event_id.state not in ["confirm", "done"]:
rself.scheduled_date = False
else:
date, sign = rself.event_id.create_date, 1
rself.scheduled_date = datetime.strptime(
date, tools.DEFAULT_SERVER_DATETIME_FORMAT
... | return super(EventMailScheduler, rself)._compute_scheduled_date() | conditional_block |
lib.rs | //! EPUB library
//! lib to read and navigate throught an epub file contents
//!
//! # Examples
//!
//! ## Opening
//!
//! ```
//! use epub::doc::EpubDoc;
//! let doc = EpubDoc::new("test.epub");
//! assert!(doc.is_ok());
//! let doc = doc.unwrap();
//!
//! ```
//!
//! ## Getting doc metatada
//!
//! Metadata is a Hash... | //! doc.go_next();
//! assert_eq!("001.xhtml", doc.get_current_id().unwrap());
//! doc.go_prev();
//! assert_eq!("000.xhtml", doc.get_current_id().unwrap());
//!
//! doc.set_current_page(2);
//! assert_eq!("001.xhtml", doc.get_current_id().unwrap());
//! assert_eq!(2, doc.get_current_page());
//! assert!(doc.set_curren... | //!
//! doc.go_next();
//! assert_eq!("000.xhtml", doc.get_current_id().unwrap()); | random_line_split |
replace_fallback.rs | use std::io;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ogg::{OggTrackBuf};
use super::super::{RequestType, Request};
use ::proto::{self, Deserialize, Serialize};
/// Skips to the end of the currently playing track
#[derive(Clone)]
pub struct ReplaceFallbackRequest {
pub track: OggTrackBuf,
... | let track = match track {
Some(track) => track,
None => return Err(io::Error::new(io::ErrorKind::Other, "missing field: track")),
};
let track = try!(OggTrackBuf::new(track)
.map_err(|_| io::Error::new(io::ErrorKind::Other, "invalid ogg")));
Ok(Repla... | {
try!(proto::expect_type(buf, proto::TYPE_STRUCT));
let field_count = try!(buf.read_u32::<BigEndian>());
let mut track: Option<Vec<u8>> = None;
let mut metadata: Option<Vec<(String, String)>> = None;
for _ in 0..field_count {
let field_name: String = try!(Deseriali... | identifier_body |
replace_fallback.rs | use std::io;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ogg::{OggTrackBuf};
use super::super::{RequestType, Request};
use ::proto::{self, Deserialize, Serialize};
/// Skips to the end of the currently playing track
#[derive(Clone)]
pub struct ReplaceFallbackRequest {
pub track: OggTrackBuf,
... | type Value = ();
type Error = ReplaceFallbackError;
fn req_type(&self) -> RequestType {
RequestType::ReplaceFallback
}
}
pub type ReplaceFallbackResult = Result<(), ReplaceFallbackError>;
#[derive(Debug, Clone)]
pub enum ReplaceFallbackError {
InvalidTrack = 1,
BadSampleRate = 2,
... | }
}
impl Request for ReplaceFallbackRequest { | random_line_split |
replace_fallback.rs | use std::io;
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use ogg::{OggTrackBuf};
use super::super::{RequestType, Request};
use ::proto::{self, Deserialize, Serialize};
/// Skips to the end of the currently playing track
#[derive(Clone)]
pub struct ReplaceFallbackRequest {
pub track: OggTrackBuf,
... | (&self, buf: &mut io::Cursor<Vec<u8>>) -> io::Result<()> {
try!(buf.write_u16::<BigEndian>(proto::TYPE_STRUCT));
let length = if self.metadata.is_some() { 2 } else { 1 };
try!(buf.write_u32::<BigEndian>(length));
try!(Serialize::write("track", buf));
try!(Serialize::write(self.... | write | identifier_name |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Computed angles.
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::... | #[inline]
pub fn radians(&self) -> CSSFloat {
self.radians64().min(f32::MAX as f64).max(f32::MIN as f64) as f32
}
/// Returns the amount of radians this angle represents as a `f64`.
///
/// Gecko stores angles as singles, but does this computation using doubles.
///
/// This is ... | }
/// Returns the amount of radians this angle represents. | random_line_split |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Computed angles.
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::... | (&self, other: &Self) -> Result<SquaredDistance, ()> {
// Use the formula for calculating the distance between angles defined in SVG:
// https://www.w3.org/TR/SVG/animate.html#complexDistances
self.radians64()
.compute_squared_distance(&other.radians64())
}
}
| compute_squared_distance | identifier_name |
angle.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Computed angles.
use crate::values::distance::{ComputeSquaredDistance, SquaredDistance};
use crate::values::... |
}
const RAD_PER_DEG: f64 = PI / 180.0;
impl Angle {
/// Creates a computed `Angle` value from a radian amount.
pub fn from_radians(radians: CSSFloat) -> Self {
Angle(radians / RAD_PER_DEG as f32)
}
/// Creates a computed `Angle` value from a degrees amount.
#[inline]
pub fn from_degr... | {
self.degrees().to_css(dest)?;
dest.write_str("deg")
} | identifier_body |
test4_grunt_spec.js | ,cwd = process.cwd()
describe("test 4 - check css is valid", function() {
var originalTimeout;
beforeEach(function() {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 4000;
});
afterEach(function() {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
});
/*... | 'use strict';
var _ = require("lodash-node")
,parserlib = require("parserlib") // for linting CSS
,fse = require("fs-extra") | random_line_split | |
test4_grunt_spec.js | 'use strict';
var _ = require("lodash-node")
,parserlib = require("parserlib") // for linting CSS
,fse = require("fs-extra")
,cwd = process.cwd()
describe("test 4 - check css is valid", function() {
var originalTimeout;
beforeEach(function() {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.... | ( done, returnedStr ) {
// Now we lint the CSS
var parser = new parserlib.css.Parser();
// will get changed to true in error handler if errors detected
var errorsFound = false;
parser.addListener("error", function(event){
console.log("Parse error: " + event.message + " (" + event.line + "," + event.col + ")... | lintCSS | identifier_name |
test4_grunt_spec.js | 'use strict';
var _ = require("lodash-node")
,parserlib = require("parserlib") // for linting CSS
,fse = require("fs-extra")
,cwd = process.cwd()
describe("test 4 - check css is valid", function() {
var originalTimeout;
beforeEach(function() {
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.... |
parser.parse( returnedStr );
}
| {
// Now we lint the CSS
var parser = new parserlib.css.Parser();
// will get changed to true in error handler if errors detected
var errorsFound = false;
parser.addListener("error", function(event){
console.log("Parse error: " + event.message + " (" + event.line + "," + event.col + ")", "error");
erro... | identifier_body |
jqLite.js | (childNodes[i]);
}
while (element.firstChild) {
element.removeChild(element.firstChild);
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false... |
// Remove monkey-patched methods (IE), | random_line_split | |
jqLite.js | ([\w:]+)/;
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
var wrapMap = {
'option': [1, '<select multiple="multiple">', '</select>'],
'thead': [1, '<table>', '</table>'],
'col': [2, '<table><colgroup>', '</colgroup></table>'],
'tr': [2, '<table><tbody>', '</t... | {
if (fired) return;
fired = true;
fn();
} | identifier_body | |
jqLite.js | Elems && param ? [this.filter(param)] : [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children;
if (!getterIfNoArguments || param != null) {
while(list.length) {
set = list.shift();
for(setIndex = 0, setLength = set.lengt... | (element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element){
jqLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
jqLiteDealoc(children[i]);
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw... | jqLiteClone | identifier_name |
multilevel-path-1.rs | // edition:2021
#![feature(rustc_attrs)]
#![allow(unused)]
struct Point {
x: i32,
y: i32,
}
struct Wrapper {
p: Point,
}
fn main() {
let mut w = Wrapper { p: Point { x: 10, y: 10 } };
// Only paths that appears within the closure that directly start off
// a variable defined outside the clos... |
*py = 20
} | random_line_split | |
multilevel-path-1.rs | // edition:2021
#![feature(rustc_attrs)]
#![allow(unused)]
struct Point {
x: i32,
y: i32,
}
struct Wrapper {
p: Point,
}
fn | () {
let mut w = Wrapper { p: Point { x: 10, y: 10 } };
// Only paths that appears within the closure that directly start off
// a variable defined outside the closure are captured.
//
// Therefore `w.p` is captured
// Note that `wp.x` doesn't start off a variable defined outside the closure.
... | main | identifier_name |
recipress.admin.js | jQuery(function($) {
var hasRecipe = $( '#hasRecipe' );
$(hasRecipe).change(function(){
$( '#recipress_table' ).slideToggle( 'slow' );
});
if($(hasRecipe).is( ':checked' ) ) $( '#recipress_table' ).show();
// the upload image button, saves the id and outputs a preview of the image
var imageFrame;
... |
// set our settings
imageFrame = wp.media({
title: 'Choose Image',
multiple: false,
library: {
type: 'image'
},
button: {
text: 'Use This Image'
}
});
// set up our select handler
imageFrame.on( 'select', function() {
selection = imageFrame.state().get('s... | {
imageFrame.open();
return;
} | conditional_block |
recipress.admin.js | jQuery(function($) {
var hasRecipe = $( '#hasRecipe' );
$(hasRecipe).change(function(){
$( '#recipress_table' ).slideToggle( 'slow' );
});
if($(hasRecipe).is( ':checked' ) ) $( '#recipress_table' ).show();
// the upload image button, saves the id and outputs a preview of the image
var imageFrame;
... | // put chosen back
clone.find('.chosen').chosen({
create_option: true,
persistent_create_option: true,
allow_single_deselect: true
});
//
return false;
});
$( '.ingredient_remove, .instruction_remove' ).live('click', function() {
$(this).parentsUntil( '.tr' ).parent().remove();
re... | random_line_split | |
StaticData.ts | /* istanbul ignore file */
/* tslint:disable */
/* eslint-disable */
import type { AppSettings } from './AppSettings';
import type { DataSource } from './DataSource';
import type { Phrase } from './Phrase';
import type { State } from './State';
import type { Unit } from './Unit';
import type { Variable } from './Varia... | units: Array<Unit>;
variableCategories: Array<VariableCategory>;
stateNames: any;
success: boolean;
status: string;
code: number;
description?: any;
summary?: any;
errors: Array<any>;
sessionTokenObject?: any;
avatar?: any;
warnings?: any;
data?: any;
} | random_line_split | |
set2.rs | extern crate openssl;
extern crate serialize;
use serialize::base64::{FromBase64};
use std::rand::{task_rng, Rng};
use std::io::BufferedReader;
use std::io::File;
use openssl::crypto::symm::{encrypt, decrypt, AES_128_ECB, AES_128_CBC};
fn xor(v1 : &[u8], v2 : &[u8]) -> Vec<u8> {
v1.iter().zip(v2.iter()).map(|(&b... |
fn ch9() {
println!("------- 9 ---------");
let mut data = Vec::from_slice("YELLOW SUBMARINE".as_bytes());
pkcs7_pad(&mut data, 20);
println!("Padded data: {}", data);
println!("Padded message: {}", bytes_to_string(data.clone()));
assert!("YELLOW SUBMARINE\x04\x04\x04\x04".as_bytes() == data.a... | {
let key = gen_key();
let iv = gen_key();
let prepend_bytes = gen_random_size_vec(5, 10);
let append_bytes = gen_random_size_vec(5, 10);
let data = prepend_bytes + input + append_bytes;
let choices = [AES_128_ECB, AES_128_CBC];
let t = task_rng().choose(choices).unwrap();
println!("Used... | identifier_body |
set2.rs | extern crate openssl;
extern crate serialize;
use serialize::base64::{FromBase64};
use std::rand::{task_rng, Rng};
use std::io::BufferedReader;
use std::io::File;
use openssl::crypto::symm::{encrypt, decrypt, AES_128_ECB, AES_128_CBC};
fn xor(v1 : &[u8], v2 : &[u8]) -> Vec<u8> {
v1.iter().zip(v2.iter()).map(|(&b... | fn ch9() {
println!("------- 9 ---------");
let mut data = Vec::from_slice("YELLOW SUBMARINE".as_bytes());
pkcs7_pad(&mut data, 20);
println!("Padded data: {}", data);
println!("Padded message: {}", bytes_to_string(data.clone()));
assert!("YELLOW SUBMARINE\x04\x04\x04\x04".as_bytes() == data.as_... | println!("Used {}", (match *t { AES_128_ECB => "ECB", AES_128_CBC => "CBC", _ => "Unknown" }));
encrypt(*t, key.as_slice(), iv, data.as_slice())
}
| random_line_split |
set2.rs | extern crate openssl;
extern crate serialize;
use serialize::base64::{FromBase64};
use std::rand::{task_rng, Rng};
use std::io::BufferedReader;
use std::io::File;
use openssl::crypto::symm::{encrypt, decrypt, AES_128_ECB, AES_128_CBC};
fn xor(v1 : &[u8], v2 : &[u8]) -> Vec<u8> {
v1.iter().zip(v2.iter()).map(|(&b... | () {
println!("------- 9 ---------");
let mut data = Vec::from_slice("YELLOW SUBMARINE".as_bytes());
pkcs7_pad(&mut data, 20);
println!("Padded data: {}", data);
println!("Padded message: {}", bytes_to_string(data.clone()));
assert!("YELLOW SUBMARINE\x04\x04\x04\x04".as_bytes() == data.as_slice(... | ch9 | identifier_name |
lexical-scope-with-macro.rs | // Copyright 2013-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-MI... | () {
let a = trivial!(10);
let b = no_new_scope!(33);
zzz();
sentinel();
new_scope!();
zzz();
sentinel();
shadow_within_macro!(100);
zzz();
sentinel();
let c = dup_expr!(10 * 20);
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()}
| main | identifier_name |
lexical-scope-with-macro.rs | // Copyright 2013-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-MI... |
fn sentinel() {()}
| {()} | identifier_body |
lexical-scope-with-macro.rs | // Copyright 2013-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-MI... | zzz();
sentinel();
new_scope!();
zzz();
sentinel();
shadow_within_macro!(100);
zzz();
sentinel();
let c = dup_expr!(10 * 20);
zzz();
sentinel();
}
fn zzz() {()}
fn sentinel() {()} | random_line_split | |
util.ts | import {provide, Provider, Component} from 'angular2/core';
import {Type, isBlank} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {
ComponentFixture,
AsyncTestCompleter,
TestComponentBuilder,
beforeEach,
ddescribe,
xdescribe,
describe,
el,
inject... | (str: string): string {
return str[0].toUpperCase() + str.substring(1);
}
| title | identifier_name |
util.ts | import {provide, Provider, Component} from 'angular2/core';
import {Type, isBlank} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {
ComponentFixture,
AsyncTestCompleter,
TestComponentBuilder,
beforeEach,
ddescribe,
xdescribe,
describe,
el,
inject... | })
export class RootCmp {
name: string;
activatedCmp: any;
}
export function compile(tcb: TestComponentBuilder,
template: string = "<router-outlet></router-outlet>") {
return tcb.overrideTemplate(RootCmp, ('<div>' + template + '</div>')).createAsync(RootCmp);
}
export var TEST_ROUTER_PRO... | directives: [ROUTER_DIRECTIVES] | random_line_split |
util.ts | import {provide, Provider, Component} from 'angular2/core';
import {Type, isBlank} from 'angular2/src/facade/lang';
import {BaseException} from 'angular2/src/facade/exceptions';
import {
ComponentFixture,
AsyncTestCompleter,
TestComponentBuilder,
beforeEach,
ddescribe,
xdescribe,
describe,
el,
inject... |
specNameBuilder.pop();
}
export function ddescribeRouter(description: string, fn: Function, exclusive = false): void {
describeRouter(description, fn, true);
}
export function describeWithAndWithout(description: string, fn: Function): void {
// the "without" case is usually simpler, so we opt to run this spec ... | {
describe(description, fn);
} | conditional_block |
anti-abuse-client.js | /* jshint browser: true */
/* global $ */
"use strict";
var formField = require("../ui/utils/form-field.js");
module.exports = function(core, config, store) {
function addBanMenu(from, menu, next) {
var room = store.get("nav", "room"),
rel = store.getRelation(),
senderRelation = store.getRelation(room, fr... |
$div = $("<div>").append(
formField("Spam control", "toggle", "spam-control", antiAbuse.spam),
formField("Blocked words list", "check", "blocklists", [
["list-en-strict", "English abusive words", antiAbuse.block.english]
]),
formField("Custom blocked phrases/word", "area", "block-custom", antiAbuse.... | {
antiAbuse.spam = true;
} | conditional_block |
anti-abuse-client.js | /* jshint browser: true */
/* global $ */
"use strict";
var formField = require("../ui/utils/form-field.js");
module.exports = function(core, config, store) {
function addBanMenu(from, menu, next) {
var room = store.get("nav", "room"),
rel = store.getRelation(),
senderRelation = store.getRelation(room, fr... | ]),
formField("Custom blocked phrases/word", "area", "block-custom", antiAbuse.customPhrases.join("\n")),
formField("", "info", "spam-control-helper-text", "One phrase/word each line")
);
tabs.spam = {
text: "Spam control",
html: $div
};
next();
}, 600);
core.on("conf-save", function(room, n... | $div = $("<div>").append(
formField("Spam control", "toggle", "spam-control", antiAbuse.spam),
formField("Blocked words list", "check", "blocklists", [
["list-en-strict", "English abusive words", antiAbuse.block.english] | random_line_split |
anti-abuse-client.js | /* jshint browser: true */
/* global $ */
"use strict";
var formField = require("../ui/utils/form-field.js");
module.exports = function(core, config, store) {
function | (from, menu, next) {
var room = store.get("nav", "room"),
rel = store.getRelation(),
senderRelation = store.getRelation(room, from),
senderRole, senderTransitionRole;
senderRelation = senderRelation ? senderRelation : {};
senderRole = senderRelation.role ? senderRelation.role : "none";
senderTransitio... | addBanMenu | identifier_name |
anti-abuse-client.js | /* jshint browser: true */
/* global $ */
"use strict";
var formField = require("../ui/utils/form-field.js");
module.exports = function(core, config, store) {
function addBanMenu(from, menu, next) | text: "Ban user",
action: function() {
core.emit("expel-up", {
to: room,
ref: from,
role: "banned",
transitionRole: senderRole,
transitionType: null
});
}
};
break;
case "banned":
menu.items.unbanuser = {
prio: 550,
text: "unban user... | {
var room = store.get("nav", "room"),
rel = store.getRelation(),
senderRelation = store.getRelation(room, from),
senderRole, senderTransitionRole;
senderRelation = senderRelation ? senderRelation : {};
senderRole = senderRelation.role ? senderRelation.role : "none";
senderTransitionRole = senderRelat... | identifier_body |
std_dirs.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | create_dir(
client,
access_container,
btree_map![
authenticator_key => MDataSeqValue { version: 0, data: access_cont_value }
],
btree_map![],
)
.map_err(From::from)
.into_box()
}
/// Generates a list of `MDataInfo` for standard dirs.
/// Returns a col... | None,
));
| random_line_split |
std_dirs.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | .into_iter()
.map(|(name, md_info)| (String::from(name), md_info))
.collect();
let std_dirs_fut = create_std_dirs(&c3, &access_cont_value);
let access_cont_fut =
create_access_containe... | {
let c2 = client.clone();
let c3 = client.clone();
let c4 = client.clone();
// Initialise standard directories
let access_container = client.access_container();
let config_dir = client.config_root_dir();
// Try to get default dirs from the access container
let access_cont_fut = access... | identifier_body |
std_dirs.rs | // Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTI... | (client: &AuthClient) -> Box<AuthFuture<()>> {
let c2 = client.clone();
let c3 = client.clone();
let c4 = client.clone();
// Initialise standard directories
let access_container = client.access_container();
let config_dir = client.config_root_dir();
// Try to get default dirs from the acce... | create | identifier_name |
asm.py | # coding=utf8
"""
asm.py - (dis)assembly features.
(c) 2014 Samuel Groß
"""
from willie import web
from willie.module import commands, nickname_commands, example
from random import choice
from binascii import hexlify, unhexlify
import string
import re
import os
from subprocess import Popen, PIPE
@commands('disas', ... |
result = Popen(['ndisasm', '-b', str(bits), '-o', '0x1000', filename], stdout=PIPE).stdout.read()
os.remove(filename)
for line in result.split('\n'):
bot.say(line)
@commands('as', 'as64', 'assemble', 'assemble64')
@example('.as push ebp; mov ebp, esp; jmp 0x14')
def assemble(bot, trigger):
"... | ""Disassemble x86 machine code."""
if not trigger.group(2):
return bot.reply('Nothing to disassemble')
try:
arg = trigger.group(2)
# remove all 0x
while "0x" in arg:
arg = arg.replace("0x","")
# remove everything except hex
arg = re.sub(r"[^a-fA-F0-9]"... | identifier_body |
asm.py | # coding=utf8
"""
asm.py - (dis)assembly features.
(c) 2014 Samuel Groß
"""
from willie import web
from willie.module import commands, nickname_commands, example
from random import choice
from binascii import hexlify, unhexlify
import string
import re
import os
from subprocess import Popen, PIPE
@commands('disas', ... | # remove everything except hex
arg = re.sub(r"[^a-fA-F0-9]", r"", arg)
code = unhexlify(arg)
except Exception:
return bot.say('Invalid hex sequence')
bits = 64 if '64' in trigger.group(1) else 32
filename = '/tmp/' + ''.join( choice(string.ascii_lowercase) for i in range(10... | rg = arg.replace("0x","")
| conditional_block |
asm.py | # coding=utf8
"""
asm.py - (dis)assembly features.
(c) 2014 Samuel Groß
"""
from willie import web
from willie.module import commands, nickname_commands, example
from random import choice
from binascii import hexlify, unhexlify
import string
import re
import os
from subprocess import Popen, PIPE
@commands('disas', ... | bot, instr):
"""Display information about any x86 instruction thats no a conditional jump."""
raw = web.get('http://www.felixcloutier.com/x86/')
match = re.search('<tr><td><a href="./(?P<page>[A-Z:]*).html">%s</a></td><td>(?P<desc>[^<]*)</td></tr>' % instr, raw)
if not match:
return bot.say('I... | 86instr( | identifier_name |
asm.py | # coding=utf8
"""
asm.py - (dis)assembly features.
(c) 2014 Samuel Groß
"""
from willie import web
from willie.module import commands, nickname_commands, example
from random import choice
from binascii import hexlify, unhexlify
import string
import re
import os
from subprocess import Popen, PIPE
@commands('disas', ... |
@commands('x86', 'instr', 'instruction')
def instruction(bot, trigger):
"""Display information about an x86 instruction."""
instr = trigger.group(2)
if not instr:
return bot.reply('Give me an instruction')
instr = instr.strip().upper()
if 'J' == instr[0] and not instr == 'JMP':
ret... | return bot.say('I can\'t find anything about that instruction, sorry')
bot.say('%s : %s -- %s' % (instr, match.group('desc'), 'http://www.felixcloutier.com/x86/%s' % match.group('page'))) | random_line_split |
shared_cache.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... | use bit_set::BitSet;
use super::super::instructions;
const INITIAL_CAPACITY: usize = 32;
const DEFAULT_CACHE_SIZE: usize = 4 * 1024 * 1024;
/// Global cache for EVM interpreter
pub struct SharedCache {
jump_destinations: Mutex<LruCache<H256, Arc<BitSet>>>,
max_size: usize,
cur_size: Mutex<usize>,
}
impl SharedCac... | random_line_split | |
shared_cache.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... | (max_size: usize) -> Self {
SharedCache {
jump_destinations: Mutex::new(LruCache::new(INITIAL_CAPACITY)),
max_size: max_size * 8, // dealing with bits here.
cur_size: Mutex::new(0),
}
}
/// Get jump destinations bitmap for a contract.
pub fn jump_destinations(&self, code_hash: &H256, code: &[u8]) -> Ar... | new | identifier_name |
shared_cache.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... |
/// Get jump destinations bitmap for a contract.
pub fn jump_destinations(&self, code_hash: &H256, code: &[u8]) -> Arc<BitSet> {
if code_hash == &SHA3_EMPTY {
return Self::find_jump_destinations(code);
}
if let Some(d) = self.jump_destinations.lock().get_mut(code_hash) {
return d.clone();
}
let d ... | {
SharedCache {
jump_destinations: Mutex::new(LruCache::new(INITIAL_CAPACITY)),
max_size: max_size * 8, // dealing with bits here.
cur_size: Mutex::new(0),
}
} | identifier_body |
shared_cache.rs | // Copyright 2015, 2016 Ethcore (UK) Ltd.
// This file is part of Parity.
// Parity 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.... |
if let Some(d) = self.jump_destinations.lock().get_mut(code_hash) {
return d.clone();
}
let d = Self::find_jump_destinations(code);
{
let mut cur_size = self.cur_size.lock();
*cur_size += d.capacity();
let mut jump_dests = self.jump_destinations.lock();
let cap = jump_dests.capacity();
/... | {
return Self::find_jump_destinations(code);
} | conditional_block |
Modules.py | from builtins import object
from PyAnalysisTools.base import _logger
from PyAnalysisTools.base.YAMLHandle import YAMLLoader
from PyAnalysisTools.AnalysisTools.FakeEstimator import MuonFakeEstimator # noqa: F401
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder # noqa: F401
from PyAnalysisTools.Ana... |
instance = mod_name(**mod_config)
modules.append(instance)
return modules
| if isinstance(val, str) and 'callee' in val:
mod_config[key] = eval(val) | conditional_block |
Modules.py | from builtins import object
from PyAnalysisTools.base import _logger
from PyAnalysisTools.base.YAMLHandle import YAMLLoader
from PyAnalysisTools.AnalysisTools.FakeEstimator import MuonFakeEstimator # noqa: F401
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder # noqa: F401
from PyAnalysisTools.Ana... | :type callee: object
:return: list of initialised modules
:rtype: list
"""
modules = []
if not isinstance(config_files, list):
config_files = [config_files]
try:
for cfg_file in config_files:
if cfg_file is None:
continue
config = YAMLL... | """
Load all modules defined in configuration files
:param config_files: list of configuration file names
:type config_files: list
:param callee: instance of calling object | random_line_split |
Modules.py | from builtins import object
from PyAnalysisTools.base import _logger
from PyAnalysisTools.base.YAMLHandle import YAMLLoader
from PyAnalysisTools.AnalysisTools.FakeEstimator import MuonFakeEstimator # noqa: F401
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder # noqa: F401
from PyAnalysisTools.Ana... | (config_files, callee):
"""
Load all modules defined in configuration files
:param config_files: list of configuration file names
:type config_files: list
:param callee: instance of calling object
:type callee: object
:return: list of initialised modules
:rtype: list
"""
modules ... | load_modules | identifier_name |
Modules.py | from builtins import object
from PyAnalysisTools.base import _logger
from PyAnalysisTools.base.YAMLHandle import YAMLLoader
from PyAnalysisTools.AnalysisTools.FakeEstimator import MuonFakeEstimator # noqa: F401
from PyAnalysisTools.AnalysisTools.RegionBuilder import RegionBuilder # noqa: F401
from PyAnalysisTools.Ana... |
def load_modules(config_files, callee):
"""
Load all modules defined in configuration files
:param config_files: list of configuration file names
:type config_files: list
:param callee: instance of calling object
:type callee: object
:return: list of initialised modules
:rtype: list
... | pass | identifier_body |
comboboxes.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Customized combobox widgets"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
from PyQt4.QtGui impo... | if qstr is None:
qstr = self.currentText()
return osp.isdir( unicode(qstr) )
def selected(self):
"""Action to be executed when a valid item has been selected"""
EditableComboBox.selected(self)
self.emit(SIGNAL("open_dir(QString)"), self.currentText())
... | 'Enter a correct directory path,\n'
'then press enter to validate')}
def is_valid(self, qstr=None):
"""Return True if string is valid"""
| random_line_split |
comboboxes.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Customized combobox widgets"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
from PyQt4.QtGui impo... |
self.insertItem(0, text)
index = self.findText('')
if index != -1:
self.removeItem(index)
self.insertItem(0, '')
if text != '':
self.setCurrentIndex(1)
else:
self.setCurrentIndex(0)
else:
... | elf.removeItem(index)
index = self.findText(text)
| conditional_block |
comboboxes.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Customized combobox widgets"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
from PyQt4.QtGui impo... | QComboBox.focusOutEvent(self, event)
# --- own methods
def is_valid(self, qstr):
"""
Return True if string is valid
Return None if validation can't be done
"""
pass
def selected(self):
"""Action to be executed when a valid item has... | ""Editable combo box base class"""
def __init__(self, parent):
QComboBox.__init__(self, parent)
self.setEditable(True)
self.setCompleter(QCompleter(self))
# --- overrides
def keyPressEvent(self, event):
"""Handle key press events"""
if event.key() == Qt.Key_... | identifier_body |
comboboxes.py | # -*- coding: utf-8 -*-
#
# Copyright © 2009-2010 Pierre Raybaut
# Licensed under the terms of the MIT License
# (see spyderlib/__init__.py for details)
"""Customized combobox widgets"""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R0911
# pylint: disable=R0201
from PyQt4.QtGui impo... | PathComboBox):
"""
QComboBox handling Python modules or packages path
(i.e. .py, .pyw files *and* directories containing __init__.py)
"""
def __init__(self, parent, adjust_to_contents=False):
PathComboBox.__init__(self, parent, adjust_to_contents)
def is_valid(self, qstr... | ythonModulesComboBox( | identifier_name |
test_interp.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from pykit.parsing import cirparser
from pykit.ir import verify, interp
source = """
#include <pykit_ir.h>
Int32 myglobal = 10;
float simple(float x) {
return x * x;
}
Int32 loop() {
Int32 i, sum = 0;
... | unittest.main() | random_line_split | |
test_interp.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from pykit.parsing import cirparser
from pykit.ir import verify, interp
source = """
#include <pykit_ir.h>
Int32 myglobal = 10;
float simple(float x) {
return x * x;
}
Int32 loop() {
Int32 i, sum = 0;
... |
if __name__ == '__main__':
unittest.main() | assert False, result | conditional_block |
test_interp.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from pykit.parsing import cirparser
from pykit.ir import verify, interp
source = """
#include <pykit_ir.h>
Int32 myglobal = 10;
float simple(float x) {
return x * x;
}
Int32 loop() {
Int32 i, sum = 0;
... |
def test_loop(self):
loop = mod.get_function('loop')
result = interp.run(loop)
assert result == 45, result
def test_exceptions(self):
f = mod.get_function('raise')
try:
result = interp.run(f)
except interp.UncaughtException as e:
exc, = ... | f = mod.get_function('simple')
result = interp.run(f, args=[10.0])
assert result == 100.0, result | identifier_body |
test_interp.py | # -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import
import unittest
from pykit.parsing import cirparser
from pykit.ir import verify, interp
source = """
#include <pykit_ir.h>
Int32 myglobal = 10;
float simple(float x) {
return x * x;
}
Int32 loop() {
Int32 i, sum = 0;
... | (self):
f = mod.get_function('simple')
result = interp.run(f, args=[10.0])
assert result == 100.0, result
def test_loop(self):
loop = mod.get_function('loop')
result = interp.run(loop)
assert result == 45, result
def test_exceptions(self):
f = mod.get_fu... | test_simple | identifier_name |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use dependency_analyzer::{get_reachable_ast, ReachableAst};
use fixture_tests::Fixture; | pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> {
let parts: Vec<&str> = fixture.content.split("%definitions%").collect();
let source_location = SourceLocationKey::standalone(fixture.file_name);
let definitions = parse_executable(parts[0], source_location).unwrap();
let base_d... | use graphql_syntax::*;
| random_line_split |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use dependency_analyzer::{get_reachable_ast, ReachableAst};
use fixture_tests::Fixture;
use graphq... | (fixture: &Fixture<'_>) -> Result<String, String> {
let parts: Vec<&str> = fixture.content.split("%definitions%").collect();
let source_location = SourceLocationKey::standalone(fixture.file_name);
let definitions = parse_executable(parts[0], source_location).unwrap();
let base_definitions = parts
... | transform_fixture | identifier_name |
mod.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use common::SourceLocationKey;
use dependency_analyzer::{get_reachable_ast, ReachableAst};
use fixture_tests::Fixture;
use graphq... | texts.push("========== Base definitions ==========".to_string());
let mut defs = base_fragment_names
.iter()
.map(|key| key.lookup())
.collect::<Vec<_>>();
defs.sort_unstable();
texts.push(defs.join(", "));
Ok(texts.join("\n"))
}
| {
let parts: Vec<&str> = fixture.content.split("%definitions%").collect();
let source_location = SourceLocationKey::standalone(fixture.file_name);
let definitions = parse_executable(parts[0], source_location).unwrap();
let base_definitions = parts
.iter()
.skip(1)
.flat_map(|par... | identifier_body |
app.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# RedisPress.alpha
# ---
# Database: Redis
# Framework: Tornado
import sys
import raven.contrib.tornado
import tornado.httpserver
import tornado.ioloop
import project.app.application
if __name__ == '__main__':
if len(sys.argv) == 2:
port = sys.argv[1] | port = 24400
sentry_key = '56b95038ef7849d7bfbfc735d2ee50e1:64c853d4c58947b5a8b663ca7ac2c8b1'
app = project.app.application.Application()
app.sentry_client = raven.contrib.tornado.AsyncSentryClient(
'http://' + sentry_key + '@lin.eternalelf.com/sentry/7',
)
srv = tornado.httpserver.... | else: | random_line_split |
app.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# RedisPress.alpha
# ---
# Database: Redis
# Framework: Tornado
import sys
import raven.contrib.tornado
import tornado.httpserver
import tornado.ioloop
import project.app.application
if __name__ == '__main__':
| if len(sys.argv) == 2:
port = sys.argv[1]
else:
port = 24400
sentry_key = '56b95038ef7849d7bfbfc735d2ee50e1:64c853d4c58947b5a8b663ca7ac2c8b1'
app = project.app.application.Application()
app.sentry_client = raven.contrib.tornado.AsyncSentryClient(
'http://' + sentry_key + '@lin.e... | conditional_block | |
video-iframe-integration.js | (`[${TAG}] ${args.join(' ')} ${DOCS_URL}`);
}
return shouldBeTrueish;
}
const validMethods = [
'pause',
'play',
'mute',
'unmute',
'fullscreenenter',
'fullscreenexit',
'showcontrols',
'hidecontrols',
];
/**
* @param {function()} win
* @param {*} opt_initializer
* @return {function()}
* @visible... | /**
* Used for checking callback return type.
* @visibleForTesting
*/
this.isAmpVideoIntegration_ = true;
/** @private @const */
this.callCounter_ = 0;
/** @private @const {!Object<number, function()>} */
this.callbacks_ = {};
/** @private @const {!Window} */
this.win_ ... |
/** @visibleForTesting */
export class AmpVideoIntegration {
/** @param {!Window} win */
constructor(win) { | random_line_split |
video-iframe-integration.js | (`[${TAG}] ${args.join(' ')} ${DOCS_URL}`);
}
return shouldBeTrueish;
}
const validMethods = [
'pause',
'play',
'mute',
'unmute',
'fullscreenenter',
'fullscreenexit',
'showcontrols',
'hidecontrols',
];
/**
* @param {function()} win
* @param {*} opt_initializer
* @return {function()}
* @visible... | (name, callback) {
userAssert(validMethods.indexOf(name) > -1, `Invalid method ${name}.`);
const wrappedCallback =
name == 'play' || name == 'pause'
? this.safePlayOrPause_(callback)
: callback;
this.methods_[name] = wrappedCallback;
this.listenToOnce_();
}
/**
* @param {... | method | identifier_name |
video-iframe-integration.js | @visibleForTesting
*/
export function getVideoJs(win, opt_initializer) {
return userAssert(
opt_initializer || /** @type {function()} */ (win.videojs),
'Video.JS not imported or initializer undefined.'
);
}
/** @visibleForTesting */
export class AmpVideoIntegration {
/** @param {!Window} win */
const... | {
this.win_.parent./*OK*/ postMessage(completeData, '*');
} | conditional_block | |
video-iframe-integration.js | (`[${TAG}] ${args.join(' ')} ${DOCS_URL}`);
}
return shouldBeTrueish;
}
const validMethods = [
'pause',
'play',
'mute',
'unmute',
'fullscreenenter',
'fullscreenexit',
'showcontrols',
'hidecontrols',
];
/**
* @param {function()} win
* @param {*} opt_initializer
* @return {function()}
* @visible... | this.listenToOnce_ = once(() => {
listenTo(this.win_, (e) => this.onMessage_(e));
});
/** @private {boolean} */
this.muted_ = false;
/** @private {boolean} */
this.usedListenToHelper_ = false;
/**
* @return {!JsonObject}
* @private
*/
this.getMetadataOnce_ = once(... | {
/**
* Used for checking callback return type.
* @visibleForTesting
*/
this.isAmpVideoIntegration_ = true;
/** @private @const */
this.callCounter_ = 0;
/** @private @const {!Object<number, function()>} */
this.callbacks_ = {};
/** @private @const {!Window} */
this.win... | identifier_body |
test_python_driver.py | import io
import json
import os
import subprocess
import sys
import unittest
from os.path import join, abspath, dirname
sys.path.append('..')
from python_driver import __version__, get_processor_instance
from python_driver.requestprocessor import (
Request, Response, RequestProcessorJSON, InBuffer, EmptyCodeExcept... | res: List[Response] = []
res = [doc for doc in self._extract_docs(self.recvbuffer)]
return res
class Test10ProcessRequestFunc(TestPythonDriverBase):
def _add_to_buffer(self, count: int, format_: str) -> None:
"""Add count test msgs to the sendbuffer"""
for i in range(count... | random_line_split | |
test_python_driver.py | import io
import json
import os
import subprocess
import sys
import unittest
from os.path import join, abspath, dirname
sys.path.append('..')
from python_driver import __version__, get_processor_instance
from python_driver.requestprocessor import (
Request, Response, RequestProcessorJSON, InBuffer, EmptyCodeExcept... |
# process request already tested with TestPythonDriverBase
def test_20_return_error(self) -> None:
self._restart_data('json')
processor = RequestProcessorJSON(self.recvbuffer)
processor.errors = ['test error']
processor._return_error('test.py', 'fatal')
res = self._loa... | self._restart_data('json')
processor = RequestProcessorJSON(self.recvbuffer)
processor._send_response(cast(Response, self.data))
res = self._loadResults('json')
self.assertEqual(len(res), 1)
self.assertDictEqual(self.data, res[0]) | identifier_body |
test_python_driver.py | import io
import json
import os
import subprocess
import sys
import unittest
from os.path import join, abspath, dirname
sys.path.append('..')
from python_driver import __version__, get_processor_instance
from python_driver.requestprocessor import (
Request, Response, RequestProcessorJSON, InBuffer, EmptyCodeExcept... |
def test_010_normal_json(self) -> None:
replies = self._send_receive(1, 'json')
self.assertEqual(len(replies), 1)
self._check_reply_dict(replies[0])
def test_020_normal_json_many(self) -> None:
replies = self._send_receive(100, 'json')
self.assertEqual(len(replies), 10... | assert key in item | conditional_block |
test_python_driver.py | import io
import json
import os
import subprocess
import sys
import unittest
from os.path import join, abspath, dirname
sys.path.append('..')
from python_driver import __version__, get_processor_instance
from python_driver.requestprocessor import (
Request, Response, RequestProcessorJSON, InBuffer, EmptyCodeExcept... | (self) -> None:
self._restart_data('json')
processor = RequestProcessorJSON(self.recvbuffer)
processor.errors = ['test error']
processor._return_error('test.py', 'fatal')
res = self._loadResults('json')
self.assertEqual(len(res), 1)
self.assertDictEqual(res[0] , {... | test_20_return_error | identifier_name |
index.ts | import type { FormatLong } from '../../../types'
import buildFormatLongFn from '../../../_lib/buildFormatLongFn/index'
const dateFormats = {
full: 'EEEE d MMMM y',
long: 'd MMMM y',
medium: 'd MMM y',
short: 'dd-MM-y',
}
const timeFormats = {
full: 'HH:mm:ss zzzz',
long: 'HH:mm:ss z',
medium: 'HH:mm:ss'... |
time: buildFormatLongFn({
formats: timeFormats,
defaultWidth: 'full',
}),
dateTime: buildFormatLongFn({
formats: dateTimeFormats,
defaultWidth: 'full',
}),
}
export default formatLong | const formatLong: FormatLong = {
date: buildFormatLongFn({
formats: dateFormats,
defaultWidth: 'full',
}), | random_line_split |
yaml_formatter.py | from yaml import load_all
try:
from yaml import CLoader as Loader
except ImportError:
print("Using pure python YAML loader, it may be slow.")
from yaml import Loader
from iengine import IDocumentFormatter
__author__ = 'reyoung'
class YAMLFormatter(IDocumentFormatter):
| def __init__(self, fn=None, content=None):
IDocumentFormatter.__init__(self)
if fn is not None:
with file(fn, "r") as f:
self.__content = load_all(f, Loader=Loader)
else:
self.__content = load_all(content, Loader=Loader)
def get_command_iterator(self,... | identifier_body | |
yaml_formatter.py | from yaml import load_all
try:
from yaml import CLoader as Loader
except ImportError:
print("Using pure python YAML loader, it may be slow.")
from yaml import Loader
from iengine import IDocumentFormatter
|
class YAMLFormatter(IDocumentFormatter):
def __init__(self, fn=None, content=None):
IDocumentFormatter.__init__(self)
if fn is not None:
with file(fn, "r") as f:
self.__content = load_all(f, Loader=Loader)
else:
self.__content = load_all(content, Loa... | __author__ = 'reyoung' | random_line_split |
yaml_formatter.py | from yaml import load_all
try:
from yaml import CLoader as Loader
except ImportError:
print("Using pure python YAML loader, it may be slow.")
from yaml import Loader
from iengine import IDocumentFormatter
__author__ = 'reyoung'
class YAMLFormatter(IDocumentFormatter):
def __init__(self, fn=None, con... |
else:
self.__content = load_all(content, Loader=Loader)
def get_command_iterator(self, *args, **kwargs):
for item in self.__content:
yield YAMLFormatter.__process_item(item)
@staticmethod
def __process_item(item):
if isinstance(item, dict) and len(item) == ... | with file(fn, "r") as f:
self.__content = load_all(f, Loader=Loader) | conditional_block |
yaml_formatter.py | from yaml import load_all
try:
from yaml import CLoader as Loader
except ImportError:
print("Using pure python YAML loader, it may be slow.")
from yaml import Loader
from iengine import IDocumentFormatter
__author__ = 'reyoung'
class YAMLFormatter(IDocumentFormatter):
def __init__(self, fn=None, con... | (item):
if isinstance(item, dict) and len(item) == 1:
key = item.iterkeys().__iter__().next()
value = item[key]
return key, value
| __process_item | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of st... | (&self) -> bool {
<Self as num_traits::Zero>::is_zero(self)
}
}
| is_zero | identifier_name |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of st... | /// Returns whether this value is zero.
fn is_zero(&self) -> bool;
}
impl<T> Zero for T
where
T: num_traits::Zero,
{
fn zero() -> Self {
<Self as num_traits::Zero>::zero()
}
fn is_zero(&self) -> bool {
<Self as num_traits::Zero>::is_zero(self)
}
} | /// implementing `Add`.
pub trait Zero {
/// Returns the zero value.
fn zero() -> Self;
| random_line_split |
lib.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
//! Calculate [specified][specified] and [computed values][computed] from a
//! tree of DOM nodes and a set of st... |
}
/// A trait pretty much similar to num_traits::Zero, but without the need of
/// implementing `Add`.
pub trait Zero {
/// Returns the zero value.
fn zero() -> Self;
/// Returns whether this value is zero.
fn is_zero(&self) -> bool;
}
impl<T> Zero for T
where
T: num_traits::Zero,
{
fn zero(... | {
match self {
selectors::attr::CaseSensitivity::CaseSensitive => a == b,
selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
}
} | identifier_body |
check_key_import.py | '''Manual check (not a discoverable unit test) for the key import,
to identify problems with gnupg, gpg, gpg1, gpg2 and so on'''
import os
import shutil
from gnupg import GPG
def setup_keyring(keyring_name):
'''Setup the keyring'''
keyring_path = os.path.join("test", "outputdata", keyring_name)
# Delet... |
return gpg
CRYPTO = setup_keyring("keyringtest")
if CRYPTO:
print("Ready", CRYPTO)
KEY_LIST = CRYPTO.list_keys(False)
NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0
print("Number of public keys:", NUM_KEYS)
if NUM_KEYS < 1:
print("ERROR: Number of keys should be 1, not", NUM_KEYS)
KEY_LIST = CRYPTO.list_keys... | print("Got one import result") | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.