file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
distributions.py | identity = {
# https://www.census.gov/prod/cen2010/briefs/c2010br-03.pdf
'sex': [('M',49.2),('F',50.8)],
# https://en.wikipedia.org/wiki/Race_and_ethnicity_in_the_United_States
'race': [('O',72.4),('U',12.6)]
}
iq = {
# Class: (mu, sigma)
# http://www.iqcomparisonsite.com/sexdifferences.aspx
... | # http://isteve.blogspot.com/2005/12/do-black-women-have-higher-iqs-than.html
# See the URL above for the provenance of the figures. As heritable measures of IQ,
# they are probably mostly garbage. But they provide a representative basis for a
# certain kind of "scientific" view of the world. And they w... | # https://commons.wikimedia.org/wiki/File:WAIS-IV_FSIQ_Scores_by_Race_and_Ethnicity.png
'O': (103.21, 13.77),
'U': (88.67, 13.68),
| random_line_split |
DependenciaFuncionalFormFilters.py | # -*- coding: UTF-8 -*-
from django import forms
from apps.registro.models import DependenciaFuncional, Jurisdiccion, TipoGestion, TipoDependenciaFuncional, TipoEducacion
class DependenciaFuncionalFormFilters(forms.Form):
| jurisdiccion = forms.ModelChoiceField(queryset=Jurisdiccion.objects.order_by('nombre'), label='Jurisdicción', required=False)
tipo_dependencia_funcional = forms.ModelChoiceField(queryset=TipoDependenciaFuncional.objects.order_by('nombre'), label='Tipo de dependencia', required=False)
tipo_gestion = forms.ModelC... | identifier_body | |
DependenciaFuncionalFormFilters.py | # -*- coding: UTF-8 -*-
from django import forms
from apps.registro.models import DependenciaFuncional, Jurisdiccion, TipoGestion, TipoDependenciaFuncional, TipoEducacion
class DependenciaFuncionalFormFilters(forms.Form):
jurisdiccion = forms.ModelChoiceField(queryset=Jurisdiccion.objects.order_by('nombre'), lab... | elf, q=None):
"""
Crea o refina un query de búsqueda.
"""
if q is None:
q = DependenciaFuncional.objects.all()
if self.is_valid():
def filter_by(field):
return self.cleaned_data.has_key(field) and self.cleaned_data[field] != '' and self.cle... | ildQuery(s | identifier_name |
DependenciaFuncionalFormFilters.py | # -*- coding: UTF-8 -*-
from django import forms
from apps.registro.models import DependenciaFuncional, Jurisdiccion, TipoGestion, TipoDependenciaFuncional, TipoEducacion
class DependenciaFuncionalFormFilters(forms.Form):
jurisdiccion = forms.ModelChoiceField(queryset=Jurisdiccion.objects.order_by('nombre'), lab... | def buildQuery(self, q=None):
"""
Crea o refina un query de búsqueda.
"""
if q is None:
q = DependenciaFuncional.objects.all()
if self.is_valid():
def filter_by(field):
return self.cleaned_data.has_key(field) and self.cleaned_data[field... | tipo_gestion = forms.ModelChoiceField(queryset=TipoGestion.objects.order_by('nombre'), label='Tipo de gestión', required=False)
nombre = forms.CharField(max_length=50, label='Nombre', required=False)
| random_line_split |
DependenciaFuncionalFormFilters.py | # -*- coding: UTF-8 -*-
from django import forms
from apps.registro.models import DependenciaFuncional, Jurisdiccion, TipoGestion, TipoDependenciaFuncional, TipoEducacion
class DependenciaFuncionalFormFilters(forms.Form):
jurisdiccion = forms.ModelChoiceField(queryset=Jurisdiccion.objects.order_by('nombre'), lab... | if filter_by('tipo_dependencia_funcional'):
q = q.filter(tipo_dependencia_funcional=self.cleaned_data['tipo_dependencia_funcional'])
return q
| q.filter(tipo_gestion=self.cleaned_data['tipo_gestion'])
| conditional_block |
Masonry.d.ts | import { PureComponent, Validator, Requireable } from 'react';
import { CellMeasurerCacheInterface, KeyMapper, MeasuredCellParent } from './CellMeasurer';
import { GridCellRenderer } from './Grid';
import { IndexRange } from '../../index';
/**
* Specifies the number of miliseconds during which to disable pointer event... | export type OnCellsRenderedCallback = (params: IndexRange) => void;
export type OnScrollCallback = (params: { clientHeight: number; scrollHeight: number; scrollTop: number }) => void;
export type MasonryCellProps = {
index: number;
isScrolling: boolean;
key: React.Key;
parent: MeasuredCellParent;
... | export const DEFAULT_SCROLLING_RESET_TIME_INTERVAL = 150;
| random_line_split |
Masonry.d.ts | import { PureComponent, Validator, Requireable } from 'react';
import { CellMeasurerCacheInterface, KeyMapper, MeasuredCellParent } from './CellMeasurer';
import { GridCellRenderer } from './Grid';
import { IndexRange } from '../../index';
/**
* Specifies the number of miliseconds during which to disable pointer event... | extends PureComponent<MasonryProps, MasonryState> {
static defaultProps: {
autoHeight: false;
keyMapper: identity;
onCellsRendered: noop;
onScroll: noop;
overscanByPixels: 20;
role: 'grid';
scrollingResetTimeInterval: typeof DEFAULT_SCROLLING_RESET_TIME_INTER... | Masonry | identifier_name |
plugins.rs | // Copyright 2012-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-MI... | n.push_str(".dll");
n
}
#[cfg(target_os="macos")]
fn libname(mut n: String) -> String {
n.push_str(".dylib");
n
}
#[cfg(all(not(target_os="windows"), not(target_os="macos")))]
fn libname(n: String) -> String {
let mut i = String::from_str("lib");
i.push_str(&n);
i.push_str(".so");
i
} | #[cfg(target_os = "windows")]
fn libname(mut n: String) -> String { | random_line_split |
plugins.rs | // Copyright 2012-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-MI... |
/// Load a plugin with the given name.
///
/// Turns `name` into the proper dynamic library filename for the given
/// platform. On windows, it turns into name.dll, on OS X, name.dylib, and
/// elsewhere, libname.so.
pub fn load_plugin(&mut self, name: String) {
let x = self.prefix.joi... | {
PluginManager {
dylibs: Vec::new(),
callbacks: Vec::new(),
prefix: prefix,
}
} | identifier_body |
plugins.rs | // Copyright 2012-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-MI... | (prefix: PathBuf) -> PluginManager {
PluginManager {
dylibs: Vec::new(),
callbacks: Vec::new(),
prefix: prefix,
}
}
/// Load a plugin with the given name.
///
/// Turns `name` into the proper dynamic library filename for the given
/// platform. On... | new | identifier_name |
poodle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Poodle implementation with a client <--> proxy <--> server
'''
import argparse
import random
import re
import select
import socket
import SocketServer
import ssl
import string
import sys
import struct
import threading
import time
from utils.color import draw
from ... |
return
def choosing_block(self, current_block):
return self.frame[current_block * self.length_block:(current_block + 1) * self.length_block]
def find_plaintext_byte(self, frame, byte):
nb_request = 0
plain = ""
print ''
while True:
self.client_conne... | (plain, nb_request) = self.find_plaintext_byte(self.frame,j)
self.request += plain
percent = 100.0 * self.byte_decipher / (length_f - 2 * self.length_block)
sys.stdout.write("\rProgression %2.0f%% - client's request %4s - byte found: %r" % (percent, nb_request, plain))
... | conditional_block |
poodle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Poodle implementation with a client <--> proxy <--> server
'''
import argparse
import random
import re
import select
import socket
import SocketServer
import ssl
import string
import sys
import struct
import threading
import time
from utils.color import draw
from ... | (self):
self.client.connection()
return
def send_request_from_the_client(self, path=0, data=0):
self.client.request(path,data)
return
def client_disconect(self):
self.client.disconnect()
return
if __name__ == '__main__':
plan = """\
+-----------------... | client_connection | identifier_name |
poodle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Poodle implementation with a client <--> proxy <--> server
'''
import argparse
import random
import re
import select
import socket
import SocketServer
import ssl
import string
import sys
import struct
import threading
import time
from utils.color import draw
from ... |
def find_plaintext_byte(self, frame, byte):
nb_request = 0
plain = ""
print ''
while True:
self.client_connection()
prefix_length = byte
suffix_length = self.length_block - byte
self.send_request_from_the_client... |
def choosing_block(self, current_block):
return self.frame[current_block * self.length_block:(current_block + 1) * self.length_block] | random_line_split |
poodle.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Poodle implementation with a client <--> proxy <--> server
'''
import argparse
import random
import re
import select
import socket
import SocketServer
import ssl
import string
import sys
import struct
import threading
import time
from utils.color import draw
from ... |
class Poodle(Client):
""" Assimilate to the attacker
detect the length of a CBC block
alter the ethernet frame of the client to decipher a byte regarding the proxy informations
"""
def __init__(self, client):
self.client = client
self.length_block = 0
self.start_exploit = ... | """ Assimilate to a MitmProxy
start a serving on his host and port and redirect the data to the server due to this handler
"""
def __init__(self, host, port):
self.host = host
self.port = port
def connection(self):
SocketServer.TCPServer.allow_reuse_address = True
httpd ... | identifier_body |
comment.js | Template.comment.helpers({
submittedText: function() {
var date = new Date(this.submitted);
console.log("vote =====>", this);
var d=date.getDate();
var m=date.getMonth()+1;
var y=date.getFullYear();
return m + " - " + d + " - " + y;
},
postID : function(postID){
... | else {
return 'disabled';
}
},
downvotedClass: function() {
var userId = Meteor.userId();
if (userId && ( !_.include(this.downvoters, userId) || _.include(this.upvoters, userId) ) ) {
return 'downvotable';
} else {
return 'disabled';
}
... | {
return 'upvotable';
} | conditional_block |
comment.js | Template.comment.helpers({
submittedText: function() {
var date = new Date(this.submitted);
console.log("vote =====>", this);
var d=date.getDate();
var m=date.getMonth()+1;
var y=date.getFullYear();
return m + " - " + d + " - " + y;
},
postID : function(postID){
... | }); | random_line_split | |
const-enum-vector.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 ... | { V1(int), V0 }
static C: [E; 3] = [E::V0, E::V1(0xDEADBEE), E::V0];
pub fn main() {
match C[1] {
E::V1(n) => assert!(n == 0xDEADBEE),
_ => panic!()
}
match C[2] {
E::V0 => (),
_ => panic!()
}
}
| E | identifier_name |
const-enum-vector.rs | // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
enum E { V1(int), V0 }
static C: [E; 3] = [E::V0, E::V1(0xDEADBEE), E::V0];
pub fn main... | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or | random_line_split |
const-enum-vector.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 ... | {
match C[1] {
E::V1(n) => assert!(n == 0xDEADBEE),
_ => panic!()
}
match C[2] {
E::V0 => (),
_ => panic!()
}
} | identifier_body | |
func_noerror_query_getattr.py | # pylint:disable=R0201
from OpenOrange import *
from Document import Document
from Label import Label
from SQLTools import codeOrder, monthCode
from datetime import datetime
class AlotmentDoc(Document):
classattr = "classattr"
def getRecorda(self):
class newObj(object):
Status = 1
... |
def getExtra7(self):
specs = self.getRecorda()
factor = 0.0
if 1 > 0:
factor = (float(specs.Status) / float(specs.Status))
txt = "WHERE?AND (%s / 1) * %s > 0\n" % (1, factor)
return txt
def run(self):
specs = self.getRecorda()
leaves = Label... | txt = ""
q = {}
q["one"] = Query()
q["one"].sql = "WHERE?AND SerNr IS NULL\n"
q["two"] = Query()
q["two"].sql = "WHERE?AND SerNr IS NOT NULL\n"
slist = ["one", "two"]
for index in slist:
txt += q[index].sql
return txt | identifier_body |
func_noerror_query_getattr.py | # pylint:disable=R0201
from OpenOrange import *
from Document import Document
from Label import Label
from SQLTools import codeOrder, monthCode
from datetime import datetime
class AlotmentDoc(Document):
classattr = "classattr"
def getRecorda(self):
class newObj(object):
Status = 1
... | (self):
specs = self.getRecorda()
subquery = Query()
subquery.sql = "SerNr"
return "ORDER BY %s, %s" % (specs.SerNr, subquery.sql)
def getExtra4(self):
specs = self.getRecorda()
labels = None
if specs.Labels:
lis = []
labs = specs.Labe... | getExtra3 | identifier_name |
func_noerror_query_getattr.py | # pylint:disable=R0201
from OpenOrange import *
from Document import Document
from Label import Label
from SQLTools import codeOrder, monthCode
from datetime import datetime
class AlotmentDoc(Document):
classattr = "classattr"
def getRecorda(self):
class newObj(object):
Status = 1
... |
return "WHERE?AND SerNr IN ('%s') " % labels
def getExtra5(self, txt):
txt = txt.replace(":1","RoomType IS NULL\n")
return txt
def getExtra6(self):
txt = ""
q = {}
q["one"] = Query()
q["one"].sql = "WHERE?AND SerNr IS NULL\n"
q["two"] = Query()
... | lis = []
labs = specs.Labels.split(",")
for lb in labs:
lis.append("','".join(Label.getTreeLeaves(lb)))
labels = "','".join(lis) | conditional_block |
func_noerror_query_getattr.py | # pylint:disable=R0201
from OpenOrange import *
from Document import Document
from Label import Label
from SQLTools import codeOrder, monthCode
from datetime import datetime
class AlotmentDoc(Document):
classattr = "classattr"
def getRecorda(self):
class newObj(object):
Status = 1
... | x += "'%s' as test_time\n, " % time("")
x += "'%i' as test_len\n, " % len(specs.RootLabel)
x += "'%s' as test_map\n, " % "','".join(map(str, mylist))
x += "'%s' as test_keys\n, " % "','".join(mydict.keys())
x += "'%s' as test_subscript\n," % ["SerNr","... | x = "'%s' as test_date\n, " % date("") | random_line_split |
hessenberg.rs | use std::cmp;
use nl::Hessenberg;
use na::{DMatrix, Matrix4};
quickcheck!{
fn hessenberg(n: usize) -> bool {
if n != 0 {
let n = cmp::min(n, 25);
let m = DMatrix::<f64>::new_random(n, n);
match Hessenberg::new(m.clone()) {
Some(hess) => {
... | }
}
} | relative_eq!(m, p * h * p.transpose(), epsilon = 1.0e-7)
},
None => true | random_line_split |
mpq.rs |
use std::fs::File;
use std::io::Read;
use std::ptr::copy_nonoverlapping;
// Result:
// 11011010100010101000001001101
// 1101101010001
fn sp(){
let bytes: [u8; 4] = [77, 80, 81, 27];
let buf_a: [u8; 2] = [77, 80];
let buf_b: [u8; 2] = [81, 27];
let mut num_a: u32 = 0;
let mut num_b: u32 = 0;
... | {
sp();
let mut f: File = File::open("test.replay").unwrap();
let mut buf = [0u8; 4];
let size = f.read(&mut buf).unwrap();
let mut data: u32 = 0;
unsafe {
copy_nonoverlapping(buf.as_ptr(), &mut data as *mut u32 as *mut u8, 4)
}
let bits = data.to_le();
let _string = std::s... | identifier_body | |
mpq.rs |
use std::fs::File;
use std::io::Read;
use std::ptr::copy_nonoverlapping;
// Result:
// 11011010100010101000001001101
// 1101101010001
fn | (){
let bytes: [u8; 4] = [77, 80, 81, 27];
let buf_a: [u8; 2] = [77, 80];
let buf_b: [u8; 2] = [81, 27];
let mut num_a: u32 = 0;
let mut num_b: u32 = 0;
unsafe {
copy_nonoverlapping(buf_a.as_ptr(), &mut num_a as *mut u32 as *mut u8, 2);
copy_nonoverlapping(buf_b.as_ptr(), &mut n... | sp | identifier_name |
mpq.rs | use std::fs::File;
use std::io::Read;
use std::ptr::copy_nonoverlapping;
// Result: | let bytes: [u8; 4] = [77, 80, 81, 27];
let buf_a: [u8; 2] = [77, 80];
let buf_b: [u8; 2] = [81, 27];
let mut num_a: u32 = 0;
let mut num_b: u32 = 0;
unsafe {
copy_nonoverlapping(buf_a.as_ptr(), &mut num_a as *mut u32 as *mut u8, 2);
copy_nonoverlapping(buf_b.as_ptr(), &mut num_b... | // 11011010100010101000001001101
// 1101101010001
fn sp(){ | random_line_split |
urls.py | # This file is part of django-doubleoptin-contactform.
# django-doubleoptin-contactform is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your opt... | ) | (r'^(?P<contact_id>\d+)/verify/$', 'doptincf.views.verify'),
(r'^received/$', direct_to_template, {'template': 'contact/verified.html'}), | random_line_split |
sonar.js | var Board = require("../lib/board.js"),
events = require("events"),
util = require("util");
/**
* Sonar
* @constructor
*
* @param {Object} opts Options: pin (analog)
*/
function Sonar( opts ) |
util.inherits( Sonar, events.EventEmitter );
module.exports = Sonar;
// Reference
//
// http://www.maxbotix.com/tutorials.htm#Code_example_for_the_BasicX_BX24p
// http://www.electrojoystick.com/tutorial/?page_id=285
// Tutorials
//
// http://www.sensorpedia.com/blog/how-to-interface-an-ultrasonic-rangefinder-wit... | {
if ( !(this instanceof Sonar) ) {
return new Sonar( opts );
}
var median, last, samples;
median = 0;
last = 0;
samples = [];
// Initialize a Device instance on a Board
Board.Device.call(
this, opts = Board.Options( opts )
);
// Sonar instance properties
this.freq = opts.freq || 100;... | identifier_body |
sonar.js | var Board = require("../lib/board.js"),
events = require("events"),
util = require("util");
/**
* Sonar
* @constructor
*
* @param {Object} opts Options: pin (analog)
*/
function Sonar( opts ) {
if ( !(this instanceof Sonar) ) |
var median, last, samples;
median = 0;
last = 0;
samples = [];
// Initialize a Device instance on a Board
Board.Device.call(
this, opts = Board.Options( opts )
);
// Sonar instance properties
this.freq = opts.freq || 100;
this.voltage = null;
// Set the pin to ANALOG mode
this.mode = t... | {
return new Sonar( opts );
} | conditional_block |
sonar.js | var Board = require("../lib/board.js"),
events = require("events"),
util = require("util");
/**
* Sonar
* @constructor
*
* @param {Object} opts Options: pin (analog)
*/
function | ( opts ) {
if ( !(this instanceof Sonar) ) {
return new Sonar( opts );
}
var median, last, samples;
median = 0;
last = 0;
samples = [];
// Initialize a Device instance on a Board
Board.Device.call(
this, opts = Board.Options( opts )
);
// Sonar instance properties
this.freq = opts.fre... | Sonar | identifier_name |
sonar.js | var Board = require("../lib/board.js"),
events = require("events"),
util = require("util");
/**
* Sonar
* @constructor
*
* @param {Object} opts Options: pin (analog)
*/
function Sonar( opts ) {
if ( !(this instanceof Sonar) ) {
return new Sonar( opts );
}
var median, last, samples;
median... |
// Throttle
setInterval(function() {
var err;
err = null;
// Nothing read since previous interval
if ( samples.length === 0 ) {
return;
}
median = samples.sort()[ Math.floor( samples.length / 2 ) ];
// Emit throttled event
this.emit( "read", err, median );
// If the m... | }.bind(this)); | random_line_split |
files.py | # -*- coding: utf-8 -*-
"""
equip.utils.files
~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
import os
__normalize_path = lambda x: os.path.abspath(x) |
def file_extension(filename):
if '.' not in filename:
return None
return filename[filename.rfind('.') + 1:].lower()
def good_ext(fext, l=None):
return fext.lower() in l if l else False
def scan_dir(directory, files, l_ext=None):
names = os.listdir(directory)
for name in names:
srcname = __normal... | random_line_split | |
files.py | # -*- coding: utf-8 -*-
"""
equip.utils.files
~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
import os
__normalize_path = lambda x: os.path.abspath(x)
def file_extension(filename):
|
def good_ext(fext, l=None):
return fext.lower() in l if l else False
def scan_dir(directory, files, l_ext=None):
names = os.listdir(directory)
for name in names:
srcname = __normalize_path(os.path.join(directory, name))
try:
if os.path.isdir(srcname):
try:
scan_dir(srcname, fi... | if '.' not in filename:
return None
return filename[filename.rfind('.') + 1:].lower() | identifier_body |
files.py | # -*- coding: utf-8 -*-
"""
equip.utils.files
~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
import os
__normalize_path = lambda x: os.path.abspath(x)
def file_extension(filename):
if '.' not in filename:
return None
return ... | (fext, l=None):
return fext.lower() in l if l else False
def scan_dir(directory, files, l_ext=None):
names = os.listdir(directory)
for name in names:
srcname = __normalize_path(os.path.join(directory, name))
try:
if os.path.isdir(srcname):
try:
scan_dir(srcname, files, l_ext)
... | good_ext | identifier_name |
files.py | # -*- coding: utf-8 -*-
"""
equip.utils.files
~~~~~~~~~~~~~~~~~
:copyright: (c) 2014 by Romain Gaucher (@rgaucher)
:license: Apache 2, see LICENSE for more details.
"""
import os
__normalize_path = lambda x: os.path.abspath(x)
def file_extension(filename):
if '.' not in filename:
return None
return ... |
elif os.path.isfile(srcname) \
and (not l_ext \
or good_ext(srcname[srcname.rfind('.')+1:], l_ext)):
if srcname not in files:
files.append(srcname)
except IOError, error:
continue
def list_dir(directory):
subdirs = os.listdir(directory)
if not subdirs:... | try:
scan_dir(srcname, files, l_ext)
except:
continue | conditional_block |
53b71e7c45b5_add_fields_for_mivs_show_info_checklist_.py | """Add fields for MIVS show_info checklist item
Revision ID: 53b71e7c45b5
Revises: ad26fcaafb78
Create Date: 2019-11-25 19:37:15.322579
"""
# revision identifiers, used by Alembic.
revision = '53b71e7c45b5'
down_revision = 'ad26fcaafb78'
branch_labels = None
depends_on = None
from alembic import op
import sqlalche... |
# ===========================================================================
# HOWTO: Handle alter statements in SQLite
#
# def upgrade():
# if is_sqlite:
# with op.batch_alter_table('table_name', reflect_kwargs=sqlite_reflect_kwargs) as batch_op:
# batch_op.alter_column('column_name', type_=s... |
sqlite_reflect_kwargs = {
'listeners': [('column_reflect', sqlite_column_reflect_listener)]
} | random_line_split |
53b71e7c45b5_add_fields_for_mivs_show_info_checklist_.py | """Add fields for MIVS show_info checklist item
Revision ID: 53b71e7c45b5
Revises: ad26fcaafb78
Create Date: 2019-11-25 19:37:15.322579
"""
# revision identifiers, used by Alembic.
revision = '53b71e7c45b5'
down_revision = 'ad26fcaafb78'
branch_labels = None
depends_on = None
from alembic import op
import sqlalche... | ():
op.add_column('indie_studio', sa.Column('contact_phone', sa.Unicode(), server_default='', nullable=False))
op.add_column('indie_studio', sa.Column('show_info_updated', sa.Boolean(), server_default='False', nullable=False))
def downgrade():
op.drop_column('indie_studio', 'show_info_updated')
op.dro... | upgrade | identifier_name |
53b71e7c45b5_add_fields_for_mivs_show_info_checklist_.py | """Add fields for MIVS show_info checklist item
Revision ID: 53b71e7c45b5
Revises: ad26fcaafb78
Create Date: 2019-11-25 19:37:15.322579
"""
# revision identifiers, used by Alembic.
revision = '53b71e7c45b5'
down_revision = 'ad26fcaafb78'
branch_labels = None
depends_on = None
from alembic import op
import sqlalche... |
else:
utcnow_server_default = "timezone('utc', current_timestamp)"
def sqlite_column_reflect_listener(inspector, table, column_info):
"""Adds parenthesis around SQLite datetime defaults for utcnow."""
if column_info['default'] == "datetime('now', 'utc')":
column_info['default'] = utcnow_server_def... | op.get_context().connection.execute('PRAGMA foreign_keys=ON;')
utcnow_server_default = "(datetime('now', 'utc'))" | conditional_block |
53b71e7c45b5_add_fields_for_mivs_show_info_checklist_.py | """Add fields for MIVS show_info checklist item
Revision ID: 53b71e7c45b5
Revises: ad26fcaafb78
Create Date: 2019-11-25 19:37:15.322579
"""
# revision identifiers, used by Alembic.
revision = '53b71e7c45b5'
down_revision = 'ad26fcaafb78'
branch_labels = None
depends_on = None
from alembic import op
import sqlalche... | op.drop_column('indie_studio', 'show_info_updated')
op.drop_column('indie_studio', 'contact_phone') | identifier_body | |
stocks.py | import numpy as np
import pandas as pd
from bokeh.plotting import * | "http://ichart.yahoo.com/table.csv?s=AAPL&a=0&b=1&c=2000",
parse_dates=['Date'])
GOOG = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=GOOG&a=0&b=1&c=2000",
parse_dates=['Date'])
MSFT = pd.read_csv(
"http://ichart.yahoo.com/table.csv?s=MSFT&a=0&b=1&c=2000",
parse_dates=['Date'])
IBM = pd.read... |
# Here is some code to read in some stock data from the Yahoo Finance API
AAPL = pd.read_csv( | random_line_split |
context-menus-main.js | const {ipcFuncMain, ipcFuncMainCb, getIpcNameFunc, sendToBackgroundPage} = require('./util-main')
const {ipcMain} = require('electron')
const getIpcName = getIpcNameFunc('ContextMenus')
const extInfos = require('../../extensionInfos')
const sharedState = require('../../sharedStateMain')
ipcMain.on('get-extension-menu'... | delete sharedState.extensionMenu[extensionId]
}) | random_line_split | |
lib.rs | /*!
# Kiss3d
Keep It Simple, Stupid 3d graphics engine.
This library is born from the frustration in front of the fact that today’s 3D
graphics library are:
* either too low level: you have to write your own shaders and opening a
window steals you 8 hours, 300 lines of code and 10L of coffee.
* or high level but t... |
c.set_color(1.0, 0.0, 0.0);
window.set_light(Light::StickToCamera);
let rot = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.014);
while window.render() {
c.prepend_to_local_rotation(&rot);
}
}
```
The same example, but that will compile for both WASM and native platforms is slig... | random_line_split | |
electron.ts | import Cloud = pxt.Cloud;
import * as cmds from "./cmds";
import * as core from "./core";
import { ProjectView } from "./srceditor";
const pxtElectron: pxt.electron.PxtElectron = (window as any).pxtElectron;
const downloadingUpdateLoadingName = "pxtelectron-downloadingupdate";
export function initElectron(projectVie... |
export function openDevTools(): void {
if (pxtElectron) {
pxtElectron.sendOpenDevTools();
}
} | {
if (!pxt.BrowserUtils.isPxtElectron()) {
return cmds.browserDownloadDeployCoreAsync(compileResult);
}
if (!deployingDeferred) {
deployingDeferred = pxt.Util.defer<void>();
pxtElectron.sendDriveDeploy(compileResult);
}
return deployingDeferred.promise
.catch((e) =>... | identifier_body |
electron.ts | import Cloud = pxt.Cloud;
import * as cmds from "./cmds";
import * as core from "./core";
import { ProjectView } from "./srceditor";
const pxtElectron: pxt.electron.PxtElectron = (window as any).pxtElectron;
const downloadingUpdateLoadingName = "pxtelectron-downloadingupdate";
export function | (projectView: ProjectView): void {
if (!pxt.BrowserUtils.isPxtElectron()) {
return;
}
pxtElectron.onTelemetry((ev: pxt.electron.TelemetryEvent) => {
pxt.tickEvent(ev.event, ev.data);
});
pxtElectron.onUpdateInstalled(() => {
core.infoNotification(lf("An update will take effe... | initElectron | identifier_name |
electron.ts | import Cloud = pxt.Cloud;
import * as cmds from "./cmds";
import * as core from "./core";
import { ProjectView } from "./srceditor";
const pxtElectron: pxt.electron.PxtElectron = (window as any).pxtElectron;
const downloadingUpdateLoadingName = "pxtelectron-downloadingupdate";
export function initElectron(projectVie... |
} | {
pxtElectron.sendOpenDevTools();
} | conditional_block |
electron.ts | import Cloud = pxt.Cloud;
import * as cmds from "./cmds";
import * as core from "./core";
import { ProjectView } from "./srceditor";
const pxtElectron: pxt.electron.PxtElectron = (window as any).pxtElectron;
const downloadingUpdateLoadingName = "pxtelectron-downloadingupdate";
export function initElectron(projectVie... | if (!deployingDeferred) {
deployingDeferred = pxt.Util.defer<void>();
pxtElectron.sendDriveDeploy(compileResult);
}
return deployingDeferred.promise
.catch((e) => {
pxt.tickEvent("electron.drivedeploy.browserdownloadinstead");
return cmds.browserDownloadDeplo... | }
| random_line_split |
DropdownMenu.ts | export default class DropDownMenu {
protected root?: HTMLElement;
protected button?: Array<HTMLElement>;
protected menu?: Array<HTMLElement>;
constructor(_root: HTMLElement) {
this.root = _root;
this.button = Array.from(
this.root.querySelectorAll(".neos-dropdown-toggle")
);
this.menu = A... |
private changeToogleIcon(): void {
const openIcon: HTMLElement = this.root.querySelector(".fa-chevron-down");
const closeIcon: HTMLElement = this.root.querySelector(".fa-chevron-up");
if (openIcon) {
openIcon.classList.replace("fa-chevron-down", "fa-chevron-up");
}
if (closeIcon) {
c... | {
this.changeToogleIcon();
this.root.classList.toggle("neos-dropdown-open");
} | identifier_body |
DropdownMenu.ts | export default class DropDownMenu {
protected root?: HTMLElement;
protected button?: Array<HTMLElement>;
protected menu?: Array<HTMLElement>;
constructor(_root: HTMLElement) {
this.root = _root;
this.button = Array.from(
this.root.querySelectorAll(".neos-dropdown-toggle")
);
this.menu = A... |
if (closeIcon) {
closeIcon.classList.replace("fa-chevron-up", "fa-chevron-down");
}
}
}
| {
openIcon.classList.replace("fa-chevron-down", "fa-chevron-up");
} | conditional_block |
DropdownMenu.ts | export default class DropDownMenu {
protected root?: HTMLElement;
protected button?: Array<HTMLElement>;
protected menu?: Array<HTMLElement>;
constructor(_root: HTMLElement) {
this.root = _root;
this.button = Array.from(
this.root.querySelectorAll(".neos-dropdown-toggle")
);
this.menu = A... | if (openIcon) {
openIcon.classList.replace("fa-chevron-down", "fa-chevron-up");
}
if (closeIcon) {
closeIcon.classList.replace("fa-chevron-up", "fa-chevron-down");
}
}
} |
private changeToogleIcon(): void {
const openIcon: HTMLElement = this.root.querySelector(".fa-chevron-down");
const closeIcon: HTMLElement = this.root.querySelector(".fa-chevron-up"); | random_line_split |
DropdownMenu.ts | export default class | {
protected root?: HTMLElement;
protected button?: Array<HTMLElement>;
protected menu?: Array<HTMLElement>;
constructor(_root: HTMLElement) {
this.root = _root;
this.button = Array.from(
this.root.querySelectorAll(".neos-dropdown-toggle")
);
this.menu = Array.from(this.root.querySelector... | DropDownMenu | identifier_name |
interpreter.rs | use std::io::{Read, stdin};
use operations::Op;
pub struct Interpreter {
memory: Vec<u8>,
pointer: i64,
ops: Vec<Op>,
}
impl Interpreter {
pub fn new(ops: Vec<Op>) -> Interpreter {
let m = (0 .. 30000).map(|_| 0).collect();
Interpreter { memory: m, pointer: 0, ops: ops }
}
pub... |
}
| {
let mut bal = 0i32;
loop {
if self.ops[*program_counter] == Op::Jump {
bal += 1;
} else if self.ops[*program_counter] == Op::JumpBack {
bal -= 1;
}
*program_counter -= 1;
if bal == 0 {
break;
... | identifier_body |
interpreter.rs | use std::io::{Read, stdin};
use operations::Op;
pub struct Interpreter {
memory: Vec<u8>,
pointer: i64,
ops: Vec<Op>,
}
impl Interpreter {
pub fn new(ops: Vec<Op>) -> Interpreter {
let m = (0 .. 30000).map(|_| 0).collect();
Interpreter { memory: m, pointer: 0, ops: ops }
}
pub... | (&mut self) {
self.memory[self.pointer as usize] -= 1;
}
fn output(&self) {
print!("{}", (self.memory[self.pointer as usize]) as char);
}
fn jump(&mut self, program_counter: &mut usize) {
let mut bal = 1i32;
if self.memory[self.pointer as usize] == 0u8 {
loo... | decrement | identifier_name |
interpreter.rs | use std::io::{Read, stdin};
use operations::Op;
pub struct Interpreter {
memory: Vec<u8>,
pointer: i64,
ops: Vec<Op>,
}
impl Interpreter {
pub fn new(ops: Vec<Op>) -> Interpreter {
let m = (0 .. 30000).map(|_| 0).collect();
Interpreter { memory: m, pointer: 0, ops: ops }
}
pub... | self.pointer -= 1;
}
fn right(&mut self) {
self.pointer += 1;
}
fn input(&mut self) {
let mut input = String::new();
stdin()
.read_line(&mut input).ok().expect("Error reading user input");
self.memory[self.pointer as usize] = input.bytes().next().ex... | }
fn left(&mut self) { | random_line_split |
MetadataNewsWebPart.ts | import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneChoiceGroup,
PropertyPaneCheckbox,
PropertyPaneCustomField,
PropertyPaneFieldType,
P... | config.pages[0].groups[1].groupFields.push(PropertyPaneTextField(`RefinerInfos[${infoIndex}].DefaultValues`, { description: "; delimited refiner values", value: this.properties.RefinerInfos[infoIndex].DefaultValues}));
config.pages[0].groups[1].groupFields.push(PropertyPaneHorizontalRule());
}
... | if (this.lookupsFetched) {
for (let infoIndex in this.properties.RefinerInfos) {
config.pages[0].groups[1].groupFields.push(PropertyPaneCheckbox(`RefinerInfos[${infoIndex}].IsSelected`, { text: this.properties.RefinerInfos[infoIndex].DisplayName})); | random_line_split |
MetadataNewsWebPart.ts | import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneChoiceGroup,
PropertyPaneCheckbox,
PropertyPaneCustomField,
PropertyPaneFieldType,
P... | () {
super.onDispose();
}
public render(): void {
const element: React.ReactElement<IMetadataNewsProps> = React.createElement(MetadataNews, this.properties);
ReactDom.render(element, this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected get di... | onDispose | identifier_name |
MetadataNewsWebPart.ts | import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneChoiceGroup,
PropertyPaneCheckbox,
PropertyPaneCustomField,
PropertyPaneFieldType,
P... |
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected get disableReactivePropertyChanges(): boolean {
return true;
}
// Get the property pane configuration
// During first opening we will fetch all lookup fields
// In order for fields to become visible we have to chan... | {
const element: React.ReactElement<IMetadataNewsProps> = React.createElement(MetadataNews, this.properties);
ReactDom.render(element, this.domElement);
} | identifier_body |
MetadataNewsWebPart.ts | import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
BaseClientSideWebPart,
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneChoiceGroup,
PropertyPaneCheckbox,
PropertyPaneCustomField,
PropertyPaneFieldType,
P... |
}
return '';
}
}
| {
return errMsg;
} | conditional_block |
ExportRequest.py | # Copyright 2016 Coursera
#
# 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, sof... |
if kwargs.get('user_id_hashing'):
if kwargs['user_id_hashing'] == 'linked':
kwargs['anonymity_level'] = ANONYMITY_LEVEL_COORDINATOR
elif kwargs['user_id_hashing'] == 'isolated':
kwargs['anonymity_level'] = ANONYMITY_LEVEL_ISOLATED
return cls(**k... | kwargs['partner_id'] = utils.lookup_partner_id_by_short_name(
kwargs['partner_short_name']) | conditional_block |
ExportRequest.py | # Copyright 2016 Coursera
#
# 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, sof... | (cls, **kwargs):
"""
Create a ExportResource object using the parameters required. Performs
course_id/partner_id inference if possible.
:param kwargs:
:return export_request: ExportRequest
"""
if kwargs.get('course_slug') and not kwargs.get('course_id'):
... | from_args | identifier_name |
ExportRequest.py | # Copyright 2016 Coursera
#
# 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, sof... | else:
return self._export_type
@property
def anonymity_level(self):
return self._anonymity_level
@property
def formatted_anonymity_level(self):
if self.anonymity_level == ANONYMITY_LEVEL_COORDINATOR:
return 'Linked'
elif self.anonymity_level == A... | return 'GRADEBOOK'
elif self._export_type == EXPORT_TYPE_CLICKSTREAM:
return 'CLICKSTREAM'
elif self._export_type == EXPORT_TYPE_TABLES:
return 'TABLES' | random_line_split |
ExportRequest.py | # Copyright 2016 Coursera
#
# 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, sof... |
@property
def export_type_display(self):
if self._export_type == EXPORT_TYPE_GRADEBOOK:
return 'GRADEBOOK'
elif self._export_type == EXPORT_TYPE_CLICKSTREAM:
return 'CLICKSTREAM'
elif self._export_type == EXPORT_TYPE_TABLES:
return 'TABLES'
e... | return self._export_type | identifier_body |
index.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {... |
editTodo(todo: Todo): void {
this.todoEdit = todo;
}
doneEditing($event: KeyboardEvent, todo: Todo): void {
const which = $event.which;
const target = $event.target as HTMLInputElement;
if (which === 13) {
todo.title = target.value;
this.todoEdit = null;
} else if (which === 27)... | {
this.addTodo(inputElement.value);
inputElement.value = '';
} | identifier_body |
index.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {... |
clearCompleted(): void {
this.todoStore.removeBy((todo: Todo) => todo.completed);
}
}
@NgModule({declarations: [TodoApp], bootstrap: [TodoApp], imports: [BrowserModule]})
export class ExampleModule {
}
platformBrowserDynamic().bootstrapModule(ExampleModule); | const isComplete = ($event.target as HTMLInputElement).checked;
this.todoStore.list.forEach((todo: Todo) => {
todo.completed = isComplete;
});
} | random_line_split |
index.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {... | (public todoStore: Store<Todo>, public factory: TodoFactory) {}
enterTodo(inputElement: HTMLInputElement): void {
this.addTodo(inputElement.value);
inputElement.value = '';
}
editTodo(todo: Todo): void {
this.todoEdit = todo;
}
doneEditing($event: KeyboardEvent, todo: Todo): void {
const wh... | constructor | identifier_name |
index.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {... | else if (which === 27) {
this.todoEdit = null;
target.value = todo.title;
}
}
addTodo(newTitle: string): void {
this.todoStore.add(this.factory.create(newTitle, false));
}
completeMe(todo: Todo): void {
todo.completed = !todo.completed;
}
deleteMe(todo: Todo): void {
this.tod... | {
todo.title = target.value;
this.todoEdit = null;
} | conditional_block |
config_regression_test.py | #!/usr/bin/env python
"""This modules contains regression tests for config API handler."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import api_regression_test_lib
from grr_response_server.gui.api_pl... |
class ApiGetGrrBinaryBlobHandlerRegressionTest(
config_plugin_test.ApiGrrBinaryTestMixin,
api_regression_test_lib.ApiRegressionTest):
api_method = "GetGrrBinaryBlob"
handler = config_plugin.ApiGetGrrBinaryBlobHandler
def Run(self):
self.SetUpBinaries()
self.Check(
"GetGrrBinaryBlob",... | api_method = "GetGrrBinary"
handler = config_plugin.ApiGetGrrBinaryHandler
def Run(self):
self.SetUpBinaries()
self.Check(
"GetGrrBinary",
args=config_plugin.ApiGetGrrBinaryArgs(type="PYTHON_HACK", path="test"))
self.Check(
"GetGrrBinary",
args=config_plugin.ApiGetGrrBi... | identifier_body |
config_regression_test.py | #!/usr/bin/env python
"""This modules contains regression tests for config API handler."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import api_regression_test_lib
from grr_response_server.gui.api_pl... | (self):
self.SetUpBinaries()
self.Check("ListGrrBinaries")
class ApiGetGrrBinaryHandlerRegressionTest(
config_plugin_test.ApiGrrBinaryTestMixin,
api_regression_test_lib.ApiRegressionTest):
api_method = "GetGrrBinary"
handler = config_plugin.ApiGetGrrBinaryHandler
def Run(self):
self.SetUp... | Run | identifier_name |
config_regression_test.py | #!/usr/bin/env python
"""This modules contains regression tests for config API handler."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import api_regression_test_lib
from grr_response_server.gui.api_pl... | api_regression_test_lib.ApiRegressionTest):
api_method = "GetGrrBinaryBlob"
handler = config_plugin.ApiGetGrrBinaryBlobHandler
def Run(self):
self.SetUpBinaries()
self.Check(
"GetGrrBinaryBlob",
args=config_plugin.ApiGetGrrBinaryBlobArgs(
type="PYTHON_HACK", path="test")... | class ApiGetGrrBinaryBlobHandlerRegressionTest(
config_plugin_test.ApiGrrBinaryTestMixin, | random_line_split |
config_regression_test.py | #!/usr/bin/env python
"""This modules contains regression tests for config API handler."""
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl import app
from grr_response_server.gui import api_regression_test_lib
from grr_response_server.gui.api_pl... | app.run(main) | conditional_block | |
operate_list.py | # Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10,
# and multiply([1, 2, 3, 4]) should return 24.
def check_list(num_list):
"""Check if input is list"""
if num_list is Non... |
def multiply(num_list):
"""Multiply list values"""
if check_list(num_list):
final_sum = 1
for i in num_list:
final_sum = final_sum * i
return final_sum
else:
return False
def main():
get_list = input("Enter list: ")
operations ... | """Compute sum of list values"""
if check_list(num_list):
final_sum = 0
for i in num_list:
final_sum = final_sum + i
return final_sum
else:
return False | identifier_body |
operate_list.py | # Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10,
# and multiply([1, 2, 3, 4]) should return 24.
def check_list(num_list):
"""Check if input is list"""
if num_list is Non... | (num_list):
"""Compute sum of list values"""
if check_list(num_list):
final_sum = 0
for i in num_list:
final_sum = final_sum + i
return final_sum
else:
return False
def multiply(num_list):
"""Multiply list values"""
if check_list... | sum | identifier_name |
operate_list.py | # Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10,
# and multiply([1, 2, 3, 4]) should return 24.
def check_list(num_list):
"""Check if input is list"""
if num_list is Non... | for i in num_list:
final_sum = final_sum * i
return final_sum
else:
return False
def main():
get_list = input("Enter list: ")
operations = [sum, multiply]
print map(lambda x: x(get_list), operations)
if __name__ == "__main__":
main() | if check_list(num_list):
final_sum = 1
| random_line_split |
operate_list.py | # Define a function sum() and a function multiply()
# that sums and multiplies (respectively) all the numbers in a list of numbers.
# For example, sum([1, 2, 3, 4]) should return 10,
# and multiply([1, 2, 3, 4]) should return 24.
def check_list(num_list):
"""Check if input is list"""
if num_list is Non... |
new_list = []
for i in num_list:
if i!='[' and i!=']' and i!=',':
new_list.append(i)
for x in new_list:
if type(x) != int:
return False
return True
def sum(num_list):
"""Compute sum of list values"""
if check_list(num_list):
... | return False | conditional_block |
abstract-data-service-adapter.ts | import { core } from './core';
import { config } from './config';
import { EntityQuery } from './entity-query';
import { IDataServiceAdapter, IAjaxAdapter, IChangeRequestInterceptorCtor, IChangeRequestInterceptor } from './interface-registry';
import { IEntity } from './entity-aspect';
import { MappingContext } from '... | {
}
// TODO use interface
checkForRecomposition(interfaceInitializedArgs: any) {
if (interfaceInitializedArgs.interfaceName === "ajax" && interfaceInitializedArgs.isDefault) {
this.initialize();
}
}
initialize() {
this.ajaxImpl = config.getAdapterInstance<IAjaxAdapter>("ajax") !;
//... | nstructor() | identifier_name |
abstract-data-service-adapter.ts | import { core } from './core';
import { config } from './config';
import { EntityQuery } from './entity-query';
import { IDataServiceAdapter, IAjaxAdapter, IChangeRequestInterceptorCtor, IChangeRequestInterceptor } from './interface-registry';
import { IEntity } from './entity-aspect';
import { MappingContext } from '... | });
return promise;
}
executeQuery(mappingContext: MappingContext) {
mappingContext.adapter = this;
let promise = new Promise<IQueryResult>((resolve, reject) => {
let url = mappingContext.getUrl();
let params = {
type: "GET",
url: url,
params: (mappingContext.qu... | }
}); | random_line_split |
abstract-data-service-adapter.ts | import { core } from './core';
import { config } from './config';
import { EntityQuery } from './entity-query';
import { IDataServiceAdapter, IAjaxAdapter, IChangeRequestInterceptorCtor, IChangeRequestInterceptor } from './interface-registry';
import { IEntity } from './entity-aspect';
import { MappingContext } from '... | getRequest(request: any, entity: IEntity, index: number) {
return request;
}
done(requests: Object[]) {
}
}
|
}
| identifier_body |
abstract-data-service-adapter.ts | import { core } from './core';
import { config } from './config';
import { EntityQuery } from './entity-query';
import { IDataServiceAdapter, IAjaxAdapter, IChangeRequestInterceptorCtor, IChangeRequestInterceptor } from './interface-registry';
import { IEntity } from './entity-aspect';
import { MappingContext } from '... | return interceptor;
} else {
return new DefaultChangeRequestInterceptor(saveContext, saveBundle) as IChangeRequestInterceptor;
}
}
/** Abstract method that needs to be overwritten in any concrete DataServiceAdapter sublclass.
This method needs to take the result returned the server and conver... | throw new Error(pre + '.done' + post);
}
| conditional_block |
contracts.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version... | // (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a... | random_line_split | |
contracts.rs | // Copyright (C) 2013-2020 Blockstack PBC, a public benefit corporation
// Copyright (C) 2020 Stacks Open Internet Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version... | {
pub contract_context: ContractContext,
}
// AARON: this is an increasingly useless wrapper around a ContractContext struct.
// will probably be removed soon.
impl Contract {
pub fn initialize_from_ast(
contract_identifier: QualifiedContractIdentifier,
contract: &ContractAST,
... | Contract | identifier_name |
listener.py | #
# Copyright 2015 IBM Corp.
#
# All Rights Reserved.
# 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 require... | (self):
self._delete_called = False
def check_delete_complete(self, data):
if self.resource_id is None:
return True
if not self._delete_called:
try:
self.client().delete_listener(self.resource_id)
self._delete_called = True
... | handle_delete | identifier_name |
listener.py | #
# Copyright 2015 IBM Corp.
#
# All Rights Reserved.
# 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 require... |
def handle_create(self):
properties = self.prepare_properties(
self.properties,
self.physical_resource_name())
properties['loadbalancer_id'] = properties.pop(self.LOADBALANCER)
return properties
def check_create_complete(self, properties):
if self.reso... | lb_id = self.properties[self.LOADBALANCER]
return self.client_plugin().check_lb_status(lb_id) | identifier_body |
listener.py | #
# Copyright 2015 IBM Corp.
#
# All Rights Reserved.
# 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 require... |
elif self.client_plugin().is_not_found(ex):
return True
raise
return self._check_lb_status()
def resource_mapping():
return {
'OS::Neutron::LBaaS::Listener': Listener,
}
| return False | conditional_block |
listener.py | #
# Copyright 2015 IBM Corp.
#
# All Rights Reserved.
# 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 require... | try:
self.client().update_listener(self.resource_id,
{'listener': prop_diff})
self._update_called = True
except Exception as ex:
if self.client_plugin().is_invalid(ex):
return False
... |
if not self._update_called: | random_line_split |
functions.py | from collections import defaultdict
from six import iteritems
def invert_mapping(mapping):
""" Invert a mapping dictionary
Parameters
----------
mapping: dict
Returns
-------
"""
inverted_mapping = defaultdict(list)
for key, value in mapping.items():
if isinstance(value,... |
def check_charge_balance(metabolites):
""" Check charge balance of the reaction """
# Check that charge is set for all metabolites
if not all(x.charge is not None for x in metabolites.keys()):
return None
else:
return sum([metabolite.charge * coefficient for metabolite, coefficient in... | """ Convert string of boolean value to actual bolean
PyQt5 stores boolean values as strings 'true' and 'false
in the settings. In order to use those stored values
they need to be converted back to the boolean values.
Parameters
----------
input_str: str
Returns
-------
bool
""... | identifier_body |
functions.py | from collections import defaultdict
from six import iteritems
def invert_mapping(mapping):
""" Invert a mapping dictionary
Parameters
----------
mapping: dict
Returns
-------
"""
inverted_mapping = defaultdict(list)
for key, value in mapping.items():
if isinstance(value,... | """ Check the balancing status of the stoichiometry
Parameters
----------
metabolites : dict - Dictionary of metabolites with stoichiometric coefficnets
Returns
-------
charge_str : str or bool
element_str : str or bool
balanced : str or bool
"""
element_result = check_elem... |
def reaction_balance(metabolites): | random_line_split |
functions.py | from collections import defaultdict
from six import iteritems
def invert_mapping(mapping):
""" Invert a mapping dictionary
Parameters
----------
mapping: dict
Returns
-------
"""
inverted_mapping = defaultdict(list)
for key, value in mapping.items():
if isinstance(value,... | (in_dict):
substrings = ['{0}: {1:.1f}'.format(*x) for x in in_dict.items()]
return "<br>".join(substrings)
def reaction_balance(metabolites):
""" Check the balancing status of the stoichiometry
Parameters
----------
metabolites : dict - Dictionary of metabolites with stoichiometric coefficne... | unbalanced_metabolites_to_string | identifier_name |
functions.py | from collections import defaultdict
from six import iteritems
def invert_mapping(mapping):
""" Invert a mapping dictionary
Parameters
----------
mapping: dict
Returns
-------
"""
inverted_mapping = defaultdict(list)
for key, value in mapping.items():
if isinstance(value,... |
else:
inverted_mapping[value].append(key)
return inverted_mapping
def generate_copy_id(base_id, collection, suffix="_copy"):
""" Generate a new id that is not present in collection
Parameters
----------
base_id: str, Original id while copying or New for new entries
colle... | inverted_mapping[element].append(key) | conditional_block |
server.js | 'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
const sl... | () {
slackAPIClient.send('channels.list',
function(err, response) {
if (err) console.log(err)
for (var i = 0; i < response.channels.length; i++) {
var channel = response.channels[i]
try {
var channelNumber = channel.name.split("-")[0]
if (!is... | fetchChannels | identifier_name |
server.js | 'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
const sl... |
function addUrlToChannel(channelId, url) {
return new Promise((resolve, reject) => {
request.post('http://itao-server-55663464.eu-central-1.elb.amazonaws.com/itao/item/add/url',
{body: url}, (err, res, body) => {
if (err) return reject(err);
try {
JSON.parse(body)[0]
console.log(`Successfully ... | {
return new Promise((resolve, reject) => {
slackAPIClient.send('channels.info',
{
channel: channelId
},
(err, response) => {
if (err) return reject(err)
resolve(response.channel.topic.value)
}
)
})
} | identifier_body |
server.js | 'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
const sl... | var verifiedIcon = req.body.verified ? "https://cdn3.iconfinder.com/data/icons/basicolor-arrows-checks/24/154_check_ok_sticker_success-512.png" : "http://www.clker.com/cliparts/H/Z/0/R/f/S/warning-icon-hi.png"
var attachment = {
callback_id: "share",
author_icon: verifiedIcon,
title_link: req... | random_line_split | |
server.js | 'use strict'
const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const BeepBoop = require('beepboop')
const bodyParser = require('body-parser')
const parameters = require('parameters-middleware');
const sl... | else if (source.source.type == 'channel') {
return `Channel: ${source.source.id}. ${source.source.name}`
}
})
msg.respond(`*Here is a list of all sources in the current feed:*\n${lines.join("\n")}`)
})
})
slapp.command('/feeds', '(help)?', (msg, text) => {
msg.respond(`Valid commands: \`list\`, \`connect... | {
return `Search: "${source.source.keywords}"`
} | conditional_block |
regression_fuzz.rs | // These tests are only run for the "default" test target because some of them
// can take quite a long time. Some of them take long enough that it's not
// practical to run them in debug mode. :-/
// See: https://oss-fuzz.com/testcase-detail/5673225499181056
//
// Ignored by default since it takes too long in debug m... |
// See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505
// See: https://github.com/rust-lang/regex/issues/722
#[test]
fn empty_any_errors_no_panic() {
assert!(regex_new!(r"\P{any}").is_err());
}
// This tests that a very large regex errors during compilation instead of
// using gratuitous amounts of ... | {
regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**");
} | identifier_body |
regression_fuzz.rs | // These tests are only run for the "default" test target because some of them
// can take quite a long time. Some of them take long enough that it's not
// practical to run them in debug mode. :-/ | #[test]
#[ignore]
fn fuzz1() {
regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**");
}
// See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505
// See: https://github.com/rust-lang/regex/issues/722
#[test]
fn empty_any_errors_no_panic() {
assert!(regex_new!(r"\P{any}").is_err());
}
// This tests th... |
// See: https://oss-fuzz.com/testcase-detail/5673225499181056
//
// Ignored by default since it takes too long in debug mode (almost a minute). | random_line_split |
regression_fuzz.rs | // These tests are only run for the "default" test target because some of them
// can take quite a long time. Some of them take long enough that it's not
// practical to run them in debug mode. :-/
// See: https://oss-fuzz.com/testcase-detail/5673225499181056
//
// Ignored by default since it takes too long in debug m... | () {
regex!(r"1}{55}{0}*{1}{55}{55}{5}*{1}{55}+{56}|;**");
}
// See: https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=26505
// See: https://github.com/rust-lang/regex/issues/722
#[test]
fn empty_any_errors_no_panic() {
assert!(regex_new!(r"\P{any}").is_err());
}
// This tests that a very large regex erro... | fuzz1 | identifier_name |
signals.py | """
Django signals for the app.
"""
import logging
from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.sites.models import Site
from .models import Response, UnitLesson
from .ct_util import get_middle_indexes
from core.common.mongo import c_milestone_orct
from core.com... | if (instance.kind == Response.ORCT_RESPONSE and not
(instance.unitLesson.kind == UnitLesson.RESOLVES or
instance.is_test or instance.is_preview or not instance.unitLesson.order)):
course = instance.course
course_id = course.id if course else None
instructors = course.get... | identifier_body | |
signals.py | """
Django signals for the app.
"""
import logging
from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.sites.models import Site
from .models import Response, UnitLesson
from .ct_util import get_middle_indexes
from core.common.mongo import c_milestone_orct
from core.com... |
# Define if it's a milestone question (either first, middle, or last)
milestone = None
questions = unit_lesson.unit.all_orct()
i = [_[0] for _ in questions.values_list('id')].index(unit_lesson_id)
if i == 0:
milestone = "first"
elif i == len(questions) - 1:
... | if student_id == instructor.id:
return | conditional_block |
signals.py | """
Django signals for the app.
"""
import logging
from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.sites.models import Site
from .models import Response, UnitLesson
from .ct_util import get_middle_indexes
from core.common.mongo import c_milestone_orct
from core.com... | (sender, instance, **kwargs):
# TODO: add check that Response has a text, as an obj can be created before a student submits
# TODO: exclude self eval submissions other than a response submission (e.g. "just guessing")
if (instance.kind == Response.ORCT_RESPONSE and not
(instance.unitLesson.kind... | run_courselet_notif_flow | identifier_name |
signals.py | """
Django signals for the app.
"""
import logging | from django.db.models.signals import post_save
from django.conf import settings
from django.contrib.sites.models import Site
from .models import Response, UnitLesson
from .ct_util import get_middle_indexes
from core.common.mongo import c_milestone_orct
from core.common.utils import send_email, suspending_receiver
lo... | random_line_split | |
tile_coding.py | # -*- coding: utf8 -*-
from typing import List, Tuple
import numpy as np
from yarll.functionapproximation.function_approximator import FunctionApproximator
class | (FunctionApproximator):
"""Map states to tiles"""
def __init__(self, x_low, x_high, y_low, y_high, n_tilings: int, n_y_tiles: int, n_x_tiles: int, n_actions: int) -> None:
super(TileCoding, self).__init__(n_actions)
self.x_low = x_low
self.x_high = x_high
self.y_low = y_low
... | TileCoding | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.