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
schema.py
# testing/schema.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import exclusions from .. import schema, event from . import config __all_...
(c, tbl): c._init_items( schema.Sequence(_truncate_name( config.db.dialect, tbl.name + '_' + c.name + '_seq'), optional=True) ) event.listen(col, 'after_parent_attach', add_seq, propagate=True) return col...
add_seq
identifier_name
schema.py
# testing/schema.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import exclusions from .. import schema, event from . import config __all_...
else: return name
return name[0:max(dialect.max_identifier_length - 6, 0)] + \ "_" + hex(hash(name) % 64)[2:]
conditional_block
schema.py
# testing/schema.py # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors # <see AUTHORS file> # # This module is part of SQLAlchemy and is released under # the MIT License: http://www.opensource.org/licenses/mit-license.php from . import exclusions from .. import schema, event from . import config __all_...
# Only going after ForeignKeys in Columns. May need to # expand to ForeignKeyConstraint too. fks = [fk for col in args if isinstance(col, schema.Column) for fk in col.foreign_keys] for fk in fks: # root around in raw spec ref = fk....
"""A schema.Table wrapper/hook for dialect-specific tweaks.""" test_opts = dict([(k, kw.pop(k)) for k in list(kw) if k.startswith('test_')]) kw.update(table_options) if exclusions.against(config._current, 'mysql'): if 'mysql_engine' not in kw and 'mysql_type' not in kw: ...
identifier_body
poi_search_app.py
#!/usr/bin/env python2.7 # # Copyright 2017 Google 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 l...
main()
conditional_block
poi_search_app.py
#!/usr/bin/env python2.7 # # Copyright 2017 Google 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 l...
self._poi.logger.error( "%s Status %s sent back to client.", e, status) response_body = "%s" % e except exceptions.PoolConnectionException as e: # Catch PoolConnectionException when connections # are not available in the pool content_type = self._poi.utils.content_type % ("te...
status = self._status % ("400 Bad Request")
random_line_split
poi_search_app.py
#!/usr/bin/env python2.7 # # Copyright 2017 Google 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 l...
(): application() if __name__ == "__main__": main()
main
identifier_name
poi_search_app.py
#!/usr/bin/env python2.7 # # Copyright 2017 Google 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 l...
def __call__(self, environ, start_response): """Callable method for the WSGI application. Callable method which performs a POI search and returns the KML/JSONP format output back in the HTTP response. Args: environ: A list which contains the WSGI environment information. start_resp...
"""Inits the status and response_headers for the HTTP response.""" self._status = "%s" self._poi = poi_search_handler.POISearch()
identifier_body
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
{ let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a do...
identifier_body
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
() { let input = io::stdin().read_to_string().unwrap(); let dom: RcDom = parse(one_input(input), ParseOpts { tree_builder: TreeBuilderOpts { drop_doctype: true, ..Default::default() }, ..Default::default() }); // The validator.nu HTML2HTML always prints a...
main
identifier_name
html2html.rs
// Copyright 2014 The html5ever Project Developers. See the // COPYRIGHT file at the top-level directory of this distribution. // // 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>,...
serialize(&mut io::stdout(), &dom.document, Default::default()) .ok().expect("serialization failed"); }
.ok().expect("writing DOCTYPE failed");
random_line_split
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. ...
pub fn split_off(&mut self, at: usize) -> Vec<BTreeMap<K, V>> { self.0.split_off(at) } pub fn extend(&mut self, xs: Vec<BTreeMap<K, V>>) { self.0.extend(xs) } pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool where Q: Ord + Eq, K: Borrow<Q>, { ...
pub fn pop(&mut self) -> Option<BTreeMap<K, V>> { self.0.pop() }
random_line_split
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. ...
pub fn get_with_height<Q: ?Sized>(&self, key: &Q) -> Option<(&V, usize)> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate().rev() { if let Some(def) = scope.get(key) { return Some((def, height)); } } ...
{ for scope in self.0.iter_mut().rev() { if let Some(def) = scope.remove(key) { return Some(def); } } None }
identifier_body
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. ...
<Q: ?Sized>(&self, key: &Q) -> Option<usize> where Q: Ord + Eq, K: Borrow<Q>, { for (height, scope) in self.0.iter().enumerate() { if scope.contains_key(key) { return Some(height); } } None } pub fn get<Q: ?Sized>(&self, ke...
get_height
identifier_name
collections.rs
use std::borrow::Borrow; use std::collections::BTreeMap; use std::fmt::{self, Debug}; // TODO: Consider using BTreeMap, possible perforance increase. Do benchmarks. /// A stack of scopes of something. Fast access due to hashmaps, and guaranteed to contain no /// duplications at any point. /// /// Used for ConstDef:s. ...
else { unsafe { (*self.next).as_ref().and_then(|n| n.entry(key)) } } } fn add(&self, key: K, val: V) -> (&K, &V) where K: PartialEq<K>, { if self.key == key { panic!("Key already exists in map") } else { unsafe { match...
{ Some((&self.key, &self.val)) }
conditional_block
hdu.py
import time import requests import answer min_question_id = 1000 max_question_id = 5604 sleep_time = 10 submit_url = 'http://acm.hdu.edu.cn/submit.php?action=submit' login_url = 'http://acm.hdu.edu.cn/userloginex.php?action=login' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/53...
(self): data = { "userpass": self.password, "username": self.username, 'login': 'Sign In' } res = self.session.post(login_url, data=data) # print(res.text.encode('UTF-8')) if res.status_code == 200: self.is_login = True ...
login
identifier_name
hdu.py
import time import requests import answer min_question_id = 1000 max_question_id = 5604 sleep_time = 10 submit_url = 'http://acm.hdu.edu.cn/submit.php?action=submit' login_url = 'http://acm.hdu.edu.cn/userloginex.php?action=login' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/53...
def get_session(self): return self.session # TODO def get_state(self, problem): return False def solve(user, id): answers = answer.get_answer("%s%d" % ('hdu', id)) if answers is None or answers == []: print(None) return None count = 1 for ans in answers: ...
data = { "check": "0", "problemid": str(problem), "usercode": code, "language": "0" } res = self.session.post(submit_url, data=data) # print(res.text.encode('UTF-8')) # TODO if res.status_code == 200: return True ...
identifier_body
hdu.py
import time import requests import answer min_question_id = 1000 max_question_id = 5604 sleep_time = 10 submit_url = 'http://acm.hdu.edu.cn/submit.php?action=submit' login_url = 'http://acm.hdu.edu.cn/userloginex.php?action=login' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/53...
return None def hdu(): print("HDU:") # name = input("Your username: ") # password = input("Your password: ") name = 'printhello' password = '123456' my = HDU(name, password) if my.login() is False: return # return for i in range(4979, max_question_id): print('i...
user.submit(id, ans) print('submit', count) if count is 2: break count += 1 time.sleep(sleep_time)
conditional_block
hdu.py
import time import requests import answer min_question_id = 1000 max_question_id = 5604 sleep_time = 10 submit_url = 'http://acm.hdu.edu.cn/submit.php?action=submit' login_url = 'http://acm.hdu.edu.cn/userloginex.php?action=login' headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537...
# TODO if res.status_code == 200: return True return False def get_session(self): return self.session # TODO def get_state(self, problem): return False def solve(user, id): answers = answer.get_answer("%s%d" % ('hdu', id)) if answers is None or...
# print(res.text.encode('UTF-8'))
random_line_split
util.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { isBlank, isPresent, isPrimitive, isStrictStringMap } from './facade/lang'; import * as o from './output/outp...
if (path == null) { return "asset:@angular/lib/" + pkg + "/index"; } else { return "asset:@angular/lib/" + pkg + "/src/" + path; } } export function createDiTokenExpression(token) { if (isPresent(token.value)) { return o.literal(token.value); } else if (token.identif...
{ type = 'src'; }
conditional_block
util.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { isBlank, isPresent, isPrimitive, isStrictStringMap } from './facade/lang'; import * as o from './output/outp...
(name) { return name.replace(/\W/g, '_'); } export function visitValue(value, visitor, context) { if (Array.isArray(value)) { return visitor.visitArray(value, context); } if (isStrictStringMap(value)) { return visitor.visitStringMap(value, context); } if (isBlank(value) || isPrim...
sanitizeIdentifier
identifier_name
util.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { isBlank, isPresent, isPrimitive, isStrictStringMap } from './facade/lang'; import * as o from './output/outp...
} return '-' + m[1].toLowerCase(); }); } export function splitAtColon(input, defaultValues) { return _splitAt(input, ':', defaultValues); } export function splitAtPeriod(input, defaultValues) { return _splitAt(input, '.', defaultValues); } function _splitAt(input, character, defaultValues) {...
export function camelCaseToDashCase(input) { return input.replace(CAMEL_CASE_REGEXP, function () { var m = []; for (var _i = 0; _i < arguments.length; _i++) { m[_i - 0] = arguments[_i];
random_line_split
util.js
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { isBlank, isPresent, isPrimitive, isStrictStringMap } from './facade/lang'; import * as o from './output/outp...
export function createDiTokenExpression(token) { if (isPresent(token.value)) { return o.literal(token.value); } else if (token.identifierIsInstance) { return o.importExpr(token.identifier) .instantiate([], o.importType(token.identifier, [], [o.TypeModifier.Const])); } el...
{ if (path === void 0) { path = null; } if (type === void 0) { type = 'src'; } if (path == null) { return "asset:@angular/lib/" + pkg + "/index"; } else { return "asset:@angular/lib/" + pkg + "/src/" + path; } }
identifier_body
test_steps__outputs_file.py
from daisychain.steps.outputs.file import OutputFile from daisychain.steps.input import InMemoryInput import tempfile import os TEST_STRING = 'THIS OUTPUT STRING IS COMPLETELY UNIQUE AND WILL NOT EXIST EVER AGAIN' def test_output_file(): t = tempfile.NamedTemporaryFile(dir=os.path.dirname(__file__), delete=False)...
(): i = OutputFile(path='/thisdirectoryreallydoesnotexist', input_step=InMemoryInput(output=TEST_STRING)) assert i.pending try: i.run() except Exception as e: pass else: assert False, "Trying to output to a directory that doesn't exist should fail"
test_output_failure
identifier_name
test_steps__outputs_file.py
from daisychain.steps.outputs.file import OutputFile from daisychain.steps.input import InMemoryInput import tempfile import os TEST_STRING = 'THIS OUTPUT STRING IS COMPLETELY UNIQUE AND WILL NOT EXIST EVER AGAIN' def test_output_file():
def test_output_failure(): i = OutputFile(path='/thisdirectoryreallydoesnotexist', input_step=InMemoryInput(output=TEST_STRING)) assert i.pending try: i.run() except Exception as e: pass else: assert False, "Trying to output to a directory that doesn't exist should fail"
t = tempfile.NamedTemporaryFile(dir=os.path.dirname(__file__), delete=False) t.close() try: i = OutputFile(path=t.name, input_step=InMemoryInput(output=TEST_STRING)) assert i.pending i.run() assert i.finished with open(t.name) as f: assert TEST_STRING in f.re...
identifier_body
test_steps__outputs_file.py
from daisychain.steps.outputs.file import OutputFile from daisychain.steps.input import InMemoryInput import tempfile import os TEST_STRING = 'THIS OUTPUT STRING IS COMPLETELY UNIQUE AND WILL NOT EXIST EVER AGAIN'
t = tempfile.NamedTemporaryFile(dir=os.path.dirname(__file__), delete=False) t.close() try: i = OutputFile(path=t.name, input_step=InMemoryInput(output=TEST_STRING)) assert i.pending i.run() assert i.finished with open(t.name) as f: assert TEST_STRING in ...
def test_output_file():
random_line_split
test_steps__outputs_file.py
from daisychain.steps.outputs.file import OutputFile from daisychain.steps.input import InMemoryInput import tempfile import os TEST_STRING = 'THIS OUTPUT STRING IS COMPLETELY UNIQUE AND WILL NOT EXIST EVER AGAIN' def test_output_file(): t = tempfile.NamedTemporaryFile(dir=os.path.dirname(__file__), delete=False)...
assert False, "Trying to output to a directory that doesn't exist should fail"
conditional_block
models.py
from django.conf import settings from django.db import models import jsonfield class Feed(models.Model): name = models.CharField(max_length=1024) url = models.URLField() homepage = models.URLField() etag = models.CharField(max_length=1024, blank=True) last_modified = models.DateTimeField(blank=Tr...
max_length=1, choices=(('T', 'Time'), ('I', 'Intelligence')), default='T', ) def __str__(self): return 'user={}, mode={}, sorting={}'.format( self.user.username, self.mode, self.sorting )
choices=(('A', 'All Items'), ('U', 'Unread Only')), default='A', ) sorting = models.CharField(
random_line_split
models.py
from django.conf import settings from django.db import models import jsonfield class Feed(models.Model):
class Entry(models.Model): feed = models.ForeignKey(Feed) entry_id = models.CharField(max_length=1024) title = models.CharField(max_length=1024) content = models.TextField() link = models.URLField(max_length=1024) time = models.DateTimeField() json = jsonfield.JSONField() updated = mo...
name = models.CharField(max_length=1024) url = models.URLField() homepage = models.URLField() etag = models.CharField(max_length=1024, blank=True) last_modified = models.DateTimeField(blank=True, null=True) subscribers = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name=...
identifier_body
models.py
from django.conf import settings from django.db import models import jsonfield class Feed(models.Model): name = models.CharField(max_length=1024) url = models.URLField() homepage = models.URLField() etag = models.CharField(max_length=1024, blank=True) last_modified = models.DateTimeField(blank=Tr...
(self): return '{} ({})'.format(self.name, self.url) class Entry(models.Model): feed = models.ForeignKey(Feed) entry_id = models.CharField(max_length=1024) title = models.CharField(max_length=1024) content = models.TextField() link = models.URLField(max_length=1024) time = models.DateT...
__str__
identifier_name
index.android.js
/**
* Sample React Native App * https://github.com/facebook/react-native */ 'use strict'; var React = require('react-native'); var { AppRegistry, StyleSheet, Text, View, } = React; var robert_and_kims_weather_app = React.createClass({ render: function() { return ( <View style={styles.container}> ...
random_line_split
ghost.py
################################################### # This is a basic script to carry on a conversation # with ghost ################################################### # create service ghost = Runtime.start("ghost", "WebGui") ear = Runtime.start("ear", "WebkitSpeechRecognition") ghostchat = Runtime.start("ghostchat"...
# I've also tried removing this because I got an iteration error for this line # for voice in voices: # NaturalReaderSpeech.setVoice("Ryan")
ghostchat.startSession("ProgramAB/bots", "ghostchat") voices = mouth.getVoices()
random_line_split
HardwareTypeDropdown.tsx
import React, { useState } from 'react'; import Styled from 'styled-components'; import { IStoreState } from '../../store'; import { changeHardwareCategory } from '../../store/modules/hardware'; import { useDispatch, useSelector } from 'react-redux'; import { CategoryTypeEnum } from '../../constants/constants'; import ...
width: 138px; height: 30px; list-style-type: none; cursor: pointer; background-color: white; padding-left: 12px; &.init { border-bottom: 1px #4c94f8 solid; &.open { .arrow { background-image: url(${ArrowUpImage}); } } ...
const DropdownContent = Styled.li`
random_line_split
sqlmap.py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import bdb import inspect import logging import os import re import shutil import sys import time import traceback import warnings warnings.filterwarnings(action="ignore", me...
smokeTest() elif conf.liveTest: liveTest() else: start() except SqlmapUserQuitException: errMsg = "user quit" logger.error(errMsg) except (SqlmapSilentQuitException, bdb.BdbQuit): pass except SqlmapShellQuitException: cmd...
random_line_split
sqlmap.py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import bdb import inspect import logging import os import re import shutil import sys import time import traceback import warnings warnings.filterwarnings(action="ignore", me...
def main(): """ Main function of sqlmap when running from command line. """ try: paths.SQLMAP_ROOT_PATH = modulePath() try: os.path.isdir(paths.SQLMAP_ROOT_PATH) except UnicodeEncodeError: errMsg = "your system does not properly handle non-ASCII paths....
""" This will get us the program's directory, even if we are frozen using py2exe """ try: _ = sys.executable if weAreFrozen() else __file__ except NameError: _ = inspect.getsourcefile(modulePath) return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfilesystem...
identifier_body
sqlmap.py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import bdb import inspect import logging import os import re import shutil import sys import time import traceback import warnings warnings.filterwarnings(action="ignore", me...
errMsg = maskSensitiveData(errMsg) excMsg = maskSensitiveData(excMsg) logger.critical(errMsg) kb.stickyLevel = logging.CRITICAL dataToStdout(excMsg) createGithubIssue(errMsg, excMsg) finally: if conf.get("showTime"): dataToStdout("\n[*] shuttin...
file_ = match.group(1) file_ = os.path.relpath(file_, os.path.dirname(__file__)) file_ = file_.replace("\\", '/') file_ = re.sub(r"\.\./", '/', file_).lstrip('/') excMsg = excMsg.replace(match.group(1), file_)
conditional_block
sqlmap.py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ import bdb import inspect import logging import os import re import shutil import sys import time import traceback import warnings warnings.filterwarnings(action="ignore", me...
(): """ This will get us the program's directory, even if we are frozen using py2exe """ try: _ = sys.executable if weAreFrozen() else __file__ except NameError: _ = inspect.getsourcefile(modulePath) return getUnicode(os.path.dirname(os.path.realpath(_)), encoding=sys.getfi...
modulePath
identifier_name
cssstylerule.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/. */ use cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; use dom::bindings::code...
(&self, value: DOMString) { // It's not clear from the spec if we should use the stylesheet's namespaces. // https://github.com/w3c/csswg-drafts/issues/1511 let namespaces = self.cssrule.parent_stylesheet().style_stylesheet().contents.namespaces.read(); let parser = SelectorParser { ...
SetSelectorText
identifier_name
cssstylerule.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/. */ use cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; use dom::bindings::code...
} impl SpecificCSSRule for CSSStyleRule { fn ty(&self) -> u16 { use dom::bindings::codegen::Bindings::CSSRuleBinding::CSSRuleConstants; CSSRuleConstants::STYLE_RULE } fn get_css(&self) -> DOMString { let guard = self.cssrule.shared_lock().read(); self.stylerule.read_with(&...
{ reflect_dom_object(box CSSStyleRule::new_inherited(parent_stylesheet, stylerule), window, CSSStyleRuleBinding::Wrap) }
identifier_body
cssstylerule.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/. */ use cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; use dom::bindings::code...
use dom::cssstylesheet::CSSStyleSheet; use dom::window::Window; use dom_struct::dom_struct; use selectors::parser::SelectorList; use servo_arc::Arc; use std::mem; use style::selector_parser::SelectorParser; use style::shared_lock::{Locked, ToCssWithGuard}; use style::stylesheets::{StyleRule, Origin}; #[dom_struct] pub...
use dom::bindings::js::{JS, MutNullableJS, Root}; use dom::bindings::reflector::{DomObject, reflect_dom_object}; use dom::bindings::str::DOMString; use dom::cssrule::{CSSRule, SpecificCSSRule}; use dom::cssstyledeclaration::{CSSModificationAccess, CSSStyleDeclaration, CSSStyleOwner};
random_line_split
cssstylerule.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/. */ use cssparser::{Parser as CssParser, ParserInput as CssParserInput}; use cssparser::ToCss; use dom::bindings::code...
} }
{ // This mirrors what we do in CSSStyleOwner::mutate_associated_block. let mut guard = self.cssrule.shared_lock().write(); let stylerule = self.stylerule.write_with(&mut guard); mem::swap(&mut stylerule.selectors, &mut s); // It seems like we will want to avo...
conditional_block
thumbnail.js
else if (typeof define === 'function' && define.amd) { define(["require", "exports", '@angular/core'], factory); } })(function (require, exports) { "use strict"; var core_1 = require('@angular/core'); /** * \@name Thumbnail * \@module ionic * \@description * A Thumbnail i...
(function (factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; }
random_line_split
thumbnail.js
(function (factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === 'function' && define.amd) { define(["require", "exports", '@angular/core'], factory); } }...
Thumbnail.decorators = [ { type: core_1.Directive, args: [{ selector: 'ion-thumbnail' },] }, ]; /** @nocollapse */ Thumbnail.ctorParameters = function () { return []; }; return Thumbnail; }()); exports.Thumbnail = T...
{ }
identifier_body
thumbnail.js
(function (factory) { if (typeof module === 'object' && typeof module.exports === 'object') { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === 'function' && define.amd) { define(["require", "exports", '@angular/core'], factory); } }...
() { /** @type {?} */ Thumbnail.decorators; /** * @nocollapse * @type {?} */ Thumbnail.ctorParameters; } }); //# sourceMappingURL=thumbnail.js.map
Thumbnail_tsickle_Closure_declarations
identifier_name
create_mapping_on_deploy.py
import argparse import structlog import logging from pyramid.paster import get_app from snovault.elasticsearch.create_mapping import run as run_create_mapping from dcicutils.log_utils import set_logging from dcicutils.deployment_utils import CreateMappingOnDeployManager log = structlog.getLogger(__name__) EPILOG = _...
(): parser = argparse.ArgumentParser( # noqa - PyCharm wrongly thinks the formatter_class is specified wrong here. description="Create Elasticsearch mapping on deployment", epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument('config_uri', help="path to...
main
identifier_name
create_mapping_on_deploy.py
import argparse import structlog import logging from pyramid.paster import get_app from snovault.elasticsearch.create_mapping import run as run_create_mapping from dcicutils.log_utils import set_logging from dcicutils.deployment_utils import CreateMappingOnDeployManager log = structlog.getLogger(__name__) EPILOG = _...
def _run_create_mapping(app, args): """ Runs create_mapping with deploy options and report errors. Allows args passed from argparse in main to override the default deployment configuration. :param app: pyramid application handle :param args: args from argparse :return: None """ try:...
""" Gets the env name of the currently running environment :param app: handle to Pyramid app :return: current env """ # Return value is presumably one of the above-declared environments return app.registry.settings.get('env.name')
identifier_body
create_mapping_on_deploy.py
import argparse import structlog import logging from pyramid.paster import get_app from snovault.elasticsearch.create_mapping import run as run_create_mapping from dcicutils.log_utils import set_logging from dcicutils.deployment_utils import CreateMappingOnDeployManager log = structlog.getLogger(__name__) EPILOG = _...
else: log.info('NOT calling run_create_mapping for env %s.' % deploy_cfg['ENV_NAME']) exit(0) except Exception as e: log.error("Exception encountered while gathering deployment information or running create_mapping") log.error("%s: %s" % (e.__class__.__name__, e)) ...
log.info('Calling run_create_mapping for env %s.' % deploy_cfg['ENV_NAME']) run_create_mapping(app=app, check_first=(not deploy_cfg['WIPE_ES']), purge_queue=args.clear_queue, # this option does not vary, so no need to override ...
conditional_block
create_mapping_on_deploy.py
import argparse import structlog import logging from pyramid.paster import get_app from snovault.elasticsearch.create_mapping import run as run_create_mapping from dcicutils.log_utils import set_logging from dcicutils.deployment_utils import CreateMappingOnDeployManager log = structlog.getLogger(__name__) EPILOG = _...
# app.registry.settings.get('production'), # level=logging.DEBUG) _run_create_mapping(app, args) exit(0) if __name__ == '__main__': main()
# Loading app will have configured from config file. Reconfigure here: set_logging(in_prod=app.registry.settings.get('production'), log_name=__name__, level=logging.DEBUG) # set_logging(app.registry.settings.get('elasticsearch.server'),
random_line_split
mod.rs
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 later version. // Parity is distributed in the hope that it will be...
} impl Deref for ServerLoop { type Target = Server; fn deref(&self) -> &Self::Target { &self.server } } /// Setup a mock signer for tests pub fn serve() -> (ServerLoop, usize, GuardedAuthCodes) { let mut path = RandomTempPath::new(); path.panic_on_drop_failure = false; let queue = Arc::new(ConfirmationsQueue...
/// RPC Event Loop pub event_loop: RpcEventLoop,
random_line_split
mod.rs
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 later version. // Parity is distributed in the hope that it will be us...
(&mut self) -> &mut AuthCodes { &mut self.authcodes } } /// Server with event loop pub struct ServerLoop { /// Signer Server pub server: Server, /// RPC Event Loop pub event_loop: RpcEventLoop, } impl Deref for ServerLoop { type Target = Server; fn deref(&self) -> &Self::Target { &self.server } } /// Se...
deref_mut
identifier_name
bodyDropTarget.d.ts
import { DraggingEvent, DragSourceType, DropTarget } from "../dragAndDrop/dragAndDropService"; import { GridPanel } from "../gridPanel/gridPanel"; import { BeanStub } from "../context/beanStub"; export interface DropListener { getIconName(): string; onDragEnter(params: DraggingEvent): void; onDragLeave(para...
extends BeanStub implements DropTarget { private dragAndDropService; private columnController; private gridPanel; private pinned; private eContainer; private eSecondaryContainers; private dropListeners; private currentDropListener; private moveColumnController; constructor(pinne...
BodyDropTarget
identifier_name
bodyDropTarget.d.ts
import { DraggingEvent, DragSourceType, DropTarget } from "../dragAndDrop/dragAndDropService"; import { GridPanel } from "../gridPanel/gridPanel";
getIconName(): string; onDragEnter(params: DraggingEvent): void; onDragLeave(params: DraggingEvent): void; onDragging(params: DraggingEvent): void; onDragStop(params: DraggingEvent): void; } export declare class BodyDropTarget extends BeanStub implements DropTarget { private dragAndDropService; ...
import { BeanStub } from "../context/beanStub"; export interface DropListener {
random_line_split
echarts-4.js
setTimeout(() => { document.getElementById('fade').style.display = 'none' }, 4000) function splitData (rawData) { const data = {} const tickerNames = [] for (let i = 0; i < rawData.length; i++) { const ticker = rawData[i].Ticker if (!data[ticker])
const dateString = rawData[i].Date const pattern = /(\d{4})(\d{2})(\d{2})/ const dateNewType = dateString.replace(pattern, '$1-$2-$3'); data[ticker].categoryData.push(dateNewType) data[ticker].values.push([rawData[i].Open, rawData[i].Close, rawData[i].Low, rawData[i].High]) data[ticker].volume....
{ data[ticker] = { categoryData: [], values: [], volume: [] } tickerNames.push(ticker) }
conditional_block
echarts-4.js
setTimeout(() => { document.getElementById('fade').style.display = 'none' }, 4000) function splitData (rawData) { const data = {} const tickerNames = [] for (let i = 0; i < rawData.length; i++) { const ticker = rawData[i].Ticker if (!data[ticker]) { data[ticker] = { categoryData: [], ...
}, brush: { type: ['lineX', 'clear'] } } }, grid: [ { left: '10%', right: '8%', height: '50%' }, { left: '10%', right: '8%', top: '63%', height: '16%' } ], xAxis: [ { typ...
{ const data = incomingData[categoryName] return { backgroundColor: '#eee', animation: false, legend: { bottom: 10, left: 'center', data: [categoryName] }, tooltip: { trigger: 'axis', axisPointer: { type: 'line' } }, toolbox: { feature: {...
identifier_body
echarts-4.js
setTimeout(() => { document.getElementById('fade').style.display = 'none' }, 4000) function splitData (rawData) { const data = {} const tickerNames = [] for (let i = 0; i < rawData.length; i++) { const ticker = rawData[i].Ticker if (!data[ticker]) { data[ticker] = { categoryData: [], ...
type: 'candlestick', data: data.values, itemStyle: { normal: { borderColor: null, borderColor0: null } }, tooltip: { formatter: (param) => { let parame = param[0]; return [ 'Date: ' + para...
], series: [ { name: categoryName,
random_line_split
echarts-4.js
setTimeout(() => { document.getElementById('fade').style.display = 'none' }, 4000) function
(rawData) { const data = {} const tickerNames = [] for (let i = 0; i < rawData.length; i++) { const ticker = rawData[i].Ticker if (!data[ticker]) { data[ticker] = { categoryData: [], values: [], volume: [] } tickerNames.push(ticker) } const dateString = ...
splitData
identifier_name
dynatempl3.js
).width() - width) // right left = width - elem.width() - 40; // animate to the original size and the new position elem.animate({ width: width, left: -left, }, 300, function() { //animation complete elem.css({'box-shadow': '0px 0px 15px #666'}) }); elem.attr('onclick', '').unbind('click'); elem.clic...
() { var start = $('#start_date').datepicker('getDate').getTime() / 1000; start = start.toString().split(".")[0]; var stop = $('#stop_date').datepicker('getDate').getTime() / 1000; stop = stop.toString().split(".")[0]; var img_url = "{0}/{1}-pinpoint={2},{3}.png?size_x={4}&size_y={5}" .format($('#ZoomModa...
ReloadZoomImg
identifier_name
dynatempl3.js
elem.css({'box-shadow': '0px 0px 15px #666'}) }); elem.attr('onclick', '').unbind('click'); elem.click(function(){ ZoomOUT(elem); }); } function ZoomOUT(elem) { // animate to the normal position and size elem.animate({ width: "100%", left: 0, top: 0, zindex: 5 }, 400, function() { // Animat...
{ // get the original image size elem.css({'width': 'auto','position': 'relative','z-index': 10}); var width = elem.width(); elem.css({'width': '100%'}) // calc a left offset to zoom centered var left = width / 2 - elem.width() / 2; // keep the image inside the screen if (elem.offset().left - left < 20) // ch...
identifier_body
dynatempl3.js
).width() - width) // right left = width - elem.width() - 40; // animate to the original size and the new position elem.animate({ width: width, left: -left, }, 300, function() { //animation complete elem.css({'box-shadow': '0px 0px 15px #666'}) }); elem.attr('onclick', '').unbind('click'); elem.clic...
var start = $('#start_date').datepicker('getDate').getTime() / 1000; start = start.toString().split(".")[0]; var stop = $('#stop_date').datepicker('getDate').getTime() / 1000; stop = stop.toString().split(".")[0]; var img_url = "{0}/{1}-pinpoint={2},{3}.png?size_x={4}&size_y={5}" .format($('#ZoomModal').d...
} function ReloadZoomImg() {
random_line_split
snapshot.py
import argparse import os import subprocess import mongoengine as me import rmc.html_snapshots.utils as utils import rmc.shared.constants as c def crawl_page(url): args = [ 'phantomjs', '--disk-cache=true', os.path.join(utils.FILE_DIR, 'phantom-server.js'), url, ] rendere...
continue full_url = os.path.join(base_url, file_url) rendered_html = crawl_page(full_url) print 'Writing: %s' % url utils.write(file_path, rendered_html) if __name__ == "__main__": parser = argparse.ArgumentParser( description='Process snapshotting argume...
urls = utils.generate_urls() for url in urls: # For urls that end with a trailing slash, create them # as the index page of a subdirectory if url and url[0] == '/': url = url[1:] if not url: file_path = 'index' file_url = '' elif url[-1] ==...
identifier_body
snapshot.py
import argparse import os import subprocess import mongoengine as me import rmc.html_snapshots.utils as utils import rmc.shared.constants as c def crawl_page(url): args = [ 'phantomjs', '--disk-cache=true', os.path.join(utils.FILE_DIR, 'phantom-server.js'),
url, ] rendered_html = subprocess.check_output(args) return rendered_html def generate_snapshots(base_url, overwrite=False): urls = utils.generate_urls() for url in urls: # For urls that end with a trailing slash, create them # as the index page of a subdirectory if...
random_line_split
snapshot.py
import argparse import os import subprocess import mongoengine as me import rmc.html_snapshots.utils as utils import rmc.shared.constants as c def crawl_page(url): args = [ 'phantomjs', '--disk-cache=true', os.path.join(utils.FILE_DIR, 'phantom-server.js'), url, ] rendere...
else: file_path = url file_url = url file_path = os.path.join(utils.HTML_DIR, file_path) if os.path.isdir(file_path): print 'Cannot have file_path that is directory: %s' % file_path if not overwrite and os.path.isfile(file_path): continue...
file_path = url + 'index' file_url = url
conditional_block
snapshot.py
import argparse import os import subprocess import mongoengine as me import rmc.html_snapshots.utils as utils import rmc.shared.constants as c def crawl_page(url): args = [ 'phantomjs', '--disk-cache=true', os.path.join(utils.FILE_DIR, 'phantom-server.js'), url, ] rendere...
(base_url, overwrite=False): urls = utils.generate_urls() for url in urls: # For urls that end with a trailing slash, create them # as the index page of a subdirectory if url and url[0] == '/': url = url[1:] if not url: file_path = 'index' file...
generate_snapshots
identifier_name
test_taps_not_list.py
#!/usr/bin/python # write an experiment that raises an exception import sys import os BOREALISPATH = os.environ['BOREALISPATH'] sys.path.append(BOREALISPATH) import experiments.superdarn_common_fields as scf from experiment_prototype.experiment_prototype import ExperimentPrototype from experiment_prototype.decimati...
(ExperimentPrototype): def __init__(self): cpid = 1 # Filter_taps is not a list rates = [5.0e6, 500.0e3, 100.0e3, 50.0e3/3] dm_rates = [10, 5, 6, 5] transition_widths = [150.0e3, 40.0e3, 15.0e3, 1.0e3] cutoffs = [20.0e3, 10.0e3, 10.0e3, 5.0e3] ripple_dbs = [...
TestExperiment
identifier_name
test_taps_not_list.py
#!/usr/bin/python # write an experiment that raises an exception import sys import os BOREALISPATH = os.environ['BOREALISPATH'] sys.path.append(BOREALISPATH) import experiments.superdarn_common_fields as scf from experiment_prototype.experiment_prototype import ExperimentPrototype from experiment_prototype.decimati...
decimation_scheme = (DecimationScheme(rates[0], rates[-1]/dm_rates[-1], stages=all_stages)) super(TestExperiment, self).__init__( cpid, output_rx_rate=decimation_scheme.output_sample_rate, decimation_scheme=decimation_scheme) if scf.IS_FORWARD_RADAR: beams_to...
def __init__(self): cpid = 1 # Filter_taps is not a list rates = [5.0e6, 500.0e3, 100.0e3, 50.0e3/3] dm_rates = [10, 5, 6, 5] transition_widths = [150.0e3, 40.0e3, 15.0e3, 1.0e3] cutoffs = [20.0e3, 10.0e3, 10.0e3, 5.0e3] ripple_dbs = [150.0, 80.0, 35.0, 9.0] ...
identifier_body
test_taps_not_list.py
#!/usr/bin/python # write an experiment that raises an exception import sys import os BOREALISPATH = os.environ['BOREALISPATH'] sys.path.append(BOREALISPATH) import experiments.superdarn_common_fields as scf from experiment_prototype.experiment_prototype import ExperimentPrototype from experiment_prototype.decimati...
"pulse_len": scf.PULSE_LEN_45KM, "num_ranges": num_ranges, "first_range": scf.STD_FIRST_RANGE, "intt": 3500, # duration of an integration, in ms "beam_angle": scf.STD_16_BEAM_ANGLE, "beam_order": beams_to_use, "scanbound": [i * 3.5 for...
slice_1 = { # slice_id = 0, there is only one slice. "pulse_sequence": scf.SEQUENCE_7P, "tau_spacing": scf.TAU_SPACING_7P,
random_line_split
test_taps_not_list.py
#!/usr/bin/python # write an experiment that raises an exception import sys import os BOREALISPATH = os.environ['BOREALISPATH'] sys.path.append(BOREALISPATH) import experiments.superdarn_common_fields as scf from experiment_prototype.experiment_prototype import ExperimentPrototype from experiment_prototype.decimati...
# changed from 10e3/3->10e3 decimation_scheme = (DecimationScheme(rates[0], rates[-1]/dm_rates[-1], stages=all_stages)) super(TestExperiment, self).__init__( cpid, output_rx_rate=decimation_scheme.output_sample_rate, decimation_scheme=decimation_scheme) if scf....
filter_taps = list( scaling_factors[stage] * create_firwin_filter_by_attenuation( rates[stage], transition_widths[stage], cutoffs[stage], ripple_dbs[stage])) all_stages.append(DecimationStage(stage, rates[stage], dm_rates[...
conditional_block
keyframes.rs
use cssparser::{AtRuleParser, Parser, QualifiedRuleParser, RuleListParser}; use cssparser::{DeclarationListParser, DeclarationParser, parse_one_rule}; use error_reporting::NullReporter; use parser::{LengthParsingMode, ParserContext, log_css_error}; use properties::{Importance, PropertyDeclaration, PropertyDeclarationBl...
random_line_split
keyframes.rs
<Locked<PropertyDeclarationBlock>>, } impl ToCssWithGuard for Keyframe { fn to_css<W>(&self, guard: &SharedRwLockReadGuard, dest: &mut W) -> fmt::Result where W: fmt::Write { let mut iter = self.selector.percentages().iter(); try!(iter.next().unwrap().to_css(dest)); for percentage in it...
{ let message = format!("Invalid keyframe rule: '{}'", input.slice_from(start)); log_css_error(input, start, &message, self.context); Err(()) }
conditional_block
keyframes.rs
{ fn to_css<W>(&self, dest: &mut W) -> fmt::Result where W: fmt::Write { write!(dest, "{}%", self.0 * 100.0) } } impl KeyframePercentage { /// Trivially constructs a new `KeyframePercentage`. #[inline] pub fn new(value: f32) -> KeyframePercentage { debug_assert!(value >= 0. && valu...
{ /// The percentage of the animation duration when this step starts. pub start_percentage: KeyframePercentage, /// Declarations that will determine the final style during the step, or /// `ComputedValues` if this is an autogenerated step. pub value: KeyframesStepValue, /// Wether a animation-t...
KeyframesStep
identifier_name
markdown_it.js
import markdownIt from 'markdown-it'; import _ from 'lodash'; import footnotes from 'markdown-it-footnote'; export default function (opts) { const mergedOpts = _.assign({}, opts, { html: true, linkify: true }); const md = markdownIt(mergedOpts).use(footnotes); if (mergedOpts.openLinksExternally) { // Rememb...
return md; }
random_line_split
markdown_it.js
import markdownIt from 'markdown-it'; import _ from 'lodash'; import footnotes from 'markdown-it-footnote'; export default function (opts) { const mergedOpts = _.assign({}, opts, { html: true, linkify: true }); const md = markdownIt(mergedOpts).use(footnotes); if (mergedOpts.openLinksExternally) { // Rememb...
else { tokens[idx].attrs[aIndex][1] = '_blank'; // replace value of existing attr } // pass token to default renderer. return defaultRender(tokens, idx, options, env, self); }; } return md; }
{ tokens[idx].attrPush(['target', '_blank']); // add new attribute }
conditional_block
ShipModel.ts
module TK.SpaceTac { /** * Single upgrade for a ship * * Upgrades allow for customizing a model, and are unlocked at given levels */ export type ShipUpgrade = { // Displayable upgrade name, should be unique on the model code: string // Upgrade points cost (may be us...
(level?: number, random = RandomGenerator.global): ShipModel { let collection = ShipModel.getDefaultCollection(); if (level) { collection = collection.filter(model => model.isAvailable(level)); } if (collection.length == 0) { console.error...
getRandomModel
identifier_name
ShipModel.ts
module TK.SpaceTac { /** * Single upgrade for a ship * * Upgrades allow for customizing a model, and are unlocked at given levels */ export type ShipUpgrade = { // Displayable upgrade name, should be unique on the model code: string // Upgrade points cost (may be us...
return result; } /** * Pick a random model in the default collection */ static getRandomModel(level?: number, random = RandomGenerator.global): ShipModel { let collection = ShipModel.getDefaultCollection(); if (level) { coll...
result.push(model); } } }
random_line_split
ShipModel.ts
module TK.SpaceTac { /** * Single upgrade for a ship * * Upgrades allow for customizing a model, and are unlocked at given levels */ export type ShipUpgrade = { // Displayable upgrade name, should be unique on the model code: string // Upgrade points cost (may be us...
if (collection.length == 0) { console.error("Couldn't pick a random model"); return range(count).map(() => new ShipModel()); } else { let result: ShipModel[] = []; while (count > 0) { let picked = random.sample...
{ collection = collection.filter(model => model.isAvailable(level)); }
conditional_block
ShipModel.ts
module TK.SpaceTac { /** * Single upgrade for a ship * * Upgrades allow for customizing a model, and are unlocked at given levels */ export type ShipUpgrade = { // Displayable upgrade name, should be unique on the model code: string // Upgrade points cost (may be us...
/** * Get the list of upgrades unlocked at a given level */ getLevelUpgrades(level: number): ShipUpgrade[] { return []; } /** * Get the list of upgrades activated, given a ship level and an upgrade set */ getActivatedUpgrades(lev...
{ return [ { code: `Level ${level} Hull Upgrade`, effects: [new AttributeEffect("hull_capacity", 1)], cost: 3 }, { code: `Level ${level} Shield Upgrade`, effects: [new AttributeEffect("shield_capacity", 1)], cost: 3 }, { code: `Level ${level} Power Upgrade`, e...
identifier_body
field_type_enum.py
# Copyright (C) 2016 Statoil ASA, Norway. # # This file is part of ERT - Ensemble based Reservoir Tool. # # ERT 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 ...
# for more details. from cwrap import BaseCEnum class FieldTypeEnum(BaseCEnum): TYPE_NAME = "field_type_enum" ECLIPSE_RESTART = None ECLIPSE_PARAMETER = None GENERAL = None UNKNOWN_FIELD_TYPE = None FieldTypeEnum.addEnum('ECLIPSE_RESTART', 1) FieldTypeEnum.addEnum('ECLIPSE_PARA...
# See the GNU General Public License at <http://www.gnu.org/licenses/gpl.html>
random_line_split
field_type_enum.py
# Copyright (C) 2016 Statoil ASA, Norway. # # This file is part of ERT - Ensemble based Reservoir Tool. # # ERT 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 ...
FieldTypeEnum.addEnum('ECLIPSE_RESTART', 1) FieldTypeEnum.addEnum('ECLIPSE_PARAMETER', 2) FieldTypeEnum.addEnum('GENERAL', 3) FieldTypeEnum.addEnum('UNKNOWN_FIELD_TYPE', 4)
TYPE_NAME = "field_type_enum" ECLIPSE_RESTART = None ECLIPSE_PARAMETER = None GENERAL = None UNKNOWN_FIELD_TYPE = None
identifier_body
field_type_enum.py
# Copyright (C) 2016 Statoil ASA, Norway. # # This file is part of ERT - Ensemble based Reservoir Tool. # # ERT 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 ...
(BaseCEnum): TYPE_NAME = "field_type_enum" ECLIPSE_RESTART = None ECLIPSE_PARAMETER = None GENERAL = None UNKNOWN_FIELD_TYPE = None FieldTypeEnum.addEnum('ECLIPSE_RESTART', 1) FieldTypeEnum.addEnum('ECLIPSE_PARAMETER', 2) FieldTypeEnum.addEnum('GENERAL', 3) FieldTypeEn...
FieldTypeEnum
identifier_name
stats.py
#!/usr/bin/env python from __future__ import print_function import argparse import numpy as N import os import sys def parse_args(args): p = argparse.ArgumentParser() p.add_argument('-i', '--input-files', default=[sys.stdin], nargs="+", type=argparse.FileType('rt'), help='input f...
, ('standard_deviation', args.standard_deviation , N.std) , ('variance', args.variance, N.var) , ('min', args.min, N.amin) , ('max', args.max, N.amax)]: if not args.a...
s = [] for (name,value,f) in [('mean', args.mean, N.mean) , ('median', args.median, N.median)
random_line_split
stats.py
#!/usr/bin/env python from __future__ import print_function import argparse import numpy as N import os import sys def parse_args(args): p = argparse.ArgumentParser() p.add_argument('-i', '--input-files', default=[sys.stdin], nargs="+", type=argparse.FileType('rt'), help='input f...
(): args = parse_args(sys.argv[1:]) for input_file in args.input_files: vals = [float(x) for x in input_file.read().split(os.linesep) if x] a = N.array(vals) s = [] for (name,value,f) in [('mean', args.mean, N.mean) , ('median', args.median, N.median) ...
main
identifier_name
stats.py
#!/usr/bin/env python from __future__ import print_function import argparse import numpy as N import os import sys def parse_args(args): p = argparse.ArgumentParser() p.add_argument('-i', '--input-files', default=[sys.stdin], nargs="+", type=argparse.FileType('rt'), help='input f...
print(' '.join(s)) if __name__=='__main__': main()
args = parse_args(sys.argv[1:]) for input_file in args.input_files: vals = [float(x) for x in input_file.read().split(os.linesep) if x] a = N.array(vals) s = [] for (name,value,f) in [('mean', args.mean, N.mean) , ('median', args.median, N.median) , (...
identifier_body
stats.py
#!/usr/bin/env python from __future__ import print_function import argparse import numpy as N import os import sys def parse_args(args): p = argparse.ArgumentParser() p.add_argument('-i', '--input-files', default=[sys.stdin], nargs="+", type=argparse.FileType('rt'), help='input f...
main()
conditional_block
Development-story-depreciated.js
/* eslint-disable no-console */ import React from 'react'; import { storiesOf } from '@storybook/react'; import Page from './Page'; import Link from '../components/Link'; storiesOf('Design|Guidelines', module) .addParameters({ options: { showPanel: false, isToolshown: false } }) .add('Development', () => ( <P...
Development is made on a GitHub repository. Feel free create an Issue or submit a pull request.{' '} <Link href="https://github.com/wfp/ui">Project on GitHub</Link> </p> <br /> <iframe title="GitHub Like" src="https://ghbtns.com/github-btn.html?user=wfp&repo=ui&...
<p>
random_line_split
url.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import urlparse def uc2utf8(input): ## argh! this feels wrong, but seems to be needed. if type(input) == unicode: return input.encode('utf-8') else: return input class URL: """ This class is for wrapping URLs into objects. It's use...
def is_auth(self): return self.username is not None def unauth(self): if not self.is_auth(): return self return URL.objectify(urlparse.ParseResult( self.scheme, '%s:%s' % (self.hostname, self.port), self.path.replace('//', '/'), self.params, self.qu...
return "URL(%s)" % str(self)
identifier_body
url.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import urlparse def uc2utf8(input): ## argh! this feels wrong, but seems to be needed. if type(input) == unicode: return input.encode('utf-8') else: return input class URL: """ This class is for wrapping URLs into objects. It's use...
else: return URL(url) ## To deal with all kind of methods/properties in the ParseResult ## class def __getattr__(self, attr): if self.url_parsed is None: self.url_parsed = urlparse.urlparse(self.url_raw) if hasattr(self.url_parsed, attr): return ...
return url
conditional_block
url.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import urlparse def uc2utf8(input): ## argh! this feels wrong, but seems to be needed. if type(input) == unicode: return input.encode('utf-8') else: return input class URL: """ This class is for wrapping URLs into objects. It's use...
@classmethod def objectify(self, url): if url is None: return None if isinstance(url, URL): return url else: return URL(url) ## To deal with all kind of methods/properties in the ParseResult ## class def __getattr__(self, attr): if...
## TODO: better naming? Will return url if url is already an URL ## object, else will instantiate a new URL object
random_line_split
url.py
#!/usr/bin/env python # -*- encoding: utf-8 -*- import urlparse def uc2utf8(input): ## argh! this feels wrong, but seems to be needed. if type(input) == unicode: return input.encode('utf-8') else: return input class URL: """ This class is for wrapping URLs into objects. It's use...
(self): if self.url_raw or self.url_parsed: return True else: return False def __ne__(self, other): return not self == other def __eq__(self, other): if str(self) == str(other): return True ## The URLs could have insignificant differe...
__nonzero__
identifier_name
test_execution_environment_completeness.py
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
'generateSequence', 'areExplicitEnvironmentsAllowed', 'createInput', 'getUserCodeClassLoader', 'getExecutorServiceLoader', 'getConfiguration', 'executeAsync', 'registerJobListener', 'clearJobListeners', 'configure'} if __name__ == '__main__': import unittest tr...
'getLastJobExecutionResult', 'readCsvFile', 'initializeContextEnvironment', 'createLocalEnvironment', 'createLocalEnvironmentWithWebUI', 'createProgramPlan', 'getIdString', 'setSessionTimeout', 'fromElements', 'createRemoteEnvironment', 'startNewSession', ...
random_line_split
test_execution_environment_completeness.py
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
@classmethod def excluded_methods(cls): # Exclude these methods for the time being, because current # ExecutionEnvironment/StreamExecutionEnvironment do not apply to the # DataSet/DataStream API, but to the Table API configuration. # Currently only the methods for configuration...
return "org.apache.flink.api.java.ExecutionEnvironment"
identifier_body
test_execution_environment_completeness.py
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
import unittest try: import xmlrunner testRunner = xmlrunner.XMLTestRunner(output='target/test-reports') except ImportError: testRunner = None unittest.main(testRunner=testRunner, verbosity=2)
conditional_block
test_execution_environment_completeness.py
################################################################################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this...
(cls): # Exclude these methods for the time being, because current # ExecutionEnvironment/StreamExecutionEnvironment do not apply to the # DataSet/DataStream API, but to the Table API configuration. # Currently only the methods for configuration is added. # 'setSessionTimeout', '...
excluded_methods
identifier_name
voice_artist.py
# coding: utf-8 # Copyright 2018 The Oppia 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
if extension not in feconf.ACCEPTED_AUDIO_EXTENSIONS: raise self.InvalidInputException( 'Invalid filename extension: it should have ' 'one of the following extensions: %s' % allowed_formats) tempbuffer = python_utils.string_io() tempbuffer.write(raw_...
raise self.InvalidInputException( 'No filename extension: it should have ' 'one of the following extensions: %s' % allowed_formats)
conditional_block
voice_artist.py
# coding: utf-8 # Copyright 2018 The Oppia 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
(self, exploration_id): """Saves an audio file uploaded by a content creator.""" raw_audio_file = self.request.get('raw_audio_file') filename = self.payload.get('filename') allowed_formats = list(feconf.ACCEPTED_AUDIO_EXTENSIONS.keys()) if not raw_audio_file: raise s...
post
identifier_name
voice_artist.py
# coding: utf-8 # Copyright 2018 The Oppia 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
set(feconf.ACCEPTED_AUDIO_EXTENSIONS[extension]))) == 0: raise self.InvalidInputException( 'Although the filename extension indicates the file ' 'is a %s file, it was not recognized as one. ' 'Found mime types: %s' % (extension, audio.mime)) ...
'Audio files must be under %s seconds in length. The uploaded ' 'file is %.2f seconds long.' % ( feconf.MAX_AUDIO_FILE_LENGTH_SEC, audio.info.length)) if len(set(audio.mime).intersection(
random_line_split
voice_artist.py
# coding: utf-8 # Copyright 2018 The Oppia 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 of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
"""Records that this user has started the state translation tutorial.""" @acl_decorators.can_play_exploration def post(self, unused_exploration_id): """Handles POST requests.""" user_services.record_user_started_state_translation_tutorial( self.user_id) self.render_json({})
identifier_body
api_metadata.py
# Copyright 2014 # The Cloudscaling Group, 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 agreed to...
main()
conditional_block
api_metadata.py
# Copyright 2014 # The Cloudscaling Group, 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 agreed to...
(): config.parse_args(sys.argv) logging.setup(CONF, "ec2api") server = service.WSGIService('metadata') service.serve(server, workers=server.workers) service.wait() if __name__ == '__main__': main()
main
identifier_name
api_metadata.py
# Copyright 2014 # The Cloudscaling Group, 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 agreed to...
if __name__ == '__main__': main()
config.parse_args(sys.argv) logging.setup(CONF, "ec2api") server = service.WSGIService('metadata') service.serve(server, workers=server.workers) service.wait()
identifier_body
api_metadata.py
# Copyright 2014 # The Cloudscaling Group, 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 agreed to...
import sys from oslo_config import cfg from oslo_log import log as logging from ec2api import config from ec2api import service CONF = cfg.CONF def main(): config.parse_args(sys.argv) logging.setup(CONF, "ec2api") server = service.WSGIService('metadata') service.serve(server, workers=server.worker...
random_line_split
__init__.py
from tehbot.plugins import * import tehbot.plugins as plugins import wolframalpha import prettytable class WolframAlphaPlugin(StandardPlugin): def __init__(self): StandardPlugin.__init__(self) self.parser.add_argument("query", nargs="+") def initialize(self, dbconn): StandardPlugin.ini...
(table, nr_cols): t = [[] for n in range(len(table))] for i in range(nr_cols): keep = False for line in table: if line[i]: keep = True break if keep: for j in range(len(table)): ...
remove_empty_columns
identifier_name