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 |
|---|---|---|---|---|
gulpfile.js | ');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
var rename =require('gulp-rename');
var svgstore =require('gulp-svgstore');
var svgmin ... |
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(pa... | return gulp
.src('templates/svg-icons.php')
.pipe(inject(svgs, { transform: fileContents }))
.pipe(gulp.dest('templates'));
}); | random_line_split |
shootout-k-nucleotide.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
get_sequence(&mut std::io::stdin(), ">THREE")
};
let input = Arc::new(input);
let nb_freqs: Vec<(uint, Future<Table>)> = range(1u, 3).map(|i| {
let input = input.clone();
(i, Future::spawn(proc() generate_frequencies(input.as_slice(), i)))
}).collect();
let occ_freqs... | {
let fd = std::io::File::open(&Path::new("shootout-k-nucleotide.data"));
get_sequence(&mut std::io::BufferedReader::new(fd), ">THREE")
} | conditional_block |
shootout-k-nucleotide.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self, frame: uint) -> String {
let mut key = self.hash();
let mut result = Vec::new();
for _ in range(0, frame) {
result.push(unpack_symbol((key as u8) & 3));
key >>= 2;
}
result.reverse();
String::from_utf8(result).unwrap()
}
}
// Hash tab... | unpack | identifier_name |
shootout-k-nucleotide.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | }
Table::search_remainder(&mut **entry, key, c)
}
}
fn iter<'a>(&'a self) -> Items<'a> {
Items { cur: None, items: self.items.iter() }
}
}
impl<'a> Iterator<&'a Entry> for Items<'a> {
fn next(&mut self) -> Option<&'a Entry> {
let ret = match self.cur {
... | if entry.code == key {
c.f(&mut **entry);
return; | random_line_split |
invariants.ts | import assertHasKey from "./invariants/assertHasKey";
import assertNotArray from "../utils/assertNotArray";
import constants from "../constants";
import makeScope from "../utils/makeScope";
import wrapArray from "../utils/wrapArray";
import {
Config,
InvariantsBaseArgs,
InvariantsExtraArgs,
ReducerName
} from ... | {
var config = extraArgs.config;
if (!config.resourceName) throw new Error("Expected config.resourceName");
const scope = makeScope(config, baseArgs.reducerName);
if (!config.key) throw new Error(scope + ": Expected config.key");
if (!extraArgs.record) throw new Error(scope + ": Expected record/s");
ext... | identifier_body | |
invariants.ts | import assertHasKey from "./invariants/assertHasKey";
import assertNotArray from "../utils/assertNotArray";
import constants from "../constants";
import makeScope from "../utils/makeScope";
import wrapArray from "../utils/wrapArray";
import {
Config,
InvariantsBaseArgs,
InvariantsExtraArgs,
ReducerName
} from ... | (
baseArgs: InvariantsBaseArgs,
extraArgs: InvariantsExtraArgs
) {
var config = extraArgs.config;
if (!config.resourceName) throw new Error("Expected config.resourceName");
const scope = makeScope(config, baseArgs.reducerName);
if (!config.key) throw new Error(scope + ": Expected config.key");
if (!ext... | invariants | identifier_name |
invariants.ts | import assertHasKey from "./invariants/assertHasKey"; |
import {
Config,
InvariantsBaseArgs,
InvariantsExtraArgs,
ReducerName
} from "../types";
export default function invariants(
baseArgs: InvariantsBaseArgs,
extraArgs: InvariantsExtraArgs
) {
var config = extraArgs.config;
if (!config.resourceName) throw new Error("Expected config.resourceName");
co... | import assertNotArray from "../utils/assertNotArray";
import constants from "../constants";
import makeScope from "../utils/makeScope";
import wrapArray from "../utils/wrapArray"; | random_line_split |
pat-tuple-2.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 ... | () {
tuple();
tuple_struct();
}
| main | identifier_name |
pat-tuple-2.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 ... | (..) => ()
}
}
fn tuple_struct() {
struct S(u8);
let x = S(1);
match x {
S(2, ..) => panic!(),
S(..) => ()
}
}
fn main() {
tuple();
tuple_struct();
} | (2, ..) => panic!(), | random_line_split |
cabi_x86_64.rs | 7,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&s... | (ccx: &CrateContext, cls: &[RegClass]) -> Type {
fn llvec_len(cls: &[RegClass]) -> usize {
let mut len = 1;
for c in cls {
if *c != SSEUp {
break;
}
len += 1;
}
return len;
}
let mut tys = Vec | llreg_ty | identifier_name |
cabi_x86_64.rs | 7,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&s... | if self.is_empty() { return false; }
self[0] == Memory
}
}
fn classify_ty(ty: Type) -> Vec<RegClass> {
fn align(off: usize, ty: Type) -> usize {
let a = ty_align(ty);
return (off + a - 1) / a * a;
}
fn ty_align(ty: Type) -> usize {
match ty.kind() {
... |
fn is_ret_bysret(&self) -> bool { | random_line_split |
cabi_x86_64.rs | 7,
X87Up,
ComplexX87,
Memory
}
trait TypeMethods {
fn is_reg_ty(&self) -> bool;
}
impl TypeMethods for Type {
fn is_reg_ty(&self) -> bool {
match self.kind() {
Integer | Pointer | Float | Double => true,
_ => false
}
}
}
impl RegClass {
fn is_sse(&s... |
}
trait ClassList {
fn is_pass_byval(&self) -> bool;
fn is_ret_bysret(&self) -> bool;
}
impl ClassList for [RegClass] {
fn is_pass_byval(&self) -> bool {
if self.is_empty() { return false; }
let class = self[0];
class == Memory
|| class == X87
|| class == Compl... | {
match *self {
SSEFs | SSEFv | SSEDs | SSEDv | SSEInt(_) => true,
_ => false
}
} | identifier_body |
framework.py | # This file is part of ICLS.
#
# ICLS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will ... | f.close()
exit() | f = open(filepath,'r')
print f.read() | random_line_split |
framework.py | # This file is part of ICLS.
#
# ICLS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will ... |
return output
#If, during parsing, help was flagged print out help text and then exit TODO read it from a md file
def print_help():
filepath = path.join(path.dirname(path.abspath(__file__)), 'DOCUMENTATION.mkd')
f = open(filepath,'r')
print f.read()
f.close()
exit() | output="========================================\n"
output+=entry['entry']+"\n"
output+=strftime("%H:%M %m.%d.%Y", strptime(entry['date'],"%Y-%m-%dT%H:%M:%S+0000"))+"\n"
output+='ID: '+entry.name | conditional_block |
framework.py | # This file is part of ICLS.
#
# ICLS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will ... | (the_color='blue',entry='',new_line=0):
color={'gray':30,'green':32,'red':31,'blue':34,'magenta':35,'cyan':36,'white':37,'highgreen':42,'highblue':44,'highred':41,'highgray':47}
if new_line==1:
new_line='\n'
else:
new_line=''
return_me='\033[1;'+str(color[the_color])+'m'+entry+'\033[1;m'+new_line
return return... | colorize | identifier_name |
framework.py | # This file is part of ICLS.
#
# ICLS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ICLS is distributed in the hope that it will ... | filepath = path.join(path.dirname(path.abspath(__file__)), 'DOCUMENTATION.mkd')
f = open(filepath,'r')
print f.read()
f.close()
exit() | identifier_body | |
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator; | use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query_validator::validate_old;
use sql::query_executer::{execute, ExecutionResult};
use sql::data_manager::DataManager;
use sql::catalog_manager::CatalogManager;
pub fn evaluate_query(query: &str, data_manager: &DataManager, catalog_manager: &C... | pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize; | random_line_split |
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator;
pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize;
use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query... | {
tokenize(query)
.and_then(parse)
.and_then(|statement| type_inferring_old(catalog_manager, statement))
.and_then(|statement| validate_old(catalog_manager, statement))
.and_then(|statement| execute(catalog_manager, data_manager, statement))
} | identifier_body | |
lib.rs | #[macro_use(expect)]
extern crate expectest;
extern crate sql;
pub mod lexer;
pub mod parser;
pub mod query_typer;
pub mod query_validator;
pub mod query_executer;
pub mod catalog_manager;
pub mod data_manager;
use sql::lexer::tokenize;
use sql::parser::parse;
use sql::query_typer::type_inferring_old;
use sql::query... | (query: &str, data_manager: &DataManager, catalog_manager: &CatalogManager) -> Result<ExecutionResult, String> {
tokenize(query)
.and_then(parse)
.and_then(|statement| type_inferring_old(catalog_manager, statement))
.and_then(|statement| validate_old(catalog_manager, statement))
.and... | evaluate_query | identifier_name |
openstack_cinder.py | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This pr... | self.cinder = self.is_installed("cinder-common")
return self.cinder
def setup(self):
super(DebianCinder, self).setup()
class RedHatCinder(OpenStackCinder, RedHatPlugin):
cinder = False
packages = ('openstack-cinder',
'python-cinder',
'python-cinder... |
def check_enabled(self): | random_line_split |
openstack_cinder.py | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This pr... | else:
self.add_copy_spec_limit("/var/log/cinder/*.log",
sizelimit=self.limit)
def postproc(self):
protect_keys = [
"admin_password", "backup_tsm_password", "chap_password",
"nas_password", "cisco_fc_fabric_password", "coraid_p... | """OpenStack cinder
"""
plugin_name = "openstack_cinder"
profiles = ('openstack', 'openstack_controller')
option_list = [("db", "gathers openstack cinder db version", "slow",
False)]
def setup(self):
if self.get_option("db"):
self.add_cmd_output(
... | identifier_body |
openstack_cinder.py | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This pr... |
self.add_copy_spec(["/etc/cinder/"])
self.limit = self.get_option("log_size")
if self.get_option("all_logs"):
self.add_copy_spec_limit("/var/log/cinder/",
sizelimit=self.limit)
else:
self.add_copy_spec_limit("/var/log/cinder... | self.add_cmd_output(
"cinder-manage db version",
suggest_filename="cinder_db_version") | conditional_block |
openstack_cinder.py | # Copyright (C) 2009 Red Hat, Inc., Joey Boggs <jboggs@redhat.com>
# Copyright (C) 2012 Rackspace US, Inc.,
# Justin Shepherd <jshepher@rackspace.com>
# Copyright (C) 2013 Red Hat, Inc., Flavio Percoco <fpercoco@redhat.com>
# Copyright (C) 2013 Red Hat, Inc., Jeremy Agee <jagee@redhat.com>
# This pr... | (self):
super(DebianCinder, self).setup()
class RedHatCinder(OpenStackCinder, RedHatPlugin):
cinder = False
packages = ('openstack-cinder',
'python-cinder',
'python-cinderclient')
def check_enabled(self):
self.cinder = self.is_installed("openstack-cinder")... | setup | identifier_name |
setup.py | import setuptools
with open("README.rst") as f:
long_description = f.read()
setuptools.setup(
name='django-diplomacy',
version="0.8.0", | description='A play-by-web app for Diplomacy',
long_description=long_description,
long_description_content_type='test/x-rst',
url='http://github.com/jbradberry/django-diplomacy',
packages=setuptools.find_packages(),
entry_points={
'turngeneration.plugins': ['diplomacy = diplomacy.plugins... | author='Jeff Bradberry',
author_email='jeff.bradberry@gmail.com', | random_line_split |
discount.server.model.test.js | 'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'), | var user, discount;
/**
* Unit tests
*/
describe('Discount Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function(... | Discount = mongoose.model('Discount');
/**
* Globals
*/ | random_line_split |
0003_comment.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-18 07:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone |
class Migration(migrations.Migration):
dependencies = [
('blog', '0002_post_subtitle'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'... | random_line_split | |
0003_comment.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-18 07:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
| dependencies = [
('blog', '0002_post_subtitle'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('author', models.CharFie... | identifier_body | |
0003_comment.py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-09-18 07:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class | (migrations.Migration):
dependencies = [
('blog', '0002_post_subtitle'),
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
... | Migration | identifier_name |
setup.py | #!/usr/bin/env python
from distutils.core import setup
import os
import sys
def main():
| author_email="bnsmith@gmail.com",
url="https://launchpad.net/caffeine",
packages=["caffeine"],
data_files=data_files,
scripts=[os.path.join("bin", "caffeine")]
)
if __name__ == "__main__":
main()
| SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH):
data_files.append(tuple((path.replace(SHARE_PATH,"s... | identifier_body |
setup.py | #!/usr/bin/env python
from distutils.core import setup
import os
import sys | def main():
SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH):
data_files.append(tuple((path.repl... | random_line_split | |
setup.py | #!/usr/bin/env python
from distutils.core import setup
import os
import sys
def main():
SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, ... | main() | conditional_block | |
setup.py | #!/usr/bin/env python
from distutils.core import setup
import os
import sys
def | ():
SHARE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"share")
data_files = []
# don't trash the users system icons!!
black_list = ['index.theme', 'index.theme~']
for path, dirs, files in os.walk(SHARE_PATH):
data_files.append(tuple((path.replace(SHAR... | main | identifier_name |
test2.js | /// <reference path="../test1.ts" />
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var test2;
(function (tes... | }
return Test2;
})(test1.Test1);
test2.Test2 = Test2;
})(test2 || (test2 = {}));
//# sourceMappingURL=/public/maps/subdir/test2.js.map | console.log('prop2', this.getProp2()); | random_line_split |
test2.js | /// <reference path="../test1.ts" />
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() |
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var test2;
(function (test2) {
var Test2 = (function (_super) {
__extends(Test2, _super);
function Test2() {
_super.call(this);
console.log('extends');
console.log('prop1... | { this.constructor = d; } | identifier_body |
test2.js | /// <reference path="../test1.ts" />
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var test2;
(function (tes... | () {
_super.call(this);
console.log('extends');
console.log('prop1', this.getProp1());
console.log('prop2', this.getProp2());
}
return Test2;
})(test1.Test1);
test2.Test2 = Test2;
})(test2 || (test2 = {}));
//# sourceMappingURL=/public/maps/subdir/... | Test2 | identifier_name |
index.js | /**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by a... | // => 'F(2.5) = 1' | var y = discreteUniform.cdf( 2.5 );
console.log( 'F(2.5) = %d', y ); | random_line_split |
uniprot_core.py | # reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
... | eend = int(tokens[5])
rough_a_length = int(int(tokens[0].split("_")[-1].split("=")[1]) / 3)
if asid[0] == "I":
rough_a_length = 0
c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c... | sstart = int(tokens[2])
start = int(tokens[3])
end = int(tokens[4]) | random_line_split |
uniprot_core.py | # reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
... |
else:
uniprot_to_index_to_core[prot] = {index: core}
except ValueError:
print "Cannot parse: " + line[0:len(line) - 1]
return uniprot_to_index_to_core
def get_sable_scores(map_file, f_sable_db_location, uniprot_core_output_location):
map_file_obj = open(map_fil... | uniprot_to_index_to_core[prot][index] = core | conditional_block |
uniprot_core.py | # reads uniprot core file and generates core features
from features_helpers import score_differences
def build_uniprot_to_index_to_core(sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
... | c1_count = 0
a_count = 0
c2_count = 0
canonical_absolute = 0
if prot in uniprot_to_index_to_core:
c1_count = score_differences(uniprot_to_index_to_core, prot, sstart, start)
a_count = score_differences(uniprot_to_index_to_core, prot, start, end)
... | map_file_obj = open(map_file, 'r')
sable_db_obj = open(f_sable_db_location, 'r')
write_to = open(uniprot_core_output_location, 'w')
uniprot_to_index_to_core = build_uniprot_to_index_to_core(sable_db_obj)
for line in map_file_obj:
tokens = line.split()
asid = tokens[0].split("_")[0]
... | identifier_body |
uniprot_core.py | # reads uniprot core file and generates core features
from features_helpers import score_differences
def | (sable_db_obj):
uniprot_to_index_to_core = {}
for line in sable_db_obj:
tokens = line.split()
try:
# PARSING ID
prot = tokens[0]
index = int(tokens[1])
core = tokens[2]
# PARSING ID
if uniprot_to_index_to_core.has_key(prot):... | build_uniprot_to_index_to_core | identifier_name |
sh.py | ) or not os.path.isdir(path):
raise Exception('Called rmtree(%s) in non-directory' % path)
if sys.platform == 'win32':
# Some people don't have the APIs installed. In that case we'll do without.
win32api = None
win32con = None
try:
import win32api
impo... | """ Preserve file metadata of 'path' """
self.path = path
self.time = None
self.mode = None | identifier_body | |
sh.py | rm(dest)
shutil.copy(src, dest)
installed.append(os.path.basename(src))
return installed
def safe_copy(src, dest):
"""
Copy a source file to a destination but
do not overwrite dest if it is more recent than src
Create any missing directories when necessary
If dest is a ... | TempDir | identifier_name | |
sh.py | has its mode set appropriately before descending into it. This should
result in the entire tree being removed, with the possible exception of
``path`` itself, because nothing attempts to change the mode of its parent.
Doing so would be hazardous, as it's not a directory slated for removal.
In the o... | return True
return False
def is_executable_binary(file_path): | random_line_split | |
sh.py |
_username = os.environ.get("USERNAME")
if _username:
return _username
return None
def mkdir(dest_dir, recursive=False):
""" Recursive mkdir (do not fail if file exists) """
try:
if recursive:
os.makedirs(dest_dir)
else:
os.mkdir(dest_dir)
except... | import pwd
uid = os.getuid() # pylint:disable=no-member
pw_info = pwd.getpwuid(uid)
if pw_info:
return pw_info.pw_name | conditional_block | |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, ... |
impl<S,T> Factory for (S, T)
where S: Factory,
T: Factory,
S::Output: ToStatic,
<S::Output as ToStatic>::Static: Upcast<S::Output>,
{
type Output = (S::Output, T::Output);
fn build(&self) -> Self::Output { (self.0.build().to_static().upcast(), self.1.build()) }
}
impl Factory... | fn build(&self) -> Self::Output;
} | random_line_split |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, ... |
}
impl Upcast<()> for ()
{
fn upcast(self) -> () { () }
}
pub trait ToStatic {
type Static: 'static;
fn to_static(self) -> Self::Static where Self: Sized;
}
impl<T, U> ToStatic for (T, U)
where T: ToStatic,
U: ToStatic
{
type Static = (T::Static, U::Static);
fn to_static(self) -> S... | { (self.0.upcast(), self.1.upcast()) } | identifier_body |
project-cache-issue-31849.rs | // run-pass
// Regression test for #31849: the problem here was actually a performance
// cliff, but I'm adding the test for reference.
pub trait Upcast<T> {
fn upcast(self) -> T;
}
impl<S1, S2, T1, T2> Upcast<(T1, T2)> for (S1,S2)
where S1: Upcast<T1>,
S2: Upcast<T2>,
{
fn upcast(self) -> (T1, ... | (self) -> Self::Static { (self.0.to_static(), self.1.to_static()) }
}
impl ToStatic for ()
{
type Static = ();
fn to_static(self) -> () { () }
}
trait Factory {
type Output;
fn build(&self) -> Self::Output;
}
impl<S,T> Factory for (S, T)
where S: Factory,
T: Factory,
S::Outpu... | to_static | identifier_name |
terminal.ts | Up = 2,
Down = 3
}
export interface ITerminalGroup {
activeInstance: ITerminalInstance | undefined;
terminalInstances: ITerminalInstance[];
title: string;
readonly onDidDisposeInstance: Event<ITerminalInstance>;
readonly onDisposed: Event<ITerminalGroup>;
readonly onInstancesChanged: Event<void>;
readonly on... | }
export const enum Direction {
Left = 0,
Right = 1, | random_line_split | |
IConnection.d.ts | /*!
* Copyright Unlok, Vaughn Royko 2011-2019
* http://www.unlok.ca
*
* Credits & Thanks:
* http://www.unlok.ca/credits-thanks/
*
* Wayward is a copyrighted and licensed work. Modification and/or distribution of any source files is prohibited. If you wish to modify the game in any way, please refer to the moddin... | bufferOffset?: number;
bufferPacketId?: number;
lastPacketNumberSent?: number;
lastPacketNumberReceived?: number;
addConnectionTimeout(): void;
addKeepAliveTimeout(): void;
addTimeout(milliseconds: number, callback: () => void): void;
clearTimeout(): void;
close(): void;
getState... | random_line_split | |
prime_field.rs | use normalize::*;
use pack::Pack;
use rand::Rand;
use std::marker::Sized;
use std::ops::Add;
use std::ops::AddAssign;
use std::ops::Div;
use std::ops::DivAssign;
use std::ops::Mul;
use std::ops::MulAssign;
use std::ops::Neg;
use std::ops::Sub;
use std::ops::SubAssign;
| Div<Self, Output = Self> + DivAssign<Self> +
MulAssign<i32> + MulAssign<i16> + MulAssign<i8> + MulAssign<Self> +
Mul<i32, Output = Self> + Mul<i16, Output = Self> +
Mul<i8, Output = Self> + Mul<Self, Output = Self> +
Neg<Output = Self> + Normalize + NormalizeEq + Pack + Rand + Sized +
SubAssign<... | /// Operations on prime fields.
pub trait PrimeField : Add<i32, Output = Self> + Add<i16, Output = Self> +
Add<i8, Output = Self> + Add<Self, Output = Self> +
AddAssign<i32> + AddAssign<i16> + AddAssign<i8> + AddAssign<Self> + | random_line_split |
sudokucsolver.js | self.importScripts('sudokuc.js');
const resultGrid = [];
let gridPtr = null;
const workingSeeds = [];
let workingSeedsHash = {};
function makeGridFromResult() {
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) |
}
return resultGrid;
}
function solveGrid(grid, Module) {
if (!gridPtr) {
return;
}
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i] = grid[y][x];
i++;
}
}
let seed = Date.... | {
resultGrid[y][x] = Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i];
i++;
} | conditional_block |
sudokucsolver.js | self.importScripts('sudokuc.js');
const resultGrid = [];
let gridPtr = null;
const workingSeeds = [];
let workingSeedsHash = {};
function makeGridFromResult() {
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
resultGrid[y][x] = Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) ... | }
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i] = grid[y][x];
i++;
}
}
let seed = Date.now();
let solved = Module.ccall('solveSudoku', 'bool', ['number', 'number'], [gridPtr, seed]);
... |
function solveGrid(grid, Module) {
if (!gridPtr) {
return; | random_line_split |
sudokucsolver.js | self.importScripts('sudokuc.js');
const resultGrid = [];
let gridPtr = null;
const workingSeeds = [];
let workingSeedsHash = {};
function makeGridFromResult() {
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
resultGrid[y][x] = Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) ... |
if(typeof(Module)!=='undefined') {
Module.onRuntimeInitialized = initialize;
}
| {
Module._free(gridPtr);
} | identifier_body |
sudokucsolver.js | self.importScripts('sudokuc.js');
const resultGrid = [];
let gridPtr = null;
const workingSeeds = [];
let workingSeedsHash = {};
function makeGridFromResult() {
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
resultGrid[y][x] = Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) ... | (grid, Module) {
if (!gridPtr) {
return;
}
for(let i=0, y=1; y<=9; y++) {
for(let x=1; x<=9; x++) {
Module.HEAPU32[(gridPtr / Uint32Array.BYTES_PER_ELEMENT) + i] = grid[y][x];
i++;
}
}
let seed = Date.now();
let solved = Module.ccall('solveSudoku',... | solveGrid | identifier_name |
lib.rs | (e.get_mut(), n.as_ptr(), m.as_ptr()) };
e
}
fn empty() -> Error {
init_dbus();
let mut e = ffi::DBusError {
name: ptr::null(),
message: ptr::null(),
dummy: 0,
padding1: ptr::null()
};
unsafe { ffi::dbus_error_init(&mut e);... |
let mut v = Vec::new();
let mut i = 0;
loop {
let s = unsafe {
let citer = clist.offset(i);
if *citer == ptr::null_mut() { break };
std::mem::transmute(citer)
};
v.push(format!("{}", c_str_to_slice(s).unwrap()))... | { panic!("Out of memory"); } | conditional_block |
lib.rs | (e.get_mut(), n.as_ptr(), m.as_ptr()) };
e
}
fn empty() -> Error {
init_dbus();
let mut e = ffi::DBusError {
name: ptr::null(),
message: ptr::null(),
dummy: 0,
padding1: ptr::null()
};
unsafe { ffi::dbus_error_init(&mut e);... | {
conn: Cell<*mut ffi::DBusConnection>,
pending_items: RefCell<LinkedList<ConnectionItem>>,
}
/// A D-Bus connection. Start here if you want to get on the D-Bus!
pub struct Connection {
i: Box<IConnection>,
}
extern "C" fn filter_message_cb(conn: *mut ffi::DBusConnection, msg: *mut ffi::DBusMessage,
... | IConnection | identifier_name |
lib.rs | mute(ffi::dbus_message_get_type(msg)) };
let r = match mtype {
ffi::DBusMessageType::Signal => {
i.pending_items.borrow_mut().push_back(ConnectionItem::Signal(m));
ffi::DBusHandlerResult::Handled
}
_ => ffi::DBusHandlerResult::NotYetHandled,
};
r
}
extern "C... | assert_eq!(reply, vec!(MessageItem::Bool(true)));
} | random_line_split | |
app.js | angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/])
.config(function ($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
$routeProvider
.when('/login', {
templateUrl: '... | else if (!nextRoute.protect && UserAuth.isLogged) {
$location.path('/overview');
}
});
}); | {
$location.path('/login');
console.error('Route protected, user not logged in');
} | conditional_block |
app.js | angular.module('MEANcraftApp', ['ngRoute', 'MEANcraftApp.login', 'MEANcraftApp.overview', 'btford.socket-io'/*,'socket-io', 'flow'*/])
.config(function ($httpProvider, $routeProvider) {
$httpProvider.interceptors.push('TokenInterceptor');
$routeProvider
.when('/login', {
templateUrl: '... | }); | }
}); | random_line_split |
projects.py | # Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# 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 appli... | (self, pid=None, tid=None):
projects_index = Projects()
if not pid and not tid:
abort(404,
detail="A tag ID or project ID must be passed as parameter")
if pid:
project = projects_index.get(pid)
else:
if tid in projects_index.get_tags(... | repos | identifier_name |
projects.py | # Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# 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 appli... |
if pid:
project = projects_index.get(pid)
else:
if tid in projects_index.get_tags():
refs = projects_index.get_references_from_tags(tid)
project = {'refs': refs}
else:
project = None
if not project:
... | abort(404,
detail="A tag ID or project ID must be passed as parameter") | conditional_block |
projects.py | # Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# 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 appli... |
from repoxplorer import version
from repoxplorer.index.projects import Projects
rx_version = version.get_version()
class ProjectsController(object):
@expose('json')
def projects(self, pid=None):
projects_index = Projects()
if pid:
project = projects_index.get(pid)
if... | from collections import OrderedDict
from pecan import abort
from pecan import expose | random_line_split |
projects.py | # Copyright 2017, Fabien Boucher
# Copyright 2017, Red Hat
#
# 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 appli... |
@expose('json')
def repos(self, pid=None, tid=None):
projects_index = Projects()
if not pid and not tid:
abort(404,
detail="A tag ID or project ID must be passed as parameter")
if pid:
project = projects_index.get(pid)
else:
... | projects_index = Projects()
if pid:
project = projects_index.get(pid)
if not project:
abort(404, detail="Project ID has not been found")
return {pid: projects_index.get(pid)}
else:
projects = projects_index.get_projects(
sou... | identifier_body |
to_str.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... | }
_ => cx.bug("expected Struct or EnumMatching in deriving(ToStr)")
};
} | } | random_line_split |
lemkelcp.py | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y =... |
def swapPos(self,v,ind,newPos):
if v == self.W:
self.wPos[ind] = newPos % (2*self.n+2)
elif v == self.Z:
self.zPos[ind] = newPos % (2*self.n+2)
def swapColumns(self,i,j):
iInd = self.Tind[:,i]
jInd = self.Tind[:,j]
... | Mi = np.array(M[:,i],copy=True)
Mj = np.array(M[:,j],copy=True)
M[:,i] = Mj
M[:,j] = Mi
return M | identifier_body |
lemkelcp.py | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y =... |
else:
return False
def step(self):
q = self.T[:,-1]
a = self.T[:,-2]
ind = np.nan
minRatio = np.inf
for i in range(self.n):
if a[i] > 0:
newRatio = q[i] / a[i]
if newRatio < minRatio:
... | ind = np.argmin(q)
self.clearDriverColumn(ind)
self.pivot(ind)
return True | conditional_block |
lemkelcp.py | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y =... | (self):
q = self.T[:,-1]
a = self.T[:,-2]
ind = np.nan
minRatio = np.inf
for i in range(self.n):
if a[i] > 0:
newRatio = q[i] / a[i]
if newRatio < minRatio:
ind = i
minRatio = newRatio
... | step | identifier_name |
lemkelcp.py | import numpy as np
class lemketableau:
def __init__(self,M,q,maxIter = 100):
n = len(q)
self.T = np.hstack((np.eye(n),-M,-np.ones((n,1)),q.reshape((n,1))))
self.n = n
self.wPos = np.arange(n)
self.zPos = np.arange(n,2*n)
self.W = 0
self.Z = 1
self.Y =... | # Solution Found
z = self.extractSolution()
return z,0,'Solution Found'
elif not stepVal:
return None,1,'Secondary ray found'
return None,2,'Max Iterations Exceeded'
def initialize(self):
q = self.T[:,-... | for k in range(self.maxIter):
stepVal = self.step()
if self.Tind[0,-2] == self.Y: | random_line_split |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a cal... |
#[inline(always)]
#[cfg_attr(feature = "clippy", allow(inline_always))]
/// Save the current context. This function will actually return twice.
/// The first return is just after saving the context and will return false
/// The second time is when the saved context gets restored and will return
... | {
unsafe {
imp::registers_load(&self.regs);
}
} | identifier_body |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a cal... | <F>(wrapper: WrapperFn, mut f: F, stack: &mut Stack) -> Self
where F: FnMut() -> (), F: Send + 'static {
let fun = move || {
f();
};
let boxed_fun: Box<FnBox()> = Box::new(fun);
let fun_ptr = Box::into_raw(Box::new(boxed_fun)) as *mut u8;
Context {
... | new | identifier_name |
mod.rs | use alloc::boxed::{Box, FnBox};
use super::stack::Stack;
#[cfg(target_arch = "x86")]
mod i686;
#[cfg(target_arch = "x86_64")]
mod x86_64;
mod imp {
#[cfg(target_arch = "x86")]
pub use super::i686::*;
#[cfg(target_arch = "x86_64")]
pub use super::x86_64::*;
}
/// A thread has to be wrapped by a cal... | pub fn load(&self) -> ! {
unsafe {
imp::registers_load(&self.regs);
}
}
#[inline(always)]
#[cfg_attr(feature = "clippy", allow(inline_always))]
/// Save the current context. This function will actually return twice.
/// The first return is just after saving the conte... |
/// Load the current context to the CPU | random_line_split |
borrowck-preserve-box-in-pat.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 ... | // exec-env:RUST_POISON_ON_FREE=1
use std::ptr;
struct F { f: ~int }
pub fn main() {
let x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_pt... | // option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
borrowck-preserve-box-in-pat.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 x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
assert_... | identifier_body | |
borrowck-preserve-box-in-pat.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 x = @mut @F {f: ~3};
match x {
@@F{f: ref b_x} => {
assert_eq!(**b_x, 3);
assert_eq!(ptr::to_unsafe_ptr(&(x.f)), ptr::to_unsafe_ptr(b_x));
*x = @F {f: ~4};
info!("ptr::to_unsafe_ptr(*b_x) = {:x}",
ptr::to_unsafe_ptr(&(**b_x)) as uint);
asse... | main | identifier_name |
mdata_info.rs | box::Key, secretbox::Nonce),
) -> Self {
MDataInfo {
name,
type_tag,
enc_info: Some(enc_info),
new_enc_info: None,
}
}
/// Construct `MDataInfo` for public data.
pub fn new_public(name: XorName, type_tag: u64) -> Self {
MDataInfo {... | {
(true, key.0, nonce.0)
} | conditional_block | |
mdata_info.rs | the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<... | (&mut self) {
if let Some(new_enc_info) = self.new_enc_info.take() {
self.enc_info = Some(new_enc_info);
}
}
/// Construct FFI wrapper for the native Rust object, consuming self.
pub fn into_repr_c(self) -> FfiMDataInfo {
let (has_enc_info, enc_key, enc_nonce) = enc_info... | commit_new_enc_info | identifier_name |
mdata_info.rs | the data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<... |
Ok(output)
}
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
... | random_line_split | |
mdata_info.rs | data where the directory is stored.
pub type_tag: u64,
/// Key to encrypt/decrypt the directory content and the nonce to be used for keys
pub enc_info: Option<(shared_secretbox::Key, secretbox::Nonce)>,
/// Future encryption info, used for two-phase data reencryption.
pub new_enc_info: Option<(sha... |
fn encrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: info.enc_entry_value(&value.content)?,
entry_version: value.entry_version,
})
}
fn decrypt_value(info: &MDataInfo, value: &Value) -> Result<Value, CoreError> {
Ok(Value {
content: i... | {
let mut output = Vec::with_capacity(values.len());
for value in values {
output.push(decrypt_value(info, value)?);
}
Ok(output)
} | identifier_body |
sqlalchemy_utils.py | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(... | global sqlalchemy_engine
if sqlalchemy_engine is None:
def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
c... | identifier_body | |
sqlalchemy_utils.py | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(... | (self) -> 'NonClosingPool':
return self.__class__(creator=self._creator,
recycle=self._recycle,
use_threadlocal=self._use_threadlocal,
reset_on_return=self._reset_on_return,
echo=self.echo,
... | recreate | identifier_name |
sqlalchemy_utils.py | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(... |
sa_connection = sqlalchemy_engine.connect()
sa_connection.execution_options(autocommit=False)
return sa_connection
| def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sqlalchemy_engine = sqlalchemy.create_engine('postgresql://',
creator=get_dj_conn,
... | conditional_block |
sqlalchemy_utils.py | from typing import Any, Optional
import sqlalchemy
from django.db import connection
from zerver.lib.db import TimeTrackingConnection
# This is a Pool that doesn't close connections. Therefore it can be used with
# existing Django database connections.
class NonClosingPool(sqlalchemy.pool.NullPool):
def status(... | sqlalchemy_engine: Optional[Any] = None
def get_sqlalchemy_connection() -> sqlalchemy.engine.base.Connection:
global sqlalchemy_engine
if sqlalchemy_engine is None:
def get_dj_conn() -> TimeTrackingConnection:
connection.ensure_connection()
return connection.connection
sq... | echo=self.echo,
logging_name=self._orig_logging_name,
_dispatch=self.dispatch)
| random_line_split |
random_trees.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from optparse import make_option
import random
import math
from django.contrib.gis.geos import Point
from treemap.models import Plot, Tree, Species
from treemap.management.util impor... | (self, *args, **options):
""" Create some seed data """
instance, user = self.setup_env(*args, **options)
species_qs = instance.scope_model(Species)
n = options['n']
self.stdout.write("Will create %s plots" % n)
get_prob = lambda option: float(min(100, max(0, option)))... | handle | identifier_name |
random_trees.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from optparse import make_option
import random
import math
from django.contrib.gis.geos import Point
from treemap.models import Plot, Tree, Species
from treemap.management.util impor... | make_option('-s', '--prob-of-species',
action='store',
type='int',
dest='pspecies',
default=50,
help=('Probability that a given tree will '
'have a species (0-100)')),
make_optio... | option_list = InstanceDataCommand.option_list + (
make_option('-r', '--radius',
action='store',
type='int',
dest='radius',
default=5000,
help='Number of meters from the center'),
make_option('-n', '--numb... | identifier_body |
random_trees.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from optparse import make_option
import random
import math
from django.contrib.gis.geos import Point
from treemap.models import Plot, Tree, Species
from treemap.management.util impor... |
self.stdout.write("Created %s trees and %s plots" % (ct, cp))
| add_species = random.random() < species_prob
if add_species:
species = random.choice(species_qs)
else:
species = None
add_diameter = random.random() < diameter_prob
if add_diameter:
diameter = 2 ... | conditional_block |
random_trees.py | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from optparse import make_option
import random
import math
from django.contrib.gis.geos import Point
from treemap.models import Plot, Tree, Species
from treemap.management.util impor... | self.stdout.write("Will create %s plots" % n)
get_prob = lambda option: float(min(100, max(0, option))) / 100.0
tree_prob = get_prob(options['ptree'])
species_prob = get_prob(options['pspecies'])
diameter_prob = get_prob(options['pdiameter'])
max_radius = options['radius... | instance, user = self.setup_env(*args, **options)
species_qs = instance.scope_model(Species)
n = options['n'] | random_line_split |
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultA... |
#[inline]
unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) {
self.vector.replace_unchecked(i, val.vector)
}
#[inline]
fn select(self, cond: Self::SimdBool, other: Self) -> Self {
self.vector.select(cond, other.vector).into()
}
}
| {
self.vector.replace(i, val.vector)
} | identifier_body |
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultA... | self.vector.extract(i).into()
}
#[inline]
unsafe fn extract_unchecked(&self, i: usize) -> Self::Element {
self.vector.extract_unchecked(i).into()
}
#[inline]
fn replace(&mut self, i: usize, val: Self::Element) {
self.vector.replace(i, val.vector)
}
#[inline]
... | VectorN::splat(val.vector).into()
}
#[inline]
fn extract(&self, i: usize) -> Self::Element { | random_line_split |
translation_simba.rs | use simba::simd::SimdValue;
use crate::base::allocator::Allocator;
use crate::base::dimension::DimName;
use crate::base::{DefaultAllocator, VectorN};
use crate::Scalar;
use crate::geometry::Translation;
impl<N: Scalar + SimdValue, D: DimName> SimdValue for Translation<N, D>
where
N::Element: Scalar,
DefaultA... | (&mut self, i: usize, val: Self::Element) {
self.vector.replace(i, val.vector)
}
#[inline]
unsafe fn replace_unchecked(&mut self, i: usize, val: Self::Element) {
self.vector.replace_unchecked(i, val.vector)
}
#[inline]
fn select(self, cond: Self::SimdBool, other: Self) -> Self ... | replace | identifier_name |
main.rs | ::header::{AUTHORIZATION, USER_AGENT};
use indicatif::{ProgressBar, ProgressStyle};
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod github;
static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";
static USERAGENT: &'static str = "release-party-br";
lazy_static! {
static ref RP_VE... | let ignored: IgnoredRepo = match toml::from_str(&buffer) {
Ok(ignored_repos) => ignored_repos,
Err(e) => {
println!(
"Couldn't parse toml from ignoredrepos.toml, not ignoring any repos. Reason: {}",
e
);
return Vec::new();
}... | random_line_split | |
main.rs | ::from_yaml(yaml);
version_string(&app)
};
}
fn main() {
let yaml = load_yaml!("release-party.yml");
let matches = App::from_yaml(yaml).get_matches();
let org_url = make_org_url(&matches);
let token = match env::var(GITHUB_TOKEN) {
Ok(env_var) => env_var,
Err(_) => {
... | suggestion_for_org_sad | identifier_name | |
main.rs | ::header::{AUTHORIZATION, USER_AGENT};
use indicatif::{ProgressBar, ProgressStyle};
use std::env;
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
mod github;
static GITHUB_TOKEN: &'static str = "RP_GITHUBTOKEN";
static USERAGENT: &'static str = "release-party-br";
lazy_static! {
static ref RP_VE... |
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn get_ignored_repos_happy_path() {
let ignored_repositories = vec!["calagator".to_owned(), "moe".to_owned()];
assert_eq!(ignored_repositories, ignored_repos());
}
#[test]
fn handle_malformed_org() {
assert_eq!(
... | {
println!("{}", message);
::std::process::exit(exit_code);
} | identifier_body |
speaksfor_util.py | (root, name):
for child in root.childNodes:
if child.nodeName == name:
return child
return None
# Write a string to a tempfile, returning name of tempfile
def write_to_tempfile(str):
str_fd, str_file = tempfile.mkstemp()
if str:
os.write(str_fd, str)
os.close(str_fd)
... | findChildNamed | identifier_name | |
speaksfor_util.py | start_index = cert.find(start_label) + len(start_label)
else:
start_index = 0
end_label = '-----END CERTIFICATE-----'
end_index = cert.find(end_label)
first_cert = cert[start_index:end_index]
pieces = first_cert.split('\n')
first_cert = "".join(pieces)
return first_cert
# Validate ... | print "Creating ABAC SpeaksFor using ABACCredential...\n"
# Write out the user cert
from tempfile import mkstemp
ma_str = ma_gid.save_to_string()
user_cert_str = user_gid.save_to_string()
if not user_cert_str.endswith(ma_str):
user_cert_str += ma_str
fp, user_cert_filename = mkstemp(suff... | identifier_body | |
speaksfor_util.py | certificate are in uppercase with colon separators.
"""
raw_key_id = gid.get_extension('subjectKeyIdentifier')
# Raw has colons separating pairs, and all characters are upper case.
# Remove the colons and convert to lower case.
keyid = raw_key_id.replace(':', '').lower()
return keyid
# Pull t... |
user_keyid = get_cert_keyid(user_gid)
tool_keyid = get_cert_keyid(tool_gid)
subject_keyid = tails[0].get_principal_keyid()
head = cred.get_head()
principal_keyid = head.get_principal_keyid()
role = head.get_role()
# Credential must pass xmlsec1 verify
cred_file = write_to_tempfile(cr... | return False, None, "Invalid ABAC-SF credential: Need exactly 1 tail element, got %d (%s)" % \
(len(tails), cred.get_summary_tostring()) | conditional_block |
speaksfor_util.py | def run_subprocess(cmd, stdout, stderr):
try:
proc = subprocess.Popen(cmd, stdout=stdout, stderr=stderr)
proc.wait()
if stdout:
output = proc.stdout.read()
else:
output = proc.returncode
return output
except Exception as e:
raise Exception(... | os.write(str_fd, str)
os.close(str_fd)
return str_file
# Run a subprocess and return output | random_line_split | |
view.py | def guess_zulip_user_from_jira(jira_username, realm):
# type: (Text, Realm) -> Optional[UserProfile]
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
# and beginning of email address
user = UserProfile.objects.filter(
Q(full_name... | 'comment_created', # we handle issue_update event instead
'comment_updated', # we handle issue_update event instead
'comment_deleted', # we handle issue_update event instead
]
| random_line_split | |
view.py | # we handle issue_update event instead
]
def guess_zulip_user_from_jira(jira_username, realm):
# type: (Text, Realm) -> Optional[UserProfile]
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
# and beginning of email address
user = UserProf... | (payload, issue_id=None):
# type: (Dict[str, Any], Text) -> Text
# Guess the URL as it is not specified in the payload
# We assume that there is a /browse/BUG-### page
# from the REST url of the issue itself
if issue_id is None:
issue_id = get_issue_id(payload)
base_url = re.match("(.*)... | get_issue_string | identifier_name |
view.py | # we handle issue_update event instead
]
def guess_zulip_user_from_jira(jira_username, realm):
# type: (Text, Realm) -> Optional[UserProfile]
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
# and beginning of email address
user = UserProf... |
def get_issue_subject(payload):
# type: (Dict[str, Any]) -> Text
return u"{}: {}".format(get_issue_id(payload), get_issue_title(payload))
def get_sub_event_for_update_issue(payload):
# type: (Dict[str, Any]) -> Text
sub_event = payload.get('issue_event_type_name', '')
if sub_event == '':
... | return get_in(payload, ['issue', 'fields', 'summary']) | identifier_body |
view.py | # we handle issue_update event instead
]
def guess_zulip_user_from_jira(jira_username, realm):
# type: (Text, Realm) -> Optional[UserProfile]
try:
# Try to find a matching user in Zulip
# We search a user's full name, short name,
# and beginning of email address
user = UserProf... |
elif sub_event == 'issue_comment_edited':
verb = 'edited comment on'
else:
verb = 'deleted comment from'
content = u"{} **{}** {}{}".format(get_issue_author(payload), verb, issue, assignee_blurb)
comment = get_in(payload, ['comment', 'body'])
if comment:
... | verb = 'added comment to' | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.