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 |
|---|---|---|---|---|
recolor.rs | use {RendTri, Shape, Color}; | shape: S,
color: Color,
}
impl<S> Recolor<S> {
pub(crate) fn new(shape: S, color: Color) -> Self {
Recolor {
shape: shape,
color: color,
}
}
}
impl<S> IntoIterator for Recolor<S>
where
S: Shape,
{
type Item = RendTri;
type IntoIter = RecolorIter<S::I... |
/// `Recolor` represents a shape which has had its color set to a new one.
#[derive(Copy, Clone, Debug)]
pub struct Recolor<S> { | random_line_split |
recolor.rs | use {RendTri, Shape, Color};
/// `Recolor` represents a shape which has had its color set to a new one.
#[derive(Copy, Clone, Debug)]
pub struct | <S> {
shape: S,
color: Color,
}
impl<S> Recolor<S> {
pub(crate) fn new(shape: S, color: Color) -> Self {
Recolor {
shape: shape,
color: color,
}
}
}
impl<S> IntoIterator for Recolor<S>
where
S: Shape,
{
type Item = RendTri;
type IntoIter = RecolorIte... | Recolor | identifier_name |
test_command.py | import pytest
from cmdtree import INT, entry
from cmdtree import command, argument, option
@argument("host", help="server listen address")
@option("reload", is_flag=True, help="if auto-reload on")
@option("port", help="server port", type=INT, default=8888)
@command(help="run a http server on given address")
def run_s... |
assert entry(
["test_miss", "path", "--kline", "fake"]
) == ("path", "fake")
def test_should_double_option_order_do_not_cause_calling_error():
@command("test_order")
@option("feed")
@option("config", help="config file path for kline database")
def hello(feed, config):
return... | return script_path, kline | identifier_body |
test_command.py | import pytest
from cmdtree import INT, entry
from cmdtree import command, argument, option
@argument("host", help="server listen address")
@option("reload", is_flag=True, help="if auto-reload on")
@option("port", help="server port", type=INT, default=8888)
@command(help="run a http server on given address")
def | (host, reload, port):
return host, port, reload
@command(help="run a http server on given address")
@argument("host", help="server listen address")
@option("port", help="server port", type=INT, default=8888)
def order(port, host):
return host, port
def test_should_return_given_argument():
from cmdtree i... | run_server | identifier_name |
test_command.py | import pytest
from cmdtree import INT, entry
from cmdtree import command, argument, option
@argument("host", help="server listen address")
@option("reload", is_flag=True, help="if auto-reload on")
@option("port", help="server port", type=INT, default=8888)
@command(help="run a http server on given address") | return host, port, reload
@command(help="run a http server on given address")
@argument("host", help="server listen address")
@option("port", help="server port", type=INT, default=8888)
def order(port, host):
return host, port
def test_should_return_given_argument():
from cmdtree import entry
result... | def run_server(host, reload, port): | random_line_split |
actor_system.rs | use threadpool::ThreadPool;
use actor::Role;
use actor_ref::ActorRef;
use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
/// A central actor system which manages the actor references and actors
///
/// Spawns the actor system with a specified number of threads in the
/// cent... | (thread_count: usize) -> ActorSystem<'sys, 'b> {
ActorSystem {
pool: ThreadPool::new(thread_count),
actor_refs: Rc::new(RefCell::new(HashMap::<String, ActorRef<'sys, 'b>>::new())),
}
}
pub fn spawn_actor(&'sys self, name: String, role: Box<Role + Sync + Send + 'static>) ... | new | identifier_name |
actor_system.rs | use threadpool::ThreadPool;
use actor::Role;
use actor_ref::ActorRef;
use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::Arc;
/// A central actor system which manages the actor references and actors
///
/// Spawns the actor system with a specified number of threads in the
/// cent... | // accessed by name. Depending on how actors are referenced this
// could be a more efficient way of referencing actors
pub pool: ThreadPool,
pub actor_refs: Rc<RefCell<HashMap<String, ActorRef<'sys, 'b>>>>
// pub actors: Rc<RefCell<HashMap<String, <Box<Role + Send + 'static>>>>>
}
impl <'sys, 'b>... | ///
pub struct ActorSystem<'sys, 'b: 'sys> {
// We can alternatively store actors in hashes so that they can be | random_line_split |
tempstorage.py | import os.path
from uuid import uuid4
import shutil
import logging
logger = logging.getLogger(__name__)
_MARKER = object()
class FileUploadTempStore(object):
session_storage_slug = 'websauna.tempstore'
def __init__(self, request):
self.tempdir = request.registry.settings['websauna.uploads_tempdir'... |
newdata = data.copy()
randid = newdata.get('randid')
if randid is not None:
file_name = os.path.join(self.tempdir, randid)
try:
newdata['fp'] = open(file_name, 'rb')
except IOError:
pass
return newdata
def __g... | return default | conditional_block |
tempstorage.py | import os.path
from uuid import uuid4
import shutil
import logging
logger = logging.getLogger(__name__)
_MARKER = object()
class FileUploadTempStore(object):
session_storage_slug = 'websauna.tempstore'
def __init__(self, request):
self.tempdir = request.registry.settings['websauna.uploads_tempdir'... |
def __getitem__(self, name):
data = self.get(name, _MARKER)
if data is _MARKER:
raise KeyError(name)
return data
| data = self.session.get(self.session_storage_slug, {}).get(name)
if data is None:
return default
newdata = data.copy()
randid = newdata.get('randid')
if randid is not None:
file_name = os.path.join(self.tempdir, randid)
try:
newdat... | identifier_body |
tempstorage.py | import os.path
from uuid import uuid4
import shutil
import logging
logger = logging.getLogger(__name__)
_MARKER = object()
class FileUploadTempStore(object):
session_storage_slug = 'websauna.tempstore'
def __init__(self, request):
self.tempdir = request.registry.settings['websauna.uploads_tempdir'... | (self, name, default=None):
data = self.session.get(self.session_storage_slug, {}).get(name)
if data is None:
return default
newdata = data.copy()
randid = newdata.get('randid')
if randid is not None:
file_name = os.path.join(self.tempdir, randid)
... | get | identifier_name |
tempstorage.py | import os.path
from uuid import uuid4
import shutil
import logging
logger = logging.getLogger(__name__)
_MARKER = object()
class FileUploadTempStore(object):
session_storage_slug = 'websauna.tempstore'
def __init__(self, request):
self.tempdir = request.registry.settings['websauna.uploads_tempdir'... | randid = cookie.get('randid')
file_name = os.path.join(self.tempdir, randid)
try:
os.remove(file_name)
except OSError:
pass
def get(self, name, default=None):
data = self.session.get(self.session_storage_slug, {}).get(name)
... | random_line_split | |
lc069-sqrtx.py | # coding=utf-8
import unittest
"""69. Sqrt(x)
https://leetcode.com/problems/sqrtx/description/
Implement `int sqrt(int x)`.
Compute and return the square root of _x_ , where _x_ is guaranteed to be a
non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only
the integer p... | (self, x):
"""
:type x: int
:rtype: int
"""
def test(self):
pass
if __name__ == "__main__":
unittest.main()
| mySqrt | identifier_name |
lc069-sqrtx.py | # coding=utf-8
import unittest
"""69. Sqrt(x)
https://leetcode.com/problems/sqrtx/description/
Implement `int sqrt(int x)`.
Compute and return the square root of _x_ , where _x_ is guaranteed to be a
non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only
the integer p... |
def test(self):
pass
if __name__ == "__main__":
unittest.main()
| """
:type x: int
:rtype: int
""" | identifier_body |
lc069-sqrtx.py | # coding=utf-8
import unittest
"""69. Sqrt(x)
https://leetcode.com/problems/sqrtx/description/
Implement `int sqrt(int x)`.
Compute and return the square root of _x_ , where _x_ is guaranteed to be a
non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only
the integer p... | def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
def test(self):
pass
if __name__ == "__main__":
unittest.main() | """
class Solution(object):
| random_line_split |
lc069-sqrtx.py | # coding=utf-8
import unittest
"""69. Sqrt(x)
https://leetcode.com/problems/sqrtx/description/
Implement `int sqrt(int x)`.
Compute and return the square root of _x_ , where _x_ is guaranteed to be a
non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only
the integer p... | unittest.main() | conditional_block | |
gulpfile.js | var gulp = require('gulp'),
plumber = require('gulp-plumber'),
rename = require('gulp-rename');
var autoprefixer = require('gulp-autoprefixer');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin'),
cache = require('gulp-cache');
var minifycss = r... | this.emit('end');
}}))
.pipe(concat('main.js'))
.pipe(gulp.dest('js/processed/'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest('js/processed/'))
});
gulp.task('default', function(){
gulp.watch("less/partials/*.less", ['styles']);
gulp.watch("js/*.js", ['scripts... | return gulp.src('js/*.js')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message); | random_line_split |
type-parameter-defaults-referencing-Self-ppaux.rs | // Copyright 2015 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 ... | (&self, other: &i32) -> i32 { *self + *other }
}
fn main() {
let x: i32 = 5;
let y = x as MyAdd<i32>;
//~^ ERROR as `MyAdd<i32>`
}
| add | identifier_name |
type-parameter-defaults-referencing-Self-ppaux.rs | // Copyright 2015 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 ... | {
let x: i32 = 5;
let y = x as MyAdd<i32>;
//~^ ERROR as `MyAdd<i32>`
} | identifier_body | |
type-parameter-defaults-referencing-Self-ppaux.rs | // Copyright 2015 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 MyAdd for i32 {
fn add(&self, other: &i32) -> i32 { *self + *other }
}
fn main() {
let x: i32 = 5;
let y = x as MyAdd<i32>;
//~^ ERROR as `MyAdd<i32>`
} | // the user, but pretty-printing the type during the error message
// caused an ICE.
trait MyAdd<Rhs=Self> { fn add(&self, other: &Rhs) -> Self; }
| random_line_split |
jquery.ui.progressbar.js | /*
* jQuery UI Progressbar 1.8.11
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Progressbar
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function ($, undefined) ... | });
$.extend($.ui.progressbar, {
version:"1.8.11"
});
})(jQuery); | } | random_line_split |
jquery.ui.progressbar.js | /*
* jQuery UI Progressbar 1.8.11
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Progressbar
*
* Depends:
* jquery.ui.core.js
* jquery.ui.widget.js
*/
(function ($, undefined) ... |
return Math.min(this.options.max, Math.max(this.min, val));
},
_percentage:function () {
return 100 * this._value() / this.options.max;
},
_refreshValue:function () {
var value = this.value();
var percentage = this._percentage();
if (this.oldValue !== value) {
t... | {
val = 0;
} | conditional_block |
linker.js | this is lifted from the (defunct) amigo2.js
* package. However, the future should be here.
*/
var us = require('underscore');
var bbop = require('bbop-core');
// Need acces to the server data.
var amigo_data_server = new (require('./data/server'))();
var amigo_data_xrefs = new (require('./data/xrefs'))();
/*
* C... |
}
}
}
///
/// External resources. For us, if we haven't found something
/// so far, try the data xrefs.
///
// Since we couldn't find anything with our explicit local
// transformation set, drop into the great abyss of the xref data.
if( ! retval && id && id !== '' ){ // not... | {
// The possibility of just tossing back an empty
// search for somebody downstream to fill in.
if( typeof(id) !== 'undefined' && id !== null ){
retval = retval + '?q=' + id;
}
} | conditional_block |
linker.js | this is lifted from the (defunct) amigo2.js
* package. However, the future should be here.
*/
var us = require('underscore');
var bbop = require('bbop-core');
// Need acces to the server data.
var amigo_data_server = new (require('./data/server'))();
var amigo_data_xrefs = new (require('./data/xrefs'))();
/*
* C... | 'function_class_closure': true,
'process_class': true,
'process_class_closure': true,
'location_list': true,
'location_list_closure': true
};
this.bio_category = {
'gp': true,
'gene_product': true,
'bioentity': true
};
this.model_category = {
'model': true
};
this.search_c... | // Noctua model stuff.
'function_class': true, | random_line_split |
renderer.rs | extern crate raster;
use std::collections::LinkedList;
use std::cell::RefCell;
use std::rc::Rc;
use geometric::Geometric2D;
pub struct Renderer<'a> {
vertices: LinkedList<&'a Rc<RefCell<Box<Geometric2D>>>>,
image: raster::Image
} | Renderer {
vertices: LinkedList::new(),
image: raster::Image::blank(height, width)
}
}
pub fn save(self) {
self.save_as("test_tmp.png".to_owned());
}
pub fn add(&mut self, geo: &'a Rc<RefCell<Box<Geometric2D>>>) {
self.vertices.push_front(geo);
... |
impl<'a> Renderer<'a> {
//Construct a new Renderer
pub fn new(height: i32, width: i32) -> Renderer<'a> { | random_line_split |
renderer.rs | extern crate raster;
use std::collections::LinkedList;
use std::cell::RefCell;
use std::rc::Rc;
use geometric::Geometric2D;
pub struct Renderer<'a> {
vertices: LinkedList<&'a Rc<RefCell<Box<Geometric2D>>>>,
image: raster::Image
}
impl<'a> Renderer<'a> {
//Construct a new Renderer
pub fn new(height: i... |
pub fn save_as(&self, filename: String) {
raster::save(&self.image, &*filename);
}
pub fn draw_outline(&mut self) {
for v in &self.vertices {
v.borrow_mut().draw_outline(&mut self.image);
}
}
pub fn draw(&mut self) {
for v in &self.vertices {
... | {
self.vertices.push_front(geo);
} | identifier_body |
renderer.rs | extern crate raster;
use std::collections::LinkedList;
use std::cell::RefCell;
use std::rc::Rc;
use geometric::Geometric2D;
pub struct Renderer<'a> {
vertices: LinkedList<&'a Rc<RefCell<Box<Geometric2D>>>>,
image: raster::Image
}
impl<'a> Renderer<'a> {
//Construct a new Renderer
pub fn | (height: i32, width: i32) -> Renderer<'a> {
Renderer {
vertices: LinkedList::new(),
image: raster::Image::blank(height, width)
}
}
pub fn save(self) {
self.save_as("test_tmp.png".to_owned());
}
pub fn add(&mut self, geo: &'a Rc<RefCell<Box<Geometric2D>>>)... | new | identifier_name |
changePassword.js | import React, { Component } from 'react';
import { Image, StatusBar, TouchableOpacity } from "react-native";
import { Container, Content, Card, CardItem, Text, View, Body, List, ListItem, Icon, Right, Button, Label, Item, Input } from 'native-base';
import styles from './styles'; | export default class PersonalInfo extends Component { // eslint-disable-line
render() { // eslint-disable-line
return (
<Container style={styles.container}>
<Content style={styles.content}>
<View style={{flexDirection : 'row', marginTop : 10, marginBottom : 20}}>
<Icon name="l... | random_line_split | |
changePassword.js |
import React, { Component } from 'react';
import { Image, StatusBar, TouchableOpacity } from "react-native";
import { Container, Content, Card, CardItem, Text, View, Body, List, ListItem, Icon, Right, Button, Label, Item, Input } from 'native-base';
import styles from './styles';
export default class PersonalInfo ... | </Item>
</Body>
<Body>
<Item floatingLabel style={{marginLeft : 20, marginRight : 20, marginTop : 5}}>
<Label>Confirm New Password</Label>
<Input />
</Item>
</Body>
<Button rounded info ... | { // eslint-disable-line
return (
<Container style={styles.container}>
<Content style={styles.content}>
<View style={{flexDirection : 'row', marginTop : 10, marginBottom : 20}}>
<Icon name="lock"/>
<Text style={{marginLeft : 10, marginTop : 5, color : '#189DAE', fontS... | identifier_body |
changePassword.js |
import React, { Component } from 'react';
import { Image, StatusBar, TouchableOpacity } from "react-native";
import { Container, Content, Card, CardItem, Text, View, Body, List, ListItem, Icon, Right, Button, Label, Item, Input } from 'native-base';
import styles from './styles';
export default class | extends Component { // eslint-disable-line
render() { // eslint-disable-line
return (
<Container style={styles.container}>
<Content style={styles.content}>
<View style={{flexDirection : 'row', marginTop : 10, marginBottom : 20}}>
<Icon name="lock"/>
<Text style={{... | PersonalInfo | identifier_name |
rparser.rs | //! common functions for all parsers
pub use crate::probe::{L3Info, L4Info, ProbeL4, ProbeResult};
use crate::Variant;
/// Direction of current packet in current stream
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Direction {
/// Packet is sent from client to server
ToServer,
/// Packet is sent f... |
}
/// Interface of a parser builder
pub trait RBuilder: Send + Sync {
fn build(&self) -> Box<dyn RParser>;
fn get_l4_probe(&self) -> Option<ProbeL4> {
None
}
}
// status: return code, events
pub const R_STATUS_EVENTS: u32 = 0x0100;
pub const R_STATUS_OK: u32 = 0x0000;
pub const R_STATUS_FAIL: ... | {
[].iter()
} | identifier_body |
rparser.rs | //! common functions for all parsers
pub use crate::probe::{L3Info, L4Info, ProbeL4, ProbeResult};
use crate::Variant;
/// Direction of current packet in current stream
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Direction {
/// Packet is sent from client to server
ToServer,
/// Packet is sent f... |
// Constants
pub const STREAM_TOSERVER: u8 = 0;
pub const STREAM_TOCLIENT: u8 = 1; | ($status & $crate::R_STATUS_EV_MASK) == $crate::R_STATUS_EVENTS
};
} | random_line_split |
rparser.rs | //! common functions for all parsers
pub use crate::probe::{L3Info, L4Info, ProbeL4, ProbeResult};
use crate::Variant;
/// Direction of current packet in current stream
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum | {
/// Packet is sent from client to server
ToServer,
/// Packet is sent from server to client
ToClient,
}
/// Return value from protocol probe trying to identify a protocol.
#[derive(Debug, Eq, PartialEq)]
pub enum ParseResult {
/// No error
///
/// Note that this does not mean that the pa... | Direction | identifier_name |
test_helper_functions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Pytroll developers
# Author(s):
# Adam Dybbroe <Firstname.Lastname @ smhi.se>
# 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 Foundat... | (self):
self.config_complete = create_config_from_yaml(TEST_YAML_CONTENT_OK)
@patch('aapp_runner.read_aapp_config.load_config_from_file')
def test_check_if_scene_is_unique_return_value(self, config):
"""Test checking if the current scene is unique or if it has been processed earlier."""
... | setUp | identifier_name |
test_helper_functions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Pytroll developers
# Author(s):
# Adam Dybbroe <Firstname.Lastname @ smhi.se>
# 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 | # 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 w... | # the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
| random_line_split |
test_helper_functions.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Pytroll developers
# Author(s):
# Adam Dybbroe <Firstname.Lastname @ smhi.se>
# 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 Foundat... | _ = check_if_scene_is_unique(aapp_config)
self.assertEqual(cm.output, expected_logging)
with self.assertLogs('aapp_runner.helper_functions', level='WARNING') as cm:
logging.getLogger('aapp_runner.helper_functions').warning('first message')
_ = check_if_scene_is_uniq... | """Test the logging when checking if the current scene is unique."""
config.return_value = self.config_complete
myfilename = "/tmp/mytestfile"
aapp_run_config = AappRunnerConfig(myfilename, 'norrkoping', 'xl-band')
aapp_config = AappL1Config(aapp_run_config.config, 'xl-band')
aa... | identifier_body |
settings.py | # Copyright (c) 2008 Joost Cassee
# Licensed under the terms of the MIT License (see LICENSE.txt)
| assert URL_TYPE in URL_TYPES, \
"LOCALE_URL_TYPE must be one of %s" % ', '.join(URL_TYPES)
LOCALE_INDEPENDENT_PATHS = getattr(settings, 'LOCALE_INDEPENDENT_PATHS', ())
assert not (URL_TYPE != 'path_prefix' and LOCALE_INDEPENDENT_PATHS), \
"LOCALE_INDEPENDENT_PATHS only used with URL_TYPE == 'path_prefi... | from django.conf import settings
URL_TYPES = ('path_prefix', 'domain_component', 'domain')
URL_TYPE = getattr(settings, 'LOCALE_URL_TYPE', 'path_prefix') | random_line_split |
default.rs | base::{Annotatable, DummyResult, ExtCtxt};
use rustc_span::symbol::Ident;
use rustc_span::symbol::{kw, sym};
use rustc_span::Span;
use smallvec::SmallVec;
pub fn expand_deriving_default(
cx: &mut ExtCtxt<'_>,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable),
) {
... | }
struct DetectNonVariantDefaultAttr<'a, 'b> {
cx: &'a ExtCtxt<'b>,
}
impl<'a, 'b> rustc_ast::visit::Visitor<'a> for DetectNonVariantDefaultAttr<' | .emit();
return Err(());
}
Ok(()) | random_line_split |
default.rs | base::{Annotatable, DummyResult, ExtCtxt};
use rustc_span::symbol::Ident;
use rustc_span::symbol::{kw, sym};
use rustc_span::Span;
use smallvec::SmallVec;
pub fn expand_deriving_default(
cx: &mut ExtCtxt<'_>,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable),
) {
... | }
}
}
fn default_enum_substructure(
cx: &mut ExtCtxt<'_>,
trait_span: Span,
enum_def: &EnumDef,
) -> P<Expr> {
let default_variant = match extract_default_variant(cx, enum_def, trait_span) {
Ok(value) => value,
Err(()) => return DummyResult::raw_expr(trait_span, true),
... | {
// Note that `kw::Default` is "default" and `sym::Default` is "Default"!
let default_ident = cx.std_path(&[kw::Default, sym::Default, kw::Default]);
let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec::new());
match summary {
Unnamed(ref fields, is_tuple) => {
... | identifier_body |
default.rs | base::{Annotatable, DummyResult, ExtCtxt};
use rustc_span::symbol::Ident;
use rustc_span::symbol::{kw, sym};
use rustc_span::Span;
use smallvec::SmallVec;
pub fn expand_deriving_default(
cx: &mut ExtCtxt<'_>,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable),
) {
... | (
cx: &mut ExtCtxt<'_>,
default_variant: &rustc_ast::Variant,
) -> Result<(), ()> {
let attrs: SmallVec<[_; 1]> =
cx.sess.filter_by_name(&default_variant.attrs, kw::Default).collect();
let attr = match attrs.as_slice() {
[attr] => attr,
[] => cx.bug(
"this method mus... | validate_default_attribute | identifier_name |
default.rs | base::{Annotatable, DummyResult, ExtCtxt};
use rustc_span::symbol::Ident;
use rustc_span::symbol::{kw, sym};
use rustc_span::Span;
use smallvec::SmallVec;
pub fn expand_deriving_default(
cx: &mut ExtCtxt<'_>,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable),
) {
... |
Named(ref fields) => {
let default_fields = fields
.iter()
.map(|&(ident, span)| cx.field_imm(span, ident, default_call(span)))
.collect();
cx.expr_struct_ident(trait_span, substr.type_ident, default_fields)
}
}
}
fn default_e... | {
if !is_tuple {
cx.expr_ident(trait_span, substr.type_ident)
} else {
let exprs = fields.iter().map(|sp| default_call(*sp)).collect();
cx.expr_call_ident(trait_span, substr.type_ident, exprs)
}
} | conditional_block |
filesystem.rs | use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
pub fn check_extension(path: &Path, valid_ext: &[&str]) -> bool {
let ext = &path.extension().expect("The file has no extension").to_str().expect("Extension is not valid utf8");
for vext in valid_ext.iter() {
if vext == ext... | Err(msg) => panic!("Found non valid utf8 characters in {} : {}.", path.display(), msg)
}
},
Err(msg) => panic!("Error reading file {} : {}.", path.display(), msg)
}
} | {
let mut path = env::current_dir().unwrap();
path.push(Path::new(path_str));
if !path.exists() {
panic!("Error reading file, path {} doesn't exist.", path.display());
}
let mut f = match File::open(&path) {
Ok(f) => f,
Err(msg) => panic!("Error reading file {} : {}.",... | identifier_body |
filesystem.rs | use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
pub fn check_extension(path: &Path, valid_ext: &[&str]) -> bool {
let ext = &path.extension().expect("The file has no extension").to_str().expect("Extension is not valid utf8");
for vext in valid_ext.iter() {
if vext == ext... |
let mut f = match File::open(&path) {
Ok(f) => f,
Err(msg) => panic!("Error reading file {} : {}.", path.display(), msg)
};
// read bytes and return as str
let mut bytes = Vec::new();
match f.read_to_end(&mut bytes) {
Ok(_) => {
match String::from_utf8(bytes) {... | {
panic!("Error reading file, path {} doesn't exist.", path.display());
} | conditional_block |
filesystem.rs | use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
pub fn | (path: &Path, valid_ext: &[&str]) -> bool {
let ext = &path.extension().expect("The file has no extension").to_str().expect("Extension is not valid utf8");
for vext in valid_ext.iter() {
if vext == ext {
return true;
}
}
false
}
pub fn read_file(path_str: &str) -> String {
... | check_extension | identifier_name |
filesystem.rs | use std::path::Path;
use std::fs::File;
use std::io::prelude::*;
use std::env;
pub fn check_extension(path: &Path, valid_ext: &[&str]) -> bool {
let ext = &path.extension().expect("The file has no extension").to_str().expect("Extension is not valid utf8");
for vext in valid_ext.iter() {
if vext == ext... | } | },
Err(msg) => panic!("Error reading file {} : {}.", path.display(), msg)
} | random_line_split |
error.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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/l... | (&self) -> Option<&StdError> {
use self::Error::*;
match *self {
Hyper(ref e) => e.cause(),
Io(ref e) => e.cause(),
Serde(ref e) => e.cause(),
UrlParse(ref e) => e.cause(),
}
}
}
impl From<hyper::Error> for Error {
fn from(error: hyper::E... | cause | identifier_name |
error.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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/l... | Io(io::Error),
/// A `serde` crate error.
Serde(serde_json::Error),
/// Error while parsing a URL.
UrlParse(url::ParseError),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
use self::Error::*;
match *self {
Hyper(ref e) => e.f... | /// A `hyper` crate error.
Hyper(hyper::Error),
/// An IO error was encountered. | random_line_split |
error.rs | // Copyright (c) 2016 Nikita Pekin and the smexybot contributors
// See the README.md file at the top-level directory of this distribution.
//
// 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/l... |
}
impl StdError for Error {
fn description(&self) -> &str {
use self::Error::*;
match *self {
Hyper(ref e) => e.description(),
Io(ref e) => e.description(),
Serde(ref e) => e.description(),
UrlParse(ref e) => e.description(),
}
}
fn... | {
use self::Error::*;
match *self {
Hyper(ref e) => e.fmt(f),
Io(ref e) => e.fmt(f),
Serde(ref e) => e.fmt(f),
UrlParse(ref e) => e.fmt(f),
}
} | identifier_body |
it-system.ts | module Kitos.Models.ItSystem {
export interface IItSystem extends IItSystemBase {
/** Gets or sets the user defined system identifier. */
ItSystemId: string; | /** Gets or sets interfaces that can use this instance. */
CanUseInterfaces: Array<IItInterfaceUse>;
/** Gets or sets the sub (child) it systems. */
Children: Array<IItSystem>;
ParentId: number;
Disabled: boolean;
/** Gets or sets the parent (master) it system. */... | /** Gets or sets exhibited interfaces for this instance. */
ItInterfaceExhibits: Array<IItInterfaceExhibit>; | random_line_split |
Holiday.py | *a+b)%19
g=(19*f+c-e)%30
h=(f+11*g)//319
j=(60*(5-d)+b)//4
k=(60*(5-d)+b)%4
m=(2*j-k-g+h)%7
n=(g-h+m+114)//31
p=(g-h+m+114)%31
jour=p+1
mois=n
return [jour, mois, an]
def dateliste(self,c, sep='/'):
"""Transforme une date chaîne 'j/m/a' en une date ... | d, n=-1):
"""Donne la date du nième jour précédent d=[j, m, a] (n<=0)"""
j, m, a = d
fm = [0,31,28,31,30,31,30,31,31,30,31,30,31]
if (a%4==0 and a%100!=0) or a%400==0: # bissextile?
fm[2] = 29
for i in xrange(0,abs(n)):
j -= 1
if j < 1:
m -= 1
... | ins(self, | identifier_name |
Holiday.py | 5*a+b)%19
g=(19*f+c-e)%30
h=(f+11*g)//319
j=(60*(5-d)+b)//4
k=(60*(5-d)+b)%4
m=(2*j-k-g+h)%7
n=(g-h+m+114)//31
p=(g-h+m+114)%31
jour=p+1
mois=n
return [jour, mois, an]
def dateliste(self,c, sep='/'):
"""Transforme une date chaîne 'j/m/a' en une date... | sd=2: tous + les 2 jours fériés supplémentaires d'Alsace-Moselle.
sd=3: idem sd=2 sans les samedis-dimanches"""
F = [] # =liste des dates des jours feries en date-liste d=[j,m,a]
L = [] # =liste des libelles du jour ferie
dp = self.datepaques(an)
# Jour de l'an
... |
def joursferiesliste(self,an, sd=0):
"""Liste des jours fériés France en date-liste de l'année an (nb entier).
sd=0 (=defaut): tous les jours fériés.
sd=1: idem sans les sammedis-dimanches. | random_line_split |
Holiday.py | 5*a+b)%19
g=(19*f+c-e)%30
h=(f+11*g)//319
j=(60*(5-d)+b)//4
k=(60*(5-d)+b)%4
m=(2*j-k-g+h)%7
n=(g-h+m+114)//31
p=(g-h+m+114)%31
jour=p+1
mois=n
return [jour, mois, an]
def dateliste(self,c, sep='/'):
"""Transforme une date chaîne 'j/m/a' en une date... | return [j,m,a]
def jourmoins(self,d, n=-1):
"""Donne la date du nième jour précédent d=[j, m, a] (n<=0)"""
j, m, a = d
fm = [0,31,28,31,30,31,30,31,31,30,31,30,31]
if (a%4==0 and a%100!=0) or a%400==0: # bissextile?
fm[2] = 29
for i in xrange(0,abs(n)):
j -= 1
... | a += 1
| conditional_block |
Holiday.py | 5*a+b)%19
g=(19*f+c-e)%30
h=(f+11*g)//319
j=(60*(5-d)+b)//4
k=(60*(5-d)+b)%4
m=(2*j-k-g+h)%7
n=(g-h+m+114)//31
p=(g-h+m+114)%31
jour=p+1
mois=n
return [jour, mois, an]
def dateliste(self,c, sep='/'):
"""Transforme une date chaîne 'j/m/a' en une date... | def numjoursem(self,d):
"""Donne le numéro du jour de la semaine d'une date d=[j,m,a]
lundi=1, mardi=2, ..., dimanche=7
Algorithme de Maurice Kraitchik (1882?1957)"""
j, m, a = d
if m<3:
m += 12
a -= 1
n = (j +2*m + (3*(m+1))//5 +a + a//4 - a//100 + a//400 +... | ne la date du nième jour précédent d=[j, m, a] (n<=0)"""
j, m, a = d
fm = [0,31,28,31,30,31,30,31,31,30,31,30,31]
if (a%4==0 and a%100!=0) or a%400==0: # bissextile?
fm[2] = 29
for i in xrange(0,abs(n)):
j -= 1
if j < 1:
m -= 1
if m<1:
... | identifier_body |
HTMLTableCellElement10.js |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANT... |
setUpPageStatus = 'running';
try {
//
// creates test document builder, may throw exception
//
builder = createConfiguredBuilder();
docsLoaded = 0;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
docsLoaded += prel... | pPage() { | identifier_name |
HTMLTableCellElement10.js | /*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANTY... | var success;
if(checkInitialization(builder, "HTMLTableCellElement10") != null) return;
var nodeList;
var testNode;
var vbgcolor;
var doc;
var docRef = null;
if (typeof(this.doc) != 'undefined') {
docRef = this.doc;
}
doc = load(docRef, "doc", "tablece... | * @author Mary Brady
* @see http://www.w3.org/TR/1998/REC-DOM-Level-1-19981001/level-one-html#ID-88135431
*/
function HTMLTableCellElement10() { | random_line_split |
HTMLTableCellElement10.js |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANT... | r docsLoaded = -1000000;
var builder = null;
//
// This function is called by the testing framework before
// running the test suite.
//
// If there are no configuration exceptions, asynchronous
// document loading is started. Otherwise, the status
// is set to complete and the exception is imm... | return "http://www.w3.org/2001/DOM-Test-Suite/level2/html/HTMLTableCellElement10";
}
va | identifier_body |
HTMLTableCellElement10.js |
/*
Copyright © 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, European Research Consortium
for Informatics and Mathematics, Keio University). All
Rights Reserved. This work is distributed under the W3C® Software License [1] in the
hope that it will be useful, but WITHOUT ANY WARRANT... | docsLoaded += preload(docRef, "doc", "tablecell");
if (docsLoaded == 1) {
setUpPageStatus = 'complete';
}
} catch(ex) {
catchInitializationError(builder, ex);
setUpPageStatus = 'complete';
}
}
//
// This method is called on the completion of
// each as... | docRef = this.doc;
}
| conditional_block |
explorerTreeData.js | import _ from 'lodash';
import { createSelector } from 'reselect';
const srcFilesSelector = state => state.srcFiles;
const featuresSelector = state => state.features;
const featureByIdSelector = state => state.featureById;
const keywordSelector = (state, keyword) => keyword;
function getMarks(feature, ele) {
const ... | (node, keyword) {
const reg = new RegExp(_.escapeRegExp(keyword), 'i');
return {
...node,
children: _.compact(node.children.map((child) => {
if (child.searchable && reg.test(child.label)) return child;
if (child.children) {
const c = filterTreeNode(child, keyword);
return c.child... | filterTreeNode | identifier_name |
explorerTreeData.js | import _ from 'lodash';
import { createSelector } from 'reselect';
const srcFilesSelector = state => state.srcFiles;
const featuresSelector = state => state.features;
const featureByIdSelector = state => state.featureById;
const keywordSelector = (state, keyword) => keyword;
function getMarks(feature, ele) {
const ... |
return keys;
}
);
| {
const pop = arr.pop();
if (pop.children) {
keys.push(pop.key);
arr = [...arr, ...pop.children];
}
} | conditional_block |
explorerTreeData.js | import _ from 'lodash';
import { createSelector } from 'reselect';
const srcFilesSelector = state => state.srcFiles;
const featuresSelector = state => state.features;
const featureByIdSelector = state => state.featureById;
const keywordSelector = (state, keyword) => keyword;
function getMarks(feature, ele) {
const ... |
export const getFilteredExplorerTreeData = createSelector(
getExplorerTreeData,
keywordSelector,
(treeData, keyword) => {
if (!keyword) return treeData;
return filterTreeNode(treeData, keyword);
}
);
// when searching the tree, all nodes should be expanded, the tree component needs expandedKeys prope... | {
const reg = new RegExp(_.escapeRegExp(keyword), 'i');
return {
...node,
children: _.compact(node.children.map((child) => {
if (child.searchable && reg.test(child.label)) return child;
if (child.children) {
const c = filterTreeNode(child, keyword);
return c.children.length > 0 ?... | identifier_body |
explorerTreeData.js | import _ from 'lodash';
import { createSelector } from 'reselect';
const srcFilesSelector = state => state.srcFiles;
const featuresSelector = state => state.features;
const featureByIdSelector = state => state.featureById;
const keywordSelector = (state, keyword) => keyword;
function getMarks(feature, ele) {
const ... | export const getExpandedKeys = createSelector(
getFilteredExplorerTreeData,
(treeData) => {
const keys = [];
let arr = [...treeData.children];
while (arr.length) {
const pop = arr.pop();
if (pop.children) {
keys.push(pop.key);
arr = [...arr, ...pop.children];
}
}
... | }
);
// when searching the tree, all nodes should be expanded, the tree component needs expandedKeys property. | random_line_split |
setup.py | import setuptools |
setuptools.setup(
name="serverless-wsgi",
version="3.0.0",
python_requires=">3.6",
author="Logan Raarup",
author_email="logan@logan.dk",
description="Amazon AWS API Gateway WSGI wrapper",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://... |
with open("README.md", "r") as fh:
long_description = fh.read() | random_line_split |
collision.rs |
use hlt::entity::{Entity, Position};
pub fn | <E: Entity, F: Entity, G: Entity>(start: &E, end: &F, circle: &G, fudge: f64) -> bool {
let Position(start_x, start_y) = start.get_position();
let Position(end_x, end_y) = end.get_position();
let Position(circle_x, circle_y) = circle.get_position();
let dx = end_x - start_x;
let dy = end_y - start_y... | intersect_segment_circle | identifier_name |
collision.rs |
use hlt::entity::{Entity, Position};
pub fn intersect_segment_circle<E: Entity, F: Entity, G: Entity>(start: &E, end: &F, circle: &G, fudge: f64) -> bool {
let Position(start_x, start_y) = start.get_position();
let Position(end_x, end_y) = end.get_position();
let Position(circle_x, circle_y) = circle.get_... |
let closest_x = start_x + dx * t;
let closest_y = start_y + dy * t;
let closest_distance = Position(closest_x, closest_y).calculate_distance_between(circle);
return closest_distance <= circle.get_radius() + fudge
}
| {
return false;
} | conditional_block |
collision.rs | let Position(end_x, end_y) = end.get_position();
let Position(circle_x, circle_y) = circle.get_position();
let dx = end_x - start_x;
let dy = end_y - start_y;
let a = dx.powi(2) + dy.powi(2);
let b = -2.0 * (start_x.powi(2) - start_x*end_x - start_x*circle_x + end_x*circle_x +
sta... | use hlt::entity::{Entity, Position};
pub fn intersect_segment_circle<E: Entity, F: Entity, G: Entity>(start: &E, end: &F, circle: &G, fudge: f64) -> bool {
let Position(start_x, start_y) = start.get_position(); | random_line_split | |
collision.rs |
use hlt::entity::{Entity, Position};
pub fn intersect_segment_circle<E: Entity, F: Entity, G: Entity>(start: &E, end: &F, circle: &G, fudge: f64) -> bool |
let closest_x = start_x + dx * t;
let closest_y = start_y + dy * t;
let closest_distance = Position(closest_x, closest_y).calculate_distance_between(circle);
return closest_distance <= circle.get_radius() + fudge
}
| {
let Position(start_x, start_y) = start.get_position();
let Position(end_x, end_y) = end.get_position();
let Position(circle_x, circle_y) = circle.get_position();
let dx = end_x - start_x;
let dy = end_y - start_y;
let a = dx.powi(2) + dy.powi(2);
let b = -2.0 * (start_x.powi(2) - start_x*... | identifier_body |
arview.js | "use strict";
define(["lib/three.min"], function() {
var Reality = function(sourceCanvas){
// Create a default camera and scene.
var camera = new THREE.Camera();
var scene = new THREE.Scene();
// Create a plane geometry to hold the sourceCanvas texture
var geometry = new T... | (object) {
scene.remove(object);
}
function setProjectionMatrix(matrix) {
camera.projectionMatrix.setFromArray( matrix );
}
return {
scene:scene,
camera:camera,
add:add,
remove:remove,
setProjectionMatr... | remove | identifier_name |
arview.js | "use strict";
define(["lib/three.min"], function() {
var Reality = function(sourceCanvas){
// Create a default camera and scene.
var camera = new THREE.Camera();
var scene = new THREE.Scene();
// Create a plane geometry to hold the sourceCanvas texture
var geometry = new T... |
function update() {
// Notify the reality scene to update it's texture
reality.update();
}
function setCameraMatrix( matrix ) {
virtual.setProjectionMatrix( matrix );
}
function add( object ) {
virtual.add( object.model );
... | {
// Render the reality scene
renderer.render(reality.scene, reality.camera);
// Render the augmented components on top of the reality scene.
renderer.render(virtual.scene, virtual.camera);
} | identifier_body |
arview.js | "use strict";
define(["lib/three.min"], function() {
var Reality = function(sourceCanvas){
// Create a default camera and scene.
var camera = new THREE.Camera();
var scene = new THREE.Scene();
// Create a plane geometry to hold the sourceCanvas texture
var geometry = new T... |
function remove(object) {
scene.remove(object);
}
function setProjectionMatrix(matrix) {
camera.projectionMatrix.setFromArray( matrix );
}
return {
scene:scene,
camera:camera,
add:add,
remove:remove,
... | } | random_line_split |
CubeTexture.ts | import { Texture } from './Texture';
import { CubeReflectionMapping } from '../Constants';
import {
UVMapping, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping,
LinearEncoding, UnsignedByteType, RGBAFormat, LinearMipMapLinearFilter,
LinearFilter
} from '../Constants';
export class CubeTexture extends ... | () {
return <Array<HTMLImageElement> >this.image;
}
set images(v: Array<HTMLImageElement>) {
this.image = v;
}
}
| images | identifier_name |
CubeTexture.ts | import { Texture } from './Texture';
import { CubeReflectionMapping } from '../Constants';
import {
UVMapping, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping,
LinearEncoding, UnsignedByteType, RGBAFormat, LinearMipMapLinearFilter,
LinearFilter
} from '../Constants';
export class CubeTexture extends ... | } | random_line_split | |
05-flickr.py | import os, sys; sys.path.append(os.path.join("..", "..", ".."))
from pattern.web import Flickr, extension
from pattern.web import RELEVANCY, LATEST, INTERESTING # Image sort order.
from pattern.web import SMALL, MEDIUM, LARGE # Image size.
# This example downloads an image from Flickr (http://flickr.com).
#... | engine = Flickr(license=None)
q = "duracell bunny"
results = engine.search(q, size=MEDIUM, sort=RELEVANCY, cached=True)
for img in results:
#print img.url # Retrieving the actual image URL executes an additional query.
print img.description
print img.author
print
# Download and save the image:
img = r... | # which is what the cached=True parameter does.
# You should obtain your own license key at:
# http://www.flickr.com/services/api/
# Otherwise you will be sharing the default key with all users of this module. | random_line_split |
05-flickr.py | import os, sys; sys.path.append(os.path.join("..", "..", ".."))
from pattern.web import Flickr, extension
from pattern.web import RELEVANCY, LATEST, INTERESTING # Image sort order.
from pattern.web import SMALL, MEDIUM, LARGE # Image size.
# This example downloads an image from Flickr (http://flickr.com).
#... |
# Download and save the image:
img = results[0]
data = img.download()
f = open(q.replace(" ","_") + extension(img.url), "w")
f.write(data)
f.close() | print img.description
print img.author
print | conditional_block |
Demo.js | /**
* @author fanguozhu
*/
function isMappingEquals(m1,m2) {
if (m1==m2){
return true;
}
return isArrayEquals(m1.master,m2.master)&&isArrayEquals(m1.sub,m2.sub);
}
function | (a1,a2) {
if (a1==a2){
return true;
}
for (var i=0;i<a1.length;i++){
if (a1[i]!=a2[i]) {
return false;
}
}
return true;
}
$(function(){
var dataWrappers = {};
var components = {};
var masters = {};
$("[@portype]").each(function(i){
var porType = $(this).attr("portype");
var porId = $(this).at... | isArrayEquals | identifier_name |
Demo.js | /**
* @author fanguozhu
*/
function isMappingEquals(m1,m2) {
if (m1==m2){
return true;
}
return isArrayEquals(m1.master,m2.master)&&isArrayEquals(m1.sub,m2.sub);
}
function isArrayEquals(a1,a2) {
if (a1==a2){
return true;
}
for (var i=0;i<a1.length;i++){
if (a1[i]!=a2[i]) {
return false;
}
}
... |
}
component.dataWrapper(dw);
}
});
for (var k in masters){
PorUtil.linkMasterAndSubs(dataWrappers[k],masters[k]);
}
for (var k in masters){
dataWrappers[k].load();
}
// var dw = new DataWrapper();
// dw.service("PR99");
//
// dw.customMethod = function(){
// this.serviceInvoker().call("custom",... | {
var m = dataWrappers[master];
var _mapping = eval("("+mapping+")");
if (!m){
m = new DataWrapper();
m.service(master);
dataWrappers[master] = m;
}
if (masters[master]){
var t = masters[master];
for (var i=0;i<t.length;i++) {
if (t[i].sub==dw&&isMappingEqua... | conditional_block |
Demo.js | /**
* @author fanguozhu
*/
function isMappingEquals(m1,m2) {
if (m1==m2){
return true;
}
return isArrayEquals(m1.master,m2.master)&&isArrayEquals(m1.sub,m2.sub);
}
function isArrayEquals(a1,a2) |
$(function(){
var dataWrappers = {};
var components = {};
var masters = {};
$("[@portype]").each(function(i){
var porType = $(this).attr("portype");
var porId = $(this).attr("id");
var param = $(this).attr("porparam");
var component;
if (param) {
component = eval("new "+porType+"('"+porId+"',"+param+... | {
if (a1==a2){
return true;
}
for (var i=0;i<a1.length;i++){
if (a1[i]!=a2[i]) {
return false;
}
}
return true;
} | identifier_body |
Demo.js | /**
* @author fanguozhu
*/
function isMappingEquals(m1,m2) {
if (m1==m2){
return true;
}
return isArrayEquals(m1.master,m2.master)&&isArrayEquals(m1.sub,m2.sub);
}
function isArrayEquals(a1,a2) {
if (a1==a2){
return true;
}
for (var i=0;i<a1.length;i++){
if (a1[i]!=a2[i]) {
return false;
}
}
... | // dw.customMethod = function(){
// this.serviceInvoker().call("custom", new EiInfo(), {
// onSuccess: function() { alert("success"); },
// onFailure: function() { alert("fail"); }
// });
// };
//
// var grid = new DataGrid("main",{autoDraw:true});
// grid.dataWrapper(dw);
//
// var opt = new DataGridOptBar("... | }
// var dw = new DataWrapper();
// dw.service("PR99");
// | random_line_split |
Parent.js | /**
* @file source/Node.js - UI Parent class
* UI Node class. Uses common.js format (compatible with require.js and
* webpack).
* @author Lukasz A.J. Wrona (lukasz.andrzej.wrona@gmail.com)
* @license GNU Lesser General Public License version 3
*/
"use strict";
define(["./Node"], function (_Node) {
/**
* @brie... |
}
return Parent;
});
| {
return this._children.length == 0;
} | identifier_body |
Parent.js | /**
* @file source/Node.js - UI Parent class
* UI Node class. Uses common.js format (compatible with require.js and
* webpack).
* @author Lukasz A.J. Wrona (lukasz.andrzej.wrona@gmail.com)
* @license GNU Lesser General Public License version 3
*/
"use strict";
define(["./Node"], function (_Node) {
/**
* @brie... | else {
if (first instanceof Array) {
return this._appendMany(first);
} else {
return this._append(first);
}
}
}
/**
* @brief Removes child from parent and returns it.
* Exception-safety: Strong-guarantee
* @param child Node: Child to be removed.
* @return Node: Function returns removed chi... | {
if (first instanceof Array) {
return this._insertManyBefore(first, second);
} else {
return this._insertBefore(first, second);
}
} | conditional_block |
Parent.js | /**
* @file source/Node.js - UI Parent class
* UI Node class. Uses common.js format (compatible with require.js and
* webpack).
* @author Lukasz A.J. Wrona (lukasz.andrzej.wrona@gmail.com)
* @license GNU Lesser General Public License version 3
*/
"use strict";
define(["./Node"], function (_Node) {
/**
* @brie... | }
_appendMany(children) { // not exception safe
children.forEach(function (child, i) {
this._validateChildCandidate(child);
this.container.appendChild(child.DOM);
this._children.push(child);
child._parent = this;
child.fadeIn(Math.max(Math.min(children.length, 20) - i, 0) * 10);
}.bind(this));
}
... | child.fadeIn(0);
return child; | random_line_split |
Parent.js | /**
* @file source/Node.js - UI Parent class
* UI Node class. Uses common.js format (compatible with require.js and
* webpack).
* @author Lukasz A.J. Wrona (lukasz.andrzej.wrona@gmail.com)
* @license GNU Lesser General Public License version 3
*/
"use strict";
define(["./Node"], function (_Node) {
/**
* @brie... | () {
this.children.forEach(function (child) {
this.remove(child);
}.bind(this));
}
/* private methods ********************************************************/
_append(child) { // exception safe
typecheck(arguments, _Node);
this._validateChildCandidate(child);
this.container.appendChild(child.DOM);
th... | clear | identifier_name |
QuestionFactory.ts | /// <reference path="ColourFactory.ts" />
/// <reference path="Question.ts" />
/**
* The QuestionFactory class creates Question objects.
*/
class QuestionFactory
{
/**
* Get a stroop Question (having different Colours for name and hex code). With a 50% chance, the blood tube's
* colour hex code and the... |
/**
* Get a regular Question item (having same Colour for name and hex code). With a 50% chance, the blood tube's
* colour hex code and the colour name on the tube box match, i.e. the correct answer would be 'Y'.
*
* @returns {Question}
*/
public static getRegularQuestion() {
... | {
var headsOrTails = Math.ceil(Math.random() * 2),
colourForBox = ColourFactory.getRandomColour(),
nameColour = ColourFactory.getRandomColourButNot([colourForBox]),
thirdColour = ColourFactory.getRandomColourButNot([colourForBox, nameColour]);
if (headsOrTails === 1)... | identifier_body |
QuestionFactory.ts | /// <reference path="ColourFactory.ts" />
/// <reference path="Question.ts" />
/**
* The QuestionFactory class creates Question objects.
*/
class QuestionFactory
{
/**
* Get a stroop Question (having different Colours for name and hex code). With a 50% chance, the blood tube's
* colour hex code and the... | } else {
return new Question(differentColour, differentColour, colourForBox);
}
}
} | colourForBox = ColourFactory.getRandomColour(),
differentColour = ColourFactory.getRandomColourButNot([colourForBox]);
if (headsOrTails === 1) {
return new Question(colourForBox, colourForBox, colourForBox); | random_line_split |
QuestionFactory.ts | /// <reference path="ColourFactory.ts" />
/// <reference path="Question.ts" />
/**
* The QuestionFactory class creates Question objects.
*/
class QuestionFactory
{
/**
* Get a stroop Question (having different Colours for name and hex code). With a 50% chance, the blood tube's
* colour hex code and the... |
}
} | {
return new Question(differentColour, differentColour, colourForBox);
} | conditional_block |
QuestionFactory.ts | /// <reference path="ColourFactory.ts" />
/// <reference path="Question.ts" />
/**
* The QuestionFactory class creates Question objects.
*/
class QuestionFactory
{
/**
* Get a stroop Question (having different Colours for name and hex code). With a 50% chance, the blood tube's
* colour hex code and the... | () {
var headsOrTails = Math.ceil(Math.random() * 2),
colourForBox = ColourFactory.getRandomColour(),
differentColour = ColourFactory.getRandomColourButNot([colourForBox]);
if (headsOrTails === 1) {
return new Question(colourForBox, colourForBox, colourForBox);
... | getRegularQuestion | identifier_name |
mod.rs | /// Convert symbols type to their corresponding Gecko values.
pub fn to_gecko_keyword(self) -> u8 {
use gecko_bindings::structs;
match self {
SymbolsType::Cyclic => structs::NS_STYLE_COUNTER_SYSTEM_CYCLIC as u8,
SymbolsType::Numeric => structs::NS_STYLE_COUNTER_SYSTEM_NUM... | {
input.expect_number().map(FontSettingTagFloat).map_err(|e| e.into())
} | identifier_body | |
mod.rs | box.rs"]
pub mod box_;
pub mod effects;
pub mod flex;
#[cfg(feature = "gecko")]
pub mod gecko;
pub mod grid;
pub mod image;
pub mod position;
pub mod rect;
pub mod svg;
pub mod text;
pub mod transform;
// https://drafts.csswg.org/css-counter-styles/#typedef-symbols-type
define_css_keyword_enum! { SymbolsType:
"cyc... | if input.try(|i| i.expect_ident_matching("normal")).is_ok() {
return Ok(FontSettings::Normal);
}
Vec::parse(context, input).map(FontSettings::Tag)
}
}
/// An integer that can also parse "on" and "off",
/// for font-feature-settings
///
/// Do not use this type anywhere except wi... | random_line_split | |
mod.rs | " => Numeric,
"alphabetic" => Alphabetic,
"symbolic" => Symbolic,
"fixed" => Fixed,
}
add_impls_for_keyword_enum!(SymbolsType);
#[cfg(feature = "gecko")]
impl SymbolsType {
/// Convert symbols type to their corresponding Gecko values.
pub fn to_gecko_keyword(self) -> u8 {
use gecko_bindings... | parse | identifier_name | |
message_dialogs.py | # -*- coding: utf-8 -*-
# message_dialogs.py
# misc Gtk.MessageDialogs
#
# Copyright (C) 2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any l... |
self.actions = actions
builder = Gtk.Builder()
builder.add_from_file(locate_ui_file('confirm_actions_dialog.ui'))
self.dialog = builder.get_object("confirm_actions_dialog")
self.dialog.set_transient_for(parent_window)
self.dialog.set_markup("<b>" + title + "</b>")
... | """
def __init__(self, parent_window, title, msg, actions): | random_line_split |
message_dialogs.py | # -*- coding: utf-8 -*-
# message_dialogs.py
# misc Gtk.MessageDialogs
#
# Copyright (C) 2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any l... |
def run(self):
""" Run the dialog
"""
response = self.dialog.run()
self.dialog.destroy()
return response == Gtk.ResponseType.OK
| """ Onclick action for treeview
"""
model, treeiter = selection.get_selected()
if treeiter and model:
selection.handler_block(self.selection_signal)
selection.unselect_iter(treeiter)
selection.handler_unblock(self.selection_signal) | identifier_body |
message_dialogs.py | # -*- coding: utf-8 -*-
# message_dialogs.py
# misc Gtk.MessageDialogs
#
# Copyright (C) 2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any l... |
raise RuntimeError("Unable to find glade file %s" % filename)
#------------------------------------------------------------------------------#
class WarningDialog(object):
""" Basic warning dialog
"""
def __init__(self, parent_window, msg):
builder = Gtk.Builder()
builder.add_from_... | return filepath | conditional_block |
message_dialogs.py | # -*- coding: utf-8 -*-
# message_dialogs.py
# misc Gtk.MessageDialogs
#
# Copyright (C) 2014 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any l... | (self, parent_window, title, msg, actions):
self.actions = actions
builder = Gtk.Builder()
builder.add_from_file(locate_ui_file('confirm_actions_dialog.ui'))
self.dialog = builder.get_object("confirm_actions_dialog")
self.dialog.set_transient_for(parent_window)
self.di... | __init__ | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-06 12:34
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.forms.widgets
class Migration(migrations.Migration):
| ('user_id', models.IntegerField()),
('user_name', models.CharField(max_length=20)),
('user_password', models.CharField(max_length=20, verbose_name=django.forms.widgets.PasswordInput)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE... | initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='RemoteServer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_na... | identifier_body |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-06 12:34
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.forms.widgets
class | (migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='RemoteServer',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True... | Migration | identifier_name |
0001_initial.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-06 12:34
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.forms.widgets
class Migration(migrations.Migration):
initial = True
depen... | ),
migrations.CreateModel(
name='UserData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user_id', models.IntegerField()),
('user_name', models.CharField(max_length=20... | ('date_added', models.DateField()),
], | random_line_split |
reporting_server.py | # Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from googleapiclient.discovery import build
from google.oauth2 import service_account
class RealTimeReportingServer():
SCOPES = ['https://www.... | for activity in activities:
for event in activity.get('events', []):
for parameter in event.get('parameters', []):
if parameter['name'] == 'DEVICE_ID' and \
parameter['value'] in deviceId:
containsEvent = True
break
return containsEvent | activities = results.get('items', []) | random_line_split |
reporting_server.py | # Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from googleapiclient.discovery import build
from google.oauth2 import service_account
class RealTimeReportingServer():
SCOPES = ['https://www.... |
return containsEvent
| containsEvent = True
break | conditional_block |
reporting_server.py | # Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from googleapiclient.discovery import build
from google.oauth2 import service_account
class RealTimeReportingServer():
SCOPES = ['https://www.... | (self, user_email):
"""Build and returns an Admin SDK Reports service object authorized with
the service accounts that act on behalf of the given user.
Args:
user_email: The email of the user. Needs permissions to access
the Admin APIs.
Returns:
Admin SDK reports service o... | create_reports_service | identifier_name |
reporting_server.py | # Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from googleapiclient.discovery import build
from google.oauth2 import service_account
class RealTimeReportingServer():
SCOPES = ['https://www.... |
def lookupevents(self, eventName, startTime, deviceId):
containsEvent = False
reportService = self.create_reports_service(self.USER_EMAIL)
results = reportService.activities().list(
userKey='all',
applicationName='chrome',
customerId='C029rpj4z',
eventName=eventName,
... | """Build and returns an Admin SDK Reports service object authorized with
the service accounts that act on behalf of the given user.
Args:
user_email: The email of the user. Needs permissions to access
the Admin APIs.
Returns:
Admin SDK reports service object.
"""
loc... | identifier_body |
notestoreid.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... |
}
| {
self.is_in_collection(&["notes"])
} | identifier_body |
notestoreid.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015, 2016 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the ... | (&self) -> bool {
self.is_in_collection(&["notes"])
}
}
| is_note_id | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.