file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
FloatingLabel.js | import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
import { Animated, StyleSheet } from 'react-native';
import { H6 } from '@ui/typography';
import styled from '@ui/styled';
export const LabelText = styled(({ theme }) => ({
color: theme.colors.text.secondary,
backgroundColor: 'transp... | () {
const scaledWidth = this.state.labelWidth * (1.05 - this.props.scaleSize);
const sideScaledWidth = scaledWidth / 2;
const scale = this.props.animation.interpolate({
inputRange: [0, 1],
outputRange: [1, this.props.scaleSize],
});
const opacity = this.props.animation.interpolate({
... | render | identifier_name |
setup.py | #!/usr/bin/env python3
from setuptools import setup
setup(
name='SecFS',
version='0.1.0',
description='6.858 final project --- an encrypted and authenticated file system',
long_description= open('README.md', 'r').read(),
author='Jon Gjengset',
author_email='jon@thesquareplanet.com',
mainta... | scripts=['bin/secfs-server', 'bin/secfs-fuse'],
license='MIT',
classifiers=[
"Development Status :: 2 - Pre-Alpha",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Topic :: Education",
"Topic :: Security",
"Topic :: System :... | maintainer_email='pdos@csail.mit.edu',
url='https://github.com/mit-pdos/6.858-secfs',
packages=['secfs', 'secfs.store'],
install_requires=['llfuse', 'Pyro4', 'serpent', 'cryptography'], | random_line_split |
build.js | #!/usr/bin/env node
/**
* Build script for /tg/station 13 codebase.
*
* This script uses Juke Build, read the docs here:
* https://github.com/stylemistake/juke-build
*
* @file
* @copyright 2021 Aleksej Komarov
* @license MIT
*/
import fs from 'fs';
import { DreamDaemon, DreamMaker } from './lib/byond.js';
imp... |
await DreamMaker(`${DME_NAME}.dme`, {
defines: ['CBT', ...defines],
});
},
});
export const DmTestTarget = new Juke.Target({
dependsOn: ({ get }) => [
get(DefineParameter).includes('ALL_MAPS') && DmMapsIncludeTarget,
],
executes: async ({ get }) => {
const defines = get(DefineParameter);... | {
Juke.logger.info('Using defines:', defines.join(', '));
} | conditional_block |
build.js | #!/usr/bin/env node
/**
* Build script for /tg/station 13 codebase.
*
* This script uses Juke Build, read the docs here:
* https://github.com/stylemistake/juke-build
*
* @file
* @copyright 2021 Aleksej Komarov
* @license MIT
*/
import fs from 'fs';
import { DreamDaemon, DreamMaker } from './lib/byond.js';
imp... | Juke.rm('tgui/public/*.bundle.*');
Juke.rm('tgui/public/*.hot-update.*');
Juke.rm('tgui/packages/tgfont/dist', { recursive: true });
Juke.rm('tgui/.yarn/cache', { recursive: true });
Juke.rm('tgui/.yarn/unplugged', { recursive: true });
Juke.rm('tgui/.yarn/webpack', { recursive: true });
Juk... | Juke.rm('tgui/public/*.chunk.*'); | random_line_split |
navMenu.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom'
import { Link } from 'react-router-dom';
import { Router } from 'react-router';
import { Components, Services } from './../../root';
import { observer } from './../../mx';
@observer
export class NavMenu extends React.Component<any, any> {
publi... | () {
var user = await Services.CurrentUserService.get();
}
public render() {
var progress = undefined;
if (Services.MessengerService.numberOfPendingHttpRequest != 0)
progress = <div role="progressbar" className="mdc-linear-progress mdc-linear-progress--indeterminate mdc-linea... | componentDidMount | identifier_name |
navMenu.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom'
import { Link } from 'react-router-dom';
import { Router } from 'react-router';
import { Components, Services } from './../../root';
import { observer } from './../../mx';
@observer
export class NavMenu extends React.Component<any, any> {
publi... | <div className="mdc-linear-progress__bar mdc-linear-progress__secondary-bar">
<span className="mdc-linear-progress__bar-inner"></span>
</div>
</div>;
return (<div>
<header className="mdc-toolbar mdc-toolbar--fixed mdc-toolbar--waterfa... | random_line_split | |
navMenu.tsx | import * as React from 'react';
import * as ReactDOM from 'react-dom'
import { Link } from 'react-router-dom';
import { Router } from 'react-router';
import { Components, Services } from './../../root';
import { observer } from './../../mx';
@observer
export class NavMenu extends React.Component<any, any> {
publi... |
public render() {
var progress = undefined;
if (Services.MessengerService.numberOfPendingHttpRequest != 0)
progress = <div role="progressbar" className="mdc-linear-progress mdc-linear-progress--indeterminate mdc-linear-progress--accent progress">
<div className="mdc-line... | {
var user = await Services.CurrentUserService.get();
} | identifier_body |
sortedIndex.js | /**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="amd" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Inv... | while (low < high) {
var mid = (low + high) >>> 1;
(callback(array[mid]) < value)
? low = mid + 1
: high = mid;
}
return low;
}
return sortedIndex;
}); | callback = callback ? createCallback(callback, thisArg, 1) : identity;
value = callback(value);
| random_line_split |
sortedIndex.js | /**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="amd" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Inv... |
return low;
}
return sortedIndex;
});
| {
var mid = (low + high) >>> 1;
(callback(array[mid]) < value)
? low = mid + 1
: high = mid;
} | conditional_block |
sortedIndex.js | /**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="amd" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Inv... |
return sortedIndex;
});
| {
var low = 0,
high = array ? array.length : low;
// explicitly reference `identity` for better inlining in Firefox
callback = callback ? createCallback(callback, thisArg, 1) : identity;
value = callback(value);
while (low < high) {
var mid = (low + high) >>> 1;
(callback(array... | identifier_body |
sortedIndex.js | /**
* Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/>
* Build: `lodash modularize modern exports="amd" -o ./modern/`
* Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE>
* Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Inv... | (array, value, callback, thisArg) {
var low = 0,
high = array ? array.length : low;
// explicitly reference `identity` for better inlining in Firefox
callback = callback ? createCallback(callback, thisArg, 1) : identity;
value = callback(value);
while (low < high) {
var mid = (low + ... | sortedIndex | identifier_name |
worddisplayvm.js | ///<reference path="./otmword.ts" />
///<reference path="./wmmodules.ts" />
///<reference path="./wgenerator.ts" />
///<reference path="./ntdialog.ts" />
/**
* 単語作成部で使用するViewModel
*/
class WordDisplayVM {
/**
* コンストラクタ
* @param el バインディングを適用するタグのid
* @param dict OTM形式辞書クラス
* @param... | /**
* 作成した単語一覧をOTM-JSON形式で出力するメソッド
*/
outputOtmJSON: function _outputOtmJSON() {
// idを振り直す
let id = 1;
this.dictionary.words.forEach((x) => {
x.entry.id = id++;
});
... | },
| random_line_split |
worddisplayvm.js | ///<reference path="./otmword.ts" />
///<reference path="./wmmodules.ts" />
///<reference path="./wgenerator.ts" />
///<reference path="./ntdialog.ts" />
/**
* 単語作成部で使用するViewModel
*/
class WordDisplayVM {
/**
* コンストラクタ
* @param el バインディングを適用するタグのid
* @param dict OTM形式辞書クラス
* @param... | let form = "";
switch (this.createSetting.mode) {
case WordGenerator.SIMPLE_SYMBOL:
form = WordGenerator.simple(this.createSetting.simple);
break;
case WordGenerator.SIMPLECV_SYMBOL:
... | te() {
| identifier_name |
test_plugin_slurm.py | # pylint: disable=missing-docstring
# this fails on Python 2.6 but Slurm environment is 2.7
import unittest
from datetime import datetime
from reporting.plugins.slurm import SlurmInput
class SlurmTestCase(unittest.TestCase):
"""Test cases for slurm module"""
def test_all_heros(self):
"""Slurm plugin:... | """Slurm plugin: _convert_to_timestamp should convert iso datetime to timestamp string correctly"""
ISO_FORMAT = '%Y-%m-%dT%H:%M:%S'
reference = datetime.utcnow().strftime(ISO_FORMAT)
converted = datetime.utcfromtimestamp(
SlurmInput._convert_to_timestamp(reference)).strftime(ISO_FOR... | identifier_body | |
test_plugin_slurm.py | # pylint: disable=missing-docstring
# this fails on Python 2.6 but Slurm environment is 2.7
import unittest
from datetime import datetime
from reporting.plugins.slurm import SlurmInput
class SlurmTestCase(unittest.TestCase):
"""Test cases for slurm module"""
def test_all_heros(self):
"""Slurm plugin:... |
self.assertEqual(qualified_count, 0)
def test_convert_to_timestamp(self):
"""Slurm plugin: _convert_to_timestamp should convert iso datetime to timestamp string correctly"""
ISO_FORMAT = '%Y-%m-%dT%H:%M:%S'
reference = datetime.utcnow().strftime(ISO_FORMAT)
converted = date... | if 'user' in message and len(message['user'].strip()):
qualified_count -= 1 | conditional_block |
test_plugin_slurm.py | # pylint: disable=missing-docstring
# this fails on Python 2.6 but Slurm environment is 2.7
import unittest
from datetime import datetime
from reporting.plugins.slurm import SlurmInput
class SlurmTestCase(unittest.TestCase):
"""Test cases for slurm module"""
def test_all_heros(self):
"""Slurm plugin:... | (self):
"""Slurm plugin: _read_data should only return job summary not steps, those do not have User value"""
data = SlurmInput._read_data('tests/sacct-with-start-end.txt')
qualified_count = len(data)
for message in data:
if 'user' in message and len(message['user'].strip()):... | test_read_data | identifier_name |
test_plugin_slurm.py | # pylint: disable=missing-docstring
# this fails on Python 2.6 but Slurm environment is 2.7
import unittest
from datetime import datetime
from reporting.plugins.slurm import SlurmInput
class SlurmTestCase(unittest.TestCase):
"""Test cases for slurm module"""
def test_all_heros(self):
"""Slurm plugin:... | self.assertTrue(isinstance(data['jobs'], list))
job = data['jobs'][0]
for required_key in ('job_id', 'partition', 'user', 'start', 'end', 'cpu_seconds'):
self.assertIn(required_key, job)
def test_read_data(self):
"""Slurm plugin: _read_data should only return job summary... | data = slurm_input.get_data()
self.assertIn('hostname', data)
self.assertIn('timestamp', data)
self.assertIn('jobs', data) | random_line_split |
caching-interceptor.ts | import { Injectable } from '@angular/core';
import {
HttpEvent, HttpHeaders, HttpRequest, HttpResponse,
HttpInterceptor, HttpHandler
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { startWith, tap } from 'rxjs/operators';
import { RequestCache } from '../request-cache.service';
impor... |
intercept(req: HttpRequest<any>, next: HttpHandler) {
// continue if not cachable.
if (!isCachable(req)) { return next.handle(req); }
const cachedResponse = this.cache.get(req);
// cache-then-refresh
if (req.headers.get('x-refresh')) {
const results$ = sendRequest(req, next, this.cache);
... | {} | identifier_body |
caching-interceptor.ts | import { Injectable } from '@angular/core';
import {
HttpEvent, HttpHeaders, HttpRequest, HttpResponse,
HttpInterceptor, HttpHandler
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { startWith, tap } from 'rxjs/operators';
import { RequestCache } from '../request-cache.service';
impor... |
return next.handle(noHeaderReq).pipe(
tap(event => {
// There may be other events besides the response.
if (event instanceof HttpResponse) {
cache.put(req, event); // Update the cache.
}
})
);
} | cache: RequestCache): Observable<HttpEvent<any>> {
// No headers allowed in npm search request
const noHeaderReq = req.clone({ headers: new HttpHeaders() }); | random_line_split |
caching-interceptor.ts | import { Injectable } from '@angular/core';
import {
HttpEvent, HttpHeaders, HttpRequest, HttpResponse,
HttpInterceptor, HttpHandler
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { startWith, tap } from 'rxjs/operators';
import { RequestCache } from '../request-cache.service';
impor... | (
req: HttpRequest<any>,
next: HttpHandler,
cache: RequestCache): Observable<HttpEvent<any>> {
// No headers allowed in npm search request
const noHeaderReq = req.clone({ headers: new HttpHeaders() });
return next.handle(noHeaderReq).pipe(
tap(event => {
// There may be other events besides the ... | sendRequest | identifier_name |
caching-interceptor.ts | import { Injectable } from '@angular/core';
import {
HttpEvent, HttpHeaders, HttpRequest, HttpResponse,
HttpInterceptor, HttpHandler
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { startWith, tap } from 'rxjs/operators';
import { RequestCache } from '../request-cache.service';
impor... |
// cache-or-fetch
return cachedResponse ?
of(cachedResponse) : sendRequest(req, next, this.cache);
}
}
/** Is this request cachable? */
function isCachable(req: HttpRequest<any>) {
// Only GET requests are cachable
return req.method === 'GET' &&
// Only npm package search is cachable in this ... | {
const results$ = sendRequest(req, next, this.cache);
return cachedResponse ?
results$.pipe( startWith(cachedResponse) ) :
results$;
} | conditional_block |
regex.rs | // Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... |
}
}
impl reflection::PredicateReflection for RegexMatchesPredicate {
fn parameters<'a>(&'a self) -> Box<dyn Iterator<Item = reflection::Parameter<'a>> + 'a> {
let params = vec![reflection::Parameter::new("count", &self.count)];
Box::new(params.into_iter())
}
}
impl fmt::Display for RegexM... | {
None
} | conditional_block |
regex.rs | // Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... | (&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let palette = crate::Palette::current();
write!(
f,
"{}.{}({})",
palette.var.paint("var"),
palette.description.paint("is_match"),
palette.expected.paint(&self.re),
)
}
}
/// Crea... | fmt | identifier_name |
regex.rs | // Copyright (c) 2018 The predicates-rs Project Developers.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distr... | use crate::utils;
use crate::Predicate;
/// An error that occurred during parsing or compiling a regular expression.
pub type RegexError = regex::Error;
/// Predicate that uses regex matching
///
/// This is created by the `predicate::str::is_match`.
#[derive(Debug, Clone)]
pub struct RegexPredicate {
re: regex::... | // except according to those terms.
use std::fmt;
use crate::reflection; | random_line_split |
interfaces.py | from zope import component
from zope import interface
from zope.interface.interfaces import IObjectEvent
from zope import location
from sparc.configuration.container import ISparcPyContainerConfiguredApplication
#EVENTS
class ISnippetAvailableForSecretsSniffEvent(IObjectEvent):
"""An object providing ISnippet is r... |
def __hash__():
"""Uniquely identifies the locatable secret among other secrets"""
class IWhitelistInfo(interface.Interface):
"""Object whitelist information"""
def __str__():
"""Detailed information on how object was whitelisted"""
class IWhitelist(interface.Interface):
"""Ident... | """String details of the secret and/or how it was found""" | identifier_body |
interfaces.py | from zope import component
from zope import interface
from zope.interface.interfaces import IObjectEvent
from zope import location
from sparc.configuration.container import ISparcPyContainerConfiguredApplication
#EVENTS
class ISnippetAvailableForSecretsSniffEvent(IObjectEvent):
"""An object providing ISnippet is r... | snippet_lines_coverage = \
interface.Attribute("Number of lines to include in each snippet "+
"if available, 0 indicates all remaining lines.")
class IByteMellonFile(IMellonFile):
"""A byte (binary) file to be processed by the application"""
read_size = interface.Attribu... | interface.Attribute("Number of lines to jump after each snippet, 0 "+
"indicates entire data.") | random_line_split |
interfaces.py | from zope import component
from zope import interface
from zope.interface.interfaces import IObjectEvent
from zope import location
from sparc.configuration.container import ISparcPyContainerConfiguredApplication
#EVENTS
class ISnippetAvailableForSecretsSniffEvent(IObjectEvent):
"""An object providing ISnippet is r... | ():
"""String locatable identity of file"""
class IUnicodeMellonFile(IMellonFile):
"""A Unicode (text) file to be processed by the application"""
snippet_lines_increment = \
interface.Attribute("Number of lines to jump after each snippet, 0 "+
"indicates entire data.... | __str__ | identifier_name |
packed-struct-vec.rs | // Copyright 2013-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 http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-android: FIXME(#9116) Bus error
use std::mem;
#[repr(packed)]
#[derive(Copy, PartialEq, Debug)]
struct Foo {
bar: u8,
baz: u64
}
pub ... | random_line_split | |
packed-struct-vec.rs | // Copyright 2013-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-MI... | () {
let foos = [Foo { bar: 1, baz: 2 }; 10];
assert_eq!(mem::size_of::<[Foo; 10]>(), 90);
for i in 0u..10 {
assert_eq!(foos[i], Foo { bar: 1, baz: 2});
}
for &foo in &foos {
assert_eq!(foo, Foo { bar: 1, baz: 2 });
}
}
| main | identifier_name |
table_view_layout_3.js | function tv_layout3() | ;
module.exports = tv_layout3; | {
var win = Titanium.UI.createWindow();
win.backgroundImage='/images/chip.jpg';
var data =[];
var section = Ti.UI.createTableViewSection();
data.push(section);
// ROW 1
var row1 = Ti.UI.createTableViewRow();
row1.backgroundColor = '#670000';
row1.selectedBackgroundColor = '#670000';
row1.height = 60;
r... | identifier_body |
table_view_layout_3.js | function | () {
var win = Titanium.UI.createWindow();
win.backgroundImage='/images/chip.jpg';
var data =[];
var section = Ti.UI.createTableViewSection();
data.push(section);
// ROW 1
var row1 = Ti.UI.createTableViewRow();
row1.backgroundColor = '#670000';
row1.selectedBackgroundColor = '#670000';
row1.height = 60;... | tv_layout3 | identifier_name |
table_view_layout_3.js | function tv_layout3() {
var win = Titanium.UI.createWindow();
win.backgroundImage='/images/chip.jpg';
var data =[];
var section = Ti.UI.createTableViewSection();
data.push(section);
// ROW 1
var row1 = Ti.UI.createTableViewRow();
row1.backgroundColor = '#670000';
row1.selectedBackgroundColor = '#670000';... |
});
row1.add(delete1);
section.add(row1);
// ROW 2
var row2 = Ti.UI.createTableViewRow();
row2.backgroundColor = '#670000';
row2.selectedBackgroundColor = '#670000';
row2.height = 60;
row2.addEventListener('click', function(e) {
Ti.API.log(e.source+" click at ("+e.x+","+e.y+")");
});
var item2 = Ti.U... | add1.show();
cost1.animate({left:10, duration:100});
item1.animate({left:10, duration:100}); | random_line_split |
mod.rs | // Copyright 2017 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 | use core::unicode::property::Pattern_White_Space;
use rustc::ty;
use syntax_pos::Span;
pub mod borrowck_errors;
pub mod elaborate_drops;
pub mod def_use;
pub mod patch;
mod alignment;
mod graphviz;
pub(crate) mod pretty;
pub mod liveness;
pub mod collect_writes;
pub use self::alignment::is_disaligned;
pub use self::... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
| random_line_split |
mod.rs | // Copyright 2017 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 ... | <'cx, 'gcx, 'tcx>(
tcx: ty::TyCtxt<'cx, 'gcx, 'tcx>,
binding_span: Span,
) -> Option<(String)> {
let hi_src = tcx.sess.source_map().span_to_snippet(binding_span).unwrap();
if hi_src.starts_with("ref")
&& hi_src["ref".len()..].starts_with(Pattern_White_Space)
{
let replacement = forma... | suggest_ref_mut | identifier_name |
mod.rs | // Copyright 2017 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 ... |
}
| {
None
} | conditional_block |
mod.rs | // Copyright 2017 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 hi_src = tcx.sess.source_map().span_to_snippet(binding_span).unwrap();
if hi_src.starts_with("ref")
&& hi_src["ref".len()..].starts_with(Pattern_White_Space)
{
let replacement = format!("ref mut{}", &hi_src["ref".len()..]);
Some(replacement)
} else {
None
}
} | identifier_body | |
aggregation.py | '''
TODO:
optimize adds, multiplies, 'or' and 'and' as they can accept more than two values
validate type info on specific functions
'''
from .matching import AstHandler, ParseError, DateTimeFunc
class AggregationParser(AstHandler):
FUNC_TO_ARGS = {'concat': '+', # more than 1
'strcasecmp': 2... | return '${0}.{1}'.format(self.handle(node.value), node.attr).replace('$$', '$')
def handle_UnaryOp(self, op):
return {self.handle(op.op): self.handle(op.operand)}
def handle_IfExp(self, op):
return {'$cond': [self.handle(op.test),
self.handle(op.body),
... | def handle_Attribute(self, node): | random_line_split |
aggregation.py | '''
TODO:
optimize adds, multiplies, 'or' and 'and' as they can accept more than two values
validate type info on specific functions
'''
from .matching import AstHandler, ParseError, DateTimeFunc
class AggregationParser(AstHandler):
FUNC_TO_ARGS = {'concat': '+', # more than 1
'strcasecmp': 2... |
if node.func.id not in self.GROUP_FUNCTIONS:
raise ParseError('Unsupported group function: {0}'.format(node.func.id),
col_offset=node.col_offset,
options=self.GROUP_FUNCTIONS)
return {'$' + node.func.id: AggregationParser().handle(no... | raise ParseError('The {0} group aggregation function accepts one argument'.format(node.func.id),
col_offset=node.col_offset) | conditional_block |
aggregation.py | '''
TODO:
optimize adds, multiplies, 'or' and 'and' as they can accept more than two values
validate type info on specific functions
'''
from .matching import AstHandler, ParseError, DateTimeFunc
class AggregationParser(AstHandler):
FUNC_TO_ARGS = {'concat': '+', # more than 1
'strcasecmp': 2... | (self, node):
return '$eq'
def handle_NotEq(self, node):
return '$ne'
def handle_Add(self, node):
return '$add'
def handle_Sub(self, node):
return '$subtract'
def handle_Mod(self, node):
return '$mod'
def handle_Mult(self, node):
return '$... | handle_Eq | identifier_name |
aggregation.py | '''
TODO:
optimize adds, multiplies, 'or' and 'and' as they can accept more than two values
validate type info on specific functions
'''
from .matching import AstHandler, ParseError, DateTimeFunc
class AggregationParser(AstHandler):
FUNC_TO_ARGS = {'concat': '+', # more than 1
'strcasecmp': 2... |
def handle_Mod(self, node):
return '$mod'
def handle_Mult(self, node):
return '$multiply'
def handle_Div(self, node):
return '$divide'
class AggregationGroupParser(AstHandler):
GROUP_FUNCTIONS = ['addToSet', 'push', 'first', 'last',
'max', 'min', 'avg'... | return '$subtract' | identifier_body |
main.py | from couchpotato.core.downloaders.base import Downloader, StatusList
from couchpotato.core.helpers.encoding import tryUrlencode, ss
from couchpotato.core.helpers.variable import cleanHost, mergeDicts
from couchpotato.core.logger import CPLog
from couchpotato.environment import Env
from datetime import timedelta
from ur... |
else:
sab_data = self.call(req_params)
except URLError:
log.error('Failed sending release, probably wrong HOST: %s', traceback.format_exc(0))
return False
except:
log.error('Failed sending release, use API key, NOT the NZB key: %s', traceb... | sab_data = self.call(req_params, params = {'nzbfile': (ss(nzb_filename), filedata)}, multipart = True) | conditional_block |
main.py | from couchpotato.core.downloaders.base import Downloader, StatusList
from couchpotato.core.helpers.encoding import tryUrlencode, ss
from couchpotato.core.helpers.variable import cleanHost, mergeDicts
from couchpotato.core.logger import CPLog
from couchpotato.environment import Env
from datetime import timedelta
from ur... | (self, item):
log.info('%s failed downloading, deleting...', item['name'])
try:
self.call({
'mode': 'history',
'name': 'delete',
'del_files': '1',
'value': item['id']
}, use_json = False)
except:
... | removeFailed | identifier_name |
main.py | from couchpotato.core.downloaders.base import Downloader, StatusList
from couchpotato.core.helpers.encoding import tryUrlencode, ss
from couchpotato.core.helpers.variable import cleanHost, mergeDicts
from couchpotato.core.logger import CPLog
from couchpotato.environment import Env
from datetime import timedelta
from ur... |
# Get old releases
for item in history.get('slots', []):
status = 'busy'
if item['status'] == 'Failed' or (item['status'] == 'Completed' and item['fail_message'].strip()):
status = 'failed'
elif item['status'] == 'Completed':
status =... | 'id': item['nzo_id'],
'name': item['filename'],
'original_status': item['status'],
'timeleft': item['timeleft'] if not queue['paused'] else -1,
}) | random_line_split |
main.py | from couchpotato.core.downloaders.base import Downloader, StatusList
from couchpotato.core.helpers.encoding import tryUrlencode, ss
from couchpotato.core.helpers.variable import cleanHost, mergeDicts
from couchpotato.core.logger import CPLog
from couchpotato.environment import Env
from datetime import timedelta
from ur... | url = cleanHost(self.conf('host')) + 'api?' + tryUrlencode(mergeDicts(request_params, {
'apikey': self.conf('api_key'),
'output': 'json'
}))
data = self.urlopen(url, timeout = 60, show_error = False, headers = {'User-Agent': Env.getIdentifier()}, **kwargs)
if use_json:
... | identifier_body | |
compat.py | # -*- test-case-name: twisted.test.test_compat -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Compatibility module to provide backwards compatibility for useful Python
features.
This is mainly for use of internal Twisted code. We encourage you to use
the latest version of Python di... |
def __gt__(self, other):
c = self.__cmp__(other)
if c is NotImplemented:
return c
return c > 0
def __ge__(self, other):
c = self.__cmp__(other)
if c is NotImplemented:
return c
return c >= 0
klass.__lt__ = __lt__
klass.__gt__ ... | c = self.__cmp__(other)
if c is NotImplemented:
return c
return c <= 0 | identifier_body |
compat.py | # -*- test-case-name: twisted.test.test_compat -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Compatibility module to provide backwards compatibility for useful Python
features.
This is mainly for use of internal Twisted code. We encourage you to use
the latest version of Python di... | (originalBytes):
for i in range(len(originalBytes)):
yield originalBytes[i:i+1]
def intToBytes(i):
return ("%d" % i).encode("ascii")
# Ideally we would use memoryview, but it has a number of differences from
# the Python 2 buffer() that make that impractical
# (http://bug... | iterbytes | identifier_name |
compat.py | # -*- test-case-name: twisted.test.test_compat -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Compatibility module to provide backwards compatibility for useful Python
features.
This is mainly for use of internal Twisted code. We encourage you to use
the latest version of Python di... |
try:
socket.AF_INET6
except AttributeError:
socket.AF_INET6 = 'AF_INET6'
try:
socket.inet_pton(socket.AF_INET6, "::")
except (AttributeError, NameError, socket.error):
socket.inet_pton = inet_pton
socket.inet_ntop = inet_ntop
adict = dict
if _PY3:
# These are actually useless in Python 2... | raise socket.error(97, 'Address family not supported by protocol') | conditional_block |
compat.py | # -*- test-case-name: twisted.test.test_compat -*-
#
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Compatibility module to provide backwards compatibility for useful Python
features.
This is mainly for use of internal Twisted code. We encourage you to use
the latest version of Python di... | given, the copy will only be of that length.
@param object: C{bytes} to be copied.
@param offset: C{int}, starting index of copy.
@param size: Optional, if an C{int} is given limit the length of copy
to this size.
"""
if size is None:
return obj... | If an offset is given, the copy starts at that offset. If a size is | random_line_split |
setup.py | """setuptools based packaging and installation module.
Defines the project properties, as well as a special command to build a
standalone executable, by using PyInstaller.
Run with --help to see available options.
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a co... | (self):
"""Run command."""
sep = ';' if sys.platform == 'win32' else ':'
command = ' '.join([
'pyinstaller',
' --onefile',
' --add-data amtt/ui/icon64x64.png{sep}amtt/ui'.format(sep=sep),
' --add-data amtt/ui/icon64x64.gif{sep}amtt/ui'.format(se... | run | identifier_name |
setup.py | """setuptools based packaging and installation module.
Defines the project properties, as well as a special command to build a
standalone executable, by using PyInstaller.
Run with --help to see available options.
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a co... |
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='amtt',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# ht... | """
Custom command to build standalone executable using PyInstaller.
Invoke by executing:
python setup.py build_standalone
"""
description = 'build standalone executable with PyInstaller'
user_options = []
def initialize_options(self):
"""Set default values for user options.""... | identifier_body |
setup.py | """setuptools based packaging and installation module.
| """
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
import sys
import distutils
import subprocess
from amtt.version import __version__ as amtt_version
here = path.abspath(path.dirname(__file__))
class... | Defines the project properties, as well as a special command to build a
standalone executable, by using PyInstaller.
Run with --help to see available options. | random_line_split |
main.py | # My files
from handlers import MainPage
from handlers import WelcomePage
from handlers import SignUpPage
from handlers import SignIn
from handlers import SignOut
from handlers import NewPost
from handlers import EditPost
from handlers import DeletePost
from handlers import SinglePost
from handlers import LikePost
from... | import webapp2
app = webapp2.WSGIApplication([
('/', MainPage),
('/signup', SignUpPage),
('/welcome', WelcomePage),
('/post/([0-9]+)', SinglePost),
('/new-post', NewPost),
('/edit-post/([0-9]+)', EditPost),
('/delete-post', DeletePost),
('/like-post', LikePost),
('/dislike-post', Di... | from handlers import EditComment
from handlers import DeleteComment
| random_line_split |
new-note.directive.js | (function(){
angular.module('app')
.directive('newNote', function()
{
return {
templateUrl: "new-note.html",
scope: {
notes: '='
},
controller: NewNoteController
};
function | ($scope, NoteService)
{
$scope.blankNote = null;
$scope.createNote = createNote;
$scope.saveNote = saveNote;
function createNote()
{
$scope.blankNote = NoteService.createBlankNote();
}
function saveNote()
{
if ($scope.blankNote && ($scope.blankNote.title.length > 0 || $sc... | NewNoteController | identifier_name |
new-note.directive.js | (function(){
angular.module('app')
.directive('newNote', function()
{
return {
templateUrl: "new-note.html",
scope: {
notes: '='
},
controller: NewNoteController
};
function NewNoteController($scope, NoteService)
{
$scope.blankNote = null;
$scope.createNote = createNote;
... | });
}
$scope.blankNote = null;
}
}
})
;
})(); | {
NoteService.saveNote($scope.blankNote).then(function(savedNote)
{
$scope.notes.unshift(savedNote); | random_line_split |
new-note.directive.js | (function(){
angular.module('app')
.directive('newNote', function()
{
return {
templateUrl: "new-note.html",
scope: {
notes: '='
},
controller: NewNoteController
};
function NewNoteController($scope, NoteService)
{
$scope.blankNote = null;
$scope.createNote = createNote;
... |
$scope.blankNote = null;
}
}
})
;
})();
| {
NoteService.saveNote($scope.blankNote).then(function(savedNote)
{
$scope.notes.unshift(savedNote);
});
} | conditional_block |
new-note.directive.js | (function(){
angular.module('app')
.directive('newNote', function()
{
return {
templateUrl: "new-note.html",
scope: {
notes: '='
},
controller: NewNoteController
};
function NewNoteController($scope, NoteService)
|
})
;
})();
| {
$scope.blankNote = null;
$scope.createNote = createNote;
$scope.saveNote = saveNote;
function createNote()
{
$scope.blankNote = NoteService.createBlankNote();
}
function saveNote()
{
if ($scope.blankNote && ($scope.blankNote.title.length > 0 || $scope.blankNote.content.len... | identifier_body |
forceListMetadata.ts | /*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
CliCommandExecution,
CliCommandExecutor,
Command,
CommandOutput,
Sfdx... | const startTime = process.hrtime();
const execution = new CliCommandExecutor(this.build({}), {
cwd: getRootWorkspacePath()
}).execute();
execution.processExitSubject.subscribe(() => {
this.logMetric(execution.command.logName, startTime);
});
return execution;
}
}
export async fun... | public execute(): CliCommandExecution { | random_line_split |
forceListMetadata.ts | /*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
CliCommandExecution,
CliCommandExecutor,
Command,
CommandOutput,
Sfdx... |
return builder.build();
}
public execute(): CliCommandExecution {
const startTime = process.hrtime();
const execution = new CliCommandExecutor(this.build({}), {
cwd: getRootWorkspacePath()
}).execute();
execution.processExitSubject.subscribe(() => {
this.logMetric(execution.comma... | {
builder.withFlag('--folder', this.folder);
} | conditional_block |
forceListMetadata.ts | /*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
CliCommandExecution,
CliCommandExecutor,
Command,
CommandOutput,
Sfdx... | (): CliCommandExecution {
const startTime = process.hrtime();
const execution = new CliCommandExecutor(this.build({}), {
cwd: getRootWorkspacePath()
}).execute();
execution.processExitSubject.subscribe(() => {
this.logMetric(execution.command.logName, startTime);
});
return executio... | execute | identifier_name |
forceListMetadata.ts | /*
* Copyright (c) 2019, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import {
CliCommandExecution,
CliCommandExecutor,
Command,
CommandOutput,
Sfdx... | {
const forceListMetadataExecutor = new ForceListMetadataExecutor(
metadataType,
defaultUsernameOrAlias,
folder
);
const execution = forceListMetadataExecutor.execute();
const cmdOutput = new CommandOutput();
const result = await cmdOutput.getCmdResult(execution);
fs.writeFileSync(outputPath, re... | identifier_body | |
conf.py | # -*- coding: utf-8 -*-
#
# M2Crypto documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 20 11:15:12 2017.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | # html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The... |
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes. | random_line_split |
gcs_storage.py | import os
import yaml
from google.cloud import storage
from google.oauth2 import service_account
from .storage import Storage
class GcsStorage(Storage):
def __init__(self, bucket, path, project=None, json_path=None):
if bucket is None:
raise ValueError('Bucket must be supplied to GCS storage')
... | (self, key):
b = self.bucket.get_blob(self.path)
contents = '{}'
if b:
contents = b.download_as_string()
else:
b = self.bucket.blob(self.path)
props = yaml.safe_load(contents)
if props is None:
props = {}
return props.get(key)... | load | identifier_name |
gcs_storage.py | import os
import yaml
from google.cloud import storage
from google.oauth2 import service_account
from .storage import Storage
class GcsStorage(Storage):
def __init__(self, bucket, path, project=None, json_path=None):
if bucket is None:
raise ValueError('Bucket must be supplied to GCS storage')
... | self.bucket = self.client.get_bucket(bucket)
super().__init__()
def store(self, key, val):
b = self.bucket.get_blob(self.path)
contents = '{}'
if b:
contents = b.download_as_string()
else:
b = self.bucket.blob(self.path)
props = yaml... |
if self.client.lookup_bucket(bucket) is None:
self.client.create_bucket(bucket)
| random_line_split |
gcs_storage.py | import os
import yaml
from google.cloud import storage
from google.oauth2 import service_account
from .storage import Storage
class GcsStorage(Storage):
def __init__(self, bucket, path, project=None, json_path=None):
if bucket is None:
raise ValueError('Bucket must be supplied to GCS storage')
... |
def load(self, key):
b = self.bucket.get_blob(self.path)
contents = '{}'
if b:
contents = b.download_as_string()
else:
b = self.bucket.blob(self.path)
props = yaml.safe_load(contents)
if props is None:
props = {}
return ... | b = self.bucket.get_blob(self.path)
contents = '{}'
if b:
contents = b.download_as_string()
else:
b = self.bucket.blob(self.path)
props = yaml.safe_load(contents)
if props is None:
props = {}
props[key] = val
b.upload_from_str... | identifier_body |
gcs_storage.py | import os
import yaml
from google.cloud import storage
from google.oauth2 import service_account
from .storage import Storage
class GcsStorage(Storage):
def __init__(self, bucket, path, project=None, json_path=None):
if bucket is None:
raise ValueError('Bucket must be supplied to GCS storage')
... |
return props.get(key)
| props = {} | conditional_block |
parallelGAModelP_AVR.py | """
This GA code creates the gaModel with a circular island model
"""
from operator import attrgetter
# import sys
from deap import base, creator, tools
import numpy
from csep.loglikelihood import calcLogLikelihood as loglikelihood
from models.mathUtil import calcNumberBins
import models.model
import random
import arr... |
for mutant in offspring:
if random.random() < MUTPB:
toolbox.mutate(mutant)
del mutant.fitness.values
# Evaluate the individuals with an invalid fitness
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
for ind, fit... | toolbox.mate(child1, child2)
del child1.fitness.values
del child2.fitness.values | conditional_block |
parallelGAModelP_AVR.py | """
This GA code creates the gaModel with a circular island model
"""
from operator import attrgetter
# import sys
from deap import base, creator, tools
import numpy
from csep.loglikelihood import calcLogLikelihood as loglikelihood
from models.mathUtil import calcNumberBins
import models.model
import random
import arr... | #calculating the number of individuals of the populations based on the number of executions
y=int(n_aval/NGEN)
x=n_aval - y*NGEN
n= x + y
pop = toolbox.population(n)
logbook = tools.Logbook()
logbook.header = "min","avg","max","std"
stats = tools.Statistics(key=lambda ind: ind.fitness.values)
stats.register(... | random_line_split | |
parallelGAModelP_AVR.py | """
This GA code creates the gaModel with a circular island model
"""
from operator import attrgetter
# import sys
from deap import base, creator, tools
import numpy
from csep.loglikelihood import calcLogLikelihood as loglikelihood
from models.mathUtil import calcNumberBins
import models.model
import random
import arr... | (individual, modelOmega, mean):
"""
This function calculates the loglikelihood of a model (individual) with
the real data from the prior X years (modelOmega, with length X).
It selects the smallest loglikelihood value.
"""
logValue = float('Infinity')
genomeModel=type(modelOmega[0])
for i in range(len(modelOm... | evaluationFunction | identifier_name |
parallelGAModelP_AVR.py | """
This GA code creates the gaModel with a circular island model
"""
from operator import attrgetter
# import sys
from deap import base, creator, tools
import numpy
from csep.loglikelihood import calcLogLikelihood as loglikelihood
from models.mathUtil import calcNumberBins
import models.model
import random
import arr... |
def gaModel(NGEN,CXPB,MUTPB,modelOmega,year,region, mean, FREQ = 10, n_aval=50000):
"""
The main function. It evolves models, namely modelLamba or individual.
This applies the gaModel with a circular island model
It uses two parallel system: 1, simple, that splits the ga evolution between cores
and 2, that di... | """
This function calculates the loglikelihood of a model (individual) with
the real data from the prior X years (modelOmega, with length X).
It selects the smallest loglikelihood value.
"""
logValue = float('Infinity')
genomeModel=type(modelOmega[0])
for i in range(len(modelOmega)):
genomeModel.bins=list(in... | identifier_body |
simple_tomo_test.py | # Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | run_protected_plugin_runner(options)
if __name__ == "__main__":
unittest.main() | "process_file": tu.get_test_data_path('simple_recon_test_process.nxs'),
"out_path": tempfile.mkdtemp()
} | random_line_split |
simple_tomo_test.py | # Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | unittest.main() | conditional_block | |
simple_tomo_test.py | # Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
if __name__ == "__main__":
unittest.main()
| options = {
"transport": "hdf5",
"process_names": "CPU0",
"data_file": tu.get_test_data_path('24737.nxs'),
"process_file": tu.get_test_data_path('simple_recon_test_process.nxs'),
"out_path": tempfile.mkdtemp()
}
run_protected_plugin_runner(... | identifier_body |
simple_tomo_test.py | # Copyright 2014 Diamond Light Source Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... | (unittest.TestCase):
def test_process(self):
options = {
"transport": "hdf5",
"process_names": "CPU0",
"data_file": tu.get_test_data_path('24737.nxs'),
"process_file": tu.get_test_data_path('simple_recon_test_process.nxs'),
"out_path": tempfile.mk... | SimpleTomoTest | identifier_name |
block_status.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | {
/// Part of the blockchain.
InChain,
/// Queued for import.
Queued,
/// Known as bad.
Bad,
/// Unknown.
Unknown,
}
impl From<QueueStatus> for BlockStatus {
fn from(status: QueueStatus) -> Self {
match status {
QueueStatus::Queued => BlockStatus::Queued,
QueueStatus::Bad => BlockStatus::Bad,
Queu... | BlockStatus | identifier_name |
block_status.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or | // but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
//!... | // (at your option) any later version.
// Parity is distributed in the hope that it will be useful, | random_line_split |
waveBlock.ts | import { NodeMaterialBlock } from '../nodeMaterialBlock';
import { NodeMaterialBlockConnectionPointTypes } from '../Enums/nodeMaterialBlockConnectionPointTypes';
import { NodeMaterialBuildState } from '../nodeMaterialBuildState';
import { NodeMaterialConnectionPoint } from '../nodeMaterialBlockConnectionPoint';
imp... | (): NodeMaterialConnectionPoint {
return this._inputs[0];
}
/**
* Gets the output component
*/
public get output(): NodeMaterialConnectionPoint {
return this._outputs[0];
}
protected _buildBlock(state: NodeMaterialBuildState) {
super._buildBlock(state)... | input | identifier_name |
waveBlock.ts | import { NodeMaterialBlock } from '../nodeMaterialBlock';
import { NodeMaterialBlockConnectionPointTypes } from '../Enums/nodeMaterialBlockConnectionPointTypes';
import { NodeMaterialBuildState } from '../nodeMaterialBuildState';
import { NodeMaterialConnectionPoint } from '../nodeMaterialBlockConnectionPoint';
imp... |
protected _buildBlock(state: NodeMaterialBuildState) {
super._buildBlock(state);
let output = this._outputs[0];
switch (this.kind) {
case WaveBlockKind.SawTooth: {
state.compilationString += this._declareOutput(output, state) + ` = ${this.input.associ... | {
return this._outputs[0];
} | identifier_body |
waveBlock.ts | import { NodeMaterialBlock } from '../nodeMaterialBlock';
import { NodeMaterialBlockConnectionPointTypes } from '../Enums/nodeMaterialBlockConnectionPointTypes';
import { NodeMaterialBuildState } from '../nodeMaterialBuildState';
import { NodeMaterialConnectionPoint } from '../nodeMaterialBlockConnectionPoint';
imp... | */
export class WaveBlock extends NodeMaterialBlock {
/**
* Gets or sets the kibnd of wave to be applied by the block
*/
public kind = WaveBlockKind.SawTooth;
/**
* Creates a new WaveBlock
* @param name defines the block name
*/
public constructor(name: string) {
... | }
/**
* Block used to apply wave operation to floats
| random_line_split |
Site.ts | /// <reference path="jquery.d.ts" />
/// <reference path="knockout.d.ts" />
class ServerDevice {
Id: Number;
Name: string;
Description: string;
DisplayOrder: Number;
IsReadOnly: boolean;
}
class Device {
Id: KnockoutObservable<Number> = ko.observable(0);
Name: KnockoutObservable<string> = ko.observable(... | public AsServerDevice(): ServerDevice {
var sd = new ServerDevice();
sd.Id = this.Id();
sd.Name = this.Name();
sd.Description = this.Description();
sd.DisplayOrder = this.DisplayOrder();
sd.IsReadOnly = this.IsReadOnly();
return sd;
}
}
class DevicesViewModel {
private _apiUrl: string;
pu... | if (sdevice != undefined) {
this.Id(sdevice.Id);
this.Name(sdevice.Name);
this.Description(sdevice.Description);
this.DisplayOrder(sdevice.DisplayOrder);
this.IsReadOnly(sdevice.IsReadOnly);
}
}
| identifier_body |
Site.ts | /// <reference path="jquery.d.ts" />
/// <reference path="knockout.d.ts" />
class ServerDevice {
Id: Number;
Name: string;
Description: string;
DisplayOrder: Number;
IsReadOnly: boolean;
}
class Device {
Id: KnockoutObservable<Number> = ko.observable(0);
Name: KnockoutObservable<string> = ko.observable(... | }
});
}
public AddNewDevice() {
this.CurrentDevice(new Device());
}
private validateDevice(dev: Device): boolean {
var cd = this.CurrentDevice();
var errorMessage: string = "";
if (cd.Name().length <= 0) {
errorMessage = "Name is required.\n";
}
if (... | me.Devices.push(new Device(device));
}
| conditional_block |
Site.ts | /// <reference path="jquery.d.ts" />
/// <reference path="knockout.d.ts" />
class ServerDevice {
Id: Number;
Name: string;
Description: string;
DisplayOrder: Number;
IsReadOnly: boolean;
}
class Device {
Id: KnockoutObservable<Number> = ko.observable(0);
Name: KnockoutObservable<string> = ko.observable(... | data: JSON.stringify(cd.AsServerDevice()),
dataType: "json",
success: function (id) {
me.loadDevice(id);
me.CurrentDevice(undefined);
}
});
}
}
public EditDevice(dev: Device) {
this.CurrentDevice(dev);
}
public UpdateDevice() {
... | type: 'post',
contentType: "application/json; charset=utf-8", | random_line_split |
Site.ts | /// <reference path="jquery.d.ts" />
/// <reference path="knockout.d.ts" />
class ServerDevice {
Id: Number;
Name: string;
Description: string;
DisplayOrder: Number;
IsReadOnly: boolean;
}
class Device {
Id: KnockoutObservable<Number> = ko.observable(0);
Name: KnockoutObservable<string> = ko.observable(... | {
this._apiUrl = "/api/Devices";
}
private _devicesReceived(data: ServerDevice[]) {
for (var i = 0; i < data.length; i++) {
this.Devices.push(new Device(data[i]));
}
}
public loadDevices() {
var me = this;
$.ajax({
url: me._apiUrl,
type: 'get',
contentType: "application/json; charset=utf-8"... | nstructor() | identifier_name |
config.rs | use std::collections::{HashMap, HashSet, BTreeMap};
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use crate::types::*;
use serde_json;
use pombase_rc_string::RcString;
// configuration for extension display names and for the "Target of" section
#[derive(Deserialize, Clone, Debug)]
pub struct Exten... | (&self) -> Option<ConfigOrganism> {
if let Some(load_organism_taxonid) = self.load_organism_taxonid {
let org = self.organism_by_taxonid(load_organism_taxonid);
if org.is_none() {
panic!("can't find configuration for load_organism_taxonid: {}",
load... | load_organism | identifier_name |
config.rs | use std::collections::{HashMap, HashSet, BTreeMap};
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use crate::types::*;
use serde_json;
use pombase_rc_string::RcString;
// configuration for extension display names and for the "Target of" section
#[derive(Deserialize, Clone, Debug)]
pub struct Exten... |
#[derive(Deserialize, Clone, Debug)]
pub struct MacromolecularComplexesConfig {
pub parent_complex_termid: RcString,
pub excluded_terms: HashSet<RcString>,
}
#[derive(Deserialize, Clone, Debug)]
pub struct RNAcentralConfig {
// SO termids of RNA features to export
pub export_so_ids: HashSet<RcString>,... | pub link: Option<RcString>,
}
pub type DatabaseName = RcString;
pub type DatabaseAliases = HashMap<DatabaseName, DatabaseName>; | random_line_split |
config.rs | use std::collections::{HashMap, HashSet, BTreeMap};
use std::io::BufReader;
use std::io::BufRead;
use std::fs::File;
use crate::types::*;
use serde_json;
use pombase_rc_string::RcString;
// configuration for extension display names and for the "Target of" section
#[derive(Deserialize, Clone, Debug)]
pub struct Exten... |
} else {
CvConfig {
feature_type: "gene".into(),
..empty_cv_config
}
}
}
}
pub fn organism_by_taxonid(&self, lookup_taxonid: u32) -> Option<ConfigOrganism> {
for org in &self.organisms {
... | {
CvConfig {
feature_type: "genotype".into(),
..empty_cv_config
}
} | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from shoop.api.factories import viewset_factory
from shoop.core.api.orders i... | """
:param router: Router
:type router: rest_framework.routers.DefaultRouter
"""
router.register("shoop/category", viewset_factory(Category))
router.register("shoop/contact", viewset_factory(Contact))
router.register("shoop/order", OrderViewSet)
router.register("shoop/product", ProductViewSe... | identifier_body | |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from shoop.api.factories import viewset_factory
from shoop.core.api.orders i... | from shoop.core.models.categories import Category
def populate_core_api(router):
"""
:param router: Router
:type router: rest_framework.routers.DefaultRouter
"""
router.register("shoop/category", viewset_factory(Category))
router.register("shoop/contact", viewset_factory(Contact))
router.r... | from shoop.core.models import Contact, Shop | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
# This file is part of Shoop.
#
# Copyright (c) 2012-2015, Shoop Ltd. All rights reserved.
#
# This source code is licensed under the AGPLv3 license found in the
# LICENSE file in the root directory of this source tree.
from shoop.api.factories import viewset_factory
from shoop.core.api.orders i... | (router):
"""
:param router: Router
:type router: rest_framework.routers.DefaultRouter
"""
router.register("shoop/category", viewset_factory(Category))
router.register("shoop/contact", viewset_factory(Contact))
router.register("shoop/order", OrderViewSet)
router.register("shoop/product",... | populate_core_api | identifier_name |
forbidden-name.directive.ts | import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn |
@Directive({
selector: '[forbiddenName]',
providers: [{provide: NG_VALIDATORS, useExisting: ForbiddenValidatorDirective, multi: true}]
})
export class ForbiddenValidatorDirective implements Validator, OnChanges {
@Input() public forbiddenName: string;
private valFn = Validators.nullValidator;
public ngOnC... | {
return (control: AbstractControl): {[key: string]: any} => {
const name = control.value;
const no = nameRe.test(name);
return no ? {forbiddenName: {name}} : null;
};
} | identifier_body |
forbidden-name.directive.ts | import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const... | (changes: SimpleChanges): void {
// const change = changes['forbiddenName'];
// if (change) {
// const val: string | RegExp = change.currentValue;
// const re = val instanceof RegExp ? val : new RegExp(val, 'i');
// this.valFn = forbiddenNameValidator(re);
// } else {
// this.valFn =... | ngOnChanges | identifier_name |
forbidden-name.directive.ts | import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';
export function forbiddenNameValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): {[key: string]: any} => {
const... | // const change = changes['forbiddenName'];
// if (change) {
// const val: string | RegExp = change.currentValue;
// const re = val instanceof RegExp ? val : new RegExp(val, 'i');
// this.valFn = forbiddenNameValidator(re);
// } else {
// this.valFn = Validators.nullValidator;
//... | public ngOnChanges(changes: SimpleChanges): void { | random_line_split |
server.ts | // the polyfills must be the first thing imported in node.js
import 'angular2-universal-polyfills';
import * as path from 'path'; | const mongoose = require('mongoose');
require('dotenv').config();
// Angular 2
import { enableProdMode } from '@angular/core';
// Angular 2 Universal
import { createEngine } from 'angular2-express-engine';
// App
import { config } from './server/config';
var cache = require('memory-cache');
import { MainModule } fro... | import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser'; | random_line_split |
server.ts | // the polyfills must be the first thing imported in node.js
import 'angular2-universal-polyfills';
import * as path from 'path';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
const mongoose = require('mongoose');
require('dotenv').config... | else {
res.render('index', {
req,
res,
preboot: false,
baseUrl: '/',
requestUrl: req.originalUrl,
originUrl: 'http://localhost:3000'
}, (err, html) => {
res.status(200).send(html);
cache.put(url, html);
... | {
res.status(200).send(html);
return;
} | conditional_block |
server.ts | // the polyfills must be the first thing imported in node.js
import 'angular2-universal-polyfills';
import * as path from 'path';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
const mongoose = require('mongoose');
require('dotenv').config... | (req, res) {
let url = req.originalUrl || '/';
let html = cache.get( url );
res.setHeader('Cache-Control', 'public, max-age=30');
if ( html ){
res.status(200).send(html);
return;
} else {
res.render('index', {
req,
res,
preboot: false,
... | ngApp | identifier_name |
server.ts | // the polyfills must be the first thing imported in node.js
import 'angular2-universal-polyfills';
import * as path from 'path';
import * as express from 'express';
import * as bodyParser from 'body-parser';
import * as cookieParser from 'cookie-parser';
const mongoose = require('mongoose');
require('dotenv').config... |
// Routes with html5pushstate
// ensure routes match client-side-app
app.get('/', ngApp);
app.get('/page', ngApp);
app.get('/login', ngApp);
app.use('/api/', apiRoutes);
app.get('*', (req, res) => {
res.status(404).json({ status: 404, message: 'No Content' });
});
// Server
let server = app.listen(process.env.P... | {
let url = req.originalUrl || '/';
let html = cache.get( url );
res.setHeader('Cache-Control', 'public, max-age=30');
if ( html ){
res.status(200).send(html);
return;
} else {
res.render('index', {
req,
res,
preboot: false,
b... | identifier_body |
interwebs.py | """
A simple HTTP interface for making GET, PUT and POST requests.
"""
import http.client
import json
from urllib.parse import urlparse, urlencode # NOQA
from base64 import b64encode
from functools import partial
from collections import namedtuple
Response = namedtuple("Response", ("payload", "headers", "status", "i... | )
return Response(response_payload, response_headers, status, is_json)
def request_url(verb, url, payload=None, headers=None, auth=None):
parsed = urlparse(url)
https = parsed.scheme == "https"
return request(
verb,
parsed.hostname,
parsed.port or 443 if https else... | return request_url(
verb,
response_headers["Location"],
headers=headers,
auth=auth | random_line_split |
interwebs.py | """
A simple HTTP interface for making GET, PUT and POST requests.
"""
import http.client
import json
from urllib.parse import urlparse, urlencode # NOQA
from base64 import b64encode
from functools import partial
from collections import namedtuple
Response = namedtuple("Response", ("payload", "headers", "status", "i... | (verb, url, payload=None, headers=None, auth=None):
parsed = urlparse(url)
https = parsed.scheme == "https"
return request(
verb,
parsed.hostname,
parsed.port or 443 if https else 80,
parsed.path,
payload=payload,
https=https,
headers=headers,
... | request_url | identifier_name |
interwebs.py | """
A simple HTTP interface for making GET, PUT and POST requests.
"""
import http.client
import json
from urllib.parse import urlparse, urlencode # NOQA
from base64 import b64encode
from functools import partial
from collections import namedtuple
Response = namedtuple("Response", ("payload", "headers", "status", "i... |
return Response(response_payload, response_headers, status, is_json)
def request_url(verb, url, payload=None, headers=None, auth=None):
parsed = urlparse(url)
https = parsed.scheme == "https"
return request(
verb,
parsed.hostname,
parsed.port or 443 if https else 80,
... | return request_url(
verb,
response_headers["Location"],
headers=headers,
auth=auth
) | conditional_block |
interwebs.py | """
A simple HTTP interface for making GET, PUT and POST requests.
"""
import http.client
import json
from urllib.parse import urlparse, urlencode # NOQA
from base64 import b64encode
from functools import partial
from collections import namedtuple
Response = namedtuple("Response", ("payload", "headers", "status", "i... |
get = partial(request, "GET")
post = partial(request, "POST")
put = partial(request, "PUT")
get_url = partial(request_url, "GET")
post_url = partial(request_url, "POST")
put_url = partial(request_url, "PUT")
| parsed = urlparse(url)
https = parsed.scheme == "https"
return request(
verb,
parsed.hostname,
parsed.port or 443 if https else 80,
parsed.path,
payload=payload,
https=https,
headers=headers,
auth=([parsed.username, parsed.password]
i... | identifier_body |
ObjectFactory.js | var inherit = require('./inherit'),
Sprite = require('../display/Sprite'),
Tilemap = require('../tilemap/Tilemap'),
Rectangle = require('../geom/Rectangle'),
BitmapText = require('../text/BitmapText');
/**
* The object factory makes it simple to create and add objects to a parent. One is added
* to a... | return this.parent.addChild(new BitmapText(text, font, style));
}
});
module.exports = ObjectFactory; | font = this.game.cache.getBitmapFont(font);
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.