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 |
|---|---|---|---|---|
lib.rs | Sign::Zero => Int::zero(),
Sign::Positive => Int::one()
}
}
}
pub struct BigFloat {
value: __mpfr_struct
}
impl fmt::Debug for BigFloat {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "BigFloat {{ prec: {}, sign: {}, exp: {}, d: {:p}, value: {} }}",
... | one | identifier_name | |
lib.rs | ::Positive
}
}
/// Converts the `Sign` value to an integral number.
///
/// The standard convention is used: `Negative` is turned to `-1`, `Zero` is turned to `0`,
/// `Positive` - to `1`.
pub fn to_int<I: Int>(self) -> I {
match self {
Sign::Negative => <I as Int>::... | r if r > 0 => Some(Ordering::Greater),
_ if Flags::Erange.is_set() => None,
_ => Some(Ordering::Equal) | random_line_split | |
lib.rs | #[derive(Copy)]
pub enum Sign {
Negative,
Zero,
Positive
}
impl Sign {
/// Obtains a `Sign` value from the given integral number.
///
/// The standard convention is used: if the given number is less than zero, then
/// `Negative` is returned; if greater than zero, then `Positive` is returne... | {
-self.clone()
} | identifier_body | |
models_tests.py | import unittest
import os
os.environ['MIAMI_ENV'] = 'test'
import simplejson as json
from miami.models import Team, User, Task
class ModelsTest(unittest.TestCase):
def test_team_toJSON(self):
team = Team('Log')
team.id = 1
self.assertEquals({'id':1, 'name': 'Log', 'color': '2a33d8'}, team.... | self.assertEquals({'name': 'Mike', 'gravater': '91f376c4b36912e5075b6170d312eab5'}, user.toJSON())
def test_task_toJSON(self):
team = Team('Log')
team.id = 1
task = Task('title1', 'detail', status='DONE', price=1, estimate=4, team=team)
task.id = 1
task.owner = User(... | random_line_split | |
models_tests.py |
import unittest
import os
os.environ['MIAMI_ENV'] = 'test'
import simplejson as json
from miami.models import Team, User, Task
class | (unittest.TestCase):
def test_team_toJSON(self):
team = Team('Log')
team.id = 1
self.assertEquals({'id':1, 'name': 'Log', 'color': '2a33d8'}, team.toJSON())
def test_user_toJSON(self):
user = User('Mike')
self.assertEquals({'name': 'Mike', 'gravater': '91f376c4b36912e50... | ModelsTest | identifier_name |
models_tests.py |
import unittest
import os
os.environ['MIAMI_ENV'] = 'test'
import simplejson as json
from miami.models import Team, User, Task
class ModelsTest(unittest.TestCase):
| def test_team_toJSON(self):
team = Team('Log')
team.id = 1
self.assertEquals({'id':1, 'name': 'Log', 'color': '2a33d8'}, team.toJSON())
def test_user_toJSON(self):
user = User('Mike')
self.assertEquals({'name': 'Mike', 'gravater': '91f376c4b36912e5075b6170d312eab5'}, user.t... | identifier_body | |
md5.rs | (u: u32, v: u32, w: u32) -> u32 {
(u & w) | (v & !w)
}
fn h(u: u32, v: u32, w: u32) -> u32 {
u ^ v ^ w
}
fn i(u: u32, v: u32, w: u32) -> u32 {
v ^ (u | !w)
}
fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 {
... | g | identifier_name | |
md5.rs | wrapping_add(C2[i + 3]), 20);
t += 20;
}
// round 3
t = 5;
for i in (0..4) {
let i = i * 4;
a = op_h(a, b, c, d, data[t & 0x0f].wrapping_add(C3[i]), 4);
d = op_h(d, a, b, c, data[(t + 3) & 0x0f].wrapping_add(C3[i + 1]), 11);
c ... | Test { input: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", output: "d174ab98d277d9f5a5611c2c9f419d9f" },
Test { input: "12345678901234567890123456789012345678901234567890123456789012345678901234567890", output: "57edf4a22be3c955ac49da2e2107b67a" },
];
#[test] | random_line_split | |
md5.rs |
fn i(u: u32, v: u32, w: u32) -> u32 {
v ^ (u | !w)
}
fn op_f(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) -> u32 {
w.wrapping_add(f(x, y, z)).wrapping_add(m).rotate_left(s).wrapping_add(x)
}
fn op_g(w: u32, x: u32, y: u32, z: u32, m: u32, s: u32) ->... | {
u ^ v ^ w
} | identifier_body | |
gulpfile.js | var gulp = require('gulp');
var gutil = require('gulp-util');
var mocha = require('gulp-mocha');
var browserify = require('gulp-browserify');
var derequire = require('gulp-derequire');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var http = require('http');
var BrowserStackTunnel = re... |
gulp.task('stop-browserstack-tunnel', function(callback) {
browserstack_tunnel.stop(callback);
});
gulp.task('run-node-test', function(callback) {
gulp
.src('./test/test.js', {read: false})
.pipe(mocha())
.on('end', callback)
.on('error', function() {});
});
gulp.task('run-browser-test', function... | callback(err);
});
}); | random_line_split |
dragscrollable.js | /*
* jQuery dragscrollable Plugin
* version: 1.0 (25-Jun-2009)
* Copyright (c) 2009 Miquel Herrera
*
* Portions Copyright (c) 2010 Reg Braithwaite
* Copyright (c) 2010 Internet Archive / Michael Ang
*
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-l... |
})( jQuery ); // confine scope | random_line_split | |
S11.11.2_A4_T2.js | // Copyright 2009 the Sputnik authors. All rights reserved.
/**
* If ToBoolean(x) is true, return x
*
* @path ch11/11.11/11.11.2/S11.11.2_A4_T2.js
* @description Type(x) and Type(y) vary between primitive number and Number object
*/
//CHECK#1
if ((-1 || 1) !== -1) {
$ERROR('#1: (-1 || 1) === -1');
}
//CHECK#2... | //CHECK#4
var x = new Number(-1);
if ((x || new Number(0)) !== x) {
$ERROR('#4: (var x = new Number(-1); (x || new Number(-1)) === x');
}
//CHECK#5
var x = new Number(NaN);
if ((x || new Number(1)) !== x) {
$ERROR('#5: (var x = new Number(NaN); (x || new Number(1)) === x');
}
//CHECK#6
var x = new Number(0);
if (... | if ((-1 || NaN) !== -1) {
$ERROR('#3: (-1 || NaN) === -1');
}
| random_line_split |
S11.11.2_A4_T2.js | // Copyright 2009 the Sputnik authors. All rights reserved.
/**
* If ToBoolean(x) is true, return x
*
* @path ch11/11.11/11.11.2/S11.11.2_A4_T2.js
* @description Type(x) and Type(y) vary between primitive number and Number object
*/
//CHECK#1
if ((-1 || 1) !== -1) {
$ERROR('#1: (-1 || 1) === -1');
}
//CHECK#2... |
//CHECK#4
var x = new Number(-1);
if ((x || new Number(0)) !== x) {
$ERROR('#4: (var x = new Number(-1); (x || new Number(-1)) === x');
}
//CHECK#5
var x = new Number(NaN);
if ((x || new Number(1)) !== x) {
$ERROR('#5: (var x = new Number(NaN); (x || new Number(1)) === x');
}
//CHECK#6
var x = new Number(0);
if... | {
$ERROR('#3: (-1 || NaN) === -1');
} | conditional_block |
private_school_tuition_data.py | import requests
import math
import re
from bs4 import BeautifulSoup
ROOT_URL = "http://nces.ed.gov/collegenavigator"
INDEX_URL = ROOT_URL + "?s=all&l=93&ct=2&ic=1&an=5&ax=50"
PAGINATION_DIV_ID = "ctl00_cphCollegeNavBody_ucResultsMain_divMsg"
def get_num_pages(pagination):
"""Returns the total number of pages given p... | (college):
"""Retrieves college tuition data and adds to college
:param college: college dictionary container
"""
response = requests.get(ROOT_URL + college['url'])
soup = BeautifulSoup(response.text, "html.parser")
expenses = soup.find("div", attrs={"id": "expenses"})
table = expenses.find("tbody")
try:
# ... | get_college_tuition_data | identifier_name |
private_school_tuition_data.py | import requests
import math
import re
from bs4 import BeautifulSoup
ROOT_URL = "http://nces.ed.gov/collegenavigator"
INDEX_URL = ROOT_URL + "?s=all&l=93&ct=2&ic=1&an=5&ax=50"
PAGINATION_DIV_ID = "ctl00_cphCollegeNavBody_ucResultsMain_divMsg"
def get_num_pages(pagination):
"""Returns the total number of pages given p... | for link in table.findChildren(href=is_college_link):
college['name'] = link.get_text()
college['url'] = link.get('href')
colleges.append(college.copy())
return colleges
def get_college_tuition_data(college):
"""Retrieves college tuition data and adds to college
:param college: college dictionar... | response = requests.get(INDEX_URL)
soup = BeautifulSoup(response.text, "html.parser")
# Get the total number of pages in the result
pagination = soup.find("div", attrs={"id": PAGINATION_DIV_ID})
pages = get_num_pages(pagination.get_text())
# Store colleges in list of dictionaries
colleges = []
college = {}
#... | identifier_body |
private_school_tuition_data.py | import requests
import math
import re
from bs4 import BeautifulSoup
ROOT_URL = "http://nces.ed.gov/collegenavigator"
INDEX_URL = ROOT_URL + "?s=all&l=93&ct=2&ic=1&an=5&ax=50"
PAGINATION_DIV_ID = "ctl00_cphCollegeNavBody_ucResultsMain_divMsg"
def get_num_pages(pagination):
"""Returns the total number of pages given p... | colleges = [college for college in colleges if not is_invalid_college(college)]
for college in colleges:
print(repr(str(college['name'])) + ", " + college['Tuition and fees']) | random_line_split | |
private_school_tuition_data.py | import requests
import math
import re
from bs4 import BeautifulSoup
ROOT_URL = "http://nces.ed.gov/collegenavigator"
INDEX_URL = ROOT_URL + "?s=all&l=93&ct=2&ic=1&an=5&ax=50"
PAGINATION_DIV_ID = "ctl00_cphCollegeNavBody_ucResultsMain_divMsg"
def get_num_pages(pagination):
"""Returns the total number of pages given p... |
colleges = [college for college in colleges if not is_invalid_college(college)]
for college in colleges:
print(repr(str(college['name'])) + ", " + college['Tuition and fees'])
| print(college['name'] + ": Retrieving tuition data")
get_college_tuition_data(college) | conditional_block |
topics.ts | import { Topic } from './types';
// TODO write unit tests to verify that all referenced topics are actually in this list.
// TODO write unit test to verify that every `related` entry has a `topic` entry with a reciprical related entry
export const topics: Topic[] = [
{
topic: 'Arise from the Dust',
},
{
... | topic: 'Ponder',
},
{
topic: 'Popular',
},
{
topic: 'Power',
},
{
topic: 'Pray',
related: ['Ask'],
},
{
topic: 'Pride',
},
{
topic: 'Priestcraft',
},
{
topic: 'Rebel',
related: ['Choose Wickedly'],
},
{
topic: 'Reject',
},
{
topic: 'Repent',
... | { | random_line_split |
images_client.py | # Copyright 2012 OpenStack Foundation
# 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 requ... |
from six.moves.urllib import parse as urllib
from tempest_lib import exceptions as lib_exc
from tempest.api_schema.response.compute.v2_1 import images as schema
from tempest.common import service_client
from tempest.common import waiters
class ImagesClient(service_client.ServiceClient):
def create_image(self, ... | # under the License.
import json | random_line_split |
images_client.py | # Copyright 2012 OpenStack Foundation
# 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 requ... |
resp, body = self.get(url)
body = json.loads(body)
self.validate_response(_schema, resp, body)
return service_client.ResponseBodyList(resp, body['images'])
def show_image(self, image_id):
"""Returns the details of a single image."""
resp, body = self.get("images/%s... | url += '?%s' % urllib.urlencode(params) | conditional_block |
images_client.py | # Copyright 2012 OpenStack Foundation
# 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 requ... |
def list_image_metadata(self, image_id):
"""Lists all metadata items for an image."""
resp, body = self.get("images/%s/metadata" % image_id)
body = json.loads(body)
self.validate_response(schema.image_metadata, resp, body)
return service_client.ResponseBody(resp, body['meta... | """Waits for an image to reach a given status."""
waiters.wait_for_image_status(self, image_id, status) | identifier_body |
images_client.py | # Copyright 2012 OpenStack Foundation
# 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 requ... | (self, detail=False, **params):
"""Returns a list of all images filtered by any parameters."""
url = 'images'
_schema = schema.list_images
if detail:
url += '/detail'
_schema = schema.list_images_details
if params:
url += '?%s' % urllib.urlenc... | list_images | identifier_name |
content_projection_spec.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 {ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, Directive, HostBinding... | tic ngComponentDef = $r3$.ɵdefineComponent({
type: MyApp,
selectors: [['my-app']],
factory: () => new MyApp(),
template: function(rf: $RenderFlags$, ctx: $MyApp$) {
if (rf & 1) {
$r3$.ɵE(0, 'simple');
$r3$.ɵT(1, 'content');
$r3$.ɵe();
... | sta | identifier_name |
content_projection_spec.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 {ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, Directive, HostBinding... | directives: () => [SimpleComponent]
});
}
});
});
| $r3$.ɵE(0, 'simple');
$r3$.ɵT(1, 'content');
$r3$.ɵe();
}
},
| conditional_block |
content_projection_spec.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 {ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, Directive, HostBinding... | }
});
// /NORMATIVE
}
@Component({
selector: 'my-app',
template: `<simple>content</simple>
<complex></complex>`
})
class MyApp {
static ngComponentDef = $r3$.ɵdefineComponent({
type: MyApp,
selectors: [['my-app']],
factory: () => new M... | $r3$.ɵEe(0, 'div', ['id', 'first']);
$r3$.ɵP(1, 1);
$r3$.ɵEe(2, 'div', ['id', 'second']);
$r3$.ɵP(3, 2);
} | random_line_split |
storage.js | /**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _stora... | }
const file = getPath(options);
_storage[file] = options.value;
fs.writeFile(file, options.value, callback);
};
Storage.get = function(options, callback) {
const file = getPath(options);
if(file in _storage) {
callback(null, _storage[file]);
return;
}
fs.readFile(file, callback);
};
Storag... |
Storage.set = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix); | random_line_split |
storage.js | /**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _stora... |
function ensureDirectoryExists(dir) {
if (!fs.existsSync(dir)){
mkdirp.sync(dir);
}
}
function ensurePrefixExists(prefix) {
ensureDirectoryExists(path.join(_defaultDir, prefix));
}
ensureDirectoryExists(_defaultDir);
const Storage = {};
Storage.set = function(options, callback) {
if(options.prefix) {
... | {
if(options.prefix) {
return path.join(_defaultDir, options.prefix, options.fileName);
}
return path.join(_defaultDir, options.fileName);
} | identifier_body |
storage.js | /**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _stora... |
}
function ensurePrefixExists(prefix) {
ensureDirectoryExists(path.join(_defaultDir, prefix));
}
ensureDirectoryExists(_defaultDir);
const Storage = {};
Storage.set = function(options, callback) {
if(options.prefix) {
ensurePrefixExists(options.prefix);
}
const file = getPath(options);
_storage[file... | {
mkdirp.sync(dir);
} | conditional_block |
storage.js | /**
* Central storage with in-memory cache
*/
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const app = process.type === 'renderer'
? require('electron').remote.app
: require('electron').app;
const _defaultDir = path.join(app.getPath('userData'), 'data');
const _stora... | (options) {
if(options.prefix) {
return path.join(_defaultDir, options.prefix, options.fileName);
}
return path.join(_defaultDir, options.fileName);
}
function ensureDirectoryExists(dir) {
if (!fs.existsSync(dir)){
mkdirp.sync(dir);
}
}
function ensurePrefixExists(prefix) {
ensureDirectoryExists(... | getPath | identifier_name |
GetNewsletterScheduleTime.py | # -*- coding: utf-8 -*-
###############################################################################
#
# GetNewsletterScheduleTime
# Get the scheduled delivery time of a specified Newsletter.
#
# Python version 2.6
#
###############################################################################
from temboo.core.c... |
def set_Name(self, value):
"""
Set the value of the Name input for this Choreo. ((required, string) The name of the newsletter for which delivery schedule information will be retrieved.)
"""
InputSet._set_input(self, 'Name', value)
def set_ResponseFormat(self, value):
""... | """
Set the value of the APIUser input for this Choreo. ((required, string) The username registered with SendGrid.)
"""
InputSet._set_input(self, 'APIUser', value) | identifier_body |
GetNewsletterScheduleTime.py | # -*- coding: utf-8 -*-
###############################################################################
#
# GetNewsletterScheduleTime
# Get the scheduled delivery time of a specified Newsletter.
#
# Python version 2.6
#
###############################################################################
from temboo.core.c... | return GetNewsletterScheduleTimeInputSet()
def _make_result_set(self, result, path):
return GetNewsletterScheduleTimeResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return GetNewsletterScheduleTimeChoreographyExecution(session, exec_id, path)
class GetNewsle... | random_line_split | |
GetNewsletterScheduleTime.py | # -*- coding: utf-8 -*-
###############################################################################
#
# GetNewsletterScheduleTime
# Get the scheduled delivery time of a specified Newsletter.
#
# Python version 2.6
#
###############################################################################
from temboo.core.c... | (self, value):
"""
Set the value of the ResponseFormat input for this Choreo. ((optional, string) The format of the response from SendGrid, in either json, or xml. Default is set to json.)
"""
InputSet._set_input(self, 'ResponseFormat', value)
class GetNewsletterScheduleTimeResultSet(... | set_ResponseFormat | identifier_name |
mail.py | # -*- coding: utf-8 -*-
"""Caliopen mail message privacy features extraction methods."""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pgpy
from caliopen_main.pi.parameters import PIParameter
from .helpers.spam import SpamScorer
from .helpers.ingress_path import get_i... |
return {'message_encrypted': is_encrypted,
'message_encryption_method': 'pgp' if is_encrypted else ''}
def _get_features(self):
"""Extract privacy features."""
features = self._features.copy()
received = self.message.headers.get('Received', [])
features.upd... | try:
body = self.message.body_plain.decode('utf-8')
if body.startswith(PGP_MESSAGE_HEADER):
is_encrypted = True
except UnicodeDecodeError:
log.warn('Invalid body_plain encoding for message')
pass | conditional_block |
mail.py | # -*- coding: utf-8 -*-
"""Caliopen mail message privacy features extraction methods."""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pgpy
from caliopen_main.pi.parameters import PIParameter
from .helpers.spam import SpamScorer
from .helpers.ingress_path import get_i... |
def emitter_certificate(self):
"""Get the certificate from emitter."""
return None
@property
def mail_agent(self):
"""Get the mailer used for this message."""
# XXX normalize better and more ?
return self.message.mail.get('X-Mailer', '').lower()
@property
... | """Return features about emitter."""
if self.is_blacklist_mx(mx):
return 'blacklisted'
if self.is_whitelist_mx(mx):
return 'whitelisted'
return 'unknown' | identifier_body |
mail.py | # -*- coding: utf-8 -*-
"""Caliopen mail message privacy features extraction methods."""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pgpy
from caliopen_main.pi.parameters import PIParameter
from .helpers.spam import SpamScorer
from .helpers.ingress_path import get_i... | features = self._features.copy()
received = self.message.headers.get('Received', [])
features.update(get_ingress_features(received, self.internal_domains))
mx = features.get('ingress_server')
reputation = None if not mx else self.emitter_reputation(mx)
features['mail_emit... | return {'message_encrypted': is_encrypted,
'message_encryption_method': 'pgp' if is_encrypted else ''}
def _get_features(self):
"""Extract privacy features.""" | random_line_split |
mail.py | # -*- coding: utf-8 -*-
"""Caliopen mail message privacy features extraction methods."""
from __future__ import absolute_import, print_function, unicode_literals
import logging
import pgpy
from caliopen_main.pi.parameters import PIParameter
from .helpers.spam import SpamScorer
from .helpers.ingress_path import get_i... | (self, mx):
"""MX is blacklisted."""
blacklisted = self.config.get('blacklistes.mx')
if not blacklisted:
return False
if mx in blacklisted:
return True
return False
def is_whitelist_mx(self, mx):
"""MX is whitelisted."""
whitelistes = ... | is_blacklist_mx | identifier_name |
once-cant-call-twice-on-heap.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 ... | {
let x = Arc::new(true);
foo(proc() {
assert!(*x);
drop(x);
});
} | identifier_body | |
once-cant-call-twice-on-heap.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 ... | blk();
blk(); //~ ERROR use of moved value
}
fn main() {
let x = Arc::new(true);
foo(proc() {
assert!(*x);
drop(x);
});
} |
#![feature(once_fns)]
use std::sync::Arc;
fn foo(blk: proc()) { | random_line_split |
once-cant-call-twice-on-heap.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 ... | () {
let x = Arc::new(true);
foo(proc() {
assert!(*x);
drop(x);
});
}
| main | identifier_name |
settingsView.js | var $ = require("jquery");
var _ = require("underscore");
var Backbone = require("backbone");
var User = require("../user");
var app = require("../app").app;
var SettingsView = Backbone.View.extend({
template : _.template($("#tmpl-settings-view").html()),
render : function(data){
data.user = User.current();
this... | module.exports = SettingsView; | }
});
| random_line_split |
ex_multi_trace_single_attribute_input_single_output.py | # External Attribute Skeleton
#
# Input: Multi-trace, single attribute
# Output: Single attribute
#
import sys,os
import numpy as np
#
# Import the module with the I/O scaffolding of the External Attribute
#
sys.path.insert(0, os.path.join(sys.path[0], '..'))
import extattrib as xa
#
# The attribute parameters - keep ... | #
while True:
xa.doInput()
#
# After doInput the TraceInfo, xa.TI, array contains information specific to this trace segment - keep what you need
#
number_of_samples = xa.TI['nrsamp']
start_time = xa.TI['z0']
current_inline = xa.TI['inl']
current_crossline = xa.TI['crl']
#
# Get the input
#
indata = xa.Inp... | zw = xa.params['ZSampMargin']['Value'][1] - xa.params['ZSampMargin']['Value'][0] + 1
select = xa.params['Select']['Selection']
#
# This is the trace processing loop | random_line_split |
ex_multi_trace_single_attribute_input_single_output.py | # External Attribute Skeleton
#
# Input: Multi-trace, single attribute
# Output: Single attribute
#
import sys,os
import numpy as np
#
# Import the module with the I/O scaffolding of the External Attribute
#
sys.path.insert(0, os.path.join(sys.path[0], '..'))
import extattrib as xa
#
# The attribute parameters - keep ... | #
# Get the input
#
indata = xa.Input['Input']
#
# Your attribute calculation goes here
#
# Warning Python loops can be slow - this is contrived just to show how to access traces in the analysis data cube
#
outdata = np.zeros(number_of_samples)
for inline in range(number_inline):
for xline in range(number_xlin... | number_inline = xa.SI['nrinl']
number_xline = xa.SI['nrcrl']
centre_trace_x = xa.SI['nrinl']//2
centre_trace_y = xa.SI['nrcrl']//2
nyquist = 1.0/(2.0*xa.SI['zstep'])
par0 = xa.params['Par_0']['Value']
zw = xa.params['ZSampMargin']['Value'][1] - xa.params['ZSampMargin']['Value'][0] + 1
select = xa.params['Select'... | identifier_body |
ex_multi_trace_single_attribute_input_single_output.py | # External Attribute Skeleton
#
# Input: Multi-trace, single attribute
# Output: Single attribute
#
import sys,os
import numpy as np
#
# Import the module with the I/O scaffolding of the External Attribute
#
sys.path.insert(0, os.path.join(sys.path[0], '..'))
import extattrib as xa
#
# The attribute parameters - keep ... | ():
#
# Initialise some constants from the attribute parameters or the SeismicInfo, xa.SI, array for use in the calculations
# These are just some examples - keep/add what you need
#
number_inline = xa.SI['nrinl']
number_xline = xa.SI['nrcrl']
centre_trace_x = xa.SI['nrinl']//2
centre_trace_y = xa.SI['nrcrl']//2
n... | doCompute | identifier_name |
ex_multi_trace_single_attribute_input_single_output.py | # External Attribute Skeleton
#
# Input: Multi-trace, single attribute
# Output: Single attribute
#
import sys,os
import numpy as np
#
# Import the module with the I/O scaffolding of the External Attribute
#
sys.path.insert(0, os.path.join(sys.path[0], '..'))
import extattrib as xa
#
# The attribute parameters - keep ... |
outdata /= (number_inline * number_xline - 1)
#------------------------------------------------------------------------------------
#
xa.Output = outdata
xa.doOutput()
#
# Assign the compute function to the attribute
#
xa.doCompute = doCompute
#
# Do it
#
xa.run(sys.argv[1:])
| if (inline != centre_trace_x and xline != centre_trace_y):
outdata += indata[inline,xline,:] | conditional_block |
__init__.py | # Inspired from VecEnv from OpenAI Baselines
class VecEnv(object):
"""
An abstract asynchronous, vectorized environment.
"""
def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
self.action_space = act... |
class CloudpickleWrapper(object):
"""
Uses cloudpickle to serialize contents (otherwise multiprocessing tries to use pickle)
"""
def __init__(self, x):
self.x = x
def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.x)
def __setstate__(self, ob):
... | return self | conditional_block |
__init__.py | # Inspired from VecEnv from OpenAI Baselines
class VecEnv(object):
"""
An abstract asynchronous, vectorized environment.
"""
def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
self.action_space = act... | Tell all the environments to start taking a step
with the given actions.
Call step_wait() to get the results of the step.
You should not call this if a step_async run is
already pending.
"""
raise NotImplementedError()
def step_wait(self):
"""
... |
def step_async(self, actions):
""" | random_line_split |
__init__.py | # Inspired from VecEnv from OpenAI Baselines
class VecEnv(object):
"""
An abstract asynchronous, vectorized environment.
"""
def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
self.action_space = act... |
def step_wait(self):
"""
Wait for the step taken with step_async().
Returns (obs, rews, dones, infos):
- obs: an array of observations, or a tuple of
arrays of observations.
- rews: an array of rewards
- dones: an array of "episode done" booleans
... | """
Tell all the environments to start taking a step
with the given actions.
Call step_wait() to get the results of the step.
You should not call this if a step_async run is
already pending.
"""
raise NotImplementedError() | identifier_body |
__init__.py | # Inspired from VecEnv from OpenAI Baselines
class | (object):
"""
An abstract asynchronous, vectorized environment.
"""
def __init__(self, num_envs, observation_space, action_space):
self.num_envs = num_envs
self.observation_space = observation_space
self.action_space = action_space
def reset(self):
"""
Reset ... | VecEnv | identifier_name |
getcoins.py | #!/usr/bin/env python3
# Copyright (c) 2020-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import argparse
import io
import requests
import subprocess
import sys
DEFAULT_GLOBAL_FAUCET = 'https://... |
try:
res = session.post(args.faucet, data=data)
except:
print('Unexpected error when contacting faucet:', sys.exc_info()[0])
exit(1)
# Display the output as per the returned status code
if res:
# When the return code is in between 200 and 400 i.e. successful
print(res.text)
elif res.status_code =... | try:
res = session.get(args.captcha)
except:
print('Unexpected error when contacting faucet:', sys.exc_info()[0])
exit(1)
# Convert SVG image to PPM, and load it
try:
rv = subprocess.run([args.imagemagick, '-', '-depth', '8', 'ppm:-'], input=res.content, check=True, capture_... | conditional_block |
getcoins.py | #!/usr/bin/env python3
# Copyright (c) 2020-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import argparse
import io
import requests
import subprocess
import sys
DEFAULT_GLOBAL_FAUCET = 'https://... | line = f.readline()
(width, height) = (int(x) for x in line.rstrip().split(b' '))
if f.readline() != b'255\n':
raise ValueError('Invalid ppm format: color depth')
data = f.read(width * height * 3)
stride = width * 3
self.size = (width, height)
self._gr... | def __init__(self, f):
if f.readline() != b'P6\n':
raise ValueError('Invalid ppm format: header') | random_line_split |
getcoins.py | #!/usr/bin/env python3
# Copyright (c) 2020-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import argparse
import io
import requests
import subprocess
import sys
DEFAULT_GLOBAL_FAUCET = 'https://... | (self, f):
if f.readline() != b'P6\n':
raise ValueError('Invalid ppm format: header')
line = f.readline()
(width, height) = (int(x) for x in line.rstrip().split(b' '))
if f.readline() != b'255\n':
raise ValueError('Invalid ppm format: color depth')
data = ... | __init__ | identifier_name |
getcoins.py | #!/usr/bin/env python3
# Copyright (c) 2020-2021 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
import argparse
import io
import requests
import subprocess
import sys
DEFAULT_GLOBAL_FAUCET = 'https://... |
def getpixel(self, pos):
return self._grid[pos[1]][pos[0]]
def print_image(img, threshold=128):
'''Print black-and-white image to terminal in braille unicode characters.'''
x_blocks = (img.size[0] + BW - 1) // BW
y_blocks = (img.size[1] + BH - 1) // BH
for yb in range(y_blocks):
... | if f.readline() != b'P6\n':
raise ValueError('Invalid ppm format: header')
line = f.readline()
(width, height) = (int(x) for x in line.rstrip().split(b' '))
if f.readline() != b'255\n':
raise ValueError('Invalid ppm format: color depth')
data = f.read(width * heig... | identifier_body |
keyframes_rule.rs | wLockReadGuard,
params: &DeepCloneParams,
) -> Self {
KeyframesRule {
name: self.name.clone(),
keyframes: self
.keyframes
.iter()
.map(|x| {
Arc::new(
lock.wrap(x.read_with(guard).deep... | <'i>(
css: &'i str,
parent_stylesheet_contents: &StylesheetContents,
lock: &SharedRwLock,
) -> Result<Arc<Locked<Self>>, ParseError<'i>> {
let url_data = parent_stylesheet_contents.url_data.read();
let namespaces = parent_stylesheet_contents.namespaces.read();
let mut... | parse | identifier_name |
keyframes_rule.rs | declaration exists in the list of
/// declarations.
///
/// This is used to know when to override the keyframe animation style.
pub declared_timing_function: bool,
}
impl KeyframesStep {
#[inline]
fn new(
percentage: KeyframePercentage,
value: KeyframesStepValue,
guard:... | random_line_split | ||
keyframes_rule.rs | : Arc<Locked<PropertyDeclarationBlock>>,
},
/// A synthetic step computed from the current computed values at the time
/// of the animation.
ComputedValues,
}
/// A single step from a keyframe animation.
#[derive(Clone, Debug, MallocSizeOf)]
pub struct KeyframesStep {
/// The percentage of the anim... | {
block.extend(iter.parser.declarations.drain(), Importance::Normal);
} | conditional_block | |
common.rs | //! Contains several types used throughout the library.
use std::fmt;
use std::error;
/// Represents a thing which has a position inside some textual document.
///
/// This trait is implemented by parsers, lexers and errors. It is used primarily to create
/// error objects.
pub trait HasPosition {
/// R... | {
row: usize,
col: usize,
msg: String
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}:{}: {}", self.row + 1, self.col + 1, self.msg)
}
}
impl HasPosition for Error {
#[inline]
fn row(&self) -> usize { self.row }
... | Error | identifier_name |
common.rs | //! Contains several types used throughout the library.
use std::fmt;
use std::error;
/// Represents a thing which has a position inside some textual document.
///
/// This trait is implemented by parsers, lexers and errors. It is used primarily to create
/// error objects.
pub trait HasPosition {
/// R... |
}
impl Error {
/// Creates a new error using position information from the provided
/// `HasPosition` object and a message.
#[inline]
pub fn new<O: HasPosition>(o: &O, msg: String) -> Error {
Error { row: o.row(), col: o.col(), msg: msg }
}
/// Creates a new error using pro... | { self.col } | identifier_body |
common.rs | //! Contains several types used throughout the library.
use std::fmt;
use std::error;
/// Represents a thing which has a position inside some textual document.
///
/// This trait is implemented by parsers, lexers and errors. It is used primarily to create
/// error objects.
pub trait HasPosition {
/// R... | fn description(&self) -> &str { &*self.msg }
}
/// XML version enumeration.
#[derive(Copy, Clone, PartialEq, Eq)]
pub enum XmlVersion {
/// XML version 1.0.
Version10,
/// XML version 1.1.
Version11
}
impl fmt::Display for XmlVersion {
fn fmt(&self, f: &mut fmt::Formatter) -> fm... | }
impl error::Error for Error {
#[inline]
| random_line_split |
mod.rs | pub type c_long = i32;
pub type c_ulong = u32;
pub type nlink_t = u32;
s! {
pub struct pthread_attr_t {
__size: [u32; 9]
}
pub struct sigset_t {
__val: [::c_ulong; 32],
}
pub struct msghdr {
pub msg_name: *mut ::c_void,
pub msg_namelen: ::socklen_t,
pub msg... | // Unknown target_arch
}
} | random_line_split | |
pageObjectExample1.js | // pageObjectExample1.js
// This is a simple page object pattern example that does the following:
// open page
// verify copyright
// fill in search form and submit
// wait for results on results page
// verify results
// Page objects are used to provide another layer of abstraction between
// the page information a... | describe('Page Object Example #1 for Web Driver IO - Tutorial Test Page Website', function() {
it('should open page using pageObjects', function () {
WebPage.open();
});
it('should verify copyright using pageObjects', function () {
var cr = WebPage.getCopyright();
(cr).should.equal("Tony Keith - tlkeith.c... |
// a test script block or suite | random_line_split |
DOUBLONnewBDD.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import psycopg2.extras
import os
import subprocess
import sys
sys.path.append("C:\\Program Files\\FME\\fmeobjects\\python27")
import fmeobjects
# ----------------------##### VARIABLES #####---------------------- #
#
# formatList : liste des format... |
for i in range(0, len(resultFormat)):
formatList = formatList + resultFormat[i]
print formatList # parametre publie format
# ###---------------------- RECUPERATION DES SRS ----------------------### #
cur = con.cursor()
cur.execute("SELECT epsg FROM preferencesrs WHERE activatesrs='Tr... | esultFormat.append(row[0])
| conditional_block |
DOUBLONnewBDD.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import psycopg2
import psycopg2.extras
import os
import subprocess
import sys
sys.path.append("C:\\Program Files\\FME\\fmeobjects\\python27")
import fmeobjects
# ----------------------##### VARIABLES #####---------------------- #
#
# formatList : liste des format... | print 'Error %s' % e
sys.exit(1)
finally:
if con:
con.close()
#os.system("fme.exe C:\\Users\\ndrissi\\Downloads\\dynamic_format_list.fmw --FORMATS_LIST " + formatList + " --SRS_LIST " + srsList + " --POSTGIS_TABLE " + mdataList + " --DEST C:\\Users\\ndrissi\\Downloads --DestDataset_... |
# #---------------------- GESTION DES ERREURS ----------------------# #
except psycopg2.DatabaseError, e:
| random_line_split |
coding.rs | //! Coding system handler.
use remacs_macros::lisp_fn;
use crate::{
data::aref,
eval::unbind_to,
hashtable::{
gethash,
HashLookupResult::{Found, Missing},
LispHashTableRef,
},
lisp::LispObject,
lists::{get, put},
minibuf::completing_read,
multibyte::LispStringRe... | include!(concat!(env!("OUT_DIR"), "/coding_exports.rs")); | random_line_split | |
coding.rs | //! Coding system handler.
use remacs_macros::lisp_fn;
use crate::{
data::aref,
eval::unbind_to,
hashtable::{
gethash,
HashLookupResult::{Found, Missing},
LispHashTableRef,
},
lisp::LispObject,
lists::{get, put},
minibuf::completing_read,
multibyte::LispStringRe... | (fname: LispStringRef) -> LispStringRef {
unsafe { c_encode_file_name(fname.into()) }.into()
}
/// Implements DECODE_SYSTEM macro
/// Decode the string `input_string` using the specified coding system
/// for system functions, if any.
pub fn decode_system(input_string: LispStringRef) -> LispStringRef {
let loc... | encode_file_name | identifier_name |
coding.rs | //! Coding system handler.
use remacs_macros::lisp_fn;
use crate::{
data::aref,
eval::unbind_to,
hashtable::{
gethash,
HashLookupResult::{Found, Missing},
LispHashTableRef,
},
lisp::LispObject,
lists::{get, put},
minibuf::completing_read,
multibyte::LispStringRe... |
/// Return t if OBJECT is nil or a coding-system.
/// See the documentation of `define-coding-system' for information
/// about coding-system objects.
#[lisp_fn]
pub fn coding_system_p(object: LispObject) -> bool {
object.is_nil()
|| coding_system_id(object) >= 0
|| object.is_symbol() && get(objec... | {
match coding_system_spec(x) {
Qnil => {
check_coding_system_lisp(x);
match coding_system_spec(x) {
Qnil => wrong_type!(Qcoding_system_p, x),
spec => spec,
}
}
spec => spec,
}
} | identifier_body |
helpershift.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class HelperShift(models.Model):
"""
n-m relation between helper and shift.
This model then can be used by other apps to "attach" more data with OneToOne fields and signals.
The fields `present` and `manual_presence... | return "{} - {} - {}".format(self.helper.event, self.helper, self.shift) | identifier_body | |
helpershift.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class HelperShift(models.Model):
"""
n-m relation between helper and shift.
This model then can be used by other apps to "attach" more data with OneToOne fields and signals.
The fields `present` and `manual_presence... | (self):
return "{} - {} - {}".format(self.helper.event, self.helper, self.shift)
| __str__ | identifier_name |
helpershift.py | from django.db import models
from django.utils.translation import ugettext_lazy as _
class HelperShift(models.Model):
"""
n-m relation between helper and shift.
This model then can be used by other apps to "attach" more data with OneToOne fields and signals.
The fields `present` and `manual_presence... | def __str__(self):
return "{} - {} - {}".format(self.helper.event, self.helper, self.shift) | default=False,
editable=False,
verbose_name=_("Presence was manually set"),
)
| random_line_split |
stub_utils.py | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 Metaswitch Networks
#
# 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 ap... |
def get_mac():
"""
Gets a random mac address.
"""
mac = ("%02x:%02x:%02x:%02x:%02x:%02x" %
(random.randint(0x00, 0xff),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff),
random.randint(0x00, 0xff),
... | return test_time | identifier_body |
stub_utils.py | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 Metaswitch Networks
#
# 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 ap... | # Logger
log = logging.getLogger(__name__)
# The current time.
test_time = 0
def set_time(value):
global test_time
test_time = value
log.debug("Time now set to : %d" % test_time)
def get_time():
return test_time
def get_mac():
"""
Gets a random mac address.
"""
mac = ("%02x:%02x:%02x... | CommandOutput = namedtuple('CommandOutput', ['stdout', 'stderr'])
| random_line_split |
stub_utils.py | # -*- coding: utf-8 -*-
# Copyright 2014, 2015 Metaswitch Networks
#
# 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 ap... | (Exception):
pass
| TestOverException | identifier_name |
2_ch_c3beta_c4smr_kro.py | # Thanks to Kurt Othmer for BioExplorer design this is translated from
from flow import *
class Flow(object):
def init(self, context):
ch1 = context.get_channel('Channel 1')
#ch1 = Notch(50, input=ch1)
ch1_dc = DCBlock(ch1).ac
ch1_raw = BandPass(0.0, 40.0, input=ch1_dc)
ch1_theta = BandPass(3.0, 7.0, inpu... |
return w
def flow():
return Flow()
| w = QtGui.QWidget()
layout = QtGui.QGridLayout()
w.setLayout(layout)
layout.addWidget(self.ch1_osci.widget(), 0, 0, 1, 4)
layout.addWidget(self.ch1_theta_threshold.widget(), 1, 0)
layout.addWidget(self.ch1_beta_threshold.widget(), 1, 1)
layout.addWidget(self.ch1_hibeta_threshold.widget(), 1, 2)
layout.... | identifier_body |
2_ch_c3beta_c4smr_kro.py | # Thanks to Kurt Othmer for BioExplorer design this is translated from
from flow import *
class | (object):
def init(self, context):
ch1 = context.get_channel('Channel 1')
#ch1 = Notch(50, input=ch1)
ch1_dc = DCBlock(ch1).ac
ch1_raw = BandPass(0.0, 40.0, input=ch1_dc)
ch1_theta = BandPass(3.0, 7.0, input=ch1_raw, type='elliptic', order=3).output
ch1_beta = BandPass(15.0, 18.0, input=ch1_raw, type='ell... | Flow | identifier_name |
equipment.py | from btmux_template_io.item_table import ITEM_TABLE
from btmux_template_io.parsers.ssw.crit_mapping import PHYSICAL_WEAPON_MAP, \
EQUIPMENT_MAP
from . ammo import add_ammo
from . common import add_crits_from_locations
from . weapons import add_weapon
def | (xml_root, unit_obj):
"""
Equipment is the general term for an item within a mech. Weapons,
ammo, melee weapons, etc.
:param lxml.etree.Element xml_root: The root of the XML doc.
:param btmux_template_io.unit.BTMuxUnit unit_obj: The unit instance
being populated.
"""
equipment_elem... | populate_equipment | identifier_name |
equipment.py | from btmux_template_io.item_table import ITEM_TABLE
from btmux_template_io.parsers.ssw.crit_mapping import PHYSICAL_WEAPON_MAP, \
EQUIPMENT_MAP
from . ammo import add_ammo
from . common import add_crits_from_locations
from . weapons import add_weapon
def populate_equipment(xml_root, unit_obj):
"""
Equipm... |
def _add_equipment(equip_e, unit_obj, map_dict):
ssw_name = equip_e.xpath('name')[0].text
try:
mapped_add_special = map_dict[ssw_name].get('add_special')
except KeyError:
raise ValueError("Unknown equipment type: %s" % ssw_name)
if mapped_add_special:
unit_obj.specials.add(ma... | raise ValueError("Invalid equipment type: %s" % e_type) | conditional_block |
equipment.py | from btmux_template_io.item_table import ITEM_TABLE
from btmux_template_io.parsers.ssw.crit_mapping import PHYSICAL_WEAPON_MAP, \
EQUIPMENT_MAP
from . ammo import add_ammo
from . common import add_crits_from_locations
from . weapons import add_weapon
def populate_equipment(xml_root, unit_obj):
"""
Equipm... | elif e_type == 'physical':
_add_equipment(equip_e, unit_obj, PHYSICAL_WEAPON_MAP)
elif e_type in ['equipment', 'CASE', 'TargetingComputer']:
_add_equipment(equip_e, unit_obj, EQUIPMENT_MAP)
else:
raise ValueError("Invalid equipment type: %s" % e_type)
def _a... | add_ammo(equip_e, unit_obj) | random_line_split |
equipment.py | from btmux_template_io.item_table import ITEM_TABLE
from btmux_template_io.parsers.ssw.crit_mapping import PHYSICAL_WEAPON_MAP, \
EQUIPMENT_MAP
from . ammo import add_ammo
from . common import add_crits_from_locations
from . weapons import add_weapon
def populate_equipment(xml_root, unit_obj):
"""
Equipm... | crits_per_item = data_dict.get('crits', 1)
add_special = data_dict.get('add_special')
if add_special:
unit_obj.specials.add(add_special)
add_crits_from_locations(
equip_e,
btmux_name,
unit_obj,
crits_per_item=crits_per_item)
| ssw_name = equip_e.xpath('name')[0].text
try:
mapped_add_special = map_dict[ssw_name].get('add_special')
except KeyError:
raise ValueError("Unknown equipment type: %s" % ssw_name)
if mapped_add_special:
unit_obj.specials.add(mapped_add_special)
btmux_name = map_dict[ssw_name]['... | identifier_body |
auracite_worker.rs | #![feature(plugin)]
#![plugin(dotenv_macros)]
extern crate auracite;
extern crate dotenv;
extern crate select;
extern crate reqwest;
use std::io::Read;
use auracite::lodestone::NewsItem;
use auracite::storage::{connect_redis, push_news};
use dotenv::dotenv;
use select::document::Document;
use select::predicate::{Cla... | (doc: &str) -> Vec<NewsItem> {
let mut topics: Vec<NewsItem> = vec![];
let document = Document::from(doc);
for (_, topic) in document.find(Class("news__list--topics")).enumerate() {
let title =
match topic.find(Class("news__list--title")).into_selection().children().first() {
... | parse_document | identifier_name |
auracite_worker.rs | #![feature(plugin)]
#![plugin(dotenv_macros)]
extern crate auracite;
extern crate dotenv;
extern crate select;
extern crate reqwest;
use std::io::Read;
use auracite::lodestone::NewsItem;
use auracite::storage::{connect_redis, push_news};
use dotenv::dotenv;
use select::document::Document;
use select::predicate::{Cla... |
fn parse_document(doc: &str) -> Vec<NewsItem> {
let mut topics: Vec<NewsItem> = vec![];
let document = Document::from(doc);
for (_, topic) in document.find(Class("news__list--topics")).enumerate() {
let title =
match topic.find(Class("news__list--title")).into_selection().children().f... | {
let mut res = reqwest::get(url).unwrap();
let mut body = String::new();
res.read_to_string(&mut body).unwrap();
body
} | identifier_body |
auracite_worker.rs | #![feature(plugin)]
#![plugin(dotenv_macros)]
extern crate auracite;
extern crate dotenv;
extern crate select;
extern crate reqwest;
use std::io::Read;
use auracite::lodestone::NewsItem;
use auracite::storage::{connect_redis, push_news};
use dotenv::dotenv;
use select::document::Document;
use select::predicate::{Cla... |
for page in PAGES.into_iter() {
let url = format!("http://{}.finalfantasyxiv.com/lodestone/topics", page);
let download = download_page(url.as_str());
let topics = parse_document(download.as_str());
match push_news(page, &topics, &conn) {
Ok(()) => println!("Pushed {} i... | fn main() {
dotenv().ok();
let conn = connect_redis().unwrap(); | random_line_split |
05_custom-validator.ts | import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';
/**
* Returns `true` if FormControl's value represen... | {
form: FormGroup;
constructor() {
this.form = new FormGroup({
'my-ssn': new FormControl('', ssnValidator)
});
}
}
@NgModule({
imports : [ BrowserModule, ReactiveFormsModule ],
declarations: [ AppComponent ],
bootstrap : [ AppComponent ]
})
class AppModule {}
platformBrowserDynamic()... | AppComponent | identifier_name |
05_custom-validator.ts | import { Component, NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { ReactiveFormsModule, FormControl, FormGroup } from '@angular/forms';
/**
* Returns `true` if FormControl's value represen... | <span [hidden]="!form.hasError('ssn', 'my-ssn')">SSN in invalid</span>
</form>
`
})
class AppComponent {
form: FormGroup;
constructor() {
this.form = new FormGroup({
'my-ssn': new FormControl('', ssnValidator)
});
}
}
@NgModule({
imports : [ BrowserModule, ReactiveFormsModul... | template: `
<form [formGroup]="form">
SSN: <input type="text" formControlName="my-ssn"> | random_line_split |
authenticate.js | 'use strict';
const jsonWebToken = require('jwt-simple');
const settings = require('../settings.js');
const passwords = require('../common/passwords.js');
/**
* @param userObject
* @returns {{access_token: String, expires: *, user: *}}
*/
function | (userObject) {
const date = new Date();
const expires = date.setDate(date.getDate() + settings.expireDays);
const token = jsonWebToken.encode({ expires: expires, username: userObject.username, role: userObject.role }, settings.secret);
return {
access_token: token,
expires: expires,
user: userObject
};
}
/... | generateToken | identifier_name |
authenticate.js | 'use strict';
const jsonWebToken = require('jwt-simple');
const settings = require('../settings.js');
const passwords = require('../common/passwords.js');
/**
* @param userObject
* @returns {{access_token: String, expires: *, user: *}}
*/
function generateToken(userObject) {
const date = new Date();
const expir... | * @param req
* @param res
* @returns {*}
*/
module.exports.getToken = function(req, res) {
const username = req.body.username;
const password = req.body.password;
if (typeof username === 'undefined' || typeof password === 'undefined') {
return res.status(401).json({ status: 401, message: 'Unauthorized' });
... |
/** | random_line_split |
authenticate.js | 'use strict';
const jsonWebToken = require('jwt-simple');
const settings = require('../settings.js');
const passwords = require('../common/passwords.js');
/**
* @param userObject
* @returns {{access_token: String, expires: *, user: *}}
*/
function generateToken(userObject) |
/**
* @param req
* @param res
* @returns {*}
*/
module.exports.getToken = function(req, res) {
const username = req.body.username;
const password = req.body.password;
if (typeof username === 'undefined' || typeof password === 'undefined') {
return res.status(401).json({ status: 401, message: 'Unauthorized'... | {
const date = new Date();
const expires = date.setDate(date.getDate() + settings.expireDays);
const token = jsonWebToken.encode({ expires: expires, username: userObject.username, role: userObject.role }, settings.secret);
return {
access_token: token,
expires: expires,
user: userObject
};
} | identifier_body |
authenticate.js | 'use strict';
const jsonWebToken = require('jwt-simple');
const settings = require('../settings.js');
const passwords = require('../common/passwords.js');
/**
* @param userObject
* @returns {{access_token: String, expires: *, user: *}}
*/
function generateToken(userObject) {
const date = new Date();
const expir... |
req.app.get('db').db.get('SELECT * FROM users WHERE username = ?', [ username ], function(error, userObject) {
if (typeof userObject !== 'undefined' && passwords.comparePassword(password, userObject.password)) {
return res.json(generateToken(userObject));
}
return res.status(401).json({ status: 401, message... | {
return res.status(401).json({ status: 401, message: 'Unauthorized' });
}
| conditional_block |
mediascape.js | //main javascript
(function init() {
// If we need to load requirejs before loading butter, make it so
if (typeof define === "undefined") {
var rscript = document.createElement("script");
rscript.onload = function () {
init();
};
rscript.src = "require.js";
do... |
window.mediascape = mediascape;
//return of mediascape object with discovery and features objects and its functions
return mediascape;
});
require(["mediascape"], function (mediascape) {
mediascape.init();
/**
*
* Polyfill for custonevents
*... | {
var args = window.mediascape.__waiting;
delete window.mediascape;
if (args) {
mediascape.init.apply(this, args);
}
} | conditional_block |
mediascape.js | //main javascript
(function init() {
// If we need to load requirejs before loading butter, make it so
if (typeof define === "undefined") {
var rscript = document.createElement("script");
rscript.onload = function () {
init();
};
rscript.src = "require.js";
do... | document.dispatchEvent(event);
});
}()); | }); | random_line_split |
mediascape.js | //main javascript
(function init() {
// If we need to load requirejs before loading butter, make it so
if (typeof define === "undefined") {
var rscript = document.createElement("script");
rscript.onload = function () {
init();
};
rscript.src = "require.js";
do... | ;
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
var event = new CustomEvent("mediascape-ready", {
"detail": {
"loaded": true
}
});
document.dispatchEvent(event);
});
}());
| {
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.d... | identifier_body |
mediascape.js | //main javascript
(function init() {
// If we need to load requirejs before loading butter, make it so
if (typeof define === "undefined") {
var rscript = document.createElement("script");
rscript.onload = function () {
init();
};
rscript.src = "require.js";
do... | (event, params) {
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.canc... | CustomEvent | identifier_name |
flash_and_debug.py | #!/usr/bin/env python
import telnetlib
import subprocess
import signal
import time
###############################################################
# This script will automatically flash and start a GDB debug
# session to the STM32 discovery board using OpenOCD. It is
# meant to be called from the rake task "debug" (... |
# Gracefully exit openocd
openocd.terminate()
| time.sleep(1) | conditional_block |
flash_and_debug.py | #!/usr/bin/env python
import telnetlib
import subprocess
import signal
import time
###############################################################
# This script will automatically flash and start a GDB debug
# session to the STM32 discovery board using OpenOCD. It is
# meant to be called from the rake task "debug" (... | tn.read_until("> ")
tn.write("exit\n")
tn.close()
###############################################################
# Start the gdb session
###############################################################
time.sleep(2)
gdb_proc = subprocess.Popen(["arm-none-eabi-gdb", "-ex", "target remote localhost:3333", "build/flash.... | tn.write("flash write_image erase build/flash.bin 0x08000000\n")
tn.read_until("> ")
tn.write("reset\n") | random_line_split |
flash_and_debug.py | #!/usr/bin/env python
import telnetlib
import subprocess
import signal
import time
###############################################################
# This script will automatically flash and start a GDB debug
# session to the STM32 discovery board using OpenOCD. It is
# meant to be called from the rake task "debug" (... |
###############################################################
# Start up the openocd thread
###############################################################
# We need gdb to respond to a SIGINT (ctrl-c), but by default,
# that will cause every other child process to die, including
# openocd. Disable sigint, then r... | pass # do nothing | identifier_body |
flash_and_debug.py | #!/usr/bin/env python
import telnetlib
import subprocess
import signal
import time
###############################################################
# This script will automatically flash and start a GDB debug
# session to the STM32 discovery board using OpenOCD. It is
# meant to be called from the rake task "debug" (... | (signal, frame):
pass # do nothing
###############################################################
# Start up the openocd thread
###############################################################
# We need gdb to respond to a SIGINT (ctrl-c), but by default,
# that will cause every other child process to die, includ... | signal_handler | identifier_name |
mod.rs | is already the *master*. So we skip over this error.
if dev.acquire_master_lock().is_err() {
warn!(log, "Unable to become drm master, assuming unprivileged mode");
} else {
dev.privileged = true;
}
dev
});
let has_univers... | Ok(PostAction::Continue)
}
| random_line_split | |
mod.rs | Fd + 'static> BasicDevice for DrmDevice<A> {}
impl<A: AsRawFd + 'static> ControlDevice for DrmDevice<A> {}
#[derive(Debug)]
pub struct FdWrapper<A: AsRawFd + 'static> {
fd: A,
pub(super) privileged: bool,
logger: ::slog::Logger,
}
impl<A: AsRawFd + 'static> AsRawFd for FdWrapper<A> {
fn as_raw_fd(&sel... | (&self) -> bool {
match *self.internal {
DrmDeviceInternal::Atomic(_) => true,
DrmDeviceInternal::Legacy(_) => false,
}
}
/// Returns a list of crtcs for this device
pub fn crtcs(&self) -> &[crtc::Handle] {
self.resources.crtcs()
}
/// Returns a set ... | is_atomic | identifier_name |
gulpfile.babel.js | /**
* Run this using node_modules/gulp/bin/gulp.js !!!
* mhm 8.6.2017
*/
'use strict';
import plugins from 'gulp-load-plugins';
//import rename from 'gulp-rename';
import yargs from 'yargs';
import gulp from 'gulp';
import rimraf from 'rimraf';
import yaml from 'js-yaml';
import fs from 'fs';
// Load all Gulp plu... |
/**
* Copies JavaScript files as-is from e.g. bower_components
* The path is manipulated to simplify the destination path.
*/
function copyJS(done) {
if (PATHS.copyjavascript) {
gulp.src(PATHS.copyjavascript, { base: '.' })
.pipe($.concat('libs.js'))
.pipe(gulp.dest(PATHS.dist + '/assets/... | {
rimraf(PATHS.dist, done);
} | identifier_body |
gulpfile.babel.js | /**
* Run this using node_modules/gulp/bin/gulp.js !!!
* mhm 8.6.2017
*/
'use strict';
import plugins from 'gulp-load-plugins';
//import rename from 'gulp-rename';
import yargs from 'yargs';
import gulp from 'gulp';
import rimraf from 'rimraf';
import yaml from 'js-yaml';
import fs from 'fs';
// Load all Gulp plu... | * The path is manipulated to simplify the destination path.
*/
function copyJS(done) {
if (PATHS.copyjavascript) {
gulp.src(PATHS.copyjavascript, { base: '.' })
.pipe($.concat('libs.js'))
.pipe(gulp.dest(PATHS.dist + '/assets/js'));
}
if(done){
done();
}
} | * Copies JavaScript files as-is from e.g. bower_components | random_line_split |
gulpfile.babel.js | /**
* Run this using node_modules/gulp/bin/gulp.js !!!
* mhm 8.6.2017
*/
'use strict';
import plugins from 'gulp-load-plugins';
//import rename from 'gulp-rename';
import yargs from 'yargs';
import gulp from 'gulp';
import rimraf from 'rimraf';
import yaml from 'js-yaml';
import fs from 'fs';
// Load all Gulp plu... |
if(done){
done();
}
}
| {
gulp.src(PATHS.copyjavascript, { base: '.' })
.pipe($.concat('libs.js'))
.pipe(gulp.dest(PATHS.dist + '/assets/js'));
} | conditional_block |
gulpfile.babel.js | /**
* Run this using node_modules/gulp/bin/gulp.js !!!
* mhm 8.6.2017
*/
'use strict';
import plugins from 'gulp-load-plugins';
//import rename from 'gulp-rename';
import yargs from 'yargs';
import gulp from 'gulp';
import rimraf from 'rimraf';
import yaml from 'js-yaml';
import fs from 'fs';
// Load all Gulp plu... | (done) {
if (PATHS.copyjavascript) {
gulp.src(PATHS.copyjavascript, { base: '.' })
.pipe($.concat('libs.js'))
.pipe(gulp.dest(PATHS.dist + '/assets/js'));
}
if(done){
done();
}
}
| copyJS | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.