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 |
|---|---|---|---|---|
uuid_key-test.js | var should = require('should')
var Store = require('../../../store/postgres')
describe('Postgres: UUID Key', function() {
var store
var database = 'uuid_key_test'
| this.timeout(5000)
beforePG(
database,
[
'CREATE EXTENSION IF NOT EXISTS \\"uuid-ossp\\"',
'CREATE TABLE uuid_tests (id uuid not null primary key default uuid_generate_v1(), another_column varchar(255))'
],
next
)
})
before(function() {
store = new Store({
... | before(function(next) { | random_line_split |
pass-by-copy.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 ... | {
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
} | identifier_body | |
pass-by-copy.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 ... | pub fn main() {
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
} | fn magic2(x: Gc<int>) { println!("{:?}", x); }
struct A { a: Gc<int> }
| random_line_split |
pass-by-copy.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 ... | (x: A) { println!("{:?}", x); }
fn magic2(x: Gc<int>) { println!("{:?}", x); }
struct A { a: Gc<int> }
pub fn main() {
let a = A {a: box(GC) 10};
let b = box(GC) 10;
magic(a); magic(A {a: box(GC) 20});
magic2(b); magic2(box(GC) 20);
}
| magic | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | (PythonPackage):
"""The Jupyter Notebook format"""
homepage = "https://github.com/jupyter/nbformat"
url = "https://github.com/jupyter/nbformat/archive/4.1.0.tar.gz"
version('4.1.0', '826b4fc4ec42553b20144f53b57b4e7b')
version('4.0.1', 'ab7172e517c9d561c0c01eef5631b4c8')
version('4.0.0', '... | PyNbformat | identifier_name |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
# | #
# For details, see https://github.com/spack/spack
# Please also see the NOTICE and LICENSE files for our notice and the LGPL.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (as
# published by the Free Software Foundation) version ... | # This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-647188 | random_line_split |
package.py | ##############################################################################
# Copyright (c) 2013-2018, Lawrence Livermore National Security, LLC.
# Produced at the Lawrence Livermore National Laboratory.
#
# This file is part of Spack.
# Created by Todd Gamblin, tgamblin@llnl.gov, All rights reserved.
# LLNL-CODE-64... | """The Jupyter Notebook format"""
homepage = "https://github.com/jupyter/nbformat"
url = "https://github.com/jupyter/nbformat/archive/4.1.0.tar.gz"
version('4.1.0', '826b4fc4ec42553b20144f53b57b4e7b')
version('4.0.1', 'ab7172e517c9d561c0c01eef5631b4c8')
version('4.0.0', '7cf61359fa4e9cf3ef5e9... | identifier_body | |
regions-early-bound-used-in-bound-method.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_eq!(b1.add(b1), 6);
} | random_line_split | |
regions-early-bound-used-in-bound-method.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 ... |
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
| {
*self.t + *g2.get()
} | identifier_body |
regions-early-bound-used-in-bound-method.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 ... | (&self) -> &'a isize {
self.t
}
}
impl<'a> Box<'a> {
fn add<'b,G:GetRef<'b>>(&self, g2: G) -> isize {
*self.t + *g2.get()
}
}
pub fn main() {
let b1 = Box { t: &3 };
assert_eq!(b1.add(b1), 6);
}
| get | identifier_name |
armv7_unknown_linux_musleabihf.rs | // Copyright 2016 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 ... | features: "+v7,+vfp3,+d16,+thumb2,-neon".to_string(),
cpu: "generic".to_string(),
max_atomic_width: Some(64),
abi_blacklist: super::arm_base::abi_blacklist(),
.. base
}
})
}
| {
let base = super::linux_musl_base::opts();
Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and LLVM
// doesn't support the "musleabihf" value.
llvm_target: "armv7-unknown-linux-gnueab... | identifier_body |
armv7_unknown_linux_musleabihf.rs | // Copyright 2016 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 ... | () -> TargetResult {
let base = super::linux_musl_base::opts();
Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and LLVM
// doesn't support the "musleabihf" value.
llvm_target: "armv7-u... | target | identifier_name |
armv7_unknown_linux_musleabihf.rs | // Copyright 2016 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 ... | Ok(Target {
// It's important we use "gnueabihf" and not "musleabihf" here. LLVM
// uses it to determine the calling convention and float ABI, and LLVM
// doesn't support the "musleabihf" value.
llvm_target: "armv7-unknown-linux-gnueabihf".to_string(),
target_endian: "little"... | let base = super::linux_musl_base::opts(); | random_line_split |
metadata.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... |
#[cfg(test)]
mod tests {
use ffi::mutable_data::metadata::mdata_encode_metadata;
use ffi_utils::test_utils::call_vec_u8;
use maidsafe_utilities::serialisation::deserialise;
use safe_core::ipc::resp::UserMetadata;
// Test serializing and deserializing metadata.
#[test]
fn serialize_metadat... | {
catch_unwind_cb(user_data, o_cb, || -> Result<_, AppError> {
let metadata = UserMetadata::clone_from_repr_c(metadata)?;
let encoded = serialise(&metadata)?;
o_cb(user_data, FFI_RESULT_OK, encoded.as_ptr(), encoded.len());
Ok(())
})
} | identifier_body |
metadata.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | } | } | random_line_split |
metadata.rs | // Copyright 2016 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License,
// version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which
// licence you accepted on initial access to the Software (the "Licences").
//
// By ... | () {
let metadata1 = UserMetadata {
name: None,
description: Some(String::from("test")),
};
let metadata_resp = match metadata1.clone().into_md_response(Default::default(), 0) {
Ok(val) => val,
_ => panic!("An error occurred"),
};
... | serialize_metadata | identifier_name |
step.rs | // step.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::fbm::FBM;
use noise::utils::step;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn | () {
let mut ngen = FBM::new_rand(24, 0.5, 2.5, 175.0);
let steps: &[f64] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0];
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(... | main | identifier_name |
step.rs | // step.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::fbm::FBM;
use noise::utils::step;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() | }
let end = precise_time_s();
let fout = File::create(&Path::new("step.png")).unwrap();
let _ = image::ImageLuma8(imbuf).save(fout, image::PNG);
println!("step.png saved");
println!("generated {} points in {} ms", img_size*img_size, (end-start)*1000.0);
} | {
let mut ngen = FBM::new_rand(24, 0.5, 2.5, 175.0);
let steps: &[f64] = [0.0, 0.2, 0.4, 0.6, 0.8, 1.0];
println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, ... | identifier_body |
step.rs | // step.rs
extern crate noise;
extern crate image;
extern crate time;
use noise::gen::NoiseGen;
use noise::gen::fbm::FBM;
use noise::utils::step;
use image::GenericImage;
use std::io::File;
use time::precise_time_s;
fn main() {
let mut ngen = FBM::new_rand(24, 0.5, 2.5, 175.0);
let steps: &[f64] = [0.0, 0.2,... | println!("Noise seed is {}", ngen.get_seed());
let img_size = 512 as u32;
let mut imbuf = image::ImageBuf::new(img_size, img_size);
let start = precise_time_s();
for x in range(0, img_size) {
for y in range(0, img_size) {
let xx = x as f64;
let yy = y as f64;
... | random_line_split | |
miss_vs_stall.py | #!/usr/bin/env python
import analyze_conf
import sys
import datetime, glob, job_stats, os, subprocess, time
import operator
import matplotlib
# Set the matplotlib output mode from config if it exists
if not 'matplotlib.pyplot' in sys.modules:
try:
matplotlib.use(analyze_conf.matplotlib_output_mode)
except NameE... | (file,mintime,wayness,lariat_dict):
retval=(None,None,None,None,None)
res=plot.get_data(file,mintime,wayness,lariat_dict)
if (res is None):
return retval
(ts, ld, tmid,
read_rate, write_rate, stall_rate, clock_rate, avx_rate, sse_rate, inst_rate,
meta_rate, l1_rate, l2_rate, l3_rate, load_rate, re... | do_work | identifier_name |
miss_vs_stall.py | #!/usr/bin/env python
import analyze_conf
import sys
import datetime, glob, job_stats, os, subprocess, time
import operator
import matplotlib
# Set the matplotlib output mode from config if it exists
if not 'matplotlib.pyplot' in sys.modules:
try:
matplotlib.use(analyze_conf.matplotlib_output_mode)
except NameE... | main() | conditional_block | |
miss_vs_stall.py | #!/usr/bin/env python
import analyze_conf
import sys
import datetime, glob, job_stats, os, subprocess, time
import operator
import matplotlib
# Set the matplotlib output mode from config if it exists
if not 'matplotlib.pyplot' in sys.modules:
try:
matplotlib.use(analyze_conf.matplotlib_output_mode)
except NameE... | if mean_mem_rate < 75.*1000000000./16.:
flag=True
return (scipy.stats.tmean(stall_frac),
scipy.stats.tmean((load_rate - (l1_rate))/load_rate),
scipy.stats.tmean(clock_rate/inst_rate),ename,
flag)
def main():
parser = argparse.ArgumentParser(description='Look for imbalance... | retval=(None,None,None,None,None)
res=plot.get_data(file,mintime,wayness,lariat_dict)
if (res is None):
return retval
(ts, ld, tmid,
read_rate, write_rate, stall_rate, clock_rate, avx_rate, sse_rate, inst_rate,
meta_rate, l1_rate, l2_rate, l3_rate, load_rate, read_frac, stall_frac) = res
# retur... | identifier_body |
miss_vs_stall.py | #!/usr/bin/env python
import analyze_conf
import sys
import datetime, glob, job_stats, os, subprocess, time
import operator
import matplotlib
# Set the matplotlib output mode from config if it exists
if not 'matplotlib.pyplot' in sys.modules:
try:
matplotlib.use(analyze_conf.matplotlib_output_mode)
except NameE... | labels.extend([l])
ax2.legend(handles,labels,bbox_to_anchor=(1.05, 1),
loc=2, borderaxespad=0., numpoints=1,ncol=4)
ax2.set_xlabel('Cycles per Execution Cycle')
ax2.set_ylabel('CPI')
fname='miss_v_stall_log'
fig1.savefig(fname)
fname='miss_v_stall'
fig2.savefig(fname)
plt.cl... | continue
else:
handles.extend([h]) | random_line_split |
ScreenMenu.ts | import GameEx = require("../../npfw/GameEx");
import ScreenEx = require("../../npfw/ScreenEx");
import Task = require("../../npfw/tasks/Task");
export class ScreenMenu extends ScreenEx.ScreenEx {
bg: any;
screensLoaded: boolean;
painted: boolean;
constructor(game: GameEx.GameEx) {
super(game)... |
public paint(delta: number): void {
console.log("ScreenMenu.BgTask.paint");
this.game.graphics.drawImage((<ScreenMenu>this.screen).bg, 0, 0);
(<ScreenMenu>this.screen).painted = true;
}
} | {
console.log("ScreenMenu.BgTask.constructor");
super(screen);
} | identifier_body |
ScreenMenu.ts | import GameEx = require("../../npfw/GameEx");
import ScreenEx = require("../../npfw/ScreenEx");
import Task = require("../../npfw/tasks/Task");
export class ScreenMenu extends ScreenEx.ScreenEx { |
bg: any;
screensLoaded: boolean;
painted: boolean;
constructor(game: GameEx.GameEx) {
super(game);
this.bg = new Image();
this.bg.src = "example/assets/main_menu.png";
this.screensLoaded = false;
this.painted = false;
}
public onStart(): void {
... | random_line_split | |
ScreenMenu.ts | import GameEx = require("../../npfw/GameEx");
import ScreenEx = require("../../npfw/ScreenEx");
import Task = require("../../npfw/tasks/Task");
export class | extends ScreenEx.ScreenEx {
bg: any;
screensLoaded: boolean;
painted: boolean;
constructor(game: GameEx.GameEx) {
super(game);
this.bg = new Image();
this.bg.src = "example/assets/main_menu.png";
this.screensLoaded = false;
this.painted = false;
}
publ... | ScreenMenu | identifier_name |
security.js | import jwt from 'jsonwebtoken'
import {COOKIE_NAMES} from '../../config/const'
export function loadUser (secret) {
return function (req, res, next) {
const userCookie = req.cookies[COOKIE_NAMES.auth]
req.user = null
if (userCookie) {
// verifies secret and checks exp
jwt.verify(userCookie, se... |
export function mustBeAuthenticated (req, res, next) {
if (req.baseUrl === '/authenticate') return next()
if (!req.user) return next({httpStatus: 401, message: 'Not authenticated'})
next()
}
| {
return function (req, res, next) {
if (req.method !== 'GET' || !forWriteOnly) {
if (req.user.roles.indexOf(role) === -1) return next({httpStatus: 403, message: 'Access denied'})
}
next()
}
} | identifier_body |
security.js | import jwt from 'jsonwebtoken'
import {COOKIE_NAMES} from '../../config/const'
export function loadUser (secret) {
return function (req, res, next) {
const userCookie = req.cookies[COOKIE_NAMES.auth]
req.user = null
if (userCookie) {
// verifies secret and checks exp
jwt.verify(userCookie, se... | if (!req.user) return next({httpStatus: 401, message: 'Not authenticated'})
next()
} | if (req.baseUrl === '/authenticate') return next() | random_line_split |
security.js | import jwt from 'jsonwebtoken'
import {COOKIE_NAMES} from '../../config/const'
export function loadUser (secret) {
return function (req, res, next) {
const userCookie = req.cookies[COOKIE_NAMES.auth]
req.user = null
if (userCookie) {
// verifies secret and checks exp
jwt.verify(userCookie, se... | (role, forWriteOnly = true) {
return function (req, res, next) {
if (req.method !== 'GET' || !forWriteOnly) {
if (req.user.roles.indexOf(role) === -1) return next({httpStatus: 403, message: 'Access denied'})
}
next()
}
}
export function mustBeAuthenticated (req, res, next) {
if (req.baseUr... | requiresRole | identifier_name |
sort_an_array_of_composites.rs | // http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
#[derive(Debug, PartialEq)]
pub struct Element {
name: String,
value: String,
}
impl Element {
fn new(name: &str, value: &str) -> Element {
Element {
name: name.to_string(),
value: value.to_string(),
... | Element::new("Cobalt", "Co"),
Element::new("Copper", "Cu"),
Element::new("Iron", "Fe"),
Element::new("Nickel", "Ni"),
Element::new("Zinc", "Zn"),
]);
}
} | ];
sort_by_name(&mut values);
assert_eq!(values,
vec![ | random_line_split |
sort_an_array_of_composites.rs | // http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
#[derive(Debug, PartialEq)]
pub struct Element {
name: String,
value: String,
}
impl Element {
fn new(name: &str, value: &str) -> Element {
Element {
name: name.to_string(),
value: value.to_string(),
... | () {
let mut values = vec![
Element::new("Iron", "Fe"),
Element::new("Cobalt", "Co"),
Element::new("Nickel", "Ni"),
Element::new("Copper", "Cu"),
Element::new("Zinc", "Zn"),
];
sort_by_name(&mut values);
println!("{:?}", values);
}
#[cfg(test)]
mod tests {
us... | main | identifier_name |
route_definition.ts | import {CONST, Type} from 'angular2/src/facade/lang';
import {RegexSerializer} from './rules/route_paths/regex_route_path';
/** | * - `component`, `loader`, `redirectTo` (requires exactly one of these)
* - `name` or `as` (optional) (requires exactly one of these)
* - `data` (optional)
*
* See also {@link Route}, {@link AsyncRoute}, {@link AuxRoute}, and {@link Redirect}.
*/
export interface RouteDefinition {
path?: string;
aux?: string... | * `RouteDefinition` defines a route within a {@link RouteConfig} decorator.
*
* Supported keys:
* - `path` or `aux` (requires exactly one of these) | random_line_split |
pkcs12.py | #
# PKCS#12 syntax
#
# ASN.1 source from:
# ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12.asn
#
# Sample captures could be obtained with "openssl pkcs12" command
#
from pyasn1_modules.rfc2459 import *
from pyasn1_modules import rfc2251
class Attributes(univ.SetOf):
|
class Version(univ.Integer): pass
class CertificationRequestInfo(univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('version', Version()),
namedtype.NamedType('subject', Name()),
namedtype.NamedType('subjectPublicKeyInfo', SubjectPublicKeyInfo()),
namedtyp... | componentType = rfc2251.Attribute() | identifier_body |
pkcs12.py | #
# PKCS#12 syntax
#
# ASN.1 source from:
# ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12.asn
#
# Sample captures could be obtained with "openssl pkcs12" command
#
from pyasn1_modules.rfc2459 import *
from pyasn1_modules import rfc2251
class Attributes(univ.SetOf):
componentType = rfc2251.Attribute()
class... | (univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('version', Version()),
namedtype.NamedType('subject', Name()),
namedtype.NamedType('subjectPublicKeyInfo', SubjectPublicKeyInfo()),
namedtype.NamedType('attributes',
Attributes().su... | CertificationRequestInfo | identifier_name |
pkcs12.py | # ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12.asn
#
# Sample captures could be obtained with "openssl pkcs12" command
#
from pyasn1_modules.rfc2459 import *
from pyasn1_modules import rfc2251
class Attributes(univ.SetOf):
componentType = rfc2251.Attribute()
class Version(univ.Integer): pass
class Certi... | #
# PKCS#12 syntax
#
# ASN.1 source from: | random_line_split | |
testclient.py | #!/usr/bin/python
import socket
import sys
HOST, PORT = "24.21.106.140", 8080
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
print "Connected to ", HOST, ":", PORT, "\n","Awaiting input\n"
data = sys.stdi... | data = sys.stdin.readline()
# Receive data from the server and shut down
finally:
sock.close() | exit = True
received = sock.recv(1024)
print "Sent: " , data
print "Received: " , received | random_line_split |
testclient.py | #!/usr/bin/python
import socket
import sys
HOST, PORT = "24.21.106.140", 8080
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
print "Connected to ", HOST, ":", PORT, "\n","Awaiting input\n"
data = sys.stdi... |
# Receive data from the server and shut down
finally:
sock.close()
| sock.sendall(data + "\n")
if data.strip() == 'bye':
exit = True
received = sock.recv(1024)
print "Sent: " , data
print "Received: " , received
data = sys.stdin.readline() | conditional_block |
rgb_depth_exclusion.py | import cv2
import os
import scipy.misc as misc
path = os.getcwd()
for x in xrange(15):
| resized_median = cv2.resize(median, (depth_adjusted[1], depth_adjusted[0]), interpolation = cv2.INTER_AREA)
and_result = cv2.bitwise_and(rgb_cropped,rgb_cropped,mask=resized_median)
cv2.imshow('and', and_result)
cv2.imwrite(path +'/output/rgb_depth_adjusted_' + str(x) + '.jpg', rgb_cropped )
| rgb = cv2.imread(path + '/output/rgb_img_' + str(x) + '.jpg')
depth = cv2.imread(path + '/output/depth_img_' + str(x) + '.jpg')
depth_inquiry = depth.copy()
# depth_inquiry[depth_inquiry > 180] = 0
# Depth threshold test - gets rid of near
depth_inquiry[depth_inquiry < 50] = 0
# depth_inquiry[... | conditional_block |
rgb_depth_exclusion.py | import cv2
import os
import scipy.misc as misc
path = os.getcwd()
for x in xrange(15):
rgb = cv2.imread(path + '/output/rgb_img_' + str(x) + '.jpg')
depth = cv2.imread(path + '/output/depth_img_' + str(x) + '.jpg')
depth_inquiry = depth.copy()
# depth_inquiry[depth_inquiry > 180] = 0
# Depth thresh... |
resized_median = cv2.resize(median, (depth_adjusted[1], depth_adjusted[0]), interpolation = cv2.INTER_AREA)
and_result = cv2.bitwise_and(rgb_cropped,rgb_cropped,mask=resized_median)
cv2.imshow('and', and_result)
cv2.imwrite(path +'/output/rgb_depth_adjusted_' + str(x) + '.jpg', rgb_cropped ) |
depth_params = (424, 512)
rgb_params = (1080, 1920)
depth_adjusted = (rgb_params[0], depth_params[1]*rgb_params[0]/depth_params[0])
rgb_cropped = rgb[:, rgb_params[1]/2-depth_adjusted[1]/2:rgb_params[1]/2+depth_adjusted[1]/2] | random_line_split |
get_ready.py | #!/usr/bin/env python
"""Robobonobo setup script.
Usage:
./get_ready.py [options]
Options:
-h, --help Show this help screen
--version Show the version.
"""
from docopt import docopt
from glob import glob
import os
GPIOS = [30, 31, 112, 113, 65, 27]
GPIO_BASE = "/sys/class/gpio"
SLOTS_GLOB = "/s... | (filename, msg, pindir=""):
with open(os.path.join(GPIO_BASE, pindir, filename), mode="w+") as ex:
ex.write(msg)
def setup_gpio(pin):
write_gpio("export", pin)
pindir = "gpio" + pin
write_gpio("direction", "out", pindir)
write_gpio("value", "0", pindir)
def setup_dto():
for match in ... | write_gpio | identifier_name |
get_ready.py | #!/usr/bin/env python
"""Robobonobo setup script.
Usage:
./get_ready.py [options]
Options:
-h, --help Show this help screen
--version Show the version.
"""
from docopt import docopt
from glob import glob
import os
GPIOS = [30, 31, 112, 113, 65, 27]
GPIO_BASE = "/sys/class/gpio"
SLOTS_GLOB = "/s... |
def setup_dto():
for match in glob(SLOTS_GLOB):
with open(match, mode="w+") as slots:
slots.write("robobonobo")
def main():
for gpio in GPIOS:
setup_gpio(str(gpio))
setup_dto()
if __name__ == "__main__":
args = docopt(__doc__, version="Robobonobo setup script v1")
... | write_gpio("export", pin)
pindir = "gpio" + pin
write_gpio("direction", "out", pindir)
write_gpio("value", "0", pindir) | identifier_body |
get_ready.py | #!/usr/bin/env python
"""Robobonobo setup script.
Usage:
./get_ready.py [options]
Options:
-h, --help Show this help screen
--version Show the version.
"""
from docopt import docopt
from glob import glob
import os
GPIOS = [30, 31, 112, 113, 65, 27]
GPIO_BASE = "/sys/class/gpio"
SLOTS_GLOB = "/s... | args = docopt(__doc__, version="Robobonobo setup script v1")
main() | conditional_block | |
get_ready.py | #!/usr/bin/env python
"""Robobonobo setup script.
Usage:
./get_ready.py [options]
Options:
-h, --help Show this help screen
--version Show the version.
"""
from docopt import docopt
from glob import glob
import os
GPIOS = [30, 31, 112, 113, 65, 27]
GPIO_BASE = "/sys/class/gpio"
SLOTS_GLOB = "/s... | args = docopt(__doc__, version="Robobonobo setup script v1")
main() | setup_dto()
if __name__ == "__main__": | random_line_split |
AppNavBtn.tsx | /*!
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | import type { IconType } from 'react-icons/lib';
interface Props {
navItem: {
label: string;
icon: IconType | typeof Icon;
path?: string;
activePath?: string;
href?: string;
};
}
const AppNavBtn: React.FC<Props> = ({ navItem }) => {
const location = useLocation();
const {
label, icon, ... | Box,
Icon,
Tooltip,
} from '@chakra-ui/react';
| random_line_split |
ionize_tree.js | ION.SimpleTree = new Class({
Implements: [Events, Options],
options:
{
'key': 'id',
'label': null,
'data' : [] // field of each item to add as data-x attribute
},
/**
*
* @param container
* @param items JSON object
* @param options object
*
*/
initialize:function(container, items,... | {
cb_name: 'rules[]',
onCheck: null
},
initialize:function(container, items, options)
{
// console.log(options);
this.parent(container, items, options);
this.rules = this.get_rules_array();
if (typeOf(options.onCheck) != 'null')
this.options.onCheck = options.onCheck;
this.enhanceTree();
},
... | ION.PermissionTree = new Class({
Extends: ION.SimpleTree,
options: | random_line_split |
ionize_tree.js | ION.SimpleTree = new Class({
Implements: [Events, Options],
options:
{
'key': 'id',
'label': null,
'data' : [] // field of each item to add as data-x attribute
},
/**
*
* @param container
* @param items JSON object
* @param options object
*
*/
initialize:function(container, items,... |
// Get LI children to add "partial rights" if some aren't checked
var cb = li.getElement('input[type=checkbox]');
if (cb.getProperty('checked') == true)
{
var cbs = li.getElements('input[type=checkbox]');
var partial = false;
cbs.each(function(cb)
{
if (partial == false)
{
i... | {
var pm = li.getElement('div.plus');
if (pm)
{
new Element('div', {'class':'tree-img line node'}).inject(pm, 'before');
pm.destroy();
}
} | conditional_block |
adapter.rs | extern crate dotalittlehelper;
use dotalittlehelper::*;
#[test]
fn read_json_configuration() {
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"},
"entity_type": "Hero",
"attributes": [{
"identity": {"id": "test_attr", "name": ... | {
let json_str = r#"{
"entitties": [{
"what": "is this"
}]
}"#;
let test_entities = adapter::read_json_configuration(json_str);
assert_eq!(0, test_entities.len());
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"}
... | identifier_body | |
adapter.rs | extern crate dotalittlehelper;
use dotalittlehelper::*;
#[test]
fn read_json_configuration() {
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"},
"entity_type": "Hero",
"attributes": [{
"identity": {"id": "test_attr", "name": ... | String::from("test_attr"), String::from("Test Attr")
),
9001
)
)
);
assert_eq!(real_entity, test_entity);
}
#[test]
#[should_panic]
fn read_json_configuration_fail() {
let json_str = r#"{
"entitties": [{
"what": "is... | entity::Attribute::new(
entity::Identity::new( | random_line_split |
adapter.rs | extern crate dotalittlehelper;
use dotalittlehelper::*;
#[test]
fn | () {
let json_str = r#"{
"entities": [{
"identity": {"id": "test", "name": "Test"},
"entity_type": "Hero",
"attributes": [{
"identity": {"id": "test_attr", "name": "Test Attr"},
"value": 9001
}]
}]
}"#;
let test_... | read_json_configuration | identifier_name |
43df309dbf3f_extend_base_image_id_to_100_chars.py | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... | op.alter_column('image', 'base_image_id',
type_=sa.String(length=36),
existing_type=sa.String(length=100),
existing_nullable=True,
) | identifier_body | |
43df309dbf3f_extend_base_image_id_to_100_chars.py | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... | ():
op.alter_column('image', 'base_image_id',
type_=sa.String(length=36),
existing_type=sa.String(length=100),
existing_nullable=True,
)
| downgrade | identifier_name |
43df309dbf3f_extend_base_image_id_to_100_chars.py | #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under ... |
def upgrade():
op.alter_column('image', 'base_image_id',
type_=sa.String(length=100),
existing_type=sa.String(length=36),
existing_nullable=True,
)
def downgrade():
op.alter_column('image', 'base_image_id',
ty... | random_line_split | |
FilterCollapse.tsx | import React from 'react';
import { $rootScope } from 'ngimport';
import { ReactInjector } from 'core/reactShims';
import { Tooltip } from 'core/presentation';
import './FilterCollapse.less';
| };
public render() {
const { filtersExpanded } = ReactInjector.insightFilterStateModel;
return (
<div className="filters-toggle layer-medium">
{!filtersExpanded && (
<div className="filters-placeholder filters-hidden">
<Tooltip value="Show filters">
<butto... | export class FilterCollapse extends React.Component<{}> {
private onClick = (pin: boolean) => {
ReactInjector.insightFilterStateModel.pinFilters(pin);
$rootScope.$apply(); // insight layout needs to change
this.setState({}); // force re-render since we are using insight filter state model to show the coll... | random_line_split |
attributes.rs | use model;
type Attribute = model::Attribute;
type Param = model::Parameter; | attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_present("param1"));
assert!(!t.is_param_present("param2"));
}
#[test]
fn test_is_param_value... |
#[test]
fn test_is_param_present() {
let mut t = Attribute {
name:String::new(), | random_line_split |
attributes.rs | use model;
type Attribute = model::Attribute;
type Param = model::Parameter;
#[test]
fn test_is_param_present() {
let mut t = Attribute {
name:String::new(),
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".... | {
let mut t = Attribute {
name:String::new(),
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_value_present("param1", "param1val"));
as... | identifier_body | |
attributes.rs | use model;
type Attribute = model::Attribute;
type Param = model::Parameter;
#[test]
fn | () {
let mut t = Attribute {
name:String::new(),
attribute_type:String::new(),
is_array:false,
params:Vec::new(),
};
let p = Param {
name:"param1".to_string(),
value:"param1val".to_string(),
};
t.params.push(Box::new(p));
assert!(t.is_param_present("param1"));
assert!(!t.is_para... | test_is_param_present | identifier_name |
closure-in-generic-function.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT. | // except according to those terms.
// xfail-android: FIXME(#10381)
// compile-flags:-Z extra-debug-info
// debugger:rbreak zzz
// debugger:run
// debugger:finish
// debugger:print x
// check:$1 = 0.5
// debugger:print y
// check:$2 = 10
// debugger:continue
// debugger:finish
// debugger:print *x
// check:$3 = 29
... | //
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed | random_line_split |
closure-in-generic-function.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <T1, T2>(a: T1, b: T2) -> (T2, T1) {
let closure = |x, y| {
zzz();
(y, x)
};
closure(a, b)
}
fn main() {
some_generic_fun(0.5, 10);
some_generic_fun(&29, ~110);
}
fn zzz() {()}
| some_generic_fun | identifier_name |
closure-in-generic-function.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn main() {
some_generic_fun(0.5, 10);
some_generic_fun(&29, ~110);
}
fn zzz() {()}
| {
let closure = |x, y| {
zzz();
(y, x)
};
closure(a, b)
} | identifier_body |
helper-click-tags.js | jQuery(document).ready(function() {
// Display initial link
jQuery("#st-clicks-tags .inside").html('<a href="#st_click_tags" id="open_clicktags">'+stHelperClickTagsL10n.show_txt+'</a><a href="#st_click_tags" id="close_clicktags">'+stHelperClickTagsL10n.hide_txt+'</a><div class="container_clicktags"></div>');
// ... | });
// Hide click tags
jQuery("#close_clicktags").click(function(event) {
event.preventDefault();
jQuery("#st-clicks-tags .container_clicktags").fadeOut('slow', function() {
jQuery("#open_clicktags").show();
jQuery("#close_clicktags").hide();
});
return false;
});
}); | return false; | random_line_split |
plot_roc.py | """
=======================================
Receiver Operating Characteristic (ROC)
=======================================
Example of Receiver Operating Characteristic (ROC) metric to evaluate
classifier output quality.
ROC curves typically feature true positive rate on the Y axis, and false
positive rate on the X a... | plt.plot(fpr["micro"], tpr["micro"],
label='micro-average ROC curve (area = {0:0.2f})'
''.format(roc_auc["micro"]))
for i in range(n_classes):
plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i]))
plt.plot([0, ... | plt.show()
# Plot ROC curve
plt.figure() | random_line_split |
plot_roc.py | """
=======================================
Receiver Operating Characteristic (ROC)
=======================================
Example of Receiver Operating Characteristic (ROC) metric to evaluate
classifier output quality.
ROC curves typically feature true positive rate on the Y axis, and false
positive rate on the X a... |
plt.plot([0, 1], [0, 1], 'k--')
plt.xlim([0.0, 1.0])
plt.ylim([0.0, 1.05])
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title('Some extension of Receiver operating characteristic to multi-class')
plt.legend(loc="lower right")
plt.show()
| plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'
''.format(i, roc_auc[i])) | conditional_block |
glue.dom.js | (function(win, doc, glue) {
'use strict';
function setStyles(collection, name, value) {
collection.each(function(element) {
element.style[name] = value;
});
}
function | (element, property) {
var propertyValue, re = /(\-([a-z]){1})/g;
// Support both camelCase and dashed property names
property = property.replace(/([A-Z])/g, '-glue1').toLowerCase();
/* istanbul ignore else */
if (win.getComputedStyle /* && !glue.isTest*/) {
propertyValue = win.getComputedSty... | getStyle | identifier_name |
glue.dom.js | (function(win, doc, glue) {
'use strict';
function setStyles(collection, name, value) {
collection.each(function(element) {
element.style[name] = value;
});
}
function getStyle(element, property) {
var propertyValue, re = /(\-([a-z]){1})/g;
// Support both camelCase and dashed property ... |
function append(context, elementString){
var domObject = glue.parseHTML(elementString);
context[0].appendChild(domObject);
return context;
}
function prepend(context, elementString){
var domObject = glue.parseHTML(elementString),
parent = context[0];
parent.insertBefore(domObject, pare... | {
if (!value) {
return context[0].getAttribute(name);
} else {
context[0].setAttribute(name, value);
return context;
}
} | identifier_body |
glue.dom.js | (function(win, doc, glue) {
'use strict';
function setStyles(collection, name, value) {
collection.each(function(element) {
element.style[name] = value;
});
}
function getStyle(element, property) {
var propertyValue, re = /(\-([a-z]){1})/g;
// Support both camelCase and dashed property ... | context[0].appendChild(domObject);
return context;
}
function prepend(context, elementString){
var domObject = glue.parseHTML(elementString),
parent = context[0];
parent.insertBefore(domObject, parent.firstChild);
return context;
}
function remove(context) {
context.each(function()... | function append(context, elementString){
var domObject = glue.parseHTML(elementString); | random_line_split |
glue.dom.js | (function(win, doc, glue) {
'use strict';
function setStyles(collection, name, value) {
collection.each(function(element) {
element.style[name] = value;
});
}
function getStyle(element, property) {
var propertyValue, re = /(\-([a-z]){1})/g;
// Support both camelCase and dashed property ... | else {
if (context.css(display) === none) {
context.css(display, 'block');
} else {
context.css(display, none);
}
return context;
}
}
function attr(context, name, value) {
if (!value) {
return context[0].getAttribute(name);
} else {
context[0].... | {
context.css(display, status);
return context;
} | conditional_block |
token.rs | // This program is subject to the terms of the GNU General Public
// License, version 2.0. If a copy of the GPL was not distributed with
// this program, You can obtain one at http://gnu.org.
use std::fmt::{Debug, Write};
use interner::{Interned};
use span::{Spanned};
/// A token with a span.
pub type SToken = Spann... | (self) -> bool {
match self {
Token::StringPart(..) => true,
Token::String(..) => true,
Token::Integer(..) => true,
Token::Ident(..) => true,
Token::True => true,
Token::False => true,
Token::Null ... | starts_expr | identifier_name |
token.rs | // This program is subject to the terms of the GNU General Public
// License, version 2.0. If a copy of the GPL was not distributed with
// this program, You can obtain one at http://gnu.org.
use std::fmt::{Debug, Write};
use interner::{Interned};
use span::{Spanned};
/// A token with a span.
pub type SToken = Spann... | Token::Concat => false,
Token::Plus => false,
Token::Times => false,
Token::Div => false,
Token::Mod => false,
Token::Overlay => false,
Token::AndAnd => false,
Token::OrOr ... | Token::Unequal => false,
Token::Lt => false,
Token::Le => false,
Token::Gt => false,
Token::Ge => false, | random_line_split |
into_searcher.rs | #![feature(core)] | mod tests {
use core::str::pattern::Searcher;
use core::str::pattern::SearchStep::{Match, Reject, Done};
use core::str::pattern::StrSearcher;
use core::str::pattern::Pattern;
// #[derive(Copy, Clone, Eq, PartialEq, Debug)]
// pub enum SearchStep {
// /// Expresses that a match of the pa... | extern crate core;
#[cfg(test)] | random_line_split |
into_searcher.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::str::pattern::Searcher;
use core::str::pattern::SearchStep::{Match, Reject, Done};
use core::str::pattern::StrSearcher;
use core::str::pattern::Pattern;
// #[derive(Copy, Clone, Eq, PartialEq, Debug)]
// pub enum SearchSte... | {
let string: &str = "玻璃";
let string_ptr: &&str = &string;
let haystack: &str = "我能吞下玻璃而不傷身體。";
let mut searcher: StrSearcher = string_ptr.into_searcher(haystack);
assert_eq!(searcher.next(), Reject(0, 3));
assert_eq!(searcher.next(), Reject(3, 6));
assert_eq!(searcher.next(), Reject(6, 9));
assert_eq!(search... | identifier_body | |
into_searcher.rs | #![feature(core)]
extern crate core;
#[cfg(test)]
mod tests {
use core::str::pattern::Searcher;
use core::str::pattern::SearchStep::{Match, Reject, Done};
use core::str::pattern::StrSearcher;
use core::str::pattern::Pattern;
// #[derive(Copy, Clone, Eq, PartialEq, Debug)]
// pub enum SearchSte... | () {
let string: &str = "玻璃";
let string_ptr: &&str = &string;
let haystack: &str = "我能吞下玻璃而不傷身體。";
let mut searcher: StrSearcher = string_ptr.into_searcher(haystack);
assert_eq!(searcher.next(), Reject(0, 3));
assert_eq!(searcher.next(), Reject(3, 6));
assert_eq!(searcher.next(), Reject(6, 9));
assert_eq!(sea... | into_searcher_test1 | identifier_name |
api-actions.js | /**
* @overview
* API handler action creator
* Takes a key-value -pair representing the event to handle as key and its respective
* handler function as the value.
*
* Event-to-URL mapping is done in {@link ApiEventPaths}.
*
* @since 0.2.0
* @version 0.3.0
*/
import { Seq, Map } from 'immutable';
import { ... | * @since 0.2.0
*/
export const handlers = Seq.Keyed(ApiEventPaths)
.flatMap((path, event) =>
Map.of(event, new Internal.ApiHandler({ path, event, handler: apiHandlerFns[event] })));
/**
* A non-`Seq` version of the @see findEventSeq function.
* @param {string... | * @type {Immutable.Iterable<any, any>} | random_line_split |
smart-patcher.py | #!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf (imran@smartitengineering.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pu... |
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
self.slotted = slotted
def get_message(self):
return self.emailMessage
de... | self.node = node | identifier_body |
smart-patcher.py | #!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf (imran@smartitengineering.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pu... | nextNode = handleNode(referenceNode, nextNode, referenceIdsClone, patchMessageReferenceNode)
if __name__ == "__main__":
arguments = sys.argv
verbose = "false"
pseudoArgs = arguments[:]
while len(pseudoArgs) > 1 :
argument = pseudoArgs[1]
if argument == "-v" or argument =... | random_line_split | |
smart-patcher.py | #!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf (imran@smartitengineering.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pu... |
msg = email.message_from_string(totalContent)
if 'subject' in msg :
subject = msg['subject']
subjectPattern = "^\[.*PATCH.*\].+"
subjectMatch = re.match(subjectPattern, subject)
utils.verboseOutput(verbose, "Checking subject: ", su... | totalContent += content + '\n' | conditional_block |
smart-patcher.py | #!/usr/bin/python
# This programs is intended to manage patches and apply them automatically
# through email in an automated fashion.
#
# Copyright (C) 2008 Imran M Yousuf (imran@smartitengineering.com)
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Pu... | (self):
return self.children
def set_node(self, node):
self.node = node
def set_children(self, children):
self.children = children
def get_references(self):
return self.references
def is_slotted(self):
return self.slotted
def set_slotted(self, slotted):
... | get_children | identifier_name |
jobs_options.ts | import UserConfig from '../../resources/user_config';
import { BaseOptions } from '../../types/data';
import { Job } from '../../types/job';
import { BuffInfo } from './buff_tracker';
export interface JobsNonConfigOptions {
JustBuffTracker: boolean;
LowerOpacityOutOfCombat: boolean;
OpacityOutOfCombat: number;
... | // One more fire IV and then despair.
BlmMediumMPThreshold: 3999,
// Should cast despair.
BlmLowMPThreshold: 2399,
};
export interface JobsOptions extends BaseOptions, JobsConfigOptions, JobsNonConfigOptions {}
const Options: JobsOptions = {
...UserConfig.getDefaultBaseOptions(),
...defaultJobsNonConfigOp... | FarThresholdOffence: 24,
PldMediumMPThreshold: 9400,
PldLowMPThreshold: 3600,
DrkMediumMPThreshold: 5999,
DrkLowMPThreshold: 2999, | random_line_split |
formatters.py | #!/usr/bin/env python
import logging
# CUSTOM LOG LEVELS
LOG_LEVEL_TOOL = 25
# Terminal colors
TERMINAL_COLOR_BLUE = '\033[94m'
TERMINAL_COLOR_GREEN = '\033[92m'
TERMINAL_COLOR_YELLOW = '\033[93m'
TERMINAL_COLOR_RED = '\033[91m'
TERMINAL_COLOR_END = '\033[0m'
class ConsoleFormatter(logging.Formatter):
"""
C... | (logging.Formatter):
"""
Custom formatter for log files
"""
def __init__(self, *args, **kwargs):
super(FileFormatter, self).__init__()
self._fmt = "[%(levelname)s] [%(asctime)s] " + "[File '%(filename)s', line %(lineno)s, in %(funcName)s] -" + \
" %(message)s"
| FileFormatter | identifier_name |
formatters.py | #!/usr/bin/env python
import logging
# CUSTOM LOG LEVELS
LOG_LEVEL_TOOL = 25
# Terminal colors
TERMINAL_COLOR_BLUE = '\033[94m'
TERMINAL_COLOR_GREEN = '\033[92m'
TERMINAL_COLOR_YELLOW = '\033[93m'
TERMINAL_COLOR_RED = '\033[91m'
TERMINAL_COLOR_END = '\033[0m'
class ConsoleFormatter(logging.Formatter):
"""
C... |
# Call the original formatter class to do the grunt work
result = super(ConsoleFormatter, self).format(record)
# Restore the original format configured by the user
self._fmt = format_orig
return result
class FileFormatter(logging.Formatter):
"""
Custom formatter for... | self._fmt = self.warn_fmt | conditional_block |
formatters.py | #!/usr/bin/env python
import logging
# CUSTOM LOG LEVELS
LOG_LEVEL_TOOL = 25
# Terminal colors
TERMINAL_COLOR_BLUE = '\033[94m'
TERMINAL_COLOR_GREEN = '\033[92m'
TERMINAL_COLOR_YELLOW = '\033[93m'
TERMINAL_COLOR_RED = '\033[91m'
TERMINAL_COLOR_END = '\033[0m'
class ConsoleFormatter(logging.Formatter):
"""
C... | super(FileFormatter, self).__init__()
self._fmt = "[%(levelname)s] [%(asctime)s] " + "[File '%(filename)s', line %(lineno)s, in %(funcName)s] -" + \
" %(message)s" | identifier_body | |
formatters.py | #!/usr/bin/env python
import logging
# CUSTOM LOG LEVELS
LOG_LEVEL_TOOL = 25
# Terminal colors
TERMINAL_COLOR_BLUE = '\033[94m'
TERMINAL_COLOR_GREEN = '\033[92m'
TERMINAL_COLOR_YELLOW = '\033[93m'
TERMINAL_COLOR_RED = '\033[91m'
TERMINAL_COLOR_END = '\033[0m'
class ConsoleFormatter(logging.Formatter):
"""
C... | super(FileFormatter, self).__init__()
self._fmt = "[%(levelname)s] [%(asctime)s] " + "[File '%(filename)s', line %(lineno)s, in %(funcName)s] -" + \
" %(message)s" | """
def __init__(self, *args, **kwargs): | random_line_split |
hard-tabs.rs | // rustfmt-wrap_comments: true
// rustfmt-hard_tabs: true
fn main() {
let x = Bar;
let y = Foo { a: x };
Foo {
a: foo(), // comment
// comment
b: bar(),
..something
};
fn foo(a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
... | * comment */ {
}
unsafe /* So this is a very long comment.
* Multi-line, too.
* Will it still format correctly? */ {
}
let chain = funktion_kall()
.go_to_next_line_with_tab()
.go_to_next_line_with_tab()
.go_to_next_line_with_tab();
let z = [xx... | }
unsafe /* very looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong | random_line_split |
hard-tabs.rs | // rustfmt-wrap_comments: true
// rustfmt-hard_tabs: true
fn main() | a: i32,
a: i32,
a: i32) {
}
let str = "AAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAaAa";
if let (some_very_large,
tuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuple) = 1 + 2 + 3 {
}
if cond() {
something();
... | {
let x = Bar;
let y = Foo { a: x };
Foo {
a: foo(), // comment
// comment
b: bar(),
..something
};
fn foo(a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32, | identifier_body |
hard-tabs.rs | // rustfmt-wrap_comments: true
// rustfmt-hard_tabs: true
fn | () {
let x = Bar;
let y = Foo { a: x };
Foo {
a: foo(), // comment
// comment
b: bar(),
..something
};
fn foo(a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32,
a: i32) {
}
let str = "AAAAAAAA... | main | identifier_name |
vmstate-static-checker.py | 'parent_obj.parent_obj.parent_obj',
'port.br.dev.exp.aer_log',
'parent_obj.parent_obj.parent_obj.exp.aer_log'],
'mch': ['d', 'parent_obj'],
'pci_bridge': ['bridge.dev', 'parent_obj', 'bridge.dev... | check_machine_type | identifier_name | |
vmstate-static-checker.py | taint = taint + 1
def check_fields_match(name, s_field, d_field):
if s_field == d_field:
return True
# Some fields changed names between qemu versions. This list
# is used to whitelist such changes in each section / description.
changed_names = {
'e1000': ['dev', 'parent_obj'],
... | if f == 'Subsections':
check_subsections(src_desc[f], dest_desc[f], src_desc["name"], sec)
def check_version(s, d, sec, desc=None):
if s["version_id"] > d["version_id"]:
print "Section \"" + sec + "\"",
if desc:
print "Description \"" + desc + "\":",
print ... | check_version(src_desc, dest_desc, sec, src_desc["name"])
if not check_fields_match(sec, src_desc["name"], dest_desc["name"]):
print "Section \"" + sec + "\":",
print "Description \"" + src_desc["name"] + "\"",
print "missing, got \"" + dest_desc["name"] + "\" instead; skipping"
bum... | identifier_body |
vmstate-static-checker.py | taint = taint + 1
def check_fields_match(name, s_field, d_field):
if s_field == d_field:
return True
# Some fields changed names between qemu versions. This list
# is used to whitelist such changes in each section / description.
changed_names = {
'e1000': ['dev', 'parent_obj'],
... |
check_descriptions(s_item["Description"], d_item["Description"], sec)
def check_descriptions(src_desc, dest_desc, sec):
check_version(src_desc, dest_desc, sec, src_desc["name"])
if not check_fields_match(sec, src_desc["name"], dest_desc["name"]):
print "Section \"" + sec + "\":",
print ... | print "Section \"" + sec + "\", Description \"" + desc + "\",",
print "Field \"" + s_item["field"] + "\": missing description"
bump_taint()
return | conditional_block |
vmstate-static-checker.py | taint = taint + 1
def check_fields_match(name, s_field, d_field):
if s_field == d_field:
return True
# Some fields changed names between qemu versions. This list
# is used to whitelist such changes in each section / description.
changed_names = {
'e1000': ['dev', 'parent_obj'],
... | if exists_in_substruct(d_item, s_item["field"]):
# listiterators don't have a prev() function, so we
# have to store our current location, descend into the
# substruct, and ensure we come out as if nothing
# happened when the substruct is over.... | # on-wire format the same, but breaking static tools
# like this one.
# First, check if dest has a new substruct. | random_line_split |
Icon.stories.js | import React from 'react';
import Icon from '@ichef/gypcrete/src/Icon';
import iconMap from '@ichef/gypcrete/src/icons/components';
export default {
title: '@ichef/gypcrete|Icon',
component: Icon,
};
export function BasicUsage() {
/**
* Show all icons, ordering from a to z.
*/
return (
<>
... | {
return (
<div>
<Icon type="cash" />
<Icon type="credit-card" />
<Icon type="ctbc-direct" />
<Icon type="ctbc-mpos" />
<Icon type="custom-pay" />
</div>
);
} | identifier_body | |
Icon.stories.js | import React from 'react';
import Icon from '@ichef/gypcrete/src/Icon';
import iconMap from '@ichef/gypcrete/src/icons/components';
export default {
title: '@ichef/gypcrete|Icon',
component: Icon,
};
export function BasicUsage() {
/**
* Show all icons, ordering from a to z.
*/
return (
<>
... | };
export function InventoryIconsSet() {
return (
<div>
<Icon type="inventory-category" />
<Icon type="inventory-item" />
</div>
);
}
export function LargeSizeOptions() {
return (
<div>
<Icon type="loading" large spinning />
<Icon type="success" large color="blue" />
<I... | random_line_split | |
Icon.stories.js | import React from 'react';
import Icon from '@ichef/gypcrete/src/Icon';
import iconMap from '@ichef/gypcrete/src/icons/components';
export default {
title: '@ichef/gypcrete|Icon',
component: Icon,
};
export function BasicUsage() {
/**
* Show all icons, ordering from a to z.
*/
return (
<>
... | () {
return (
<div>
<Icon type="add-item" />
<Icon type="add-multi-items" />
<Icon type="clear-item" />
</div>
);
}
export function PaginationIconsSet() {
return (
<div>
<Icon type="first-page" />
<Icon type="prev-page" />
<Icon type="next-page" />
<Icon type... | MenuPageIconsSet | identifier_name |
svn.py | True for now.
if utils.is_url(package_dir):
return True
# TODO: Allow specifying a git URL to build from.
pwd = os.getcwd()
try:
try:
os.chdir(package_dir)
except OSError as ose:
if ose.errno == errno.ENOENT:
raise Error("%s is not a valid... | # names, one containing the restricted SVN branches and one containing the
# restricted Koji targets.
#
# We're permissive by default: if neither the branch nor the target match any
# of the regexps in their respective dicts, the build is allowed. On the other
# hand, if both are restricted then the branch name has to ... | # We need to forbid building from certain SVN branches into certain Koji
# targets. This is implemented by having two dicts mapping regexp patterns to | random_line_split |
svn.py | for now.
if utils.is_url(package_dir):
return True
# TODO: Allow specifying a git URL to build from.
pwd = os.getcwd()
try:
try:
os.chdir(package_dir)
except OSError as ose:
if ose.errno == errno.ENOENT:
raise Error("%s is not a valid pack... | (package_dir):
"""Return True if there are uncommitted changes in the SVN working dir."""
if utils.is_url(package_dir):
return False
out, err = utils.sbacktick("svn status -q " + package_dir, err2out=True)
if err:
raise SVNError("Exit code %d getting SVN status. Output:\n%s" % (err, out)... | is_uncommitted | identifier_name |
svn.py | True for now.
if utils.is_url(package_dir):
return True
# TODO: Allow specifying a git URL to build from.
pwd = os.getcwd()
try:
try:
os.chdir(package_dir)
except OSError as ose:
if ose.errno == errno.ENOENT:
raise Error("%s is not a valid... |
#
# Branch checking
#
# We need to forbid building from certain SVN branches into certain Koji
# targets. This is implemented by having two dicts mapping regexp patterns to
# names, one containing the restricted SVN branches and one containing the
# restricted Koji targets.
#
# We're permissive by default: if neithe... | """Check if package_info points to a valid package dir (i.e. contains
at least an osg/ dir or an upstream/ dir).
"""
url = package_info['canon_url']
rev = package_info['revision']
command = ["svn", "ls", url, "-r", rev]
out, err = utils.sbacktick(command, err2out=True)
if err:
raise... | identifier_body |
svn.py | True for now.
if utils.is_url(package_dir):
return True
# TODO: Allow specifying a git URL to build from.
pwd = os.getcwd()
try:
try:
os.chdir(package_dir)
except OSError as ose:
if ose.errno == errno.ENOENT:
raise Error("%s is not a valid... |
return False
def restricted_branch_matches_target(branch, target):
"""Return True if the pattern that matches `branch` is associated with the
same name (e.g. 'devops', 'main', 'upcoming', 'versioned') as the pattern that
matches `target`; False otherwise.
Special cases:
- if the name is 'versi... | if re.search(pattern, target):
return True | conditional_block |
tableExamples.service.js | /*
* @class TableExamplesService
*/
export default class TableExamplesService {
constructor($http) {
this.$http = $http;
}
static getClassName() { return 'TableExamplesService'; }
getClassName() { return TableExamplesService.getClassName(); }
/*
* @func getColumns
* @desc getes a list of columns... | () {
return this.$http.get('http://localhost:3001/api/People');
}
/*
* @func addData
* @desc adds an item to the api
* @param item
*/
addData(item) {
return this.$http.post('http://localhost:3001/api/People', item);
}
} | getData | identifier_name |
tableExamples.service.js | /*
* @class TableExamplesService
*/
export default class TableExamplesService {
constructor($http) |
static getClassName() { return 'TableExamplesService'; }
getClassName() { return TableExamplesService.getClassName(); }
/*
* @func getColumns
* @desc getes a list of columns representing the dataset that
* allows data tables to map the array of data to the table
*/
getColumns() {
return this... | {
this.$http = $http;
} | identifier_body |
tableExamples.service.js | /*
* @class TableExamplesService
*/
export default class TableExamplesService {
constructor($http) {
this.$http = $http;
}
static getClassName() { return 'TableExamplesService'; }
getClassName() { return TableExamplesService.getClassName(); }
/*
* @func getColumns
* @desc getes a list of columns... |
/*
* @func addColumn
* @desc adds a col
* allows data tables to map the array of data to the table
*/
addColumn(item) {
return this.$http.post('http://localhost:3001/api/DataTable/Columns/People', item);
}
/*
* @func getData
* @desc gets a list of items from the api
*/
getData() {
... | return this.$http.get('http://localhost:3001/api/DataTable/Columns/People');
} | random_line_split |
rawDebugSession.ts | arts/debug/node/v8Protocol');
import stdfork = require('vs/base/node/stdFork');
import { IMessageService } from 'vs/platform/message/common/message';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
export class RawDebugSession extends v8.V8Protocol implements debug.IRawDebugSession {
priva... |
public setFunctionBreakpoints(args: DebugProtocol.SetFunctionBreakpointsArguments): TPromise<DebugProtocol.SetFunctionBreakpointsResponse> {
return this.send('setFunctionBreakpoints', args);
}
public setExceptionBreakpoints(args: DebugProtocol.SetExceptionBreakpointsArguments): TPromise<DebugProtocol.SetExcepti... | {
return this.send('setBreakpoints', args);
} | identifier_body |
rawDebugSession.ts | arts/debug/node/v8Protocol');
import stdfork = require('vs/base/node/stdFork');
import { IMessageService } from 'vs/platform/message/common/message';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
export class RawDebugSession extends v8.V8Protocol implements debug.IRawDebugSession {
priva... | }
public setFunctionBreakpoints(args: DebugProtocol.SetFunctionBreakpointsArguments): TPromise<DebugProtocol.SetFunctionBreakpointsResponse> {
return this.send('setFunctionBreakpoints', args);
}
public setExceptionBreakpoints(args: DebugProtocol.SetExceptionBreakpointsArguments): TPromise<DebugProtocol.SetExcep... |
public setBreakpoints(args: DebugProtocol.SetBreakpointsArguments): TPromise<DebugProtocol.SetBreakpointsResponse> {
return this.send('setBreakpoints', args); | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.