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 |
|---|---|---|---|---|
Acao.js | // Representa um ação que pode ser desfeita e refeita
// A ação é associada a uma aba aberta
// Nas funções redo e undo, this se refere à aba associada à ação
function Acao(nome, redo, undo) {
var aba = Interface.abaFoco
this.id = String(Math.random())
this.nome = nome
this.redo = redo
this.undo = undo
if (ab... | return null
}
// Desfaz a última ação na aba
Acao.desfazer = function (aba) {
var acao
if (aba.posHistorico > 0) {
acao = aba.historico[aba.posHistorico-1]
if (acao.undo) {
acao.undo.call(aba)
aba.posHistorico--
if ((aba.posHistorico && aba.historico[aba.posHistorico-1].id!=aba.idAcaoSalvo)
|| (!ab... | var aba, acao
aba = Interface.abaFoco
acao = aba.historico[aba.posHistorico]
if (aba.posHistorico < aba.historico.length && acao.redo)
return acao.nome | random_line_split |
collectd.py | # Copyright 2015-2016 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
class CollectdClient(object):
"""Collectd client.
Args:
path (str): path to the collectd unix socket
"""
def __init__(self, path):
self.path = path
self.socket = None
def _open_socket(self):
if self.socket is not None:
return
_socket = socket.... | random_line_split | |
collectd.py | # Copyright 2015-2016 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
self._send_cmd(
cmd
)
def putval(self, identifier, value, timestamp='N',
type_='minemeld_counter', hostname='minemeld', interval=None):
if isinstance(timestamp, int):
timestamp = '%d' % timestamp
identifier = '/'.join([hostname, identifier, ... | cmd += ' identifier=%s' % identifier | conditional_block |
collectd.py | # Copyright 2015-2016 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | (self, identifier, value, timestamp='N',
type_='minemeld_counter', hostname='minemeld', interval=None):
if isinstance(timestamp, int):
timestamp = '%d' % timestamp
identifier = '/'.join([hostname, identifier, type_])
command = 'PUTVAL %s' % identifier
if inter... | putval | identifier_name |
collectd.py | # Copyright 2015-2016 Palo Alto Networks, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
def _send_cmd(self, command):
self._open_socket()
self.socket.send(command+'\n')
ans = self._readline()
status, message = ans.split(None, 1)
status = int(status)
if status < 0:
raise RuntimeError('Error communicating with collectd %s' %
... | result = ''
data = None
while data != '\n':
data = self.socket.recv(1)
if data == '\n' or data is None:
return result
result += data | identifier_body |
rwlock.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 ... | c::ReleaseSRWLockExclusive(self.inner.get())
}
#[inline]
pub unsafe fn destroy(&self) {
// ...
}
} | pub unsafe fn write_unlock(&self) { | random_line_split |
rwlock.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 ... |
#[inline]
pub unsafe fn write(&self) {
c::AcquireSRWLockExclusive(self.inner.get())
}
#[inline]
pub unsafe fn try_write(&self) -> bool {
c::TryAcquireSRWLockExclusive(self.inner.get()) != 0
}
#[inline]
pub unsafe fn read_unlock(&self) {
c::ReleaseSRWLockShared(se... | {
c::TryAcquireSRWLockShared(self.inner.get()) != 0
} | identifier_body |
rwlock.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) -> bool {
c::TryAcquireSRWLockExclusive(self.inner.get()) != 0
}
#[inline]
pub unsafe fn read_unlock(&self) {
c::ReleaseSRWLockShared(self.inner.get())
}
#[inline]
pub unsafe fn write_unlock(&self) {
c::ReleaseSRWLockExclusive(self.inner.get())
}
#[inline... | try_write | identifier_name |
selector.ts | import { createSelector } from 'reselect';
import { State } from '../../state';
import * as _ from 'lodash';
import { DtoProject } from '../../common/interfaces/dto_project';
import { allProject } from '../../misc/constants';
import { DtoCollection } from '../../common/interfaces/dto_collection';
const getProjects = (... |
return _.filter(sortCollections, c => c.projectId === projectId);
};
};
export const getDisplayCollectionSelector = () => {
return createSelector(
[getSelectedProject, getDisplayCollectionSelectorForProject],
(selectedProject, getProjectCollections) => getProjectCollections(selectedPro... | {
return sortCollections;
} | conditional_block |
selector.ts | import { createSelector } from 'reselect';
import { State } from '../../state';
import * as _ from 'lodash';
import { DtoProject } from '../../common/interfaces/dto_project';
import { allProject } from '../../misc/constants';
import { DtoCollection } from '../../common/interfaces/dto_collection';
const getProjects = (... | [getProjects, getUserId],
(projects, userId) => {
return _.chain(projects)
.values<DtoProject>()
.sortBy('name')
.sortBy(t => t.owner.id !== userId)
.sortBy(t => t.isMe ? 0 : 1)
.value()
.map(t =>... | export const getProjectsIdNameStateSelector = () => {
return createSelector( | random_line_split |
test_invalid_services.py | from typing import Any
import pytest
from run_test_service_helper import start_service
def test_invalid_filename(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(SystemExit):
services, future = start_service("tests/services/no_service_existing.py", monkeypatch)
out, err = capsy... | (monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(SyntaxError):
services, future = start_service("tests/services/syntax_error_service.py", monkeypatch)
out, err = capsys.readouterr()
assert "Unable to load service file" in err
def test_import_error(monkeypatch: Any, capsys: A... | test_syntax_error_service | identifier_name |
test_invalid_services.py | from typing import Any
import pytest
from run_test_service_helper import start_service
def test_invalid_filename(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(SystemExit):
services, future = start_service("tests/services/no_service_existing.py", monkeypatch)
out, err = capsy... |
def test_syntax_error_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(SyntaxError):
services, future = start_service("tests/services/syntax_error_service.py", monkeypatch)
out, err = capsys.readouterr()
assert "Unable to load service file" in err
def test_import_e... | with pytest.raises(NameError):
services, future = start_service("tests/services/invalid_service.py", monkeypatch)
out, err = capsys.readouterr()
assert "Unable to load service file" in err | identifier_body |
test_invalid_services.py | from typing import Any
import pytest
from run_test_service_helper import start_service
def test_invalid_filename(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(SystemExit):
services, future = start_service("tests/services/no_service_existing.py", monkeypatch)
out, err = capsy... |
def test_invalid_service(monkeypatch: Any, capsys: Any, loop: Any) -> None:
with pytest.raises(NameError):
services, future = start_service("tests/services/invalid_service.py", monkeypatch)
out, err = capsys.readouterr()
assert "Unable to load service file" in err
def test_syntax_error_service(... | random_line_split | |
webpack.config.prod.js | // For info about this file refer to webpack and webpack-hot-middleware documentation
// For info on how we're generating bundles with hashed filenames for cache busting: https://medium.com/@okonetchnikov/long-term-caching-of-static-assets-with-webpack-1ecb139adb95#.w99i89nsz
import webpack from 'webpack';
import Extra... | useShortDoctype: true,
removeEmptyAttributes: true,
removeStyleLinkTypeAttributes: true,
keepClosingSlash: true,
minifyJS: true,
minifyCSS: true,
minifyURLs: true
},
inject: true,
// Note that you can add custom options here if you need to handle... | removeRedundantAttributes: true, | random_line_split |
ifmt.rs | Formatter) -> fmt::Result {
f.write_str("adios")
}
}
impl fmt::Display for C {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.pad_integral(true, "☃", "123")
}
}
macro_rules! t {
($a:expr, $b:expr) => { assert_eq!($a, $b) }
}
pub fn main() {
// Various edge cases without f... | vec!(0u8));
println!("hello");
println!("this is a {}", "test");
println!("{foo}", foo="bar");
}
// Just make sure that the macros ar | identifier_body | |
ifmt.rs | (box_syntax)]
use std::fmt;
use std::usize;
struct A;
struct B;
struct C;
impl fmt::LowerHex for A {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("aloha")
}
}
impl fmt::UpperHex for B {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("adios")
}... | t!(format!("hello"), "hello");
t!(format!("hello {{"), "hello {");
// default formatters should work
t!(format!("{}", 1.0f32), "1");
t!(format!("{}", 1.0f64), "1");
t!(format!("{}", "a"), "a");
t!(format!("{}", "a".to_string()), "a");
t!(format!("{}", false), "false");
t!(format!("{... | // Various edge cases without formats
t!(format!(""), ""); | random_line_split |
ifmt.rs | a");
// At least exercise all the formats
t!(format!("{}", true), "true");
t!(format!("{}", '☃'), "☃");
t!(format!("{}", 10), "10");
t!(format!("{}", 10_usize), "10");
t!(format!("{:?}", '☃'), "'\\u{2603}'");
t!(format!("{:?}", 10), "10");
t!(format!("{:?}", 10_usize), "10");
t!(for... | O: | identifier_name | |
webParser.py | the License for the specific language governing permissions and
limitations under the License.
"""
import urllib
import re
from HTMLParser import HTMLParser
from courseClasses import Course, Lecture, Tutorial, Reserve
class CustomHTMLParser(HTMLParser):
"""this class reads a HTML stream, then parses out the "d... |
def processSlot(self):
"""we check to see if this is the BEGINNING of a valid row"""
if (self.webData[self.index+1][:3].upper() == "LEC"
or self.webData[self.index+1][:3].upper() == "LAB") \
and "ONLINE" not in self.webData[self.index+2]:
# we don't wan... | if self.webData[self.index] != "":
self.processSlot()
self.index += 1
if self.index == len(self.webData):
return | conditional_block |
webParser.py | the License for the specific language governing permissions and
limitations under the License.
"""
import urllib
import re
from HTMLParser import HTMLParser
from courseClasses import Course, Lecture, Tutorial, Reserve
class CustomHTMLParser(HTMLParser):
"""this class reads a HTML stream, then parses out the "d... |
def run(self, courseString, sessionString):
"""this is the method that the main class can call
if successful, returns the Course class
if not, returns an error message"""
self.session = self.parseSession(sessionString)
if self.session is None:
return "SessionNa... | self.webData = []
self.index = -1
self.session = None
self.thisCourse = None | identifier_body |
webParser.py | the License for the specific language governing permissions and
limitations under the License.
"""
import urllib
import re
from HTMLParser import HTMLParser
from courseClasses import Course, Lecture, Tutorial, Reserve
class CustomHTMLParser(HTMLParser):
"""this class reads a HTML stream, then parses out the "d... | """this function will convert the class times to minutes-past-
the-previous-midnight, and converts the days to numbers.
Also, some reservation-postprocessing"""
map(lambda x: x.calcMiscSeats(), course.lectures)
for lec in course.lectures:
lec.courseID = course.subjec... | return True
else:
return False
def postProcess(self, course): | random_line_split |
webParser.py | License for the specific language governing permissions and
limitations under the License.
"""
import urllib
import re
from HTMLParser import HTMLParser
from courseClasses import Course, Lecture, Tutorial, Reserve
class CustomHTMLParser(HTMLParser):
"""this class reads a HTML stream, then parses out the "data"... | (self, sessionString):
try:
ret = "1"
ret += sessionString.split()[1][-2:] # last 2 digits of year
tempMap = (("fall", "9"), ("winter", "1"), ("spring", "5"))
for season in tempMap:
if season[0] in sessionString.lower():
ret +=... | parseSession | identifier_name |
lib.rs | //! If you already know the name of what you are looking for the
//! fastest way to find it is to use the <a href="#"
//! onclick="focusSearchBar();">search bar</a> at the top of the page.
//!
//! Otherwise, you may want to jump to one of these useful sections:
//!
//! * [`std::*` modules](#modules)
//! * [Primitive ty... | //!
//! # How to read this documentation
//! | random_line_split | |
Profile.ts | //=============================================================================
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTH... | // ****************************************************************************
// Controller app.profile
//
interface IProfileScope extends ng.IScope {
currentTheme: string
profile: IUser
updateTheme(): void
save(isValid: boolean): void
submitted: boolean
submitting: boolean
themes: Array<... | random_line_split | |
Profile.ts | //=============================================================================
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTH... | }
}
]) | $scope.submitting = true
repositories.users.save($scope.profile).then(() => {
services.logger.success('Updated profile')
$scope.updateTheme()
$scope.submitted = false
$scope.submitting = false
... | conditional_block |
index.js | 'use strict';
function valuefy(value) {
if (typeof value !== 'object') {
return (typeof value === 'string') ? `"${value}"` : value;
}
let values = [];
if (Array.isArray(value)) {
for (const v of value) {
values.push(valuefy(v));
}
values = `[${values.join(',')}]`;
} else {
for (let v in value) {
... |
function objectify(v) {
if (v[0] === '{') {
return JSON.parse(extract(v, '}'));
} else if (v[0] === '[') {
const set = [];
const es = extract(v, ']', true);
if (es[0] === '[' || es[0] === '{') {
set.push(objectify(es));
} else {
for (const e of es.split(',')) {
set.push(objectify(e));
}
}
... | {
const start = onlyContent ? 1 : 0;
const pad = onlyContent ? 0 : 1;
return t.slice(start, t.lastIndexOf(outter) + pad);
} | identifier_body |
index.js | 'use strict';
function | (value) {
if (typeof value !== 'object') {
return (typeof value === 'string') ? `"${value}"` : value;
}
let values = [];
if (Array.isArray(value)) {
for (const v of value) {
values.push(valuefy(v));
}
values = `[${values.join(',')}]`;
} else {
for (let v in value) {
if ({}.hasOwnProperty.call(val... | valuefy | identifier_name |
index.js | 'use strict';
function valuefy(value) {
if (typeof value !== 'object') {
return (typeof value === 'string') ? `"${value}"` : value;
}
let values = [];
if (Array.isArray(value)) {
for (const v of value) {
values.push(valuefy(v));
}
values = `[${values.join(',')}]`;
} else {
for (let v in value) {
... | }
return values;
}
function extract(t, outter, onlyContent) {
const start = onlyContent ? 1 : 0;
const pad = onlyContent ? 0 : 1;
return t.slice(start, t.lastIndexOf(outter) + pad);
}
function objectify(v) {
if (v[0] === '{') {
return JSON.parse(extract(v, '}'));
} else if (v[0] === '[') {
const set = [];... | random_line_split | |
index.js | 'use strict';
function valuefy(value) {
if (typeof value !== 'object') {
return (typeof value === 'string') ? `"${value}"` : value;
}
let values = [];
if (Array.isArray(value)) | else {
for (let v in value) {
if ({}.hasOwnProperty.call(value, v)) {
values.push(`"${v}":${valuefy(value[v])}`);
}
}
values = `{${values.join(',')}}`;
}
return values;
}
function serialize(target) {
if (!target || typeof target !== 'object') {
throw new TypeError('Invalid type of target');
}
... | {
for (const v of value) {
values.push(valuefy(v));
}
values = `[${values.join(',')}]`;
} | conditional_block |
trailing-comma.rs | // run-pass
// pretty-expanded FIXME #23616
fn f<T,>(_: T,) {}
struct Foo<T,>(T);
struct Bar;
impl Bar {
fn f(_: isize,) {}
fn g(self, _: isize,) {}
fn h(self,) {}
}
enum Baz {
Qux(isize,), | let (_, _,) = (1, 1,);
let [_, _,] = [1, 1,];
let [_, _, .., _,] = [1, 1, 1, 1,];
let [_, _, _, ..,] = [1, 1, 1, 1,];
let x: Foo<isize,> = Foo::<isize,>(1);
Bar::f(0,);
Bar.g(0,);
Bar.h();
let x = Baz::Qux(1,);
} | }
#[allow(unused,)]
pub fn main() {
f::<isize,>(0,); | random_line_split |
trailing-comma.rs | // run-pass
// pretty-expanded FIXME #23616
fn f<T,>(_: T,) {}
struct Foo<T,>(T);
struct Bar;
impl Bar {
fn f(_: isize,) {}
fn g(self, _: isize,) {}
fn h(self,) |
}
enum Baz {
Qux(isize,),
}
#[allow(unused,)]
pub fn main() {
f::<isize,>(0,);
let (_, _,) = (1, 1,);
let [_, _,] = [1, 1,];
let [_, _, .., _,] = [1, 1, 1, 1,];
let [_, _, _, ..,] = [1, 1, 1, 1,];
let x: Foo<isize,> = Foo::<isize,>(1);
Bar::f(0,);
Bar.g(0,);
Bar.h();
le... | {} | identifier_body |
trailing-comma.rs | // run-pass
// pretty-expanded FIXME #23616
fn f<T,>(_: T,) {}
struct Foo<T,>(T);
struct Bar;
impl Bar {
fn f(_: isize,) {}
fn g(self, _: isize,) {}
fn | (self,) {}
}
enum Baz {
Qux(isize,),
}
#[allow(unused,)]
pub fn main() {
f::<isize,>(0,);
let (_, _,) = (1, 1,);
let [_, _,] = [1, 1,];
let [_, _, .., _,] = [1, 1, 1, 1,];
let [_, _, _, ..,] = [1, 1, 1, 1,];
let x: Foo<isize,> = Foo::<isize,>(1);
Bar::f(0,);
Bar.g(0,);
Bar.h(... | h | identifier_name |
utils.py |
# This default values in trees are Very important for outgroup
# selection algorithm to work:
tree.DEFAULT_SUPPORT = 1.0
tree.DEFAULT_DIST = 1.0
#from ete3.treeview import drawer
#drawer.GUI_TIMEOUT = 1
TIME_FORMAT = '%a %b %d %H:%M:%S %Y'
AA = set('ACEDGFIHKMLNQPSRTWVY*-.UOBZJX') | set('acedgfihkmlnqpsrtwvyuobzjx'... | instance(i, float):
return "%0.2f" %i
else:
return str(i)
| identifier_body | |
utils.py | _dir", GLOBALS.get("dbdir", base_dir))
if base_dir and base_dir != out_dir:
try:
log.log(20, "Copying new db files to output directory %s..." %out_dir)
if not pexist(out_dir):
os.makedirs(out_dir)
if os.system("cp -a %s/* %s/" %(scratch_dir, out_dir)):
... | ity = node.alg_mean_identn
| conditional_block | |
utils.py | Bioinformatics (2014) 30 (9): 1312-1313."""
MAFFT_CITE = u"""Katoh K, Kuma K, Toh H, Miyata T. MAFFT version 5:
improvement in accuracy of multiple sequence alignment. Nucleic Acids
Res. 2005 Jan 20;33(2):511-8."""
TRIMAL_CITE = u"""Capella-Gutiérrez S, Silla-Martínez JM, Gabaldón T.
trimAl: a tool for automated alig... | m = re.search("/(tasks/.+)", fullpath)
if m:
return m.groups()[0]
else:
return fullpath
def ask(string, valid_values, default=-1, case_sensitive=False):
""" Asks for a keyborad answer """
v = None
if not case_sensitive:
valid_values = [value.lower() for value in valid_va... | return str(value).lower() in set(["1", "true", "yes"])
def rpath(fullpath):
'Returns relative path of a task file (if possible)' | random_line_split |
utils.py | .time()*random.random()))
HOSTNAME = socket.gethostname()
def tobool(value):
return str(value).lower() in set(["1", "true", "yes"])
def rpath(fullpath):
'Returns relative path of a task file (if possible)'
m = re.search("/(tasks/.+)", fullpath)
if m:
return m.groups()[0]
else:
ret... | prepostorder(tree | identifier_name | |
pg.rs | use diesel::*;
use diesel::pg::PgConnection;
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token::str_to_ident;
use syntax::ptr::P;
use super::data_structures::*;
table! {
pg_attribute (attrelid) {
attrelid -> Oid,
attname -> VarChar,
atttypid -> ... | {
use self::pg_attribute::dsl::*;
use self::pg_index::dsl::{pg_index, indisprimary, indexrelid, indrelid};
use self::pg_class::dsl::*;
let table_oid = pg_class.select(oid).filter(relname.eq(table_name)).limit(1);
let pk_query = pg_index.select(indexrelid)
.filter(indrelid.eq_any(table_oid)... | identifier_body | |
pg.rs | use diesel::*;
use diesel::pg::PgConnection;
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token::str_to_ident;
use syntax::ptr::P;
use super::data_structures::*;
table! {
pg_attribute (attrelid) {
attrelid -> Oid,
attname -> VarChar,
atttypid -> ... | (cx: &mut ExtCtxt, _span: Span, attr: &ColumnInformation) -> P<ast::Ty> {
let tpe = if attr.type_name.starts_with("_") {
let subtype = str_to_ident(&capitalize(&attr.type_name[1..]));
quote_ty!(cx, Array<$subtype>)
} else {
let type_name = str_to_ident(&capitalize(&attr.type_name));
... | determine_column_type | identifier_name |
pg.rs | use diesel::*;
use diesel::pg::PgConnection;
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token::str_to_ident;
use syntax::ptr::P;
use super::data_structures::*;
table! {
pg_attribute (attrelid) {
attrelid -> Oid,
attname -> VarChar,
atttypid -> ... | }
}
table! {
pg_class (oid) {
oid -> Oid,
relname -> VarChar,
}
}
pub fn determine_column_type(cx: &mut ExtCtxt, _span: Span, attr: &ColumnInformation) -> P<ast::Ty> {
let tpe = if attr.type_name.starts_with("_") {
let subtype = str_to_ident(&capitalize(&attr.type_name[1..]));
... | pg_index (indrelid) {
indrelid -> Oid,
indexrelid -> Oid,
indkey -> Array<SmallInt>,
indisprimary -> Bool, | random_line_split |
pg.rs | use diesel::*;
use diesel::pg::PgConnection;
use syntax::ast;
use syntax::codemap::Span;
use syntax::ext::base::*;
use syntax::parse::token::str_to_ident;
use syntax::ptr::P;
use super::data_structures::*;
table! {
pg_attribute (attrelid) {
attrelid -> Oid,
attname -> VarChar,
atttypid -> ... | else {
tpe
}
}
fn capitalize(name: &str) -> String {
name[..1].to_uppercase() + &name[1..]
}
pub fn load_table_names(connection: &PgConnection) -> QueryResult<Vec<String>> {
use diesel::prelude::*;
use diesel::expression::dsl::sql;
let query = select(sql::<types::VarChar>("table_name FRO... | {
quote_ty!(cx, Nullable<$tpe>)
} | conditional_block |
ip.py | from netfields import InetAddressField, CidrAddressField
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from nodeshot.core.base.models import BaseAccessLevel
from ..managers import NetAccessLevelM... | @staticmethod
def autocomplete_search_fields():
return ('address__icontains',) | conditional_block | |
ip.py | from netfields import InetAddressField, CidrAddressField
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from nodeshot.core.base.models import BaseAccessLevel
from ..managers import NetAccessLevelM... |
def save(self, *args, **kwargs):
"""
Determines ip protocol version automatically.
Stores address in interface shortcuts for convenience.
"""
self.protocol = 'ipv%d' % self.address.version
# save
super(Ip, self).save(*args, **kwargs)
# TODO: do we r... | """ TODO """
# netaddr.IPAddress('10.40.2.1') in netaddr.IPNetwork('10.40.0.0/24')
pass | identifier_body |
ip.py | from netfields import InetAddressField, CidrAddressField
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from nodeshot.core.base.models import BaseAccessLevel
from ..managers import NetAccessLevelM... | (self):
return self.interface.owner
if 'grappelli' in settings.INSTALLED_APPS:
@staticmethod
def autocomplete_search_fields():
return ('address__icontains',)
| owner | identifier_name |
ip.py | from netfields import InetAddressField, CidrAddressField
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from nodeshot.core.base.models import BaseAccessLevel
from ..managers import NetAccessLevelM... | return ('address__icontains',) | random_line_split | |
NotificationFilterStringFilter.tsx | import * as React from 'react';
import { Btn } from 'View/Ui/Index';
interface INotificationFilterStringFilterProps
{
stringFilters: IGitHubNotificationFilterSetStringFilter[];
className?: string;
getTitle(): string;
getFilterTitle(filter: IGitHubNotificationFilterSetStringFilter): string;
getFilterIsAc... | {
return (
<div className={this.props.className}>
<div className="soft-delta soft-zeta--bottom">
<label className="text--zeta">{this.props.getTitle()}</label>
</div>
{this.props.stringFilters
.map(filter =>
(
<div key={filter.name}
... | };
class NotificationFilterStringFilter extends React.Component<INotificationFilterStringFilterProps, any>
{
render() | random_line_split |
item.rs | //! Language items and abstract-syntax tree.
use std::fmt;
use vm;
/// The equivalent of a routine/function.
#[derive(PartialEq, Clone, Debug)]
pub struct Block<I>(pub Vec<BlockItem<I>>);
/// Language items only valid in a block.
#[derive(PartialEq, Clone, Debug)]
pub enum BlockItem<I> {
Call(String),
Litera... | StackItem::String(ref s) => write!(f, "\"{}\"", *s),
StackItem::Boolean(b) => write!(f, "{}", b),
StackItem::Symbol(ref s) => write!(f, ":{}", *s),
StackItem::Block(ref b) => write!(f, "{{ {}}}", *b),
}
}
} | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
StackItem::Integer(ref i) => write!(f, "{}", *i),
StackItem::Float(n) => write!(f, "{}", n), | random_line_split |
item.rs | //! Language items and abstract-syntax tree.
use std::fmt;
use vm;
/// The equivalent of a routine/function.
#[derive(PartialEq, Clone, Debug)]
pub struct | <I>(pub Vec<BlockItem<I>>);
/// Language items only valid in a block.
#[derive(PartialEq, Clone, Debug)]
pub enum BlockItem<I> {
Call(String),
Literal(StackItem<I>),
}
impl<I> fmt::Display for Block<I> where I: fmt::Display {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for item in &self... | Block | identifier_name |
platform.js | /*
* gaze
* https://github.com/shama/gaze
*
* Copyright (c) 2014 Kyle Robinson Young
* Licensed under the MIT license.
*/
'use strict';
var PathWatcher = null;
var statpoll = require('./statpoll.js');
var helper = require('./helper');
var fs = require('graceful-fs');
var path = require('path');
// Define objec... | () {
statpoll(file, function(event) {
var filepath = file;
if (process.platform === 'linux') {
var go = platformUtils.linuxWorkarounds(event, filepath, cb);
if (go === false) { return; }
}
platformUtils.cbstack(null, event, filepath);
});
}
// Add callback to watched... | useStatPoll | identifier_name |
platform.js | /*
* gaze
* https://github.com/shama/gaze
*
* Copyright (c) 2014 Kyle Robinson Young
* Licensed under the MIT license.
*/
'use strict';
var PathWatcher = null;
var statpoll = require('./statpoll.js');
var helper = require('./helper');
var fs = require('graceful-fs');
var path = require('path');
// Define objec... | statpoll(file, function(event) {
var filepath = file;
if (process.platform === 'linux') {
var go = platformUtils.linuxWorkarounds(event, filepath, cb);
if (go === false) { return; }
}
platformUtils.cbstack(null, event, filepath);
});
}
// Add callback to watched
wa... | // Helper for when to use statpoll
function useStatPoll() { | random_line_split |
platform.js | /*
* gaze
* https://github.com/shama/gaze
*
* Copyright (c) 2014 Kyle Robinson Young
* Licensed under the MIT license.
*/
'use strict';
var PathWatcher = null;
var statpoll = require('./statpoll.js');
var helper = require('./helper');
var fs = require('graceful-fs');
var path = require('path');
// Define objec... |
// Add callback to watched
watched[file] = [cb];
// By default try using native OS watchers
if (platform.mode === 'auto' || platform.mode === 'watch') {
// Delay adding files to watch
// Fixes the duplicate handle race condition when renaming files
// ie: (The handle(26) returned by watching [fil... | {
statpoll(file, function(event) {
var filepath = file;
if (process.platform === 'linux') {
var go = platformUtils.linuxWorkarounds(event, filepath, cb);
if (go === false) { return; }
}
platformUtils.cbstack(null, event, filepath);
});
} | identifier_body |
index.d.ts | // Type definitions for haversine 1.1 | // Definitions by: Christian Rackerseder <https://github.com/screendriver>
// Dan Vanderkam <https://github.com/danvk>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
declare namespace haversine {
interface CoordinateLongitudeLatitude {
longitud... | // Project: https://github.com/njj/haversine, https://github.com/niix/haversine | random_line_split |
font.d.ts | export class Fo |
public static default: Font;
public fontFamily: string;
public fontStyle: FontStyle;
public fontWeight: FontWeight;
public fontSize: number;
public fontScale: number;
public isBold: boolean;
public isItalic: boolean;
constructor(family: string, size: number, style: FontStyle, weight: FontWeight);
public ... | nt { | identifier_name |
font.d.ts | export class Font {
public static default: Font;
public fontFamily: string;
public fontStyle: FontStyle;
public fontWeight: FontWeight;
public fontSize: number;
public fontScale: number;
public isBold: boolean;
public isItalic: boolean;
constructor(family: string, size: number, style: FontStyle, weight: Fo... | public withFontStyle(style: string): Font;
public withFontWeight(weight: string): Font;
public withFontSize(size: number): Font;
public withFontScale(scale: number): Font;
public static equals(value1: Font, value2: Font): boolean;
}
export type FontStyle = 'normal' | 'italic';
export namespace FontStyle {
expor... | public withFontFamily(family: string): Font; | random_line_split |
list-sites.js | 'use strict'
import { Page, User } from '../../../models'
export function ListSites (userId) {
return new Promise((resolve, reject) => {
User
.findOne({ _id: userId })
.select('id, accounts')
.exec((err, user) => {
if (err) {
reject({
status: 400,
mess... |
const userSites = user.accounts
.map(i => i.account_id)
Page
.find({ fb_account_id: { $in: userSites }, active: true })
.sort({name: 1})
.select('-__v')
.exec((err, list) => {
if (err) {
reject({
status: 400,
... | {
reject({
status: 404,
message: 'User sites not found!'
})
return
} | conditional_block |
list-sites.js | 'use strict'
import { Page, User } from '../../../models'
export function ListSites (userId) {
return new Promise((resolve, reject) => {
User
.findOne({ _id: userId })
.select('id, accounts')
.exec((err, user) => {
if (err) {
reject({
status: 400,
mess... | .sort({name: 1})
.select('-__v')
.exec((err, list) => {
if (err) {
reject({
status: 400,
message: 'Unable to query sites list!'
})
return
}
const sites = list.map(i => {
... | const userSites = user.accounts
.map(i => i.account_id)
Page
.find({ fb_account_id: { $in: userSites }, active: true }) | random_line_split |
list-sites.js | 'use strict'
import { Page, User } from '../../../models'
export function | (userId) {
return new Promise((resolve, reject) => {
User
.findOne({ _id: userId })
.select('id, accounts')
.exec((err, user) => {
if (err) {
reject({
status: 400,
message: 'Unable to query user sites!'
})
return
}
if... | ListSites | identifier_name |
list-sites.js | 'use strict'
import { Page, User } from '../../../models'
export function ListSites (userId) |
const userSites = user.accounts
.map(i => i.account_id)
Page
.find({ fb_account_id: { $in: userSites }, active: true })
.sort({name: 1})
.select('-__v')
.exec((err, list) => {
if (err) {
reject({
status: 400,
... | {
return new Promise((resolve, reject) => {
User
.findOne({ _id: userId })
.select('id, accounts')
.exec((err, user) => {
if (err) {
reject({
status: 400,
message: 'Unable to query user sites!'
})
return
}
if (!user) {... | identifier_body |
grid_world_3D_env.py | import numpy as np
from .base import Env
from rllab.spaces import Discrete
from rllab.envs.base import Step
from rllab.core.serializable import Serializable
MAPS = {
"chain": [
"GFFFFFFFFFFFFFSFFFFFFFFFFFFFG"
],
"4x4_safe": [
"SFFF",
"FWFW",
"FFFW",
"WFFG"
],
... | print('z', start_z)
self.start_state = start_x * self.n_col + start_y + start_z * (self.n_col + self.n_row)
self.state = None
self.domain_fig = None
def reset(self):
self.state = self.start_state
return self.state
@staticmethod
def action_from_direction(d):... | Serializable.quick_init(self, locals())
#print("desc before isinstance",desc)
if isinstance(desc, str):
desc = MAPS[desc]
#print("desc before nparray \n",desc)
desc[0] = list(map(list, desc[0]))
#print(desc[0])
desc[1] = list(map(list, desc[1]))
#print... | identifier_body |
grid_world_3D_env.py | import numpy as np
from .base import Env
from rllab.spaces import Discrete
from rllab.envs.base import Step
from rllab.core.serializable import Serializable
MAPS = {
"chain": [
"GFFFFFFFFFFFFFSFFFFFFFFFFFFFG"
],
"4x4_safe": [
"SFFF",
"FWFW",
"FFFW",
"WFFG"
],
... | def action_from_direction(d):
"""
Return the action corresponding to the given direction. This is a helper method for debugging and testing
purposes.
:return: the action index corresponding to the given direction
"""
return dict(
left=0,
down=1... | self.state = self.start_state
return self.state
@staticmethod | random_line_split |
grid_world_3D_env.py | import numpy as np
from .base import Env
from rllab.spaces import Discrete
from rllab.envs.base import Step
from rllab.core.serializable import Serializable
MAPS = {
"chain": [
"GFFFFFFFFFFFFFSFFFFFFFFFFFFFG"
],
"4x4_safe": [
"SFFF",
"FWFW",
"FFFW",
"WFFG"
],
... | (self, state, action):
"""
Given the state and action, return a list of possible next states and their probabilities. Only next states
with nonzero probabilities will be returned
:param state: start state
:param action: action
:return: a list of pairs (s', p(s'|s,a))
... | get_possible_next_states | identifier_name |
grid_world_3D_env.py | import numpy as np
from .base import Env
from rllab.spaces import Discrete
from rllab.envs.base import Step
from rllab.core.serializable import Serializable
MAPS = {
"chain": [
"GFFFFFFFFFFFFFSFFFFFFFFFFFFFG"
],
"4x4_safe": [
"SFFF",
"FWFW",
"FFFW",
"WFFG"
],
... |
#print("desc before nparray \n",desc)
desc[0] = list(map(list, desc[0]))
#print(desc[0])
desc[1] = list(map(list, desc[1]))
#print(desc[1])
desc= np.array(list(desc))
#print("desc after nparray \n",desc)
desc[desc == '.'] = 'F'
desc[desc == 'o'] =... | desc = MAPS[desc] | conditional_block |
create_sec_package.py | #!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. All Rights Reserved.
# | #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##... | # 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 | random_line_split |
create_sec_package.py | #!/usr/bin/env python3
###############################################################################
# Copyright 2017 The Apollo Authors. 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... |
homedir = os.environ['HOME']
release_tgz = homedir + '/.cache/apollo_release.tar.gz'
sec_release_tgz = homedir + '/.cache/sec_apollo_release.tar.gz'
package_token = homedir + '/.cache/package_token'
ret = sec_api.sec_upgrade_get_package(
release_tgz, sec_release_tgz, package_token)
if ret is True:
print('Sec... | print('Security environment init failed!')
exit(1) | conditional_block |
harfbuzz.rs | byte_range = 0..0;
let mut y_pos = Au(0);
// main loop over each glyph. each iteration usually processes 1 glyph and 1+ chars.
// in cases with complex glyph-character associations, 2+ glyphs and 1+ chars can be
// processed.
while glyph_span.start < glyph_count {
... |
let font: *mut Font = font_data as *mut Font;
assert!(!font.is_null());
unsafe {
let advance = (*font).glyph_h_kerning(first_glyph as GlyphId, second_glyph as GlyphId);
Shaper::float_to_fixed(advance)
}
}
| identifier_body | |
harfbuzz.rs | _i).cluster
}
}
pub fn len(&self) -> usize {
self.count
}
/// Returns shaped glyph data for one glyph, and updates the y-position of the pen.
pub fn entry_for_glyph(&self, i: usize, y_pos: &mut Au) -> ShapedGlyphEntry {
assert!(i < self.count);
unsafe {
... |
while byte_range.end < byte_max {
byte_range.end += 1;
// Extend the byte range to include any following byte without its own glyph.
while byte_range.end < byte_max && byte_to_glyph[byte_range.end] == NO_GLYPH {
byte_range.end += 1;
... | // processed.
while glyph_span.start < glyph_count {
debug!("Processing glyph at idx={}", glyph_span.start);
glyph_span.end = glyph_span.start;
byte_range.end = glyph_data.byte_offset_of_glyph(glyph_span.start) as usize; | random_line_split |
harfbuzz.rs | _t = hb_buffer_create();
hb_buffer_set_direction(
hb_buffer,
if options.flags.contains(ShapingFlags::RTL_FLAG) {
HB_DIRECTION_RTL
} else {
HB_DIRECTION_LTR
},
);
hb_buffer_set_scr... | ontFuncs( | identifier_name | |
heapCaptureMiddleware.js | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict... | (capture, onFailure, onSuccess) {
const urls = new Set();
const sourcemaps = new Map();
for (const id in capture.refs) {
const ref = capture.refs[id];
if ((ref.type === 'ScriptExecutable' ||
ref.type === 'EvalExecutable' ||
ref.type === 'ProgramExecutable' ||
ref.type === 'Function... | getSourceMapsForCapture | identifier_name |
heapCaptureMiddleware.js | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict... | ref.value.line = original.line;
ref.value.col = original.column;
}
}
}
onSuccess(capture);
});
}
module.exports = function(req, res, next) {
if (req.url !== '/jscheapcaptureupload') {
next();
return;
}
console.log('symbolicating Heap Capture');
symbolicateH... | {
getSourceMapsForCapture(capture, onFailure, (sourcemaps) => {
for (const id in capture.refs) {
const ref = capture.refs[id];
if (ref.type === 'ScriptExecutable' ||
ref.type === 'EvalExecutable' ||
ref.type === 'ProgramExecutable' ||
ref.type === 'FunctionExecutable') {
... | identifier_body |
heapCaptureMiddleware.js | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict... |
if (url === 'assets://default_bundle') {
onFailure('Don\'t know how to symbolicate in-app bundle, please load from server');
return;
}
const parsedUrl = urlLib.parse(url);
const options = {
host: 'localhost',
port: parsedUrl.port,
path: parsedUrl.pathname.replace(/\.bundle$/, '.map') + pa... | {
onFailure('must provide a URL');
return;
} | conditional_block |
heapCaptureMiddleware.js | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict... | console.log('Packaging Trace');
var captureHtml = captureDir + '/capture_' + Date.now() + '.html';
var capture = fs.createWriteStream(captureHtml);
var inliner = spawn(
'inliner',
['--nocompress', 'heapCapture.html'],
{ cwd: path.join(__dirname, '/heapCapture/'),
... | fs.appendFileSync(preload, ';');
const captureDir = path.join(__dirname, 'heapCapture/captures');
if (!fs.existsSync(captureDir)) {
fs.mkdirSync(captureDir);
} | random_line_split |
util.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_blocks)]
use construct::ConstructionResult;
use incremental::RestyleDamage;
use parallel::DomPara... |
#[inline(always)]
fn borrow_layout_data<'a>(&'a self) -> Ref<'a,Option<LayoutDataWrapper>> {
unsafe {
mem::transmute(self.get().layout_data())
}
}
#[inline(always)]
fn mutate_layout_data<'a>(&'a self) -> RefMut<'a,Option<LayoutDataWrapper>> {
unsafe {
... | {
mem::transmute(self.get().layout_data_unchecked())
} | identifier_body |
util.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_blocks)]
use construct::ConstructionResult;
use incremental::RestyleDamage;
use parallel::DomPara... | before_style: None,
after_style: None,
restyle_damage: RestyleDamage::empty(),
flow_construction_result: ConstructionResult::None,
before_flow_construction_result: ConstructionResult::None,
after_flow_construction_result: ConstructionResult::None,
... | PrivateLayoutData { | random_line_split |
util.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#![allow(unsafe_blocks)]
use construct::ConstructionResult;
use incremental::RestyleDamage;
use parallel::DomPara... | {
pub chan: Option<LayoutChan>,
pub shared_data: SharedLayoutData,
pub data: Box<PrivateLayoutData>,
}
#[allow(dead_code)]
fn static_assertion(x: Option<LayoutDataWrapper>) {
unsafe {
let _: Option<::script::dom::node::LayoutData> =
::std::intrinsics::transmute(x);
}
}
/// A t... | LayoutDataWrapper | identifier_name |
renumber.rs | use rustc_index::vec::IndexVec;
use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};
use rustc_middle::mir::visit::{MutVisitor, TyContext};
use rustc_middle::mir::{Body, Location, PlaceElem, Promoted};
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
/// Replaces... | }
} | }
fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _location: Location) {
*constant = self.renumber_regions(&*constant); | random_line_split |
renumber.rs | use rustc_index::vec::IndexVec;
use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};
use rustc_middle::mir::visit::{MutVisitor, TyContext};
use rustc_middle::mir::{Body, Location, PlaceElem, Promoted};
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
/// Replaces... |
None
}
#[instrument(skip(self), level = "debug")]
fn visit_substs(&mut self, substs: &mut SubstsRef<'tcx>, location: Location) {
*substs = self.renumber_regions(*substs);
debug!(?substs);
}
#[instrument(skip(self), level = "debug")]
fn visit_region(&mut self, region:... | {
let new_ty = self.renumber_regions(ty);
if new_ty != ty {
return Some(PlaceElem::Field(field, new_ty));
}
} | conditional_block |
renumber.rs | use rustc_index::vec::IndexVec;
use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};
use rustc_middle::mir::visit::{MutVisitor, TyContext};
use rustc_middle::mir::{Body, Location, PlaceElem, Promoted};
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
/// Replaces... |
/// Replaces all regions appearing in `value` with fresh inference
/// variables.
#[instrument(skip(infcx), level = "debug")]
pub fn renumber_regions<'tcx, T>(infcx: &InferCtxt<'_, 'tcx>, value: T) -> T
where
T: TypeFoldable<'tcx>,
{
infcx.tcx.fold_regions(value, &mut false, |_region, _depth| {
let or... | {
debug!(?body.arg_count);
let mut visitor = NllVisitor { infcx };
for body in promoted.iter_mut() {
visitor.visit_body(body);
}
visitor.visit_body(body);
} | identifier_body |
renumber.rs | use rustc_index::vec::IndexVec;
use rustc_infer::infer::{InferCtxt, NllRegionVariableOrigin};
use rustc_middle::mir::visit::{MutVisitor, TyContext};
use rustc_middle::mir::{Body, Location, PlaceElem, Promoted};
use rustc_middle::ty::subst::SubstsRef;
use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
/// Replaces... | (&mut self, region: &mut ty::Region<'tcx>, location: Location) {
let old_region = *region;
*region = self.renumber_regions(&old_region);
debug!(?region);
}
fn visit_const(&mut self, constant: &mut &'tcx ty::Const<'tcx>, _location: Location) {
*constant = self.renumber_regions(&... | visit_region | identifier_name |
FileOperations.py | # -*- coding: utf-8 -*-
__author__ = 'Pulimootil'
"""
This class will handle all the file related operations
"""
import os
import cv2
class FileOperatoins(object):
def __init__(self, filename, xmlFile):
self.checkFile(filename, xmlFile)
''' Set the output folder '''
def setOutput(self, outpu... |
''' Set the output image filename '''
def setOutputImageName(self, tag):
try:
self.outputName = self.outputFolder + os.path.sep + \
os.path.splitext(os.path.basename(self.imgFilename))[0] + tag + \
os.path.splitext(self.imgFilena... | self.distortedImage = img | identifier_body |
FileOperations.py | # -*- coding: utf-8 -*-
__author__ = 'Pulimootil'
"""
This class will handle all the file related operations
"""
import os
import cv2
class FileOperatoins(object):
def __init__(self, filename, xmlFile):
self.checkFile(filename, xmlFile)
''' Set the output folder '''
def setOutput(self, outpu... |
if os.path.isfile(xmlFilename):
self.xmlFilename = xmlFilename
else:
raise 'Invalid xml filename:' + xmlFilename
| raise 'Invalid image filename:' + imgfilename | conditional_block |
FileOperations.py | # -*- coding: utf-8 -*-
__author__ = 'Pulimootil'
"""
This class will handle all the file related operations
"""
import os
import cv2
class FileOperatoins(object):
def | (self, filename, xmlFile):
self.checkFile(filename, xmlFile)
''' Set the output folder '''
def setOutput(self, outputFolder):
self.outputFolder = outputFolder
''' Get the image file '''
def getImage(self, color):
if color:
self.img = cv2.imread(self.imgFilename, 1... | __init__ | identifier_name |
FileOperations.py | # -*- coding: utf-8 -*-
__author__ = 'Pulimootil'
"""
This class will handle all the file related operations
"""
|
class FileOperatoins(object):
def __init__(self, filename, xmlFile):
self.checkFile(filename, xmlFile)
''' Set the output folder '''
def setOutput(self, outputFolder):
self.outputFolder = outputFolder
''' Get the image file '''
def getImage(self, color):
if color:
... | import os
import cv2 | random_line_split |
freelancer.js | /*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('body').on('click', '.page-scroll... |
function setLanguageEn() {
$.post('index.php',{ language: 'en'});
} | {
$.post('index.php',{ language: 'pl'});
} | identifier_body |
freelancer.js | /*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('body').on('click', '.page-scroll... | () {
$.post('index.php',{ language: 'pl'});
}
function setLanguageEn() {
$.post('index.php',{ language: 'en'});
} | setLanguagePl | identifier_name |
freelancer.js | /*!
* Start Bootstrap - Freelancer Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('body').on('click', '.page-scroll... | // Floating label headings for the contact form
$(function() {
$("body").on("input propertychange", ".floating-label-form-group", function(e) {
$(this).toggleClass("floating-label-form-group-with-value", !! $(e.target).val());
}).on("focus", ".floating-label-form-group", function() {
$(this).add... | random_line_split | |
polarization.py | # Licensed under GPL version 3 - see LICENSE.rst
import numpy as np
import astropy.units as u
from .utils import norm_vector, e2h
__all__ = ['polarization_vectors', 'Q_reflection', 'paralleltransport_matrix',
'parallel_transport']
def polarization_vectors(dir_array, angles):
'''Converts polarization... | this plane is not well defined and the resulting matrix elements will
be set to ``np.nan``, unless ``replace_nans`` is set.
Note that the ray matrix returned works on an eukledian 3d vector, not a
homogeneous vector. (Polarization is a vector, thus the forth element of the
homogeneous vector is alw... | Parallel transport for a vector implies that the component s
(perpendicular, from German *senkrecht*) to the planes spanned by
``dir1`` and ``dir2`` stays the same. If ``dir1`` is parallel to ``dir2`` | random_line_split |
polarization.py | # Licensed under GPL version 3 - see LICENSE.rst
import numpy as np
import astropy.units as u
from .utils import norm_vector, e2h
__all__ = ['polarization_vectors', 'Q_reflection', 'paralleltransport_matrix',
'parallel_transport']
def polarization_vectors(dir_array, angles):
'''Converts polarization... |
# polarization relative to positive y or x at 0
v_1 = ~pol_convention_x[:, np.newaxis] * (y - r * np.dot(r, y)[:, np.newaxis])
v_1 += pol_convention_x[:, np.newaxis] * (x - r * np.dot(r, x)[:, np.newaxis])
v_1 /= np.linalg.norm(v_1, axis=1)[:, np.newaxis]
# right hand coordinate system is v_1, v_2... | angles = angles.to(u.rad) | conditional_block |
polarization.py | # Licensed under GPL version 3 - see LICENSE.rst
import numpy as np
import astropy.units as u
from .utils import norm_vector, e2h
__all__ = ['polarization_vectors', 'Q_reflection', 'paralleltransport_matrix',
'parallel_transport']
def polarization_vectors(dir_array, angles):
'''Converts polarization... | raise ValueError('delta_dir must have dimension (n, 4).')
m = delta_dir[..., None, :] * delta_dir[..., :, None]
return np.eye(4) - 2 / (np.linalg.norm(delta_dir, axis=1)**2)[:, None, None] * m
def paralleltransport_matrix(dir1, dir2, jones=np.eye(2), replace_nans=True):
'''Calculate parallel trans... | '''Reflection of a polarization vector on a non-polarizing surface.
This can also be used for other elements that change the direction of the
photon without adding any more polarization and where both sides
propagate in the same medium.
See `Yun (2011) <http://hdl.handle.net/10150/202979>`_, eqn 4.3.13... | identifier_body |
polarization.py | # Licensed under GPL version 3 - see LICENSE.rst
import numpy as np
import astropy.units as u
from .utils import norm_vector, e2h
__all__ = ['polarization_vectors', 'Q_reflection', 'paralleltransport_matrix',
'parallel_transport']
def | (dir_array, angles):
'''Converts polarization angles to vectors in the direction of polarization.
Follows convention: Vector perpendicular to photon direction and closest to +y axis is
angle 0 for polarization direction, unless photon direction is parallel to the y axis,
in which case the vector closes... | polarization_vectors | identifier_name |
fs-client.ts | import fs from 'fs';
import mkdirp from 'mkdirp';
import path from 'path';
type FSWraps =
| typeof fs.promises.readFile
| typeof fs.promises.writeFile
| typeof fs.promises.unlink
| typeof fs.promises.readdir
| typeof fs.promises.mkdir
| typeof fs.promises.rmdir
| typeof fs.promises.stat
| typeof fs.pro... | promises: {
readFile: wrap(fs.promises.readFile),
writeFile: wrap(fs.promises.writeFile),
unlink: wrap(fs.promises.unlink),
readdir: wrap(fs.promises.readdir),
mkdir: wrap(fs.promises.mkdir),
rmdir: wrap(fs.promises.rmdir),
stat: wrap(fs.promises.stat),
lstat: wrap(fs... |
return { | random_line_split |
webpack.base.conf.js | console.log('build/webpack.base.conf.js');
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve(dir) |
module.exports = {
entry: {
app: ['babel-polyfill', './src/main.js']
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production' ?
config.build.assetsPublicPath : config.dev.assetsPublicPath
},
ext... | {
return path.join(__dirname, '..', dir)
} | identifier_body |
webpack.base.conf.js | console.log('build/webpack.base.conf.js');
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve(dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: ['babel-polyfill'... | } | random_line_split | |
webpack.base.conf.js | console.log('build/webpack.base.conf.js');
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function | (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: ['babel-polyfill', './src/main.js']
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production' ?
config.build.assetsPub... | resolve | identifier_name |
lib.rs | #![doc(html_root_url = "https://mackwic.github.io/rspec")]
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![allow(dead_code)]
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate derive_new;
#[cfg(feature = "expectest_compat")]
extern crate expectest;... |
#[cfg(test)]
mod tests {
pub use super::*;
pub use block::*;
// Test list:
// x check that tests can call `assert_eq!`
// x check that tests can return Err or Ok
// x runner can count the tests
// x runner can count the success and failed
// x check that we can use before in a descri... | {
use std::io;
use std::sync::Arc;
use logger::Logger;
use runner::{ConfigurationBuilder, Runner};
let logger = Arc::new(Logger::new(io::stdout()));
let configuration = ConfigurationBuilder::default().build().unwrap();
let runner = Runner::new(configuration, vec![logger]);
runner.run(... | identifier_body |
lib.rs | #![doc(html_root_url = "https://mackwic.github.io/rspec")]
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![allow(dead_code)]
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate derive_new;
#[cfg(feature = "expectest_compat")]
extern crate expectest;... | <T>(suite: &Suite<T>)
where
T: Clone + Send + Sync + ::std::fmt::Debug,
{
use std::io;
use std::sync::Arc;
use logger::Logger;
use runner::{ConfigurationBuilder, Runner};
let logger = Arc::new(Logger::new(io::stdout()));
let configuration = ConfigurationBuilder::default().build().unwrap();... | run | identifier_name |
lib.rs | #![doc(html_root_url = "https://mackwic.github.io/rspec")]
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
#![allow(dead_code)]
#[macro_use]
extern crate derive_builder;
#[macro_use]
extern crate derive_new;
#[cfg(feature = "expectest_compat")]
extern crate expectest;... | /// # Examples
///
/// ```
/// # extern crate rspec;
/// #
/// # pub fn main() {
/// rspec::run(&rspec::given("a scenario", (), |ctx| {
/// ctx.when("...", |ctx| {
/// // ...
/// });
///
/// ctx.then("...", |env| { /* ... */ });
/// }));
/// # }
/// ```
pub fn run<T>(suite: &Suite<T>)
where
T: C... |
/// A wrapper for conveniently running a test suite with
/// the default configuration with considerebly less glue-code.
/// | random_line_split |
views.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2013-10-11
#
# @author: Bartosz Nowak sztosz@gmail.com
#
# This file is licensed GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
from __future__ import unicode_literals
import unicodecsv
from datetime import datetime, timedelta
from pytz import timezone
from... | elf):
self.a = {}
self.b = {}
self.c = {}
objects = models.DamageReport.objects.select_related('category').order_by('-date')
for report in objects:
_date = report.day_str()
if _date not in self.a:
self.a[_date] = 0
if _date ... | iew(s | identifier_name |
views.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2013-10-11
#
# @author: Bartosz Nowak sztosz@gmail.com
#
# This file is licensed GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
from __future__ import unicode_literals
import unicodecsv
from datetime import datetime, timedelta
from pytz import timezone
from... |
for k, v in self.a.iteritems():
reports[0]['data'].append([k, v])
for k, v in self.b.iteritems():
reports[1]['data'].append([k, v])
for k, v in self.c.iteritems():
reports[2]['data'].append([k, v])
return reports
| lf.a = {}
self.b = {}
self.c = {}
objects = models.DamageReport.objects.select_related('category').order_by('-date')
for report in objects:
_date = report.day_str()
if _date not in self.a:
self.a[_date] = 0
if _date not in self.b:
... | identifier_body |
views.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2013-10-11
#
# @author: Bartosz Nowak sztosz@gmail.com
#
# This file is licensed GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
from __future__ import unicode_literals
import unicodecsv
from datetime import datetime, timedelta
from pytz import timezone
from... | for k, v in self.c.iteritems():
reports[2]['data'].append([k, v])
return reports
| ports[1]['data'].append([k, v])
| conditional_block |
views.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Created on 2013-10-11
#
# @author: Bartosz Nowak sztosz@gmail.com
#
# This file is licensed GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
from __future__ import unicode_literals
import unicodecsv
from datetime import datetime, timedelta
from pytz import timezone
from... |
for report in objects:
_date = report.day_str()
if _date not in self.a:
self.a[_date] = 0
if _date not in self.b:
self.b[_date] = 0
if _date not in self.c:
self.c[_date] = 0
getattr(self, report.categor... | self.b = {}
self.c = {}
objects = models.DamageReport.objects.select_related('category').order_by('-date') | random_line_split |
LoadLinkView.js | /**
* Created by mathabaws on 6/1/15.
*/
// LoadLinkView.js
//
// Load a specific view from a model that has a link specified for it. This is similar to LoadModel.js but without the
// pre-canned set of models. This one will be passed a model URN and view GUID.
//
// Jim Awe
// Autodesk, Inc.
var _viewer = null; ... |
}
// load a specific document into the intialized viewer
function loadDocument(urnStrModel, viewGUID, addEmbedToolbar) {
if (!urnStrModel || (0 === urnStrModel.length)) {
alert("You must specify a URN!");
return;
}
var fullUrnStr = "urn:" + urnStrModel;
Autodesk.Viewing.Document.loa... | {
alert("ERROR: Couldn't initialize viewer!");
console.log("ERROR Code: " + retCode); // TBD: do real error handling here
} | conditional_block |
LoadLinkView.js | /**
* Created by mathabaws on 6/1/15.
*/
// LoadLinkView.js
//
// Load a specific view from a model that has a link specified for it. This is similar to LoadModel.js but without the
// pre-canned set of models. This one will be passed a model URN and view GUID.
//
// Jim Awe
// Autodesk, Inc.
var _viewer = null; ... |
function loadViewErrorFunc() {
console.log("ERROR: could not load asset into viewer...");
}
// load a particular viewable into the viewer
function loadView(document, viewObj) {
var path = document.getViewablePath(viewObj);
console.log("Loading view URN: " + path);
_viewer.load(path, document.getPrope... | {
console.log("Loaded viewer successfully with given asset...");
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.