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 |
|---|---|---|---|---|
test_pdb_chain.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2018 João Pedro Rodrigues
#
# 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
#
# Unl... | unittest.TestCase):
"""
Generic class for testing tools.
"""
def setUp(self):
# Dynamically import the module
name = 'pdbtools.pdb_chain'
self.module = __import__(name, fromlist=[''])
def exec_module(self):
"""
Execs module.
"""
with OutputC... | estTool( | identifier_name |
spotcheck.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from builtins import zip
import pycrfsuite
def compareTaggers(model1, model2, string_list, module_name):
"""
Compare two models. Given a list of strings, prints out tokens & tags
whenever the two taggers parse a string differe... |
print("\n\n%s of %s strings were labeled differently"%(count_discrepancies, len(string_list)))
def print_spaced(s1, s2, s3):
n = 25
print(s1 + " "*(n-len(s1)) + s2 + " "*(n-len(s2)) + s3)
def validateTaggers(model1, model2, labeled_string_list, module_name):
module = __import__(module_name)
ta... | print_spaced(token[0], token[1], token[2]) | conditional_block |
spotcheck.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from builtins import zip
import pycrfsuite
def compareTaggers(model1, model2, string_list, module_name):
"""
Compare two models. Given a list of strings, prints out tokens & tags
whenever the two taggers parse a string differe... | (model1, model2, labeled_string_list, module_name):
module = __import__(module_name)
tagger1 = pycrfsuite.Tagger()
tagger1.open(module_name+'/'+model1)
tagger2 = pycrfsuite.Tagger()
tagger2.open(module_name+'/'+model2)
wrong_count_1 = 0
wrong_count_2 = 0
wrong_count_both = 0
corre... | validateTaggers | identifier_name |
spotcheck.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from builtins import zip
import pycrfsuite
def compareTaggers(model1, model2, string_list, module_name):
"""
Compare two models. Given a list of strings, prints out tokens & tags
whenever the two taggers parse a string differe... | correct_count += 1
print("\n\nBOTH WRONG: ", wrong_count_both)
print("%s WRONG: %s" %(model1, wrong_count_1))
print("%s WRONG: %s" %(model2, wrong_count_2))
print("BOTH CORRECT: ", correct_count) | print("%s: "%model1, tags1)
print("*%s: "%model2, tags2)
wrong_count_2 += 1
else: | random_line_split |
spotcheck.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
from builtins import zip
import pycrfsuite
def compareTaggers(model1, model2, string_list, module_name):
|
def print_spaced(s1, s2, s3):
n = 25
print(s1 + " "*(n-len(s1)) + s2 + " "*(n-len(s2)) + s3)
def validateTaggers(model1, model2, labeled_string_list, module_name):
module = __import__(module_name)
tagger1 = pycrfsuite.Tagger()
tagger1.open(module_name+'/'+model1)
tagger2 = pycrfsuite.Tagge... | """
Compare two models. Given a list of strings, prints out tokens & tags
whenever the two taggers parse a string differently. This is for spot-checking models
:param tagger1: a .crfsuite filename
:param tagger2: another .crfsuite filename
:param string_list: a list of strings to be checked
:par... | identifier_body |
InstapaperShareButton.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
var _createShareButton = require('./utils/createShareButton'... |
function instapaperLink(url, _ref) {
var title = _ref.title,
description = _ref.description;
(0, _assert2.default)(url, 'instapaper.url');
return 'http://www.instapaper.com/hello2' + (0, _objectToGetParams2.default)({
url: url,
title: title,
description: description
});
}
var InstapaperSh... | { return obj && obj.__esModule ? obj : { default: obj }; } | identifier_body |
InstapaperShareButton.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
var _createShareButton = require('./utils/createShareButton'... | (url, _ref) {
var title = _ref.title,
description = _ref.description;
(0, _assert2.default)(url, 'instapaper.url');
return 'http://www.instapaper.com/hello2' + (0, _objectToGetParams2.default)({
url: url,
title: title,
description: description
});
}
var InstapaperShareButton = (0, _createSh... | instapaperLink | identifier_name |
InstapaperShareButton.js | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
var _assert = require('assert');
var _assert2 = _interopRequireDefault(_assert);
var _createShareButton = require('./utils/createShareButton'... | var _objectToGetParams = require('./utils/objectToGetParams');
var _objectToGetParams2 = _interopRequireDefault(_objectToGetParams);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function instapaperLink(url, _ref) {
var title = _ref.title,
description = _ref.... | random_line_split | |
dirac-rss-list-status.py | #!/usr/bin/env python
"""
dirac-rss-list-status
Script that dumps the DB information for the elements into the standard output.
If returns information concerning the StatusType and Status attributes.
Usage:
dirac-rss-list-status
--element= Element family to be Synchronized ( Sit... |
subLogger.debug( "The switches used are:" )
map( subLogger.debug, switches.iteritems() )
return switches
#...............................................................................
def getElements():
'''
Given the switches, gets a list of elements with their respective statustype
and status at... | subLogger.error( "Found %s as element switch" % switches[ 'element' ] )
subLogger.error( "Please, check documentation below" )
Script.showHelp()
DIRACExit( 1 ) | conditional_block |
dirac-rss-list-status.py | #!/usr/bin/env python
"""
dirac-rss-list-status
Script that dumps the DB information for the elements into the standard output.
If returns information concerning the StatusType and Status attributes.
Usage:
dirac-rss-list-status
--element= Element family to be Synchronized ( Sit... | ():
'''
Given the switches, gets a list of elements with their respective statustype
and status attributes.
'''
rssClient = ResourceStatusClient.ResourceStatusClient()
meta = { 'columns' : [] }
for key in ( 'Name', 'StatusType', 'Status', 'ElementType', 'TokenOwner' ):
#Transforms from upper low... | getElements | identifier_name |
dirac-rss-list-status.py | #!/usr/bin/env python
"""
dirac-rss-list-status
Script that dumps the DB information for the elements into the standard output.
If returns information concerning the StatusType and Status attributes.
Usage:
dirac-rss-list-status
--element= Element family to be Synchronized ( Sit... |
#...............................................................................
if __name__ == "__main__":
subLogger = gLogger.getSubLogger( __file__ )
#Script initialization
registerSwitches()
registerUsageMessage()
switchDict = parseSwitches()
#Run script
run()
#Bye
DIRACExit( 0 )
########... | '''
Main function of the script
'''
elements = getElements()
if not elements[ 'OK' ]:
subLogger.error( elements )
DIRACExit( 1 )
elements = elements[ 'Value' ]
tabularPrint( elements ) | identifier_body |
dirac-rss-list-status.py | #!/usr/bin/env python
"""
dirac-rss-list-status
Script that dumps the DB information for the elements into the standard output.
If returns information concerning the StatusType and Status attributes.
Usage:
dirac-rss-list-status
--element= Element family to be Synchronized ( Sit... |
def registerUsageMessage():
'''
Takes the script __doc__ and adds the DIRAC version to it
'''
hLine = ' ' + '='*78 + '\n'
usageMessage = hLine
usageMessage += ' DIRAC %s\n' % version
usageMessage += __doc__
usageMessage += '\n' + hLine
Script.setUsageMessage( usageMessage )
def parseSwitches(... | Script.registerSwitch( '', switch[ 0 ], switch[ 1 ] ) | random_line_split |
car.py | """
Created on 11.09.2014
@author: benjamin@boerngen-schmidt.de
"""
from abc import ABCMeta, abstractmethod
import random
import datetime
class BaseCar(metaclass=ABCMeta):
"""
Represents the fundamentals of a car
"""
def __init__(self, env, tank_size):
"""
Constructor
:type ta... | return 0.08
class RefillWarning(Exception):
pass | random_line_split | |
car.py | """
Created on 11.09.2014
@author: benjamin@boerngen-schmidt.de
"""
from abc import ABCMeta, abstractmethod
import random
import datetime
class BaseCar(metaclass=ABCMeta):
"""
Represents the fundamentals of a car
"""
def __init__(self, env, tank_size):
"""
Constructor
:type ta... | (Exception):
pass
| RefillWarning | identifier_name |
car.py | """
Created on 11.09.2014
@author: benjamin@boerngen-schmidt.de
"""
from abc import ABCMeta, abstractmethod
import random
import datetime
class BaseCar(metaclass=ABCMeta):
"""
Represents the fundamentals of a car
"""
def __init__(self, env, tank_size):
"""
Constructor
:type ta... |
@property
def driven_distance(self):
"""
The car's odometer
:return: The total distance the car has traveled
:rtype: float
"""
return self._driven_distance
@property
def fuel_type(self):
"""
The car's fuel type
:return: Type of f... | """Returns the nodes target ID
:rtype: int
"""
return self._current_position | identifier_body |
car.py | """
Created on 11.09.2014
@author: benjamin@boerngen-schmidt.de
"""
from abc import ABCMeta, abstractmethod
import random
import datetime
class BaseCar(metaclass=ABCMeta):
"""
Represents the fundamentals of a car
"""
def __init__(self, env, tank_size):
"""
Constructor
:type ta... |
def _do_driving(self, segment):
"""
Drives the given route segment
Uses the segment data to simulate the driving of the car. Thereby fuel is consumed to the amount calculated
by the consume_fuel method.
:param segment: a single fragment of the route
:type segment:... | self._do_driving(segment)
self.env.consume_time(datetime.timedelta(seconds=segment.travel_time))
# check if driving the segment has
if self._tankFilling <= 5.0 and not ignore_refill_warning:
raise RefillWarning() | conditional_block |
test_settings.py | # encoding: utf-8
import logging
# emplacement ou charger les fichier de configuration par instances
INSTANCES_DIR = '/etc/jormungandr.d'
# Start the thread at startup, True in production, False for test environments
START_MONITORING_THREAD = False
# chaine de connnection à postgresql pour la base jormungandr
SQLAL... |
REDIS_PASSWORD = None
# Desactive l'utilisation du cache, et donc de redis
CACHE_DISABLED = False
# durée de vie des info d'authentification dans le cache en secondes
AUTH_CACHE_TTL = 300
ERROR_HANDLER_FILE = 'jormungandr.log'
ERROR_HANDLER_TYPE = 'rotating' # can be timedrotating
ERROR_HANDLER_PARAMS = {'maxBytes... | REDIS_DB = 0 | random_line_split |
lib.rs | #![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi... | reg.add_attr("feature(custom_attribute)");
reg.add_decorator("derive_Serialize", ser::expand_derive_serialize);
reg.add_decorator("derive_Deserialize", de::expand_derive_deserialize);
reg.add_post_expansion_pass(strip_attributes);
}
#[cfg(not(feature = "with-syntex"))]
pub fn register(reg: &mut rustc... |
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
}
reg.add_attr("feature(custom_derive)"); | random_line_split |
lib.rs | #![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi... |
#[cfg(not(feature = "with-syntex"))]
pub fn register(reg: &mut rustc_plugin::Registry) {
reg.register_syntax_extension(
syntax::parse::token::intern("derive_Serialize"),
syntax::ext::base::MultiDecorator(
Box::new(ser::expand_derive_serialize)));
reg.register_syntax_extension(
... | {
use syntax::{ast, fold};
/// Strip the serde attributes from the crate.
#[cfg(feature = "with-syntex")]
fn strip_attributes(krate: ast::Crate) -> ast::Crate {
/// Helper folder that strips the serde attributes after the extensions have been expanded.
struct StripAttributeFolder;
... | identifier_body |
lib.rs | #![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi... |
_ => {}
}
Some(attr)
}
fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
fold::noop_fold_mac(mac, self)
}
}
fold::Folder::fold_crate(&mut StripAttributeFolder, krate)
}
reg.add_attr("fe... | { return None; } | conditional_block |
lib.rs | #![cfg_attr(feature = "nightly-testing", plugin(clippy))]
#![cfg_attr(feature = "nightly-testing", feature(plugin))]
#![cfg_attr(feature = "nightly-testing", allow(used_underscore_binding))]
#![cfg_attr(not(feature = "with-syntex"), feature(rustc_private, plugin))]
#![cfg_attr(not(feature = "with-syntex"), plugin(quasi... | ;
impl fold::Folder for StripAttributeFolder {
fn fold_attribute(&mut self, attr: ast::Attribute) -> Option<ast::Attribute> {
match attr.node.value.node {
ast::MetaItemKind::List(ref n, _) if n == &"serde" => { return None; }
_ => {}
... | StripAttributeFolder | identifier_name |
graph.py | # Graph functions used by KCC intersite
#
# Copyright (C) Dave Craft 2011
# Copyright (C) Andrew Bartlett 2015
#
# Andrew Bartlett's alleged work performed by his underlings Douglas
# Bagnall and Garming Sam.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Genera... |
root = current
current = vertex
while current.component_id is not root:
n = current.component_id
current.component_id = root
current = n
return root
def add_out_edge(graph, output_edges, e):
"""Kruskal helper to add output edges
:param graph: the InterSiteGraph
... | current = current.component_id | conditional_block |
graph.py | # Graph functions used by KCC intersite
#
# Copyright (C) Dave Craft 2011
# Copyright (C) Andrew Bartlett 2015
#
# Andrew Bartlett's alleged work performed by his underlings Douglas
# Bagnall and Garming Sam.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Genera... | (graph, examine, internal_edges):
"""Find the set of all vertices touching an edge to examine
:param graph: an IntersiteGraph object
:param examine: an edge
:param internal_edges: a set that internal edges get added to
:return: None
"""
vertices = []
for v in examine.vertices:
#... | process_edge | identifier_name |
graph.py | # Graph functions used by KCC intersite
#
# Copyright (C) Dave Craft 2011
# Copyright (C) Andrew Bartlett 2015
#
# Andrew Bartlett's alleged work performed by his underlings Douglas
# Bagnall and Garming Sam.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Genera... |
:param graph: an IntersiteGraph object
:param edge_type: a transport type GUID
:param include_black: boolean, whether to include black vertices
:return: A heap queue of vertices
"""
queue = []
setup_vertices(graph)
for vertex in graph.vertices:
if vertex.is_white():
... |
def setup_dijkstra(graph, edge_type, include_black):
"""Create a vertex queue for Dijksta's algorithm. | random_line_split |
graph.py | # Graph functions used by KCC intersite
#
# Copyright (C) Dave Craft 2011
# Copyright (C) Andrew Bartlett 2015
#
# Andrew Bartlett's alleged work performed by his underlings Douglas
# Bagnall and Garming Sam.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Genera... |
def is_black(self):
assert(self.color != VertexColor.unknown)
return (self.color == VertexColor.black)
def is_white(self):
assert(self.color != VertexColor.unknown)
return (self.color == VertexColor.white)
class IntersiteGraph(object):
"""Graph for representing the inter... | assert(self.color != VertexColor.unknown)
return (self.color == VertexColor.red) | identifier_body |
test_cert_setup.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# 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):
pki = openssl.ConfigurePKI(None, None)
pki.run()
self.assertTrue(os.path.exists(CONF.signing.certfile))
self.assertTrue(os.path.exists(CONF.signing.ca_certs))
self.assertTrue(os.path.exists(CONF.signing.keyfile))
def test_create_ssl_certs(self):
ssl = openssl... | test_create_pki_certs | identifier_name |
test_cert_setup.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# 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... |
def test_create_pki_certs(self):
pki = openssl.ConfigurePKI(None, None)
pki.run()
self.assertTrue(os.path.exists(CONF.signing.certfile))
self.assertTrue(os.path.exists(CONF.signing.ca_certs))
self.assertTrue(os.path.exists(CONF.signing.keyfile))
def test_create_ssl_cer... | self.opt_in_group('signing', token_format='PKI')
self.opt_in_group('signing', certfile='invalid')
user = {
'id': 'fake1',
'name': 'fake1',
'password': 'fake1',
'domain_id': DEFAULT_DOMAIN_ID
}
body_dict = {
'passwordCredentials'... | identifier_body |
test_cert_setup.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack LLC
#
# 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... | import os
import shutil
from keystone.common import openssl
from keystone import exception
from keystone import test
from keystone import token
import default_fixtures
ROOTDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SSLDIR = "%s/tests/ssl/" % ROOTDIR
CONF = test.CONF
DEFAULT_DOMAIN_ID = CONF.i... | random_line_split | |
farmer-wife.tsx | import React from 'react'
export default function FarmerWife() | {
return (
<symbol
id='maphubs-icon-farmer-wife'
viewBox='0 0 124.836 308.19'
preserveAspectRatio='xMidYMid meet'
>
<g>
<path d='M40.3,38.587c0.089-0.605,0.197-1.211,0.338-1.817C43.01,26.586,51.958,19.475,62.4,19.475 c1.705,0,3.417,0.197,5.089,0.586c9.255,2.155,15.823,9.805,1... | identifier_body | |
farmer-wife.tsx | import React from 'react'
export default function | () {
return (
<symbol
id='maphubs-icon-farmer-wife'
viewBox='0 0 124.836 308.19'
preserveAspectRatio='xMidYMid meet'
>
<g>
<path d='M40.3,38.587c0.089-0.605,0.197-1.211,0.338-1.817C43.01,26.586,51.958,19.475,62.4,19.475 c1.705,0,3.417,0.197,5.089,0.586c9.255,2.155,15.823,9.80... | FarmerWife | identifier_name |
HeroCard.ts | import Card from "./Card";
export default class HeroCard extends Card {
public premium = false;
public bodyTextColor = "black";
public bodyTextCoords = {
dx: 143,
dy: 627,
dWidth: 376,
dHeight: 168,
sWidth: 376,
sHeight: 168,
};
public cardFoundationAsset = null;
public cardFoundationCoords = null;
... |
}
| {
return {
dx: 247,
dy: 625,
dWidth: 170,
dHeight: 170,
};
} | identifier_body |
HeroCard.ts | import Card from "./Card";
export default class HeroCard extends Card {
public premium = false;
public bodyTextColor = "black";
public bodyTextCoords = {
dx: 143,
dy: 627,
dWidth: 376,
dHeight: 168,
sWidth: 376,
sHeight: 168,
};
public cardFoundationAsset = null;
public cardFoundationCoords = null;
... | else {
return {dx: 556, dy: 825};
}
}
public getWatermarkCoords() {
return {
dx: 247,
dy: 625,
dWidth: 170,
dHeight: 170,
};
}
}
| {
return {dx: 554, dy: 822};
} | conditional_block |
HeroCard.ts | import Card from "./Card";
export default class HeroCard extends Card {
public premium = false;
public bodyTextColor = "black";
public bodyTextCoords = {
dx: 143,
dy: 627,
dWidth: 376,
dHeight: 168,
sWidth: 376,
sHeight: 168,
};
public cardFoundationAsset = null;
public cardFoundationCoords = null;
... | public artClipPolygon = [
{x: 334, y: 134},
{x: 369, y: 143},
{x: 406, y: 164},
{x: 435, y: 187},
{x: 453, y: 213},
{x: 469, y: 245},
{x: 479, y: 270},
{x: 481, y: 290},
{x: 483, y: 332},
{x: 483, y: 380},
{x: 483, y: 438},
{x: 484, y: 485},
{x: 435, y: 473},
{x: 389, y: 467},
{x: 346, y:... | }; | random_line_split |
HeroCard.ts | import Card from "./Card";
export default class | extends Card {
public premium = false;
public bodyTextColor = "black";
public bodyTextCoords = {
dx: 143,
dy: 627,
dWidth: 376,
dHeight: 168,
sWidth: 376,
sHeight: 168,
};
public cardFoundationAsset = null;
public cardFoundationCoords = null;
public baseCardFrameAsset = "frame-hero-";
public baseCa... | HeroCard | identifier_name |
clients.rs | // Learn stuff about our users.
+ my name is *
- <set name=<formal>>Nice to meet you, <get name>.
- <set name=<formal>><get name>, nice to meet you.
+ my name is <bot master>
- <set name=<bot master>>That's my master's name too.
+ my name is <bot name>
- <set name=<bot name>>What a coincidence! That's my name too!
-... |
+ i have a girlfriend
- <set status=girlfriend>What's her name?
+ i have a boyfriend
- <set status=boyfriend>What's his name?
+ *
% whats her name
- <set spouse=<formal>>That's a pretty name.
+ *
% whats his name
- <set spouse=<formal>>That's a cool name.
+ my (girlfriend|boyfriend)* name is *
- <set spouse=<forma... | + my favorite * is *
- <set fav<star1>=<star2>>Why is it your favorite?
+ i am single
- <set status=single><set spouse=nobody>I am too. | random_line_split |
main.py | from __future__ import unicode_literals
import json
import os
from devpi_common.request import new_requests_session
from devpi_slack import __version__
def devpiserver_indexconfig_defaults():
return {"slack_icon": None, "slack_hook": None, "slack_user": None}
def devpiserver_on_upload_sync(log, application_u... | # -*- coding: utf-8 -*- | random_line_split | |
main.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import os
from devpi_common.request import new_requests_session
from devpi_slack import __version__
def devpiserver_indexconfig_defaults():
return {"slack_icon": None, "slack_hook": None, "slack_user": None}
def devpiserver_on_upload... |
session = new_requests_session(agent=("devpi-slack", __version__))
try:
r = session.post(
slack_hook,
data={
'payload': json.dumps({
"text": "Uploaded {}=={} to {}".format(
project,
version,
... | return | conditional_block |
main.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import os
from devpi_common.request import new_requests_session
from devpi_slack import __version__
def devpiserver_indexconfig_defaults():
|
def devpiserver_on_upload_sync(log, application_url, stage, project, version):
slack_hook = stage.ixconfig.get("slack_hook") or os.getenv("SLACK_HOOK")
slack_icon = stage.ixconfig.get("slack_icon") or os.getenv(
"SLACK_ICON", "http://doc.devpi.net/latest/_static/devpicat.jpg")
slack_user = stage.... | return {"slack_icon": None, "slack_hook": None, "slack_user": None} | identifier_body |
main.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import os
from devpi_common.request import new_requests_session
from devpi_slack import __version__
def devpiserver_indexconfig_defaults():
return {"slack_icon": None, "slack_hook": None, "slack_user": None}
def | (log, application_url, stage, project, version):
slack_hook = stage.ixconfig.get("slack_hook") or os.getenv("SLACK_HOOK")
slack_icon = stage.ixconfig.get("slack_icon") or os.getenv(
"SLACK_ICON", "http://doc.devpi.net/latest/_static/devpicat.jpg")
slack_user = stage.ixconfig.get(
"slack_user... | devpiserver_on_upload_sync | identifier_name |
setup.py | from setuptools import setup, find_packages
setup(
name = 'django-dzenlog',
version = __import__('django_dzenlog').__version__,
description = '''Django Dzenlog is a set of models and templates, which can be '''
'''used to create blogs with different kinds media.''',
long_description =... | For example, for can create a blog with two post types: textual
posts and links to internet resources. In that case, all you need
is to define two models: `TextPost` and `LinkPost`. Each of these
models should be derived from `django_dzenlog.models.GeneralPost`.
Features
========
* Simple way to add new types of post... | random_line_split | |
controllers.js | var cartApp = angular.module('cartApp', []);
cartApp.controller('cartCtrl', function($scope, $http) {
$scope.refreshCart = function(cartId) {
$http.get('/webstore/rest/cart/' + $scope.cartId)
.success(function(data) {
$scope.cart = data;
});
}; | $http.delete('/webstore/rest/cart/' + $scope.cartId)
.success(function(data) {
$scope.refreshCart($scope.cartId);
});
};
$scope.initCartId = function(cartId) {
$scope.cartId = cartId;
$scope.refreshCart($scope.cartId);
};
$scope.addToCar... |
$scope.clearCart = function() { | random_line_split |
getRendererFrom.ts | /* eslint-disable no-underscore-dangle */
import { OPT_OUT } from '../../shared/constants';
import {
AddonOptions,
AnyFunctionReturns,
ContextNode,
GenericProp,
PropsMap,
} from '../../shared/types.d';
/**
* @private
* Aggregate component vNodes with activated props in a descending order,
* based on the g... | // reverse the array to get the correct wrapping sequence (i.e. left(right))
.reverse()
.reduce((acc, C, index) => h(C, options.deep || index === last ? props : null, acc), vNode);
};
/**
* @nosideeffects
* Aggregate aggregated-components among all contextual nodes in a descending order;
* t... | ? vNode
: components
// shallow clone the array since .reverse() is not pure
.concat() | random_line_split |
commands.py | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
finally:
environ['ASPERA_SCP_PASS'] = old_ascp_pass
LogEntry.create('Runtime',
('Submission of sequences of pre_processed_id: '
'%d completed successfully' %
preprocessed_data_id))
# s... | try:
stdout, stderr, _ = system_call(cmd)
except Exception as e:
stdout = ''
stderr = str(e)
le = LogEntry.create(
'Fatal', "Command: %s\nError: %s\n" % (cmd,
... | conditional_block |
commands.py | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | """Submit artifact to VAMPS
Parameters
----------
artifact_id : int
The artifact id
Raises
------
ComputeError
- If the artifact cannot be submitted to VAMPS
- If the artifact is associated with more than one prep template
"""
artifact = Artifact(artifact_id)
... | identifier_body | |
commands.py | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | ebi_submission.study.ebi_study_accession = st_acc
if sa_acc:
ebi_submission.sample_template.ebi_sample_accessions = sa_acc
if bio_acc:
ebi_submission.sample_template.biosample_accessions = bio_acc
if ex_acc:
ebi_submissi... | ebi_submission.study.ebi_submission_status = 'submitted'
if action == 'ADD':
if st_acc: | random_line_split |
commands.py | # -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... | (artifact_id):
"""Submit artifact to VAMPS
Parameters
----------
artifact_id : int
The artifact id
Raises
------
ComputeError
- If the artifact cannot be submitted to VAMPS
- If the artifact is associated with more than one prep template
"""
artifact = Artif... | submit_VAMPS | identifier_name |
utils.py | # -*- coding: utf-8 -*-
import re
from django.utils.translation import ugettext_lazy as _
from .router import Patterns
HTTP_STATUS_CODES = (
# Infomational
(100, _('Continue')),
(101, _('Switching Protocols')),
(102, _('Processing (WebDAV)')),
# Success
(200, _('OK')),
(201, _('Created')... | '''
Calculate the verbose_name by converting from InitialCaps to
"lowercase with spaces".
'''
return re.sub(
'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))',
' \\1',
class_name,
).strip() | identifier_body | |
utils.py | # -*- coding: utf-8 -*-
import re
from django.utils.translation import ugettext_lazy as _
from .router import Patterns
HTTP_STATUS_CODES = (
# Infomational
(100, _('Continue')),
(101, _('Switching Protocols')),
(102, _('Processing (WebDAV)')),
# Success
(200, _('OK')),
(201, _('Created')... | (class_name):
'''
Calculate the verbose_name by converting from InitialCaps to
"lowercase with spaces".
'''
return re.sub(
'(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))',
' \\1',
class_name,
).strip()
| get_verbose_name | identifier_name |
utils.py | # -*- coding: utf-8 -*-
import re
from django.utils.translation import ugettext_lazy as _
from .router import Patterns
HTTP_STATUS_CODES = (
# Infomational
(100, _('Continue')),
(101, _('Switching Protocols')),
(102, _('Processing (WebDAV)')),
# Success
(200, _('OK')),
(201, _('Created')... | (423, _('Locked (WebDAV)')),
(424, _('Failed Dependency (WebDAV)')),
(425, _('Unordered Collection')),
(426, _('Upgrade Required')),
(449, _('Retry With')),
# Server Error
(500, _('Internal Server Error')),
(501, _('Not Implemented')),
(502, _('Bad Gateway')),
(503, _('Service U... | (415, _('Unsupported Media Type')),
(416, _('Requested Range Not Satisfiable')),
(417, _('Expectation Failed')),
(418, _('I\'m a teapot')), # April Fools
(422, _('Unprocessable Entity (WebDAV)')), | random_line_split |
views.py | from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth.views import logout_then_login, LoginView
from django.contrib.auth import authenticate, login
from django.contrib.flatpages.models import FlatPage
from django.views.decora... |
@never_cache
def eula(request, readonly=True, redirect_to=None):
redirect_to = redirect_to or settings.LOGIN_REDIRECT_URL
if request.method == 'POST':
# only if these agree do we let them pass, otherwise they get logged out
if request.POST.get('decision', '').lower() == 'i agree':
... | "Displays the login form and handles the login action."
is_IE = False
user_agent = request.META['HTTP_USER_AGENT']
error_message = None
# if the user is already logged-in, simply redirect them to the entry page
if request.user.is_authenticated:
return HttpResponseRedirect(settings.LOGIN_RED... | identifier_body |
views.py | from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth.views import logout_then_login, LoginView
from django.contrib.auth import authenticate, login
from django.contrib.flatpages.models import FlatPage
from django.views.decora... |
else:
error_message = "Too many Login attempts. Please see 'forgot password' link below for instructions"
return render(request, template_name, {
'login_not_allowed': not login_allowed,
'is_IE': is_IE,
'error': error_message,
})
@never_cache
def eula(request, rea... | try:
username = request.POST['email']
password = request.POST['password']
except:
error_message = "Please enter both username and password"
if (not username or not password):
error_message = "Please enter both username and password"... | conditional_block |
views.py | from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth.views import logout_then_login, LoginView
from django.contrib.auth import authenticate, login
from django.contrib.flatpages.models import FlatPage
from django.views.decora... | (request, readonly=True, redirect_to=None):
redirect_to = redirect_to or settings.LOGIN_REDIRECT_URL
if request.method == 'POST':
# only if these agree do we let them pass, otherwise they get logged out
if request.POST.get('decision', '').lower() == 'i agree':
request.user.profile.e... | eula | identifier_name |
views.py | from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib.auth.views import logout_then_login, LoginView
from django.contrib.auth import authenticate, login
from django.contrib.flatpages.models import FlatPage
from django.views.decora... |
@never_cache
def throttled_login(request):
"Displays the login form and handles the login action."
is_IE = False
user_agent = request.META['HTTP_USER_AGENT']
error_message = None
# if the user is already logged-in, simply redirect them to the entry page
if request.user.is_authenticated:
... |
import re | random_line_split |
mod_dir_path.rs | // Copyright 2012-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... | {
assert_eq!(mod_dir_simple::syrup::foo(), 10);
#[path = "auxiliary"]
mod foo {
mod two_macros_2;
}
#[path = "auxiliary"]
mod bar {
macro_rules! m { () => { mod two_macros_2; } }
m!();
}
} | identifier_body | |
mod_dir_path.rs | // Copyright 2012-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... | () {
assert_eq!(mod_dir_simple::syrup::foo(), 10);
#[path = "auxiliary"]
mod foo {
mod two_macros_2;
}
#[path = "auxiliary"]
mod bar {
macro_rules! m { () => { mod two_macros_2; } }
m!();
}
}
| main | identifier_name |
mod_dir_path.rs | // Copyright 2012-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... | mod foo {
mod two_macros_2;
}
#[path = "auxiliary"]
mod bar {
macro_rules! m { () => { mod two_macros_2; } }
m!();
}
} |
pub fn main() {
assert_eq!(mod_dir_simple::syrup::foo(), 10);
#[path = "auxiliary"] | random_line_split |
sensor.py | """Get ride details and liveboard details for NMBS (Belgian railway)."""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_NAME,
CONF_SHOW_ON_MAP,
)
import home... | (self):
"""Return the state of the device."""
return self._state
@property
def station_coordinates(self):
"""Get the lat, long coordinates for station."""
if self._state is None or not self._attrs:
return []
latitude = float(self._attrs["departure"]["station... | state | identifier_name |
sensor.py | """Get ride details and liveboard details for NMBS (Belgian railway)."""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_NAME,
CONF_SHOW_ON_MAP,
)
import home... |
class NMBSSensor(Entity):
"""Get the the total travel time for a given connection."""
def __init__(
self, api_client, name, show_on_map, station_from, station_to, excl_vias
):
"""Initialize the NMBS connection sensor."""
self._name = name
self._show_on_map = show_on_map
... | """Get the next train from a station's liveboard."""
def __init__(self, api_client, live_station):
"""Initialize the sensor for getting liveboard data."""
self._station = live_station
self._api_client = api_client
self._attrs = {}
self._state = None
@property
def n... | identifier_body |
sensor.py | """Get ride details and liveboard details for NMBS (Belgian railway)."""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_NAME,
CONF_SHOW_ON_MAP,
)
import home... |
attrs = {
"departure": f"In {departure} minutes",
"destination": self._station_to,
"direction": self._attrs["departure"]["direction"]["name"],
"platform_arriving": self._attrs["arrival"]["platform"],
"platform_departing": self._attrs["departure"]["pla... | if self._state is None or not self._attrs:
return None
delay = get_delay_in_minutes(self._attrs["departure"]["delay"])
departure = get_time_until(self._attrs["departure"]["time"]) | random_line_split |
sensor.py | """Get ride details and liveboard details for NMBS (Belgian railway)."""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CONF_NAME,
CONF_SHOW_ON_MAP,
)
import home... |
if delay > 0:
attrs["delay"] = f"{delay} minutes"
return attrs
@property
def state(self):
"""Return the state of the device."""
return self._state
@property
def station_coordinates(self):
"""Get the lat, long coordinates for station."""
if... | via = self._attrs["vias"]["via"][0]
attrs["via"] = via["station"]
attrs["via_arrival_platform"] = via["arrival"]["platform"]
attrs["via_transfer_platform"] = via["departure"]["platform"]
attrs["via_transfer_time"] = get_delay_in_minutes(
via["timeBetween"... | conditional_block |
actions.js | * Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your op... | /*
* SonarQube | random_line_split | |
actions.js | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License... | else {
dispatch(receiveValues([{ key }]));
}
dispatch(passValidation(key));
dispatch(stopLoading(key));
})
.catch(e => {
dispatch(stopLoading(key));
parseError(e).then(message => dispatch(failValidation(key, message)));
return Promise.reject();
... | {
dispatch(receiveValues(values));
} | conditional_block |
model.js | /**
* Copyright 2013-present NightWorld.
*
* 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 ag... | console.log('in getAccessToken (bearerToken: ' + bearerToken + ')');
dal.doGet(OAuthAccessTokenTable,
{"accessToken": {"S": bearerToken}}, true, function(err, data) {
if (data && data.expires) {
data.expires = new Date(data.expires * 1000);
}
callback(err, data);
});
};
model.get... | random_line_split | |
regions-close-associated-type-into-object.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | <'a, T: Iter>(v: T) -> Box<X+'a>
where T::Item : 'a
{
let item = v.into_item();
Box::new(item) // OK, T::Item : 'a is declared
}
fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<X+'a>
where T::Item : Clone
{
let item = Clone::clone(w);
Box::new(item) // OK, T::Item : 'a is implied
}
fn ok3<'a... | ok1 | identifier_name |
regions-close-associated-type-into-object.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
fn ok2<'a, T: Iter>(v: &T, w: &'a T::Item) -> Box<X+'a>
where T::Item : Clone
{
let item = Clone::clone(w);
Box::new(item) // OK, T::Item : 'a is implied
}
fn ok3<'a, T: Iter>(v: &'a T) -> Box<X+'a>
where T::Item : Clone + 'a
{
let item = Clone::clone(v.as_item());
Box::new(item) // OK, T::It... | {
let item = v.into_item();
Box::new(item) // OK, T::Item : 'a is declared
} | identifier_body |
regions-close-associated-type-into-object.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let item = Clone::clone(w);
Box::new(item) // OK, T::Item : 'a is implied
}
fn ok3<'a, T: Iter>(v: &'a T) -> Box<X+'a>
where T::Item : Clone + 'a
{
let item = Clone::clone(v.as_item());
Box::new(item) // OK, T::Item : 'a was declared
}
fn meh1<'a, T: Iter>(v: &'a T) -> Box<X+'a>
where T::Item ... | where T::Item : Clone
{ | random_line_split |
object_proxy.js | /**
@module ember
@submodule ember-runtime
*/
import Ember from "ember-metal/core"; // Ember.assert
import {get} from "ember-metal/property_get";
import {set} from "ember-metal/property_set";
import {meta} from "ember-metal/utils";
import {addObserver, removeObserver, addBeforeObserver, removeBeforeObserver} from "embe... |
proxy.get('fullName'); // 'Tom Dale'
```
@class ObjectProxy
@namespace Ember
@extends Ember.Object
*/
var ObjectProxy = EmberObject.extend({
/**
The object whose properties will be forwarded.
@property content
@type Ember.Object
@default null
*/
content: null,
_contentDidChange: ob... | proxy.get('fullName'); // undefined
proxy.set('content', {
firstName: 'Tom', lastName: 'Dale'
}); // triggers property change for fullName on proxy | random_line_split |
object_proxy.js | /**
@module ember
@submodule ember-runtime
*/
import Ember from "ember-metal/core"; // Ember.assert
import {get} from "ember-metal/property_get";
import {set} from "ember-metal/property_set";
import {meta} from "ember-metal/utils";
import {addObserver, removeObserver, addBeforeObserver, removeBeforeObserver} from "embe... |
/**
`Ember.ObjectProxy` forwards all properties not defined by the proxy itself
to a proxied `content` object.
```javascript
object = Ember.Object.create({
name: 'Foo'
});
proxy = Ember.ObjectProxy.create({
content: object
});
// Access and change existing properties
proxy.get('name') ... | {
var key = contentKey.slice(8); // remove "content."
if (key in this) { return; } // if shadowed in proxy
propertyDidChange(this, key);
} | identifier_body |
object_proxy.js | /**
@module ember
@submodule ember-runtime
*/
import Ember from "ember-metal/core"; // Ember.assert
import {get} from "ember-metal/property_get";
import {set} from "ember-metal/property_set";
import {meta} from "ember-metal/utils";
import {addObserver, removeObserver, addBeforeObserver, removeBeforeObserver} from "embe... | (content, contentKey) {
var key = contentKey.slice(8); // remove "content."
if (key in this) { return; } // if shadowed in proxy
propertyWillChange(this, key);
}
function contentPropertyDidChange(content, contentKey) {
var key = contentKey.slice(8); // remove "content."
if (key in this) { return; } // if sh... | contentPropertyWillChange | identifier_name |
object_proxy.js | /**
@module ember
@submodule ember-runtime
*/
import Ember from "ember-metal/core"; // Ember.assert
import {get} from "ember-metal/property_get";
import {set} from "ember-metal/property_set";
import {meta} from "ember-metal/utils";
import {addObserver, removeObserver, addBeforeObserver, removeBeforeObserver} from "embe... |
var content = get(this, 'content');
Ember.assert(EmberStringUtils.fmt("Cannot delegate set('%@', %@) to the 'content' property of object proxy %@: its 'content' is undefined.", [key, value, this]), content);
return set(content, key, value);
}
});
export default ObjectProxy;
| {
// if marked as prototype then just defineProperty
// rather than delegate
defineProperty(this, key, null, value);
return value;
} | conditional_block |
env.py | from __future__ import with_statement
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Pyth... | run_migrations_online() | conditional_block | |
env.py | from __future__ import with_statement
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides | # This line sets up loggers basically.
fileConfig(config.config_file_name)
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
target_metadata = None
# other values from the config, defined by the needs of env.py,
# can be acquired... | # access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging. | random_line_split |
env.py | from __future__ import with_statement
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Pyth... | ():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool)
with co... | run_migrations_online | identifier_name |
env.py | from __future__ import with_statement
from logging.config import fileConfig
from alembic import context
from sqlalchemy import engine_from_config, pool
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Pyth... |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass... | """Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script outp... | identifier_body |
builder.rs | use num::{Integer, NumCast, Unsigned};
use std::hash::Hash;
use typenum::NonZero;
use crate::buffer::{BufferError, MeshBuffer};
use crate::builder::{FacetBuilder, MeshBuilder, SurfaceBuilder};
use crate::constant::{Constant, ToType, TypeOf};
use crate::geometry::{FromGeometry, IntoGeometry};
use crate::index::{Flat, G... |
}
impl<P, G> FacetBuilder<P::Vertex> for BufferBuilder<P, G>
where
P: Grouping<Group = P> + Topological,
P::Vertex: Copy + Hash + Integer + Unsigned,
Vec<P>: IndexBuffer<P>,
{
type Facet = ();
type Key = ();
fn insert_facet<T, U>(&mut self, keys: T, _: U) -> Result<Self::Key, Self::Error>
... | {
let keys = keys.as_ref();
if keys.len() == N {
self.indices.extend(keys.iter());
Ok(())
}
else {
// TODO: These numbers do not necessarily represent arity (i.e., the
// number of edges of each topological structure). Use a
... | identifier_body |
builder.rs | use num::{Integer, NumCast, Unsigned};
use std::hash::Hash;
use typenum::NonZero;
use crate::buffer::{BufferError, MeshBuffer};
use crate::builder::{FacetBuilder, MeshBuilder, SurfaceBuilder};
use crate::constant::{Constant, ToType, TypeOf};
use crate::geometry::{FromGeometry, IntoGeometry};
use crate::index::{Flat, G... | (self) -> Self::Abort {}
}
| abort | identifier_name |
builder.rs | use num::{Integer, NumCast, Unsigned};
use std::hash::Hash;
use typenum::NonZero;
use crate::buffer::{BufferError, MeshBuffer};
use crate::builder::{FacetBuilder, MeshBuilder, SurfaceBuilder};
use crate::constant::{Constant, ToType, TypeOf};
use crate::geometry::{FromGeometry, IntoGeometry};
use crate::index::{Flat, G... |
else {
// TODO: These numbers do not necessarily represent arity (i.e., the
// number of edges of each topological structure). Use a
// different error variant to express this.
Err(BufferError::ArityConflict {
expected: N,
... | {
self.indices.extend(keys.iter());
Ok(())
} | conditional_block |
builder.rs | use crate::builder::{FacetBuilder, MeshBuilder, SurfaceBuilder};
use crate::constant::{Constant, ToType, TypeOf};
use crate::geometry::{FromGeometry, IntoGeometry};
use crate::index::{Flat, Grouping, IndexBuffer};
use crate::primitive::Topological;
use crate::transact::{ClosedInput, Transact};
use crate::Arity;
// TOD... | use num::{Integer, NumCast, Unsigned};
use std::hash::Hash;
use typenum::NonZero;
use crate::buffer::{BufferError, MeshBuffer}; | random_line_split | |
HealPetPet.py | from neolib.plots.Step import Step
from neolib.NST import NST
import time
class HealPetPet(Step):
_paths = {
'links': '//*[@id="content"]/table/tr/td[2]//a/@href',
'img': '//*[@id="content"]/table/tr/td[2]/div/img/@src',
'cert': '//area/@href',
}
_HEALS = {
'http://images... |
f = open('test.html', 'w', encoding='utf-8')
f.write(pg.content)
f.close()
if len(self._xpath('cert', pg)) > 0:
print('Found certificate!')
url = self._base_url + self._xpath('cert', pg)[0]
pg = self._usr.get_page(url)
... | pg = self._usr.get_page(self.link[0]) | conditional_block |
HealPetPet.py | from neolib.plots.Step import Step
from neolib.NST import NST
import time
class HealPetPet(Step):
_paths = {
'links': '//*[@id="content"]/table/tr/td[2]//a/@href',
'img': '//*[@id="content"]/table/tr/td[2]/div/img/@src',
'cert': '//area/@href',
}
_HEALS = {
'http://images... | check = ''
for i in range(0, 11):
if check:
pg = self._usr.get_page(check)
else:
pg = self._usr.get_page(self.link[0])
f = open('test.html', 'w', encoding='utf-8')
f.write(pg.content)
f.close()
if len(self.... | identifier_body | |
HealPetPet.py | from neolib.plots.Step import Step
from neolib.NST import NST
import time
class HealPetPet(Step):
_paths = {
'links': '//*[@id="content"]/table/tr/td[2]//a/@href',
'img': '//*[@id="content"]/table/tr/td[2]/div/img/@src',
'cert': '//area/@href',
}
_HEALS = {
'http://images... | (self, last_pg=None):
# Heal the PetPet 10 times to get the certificate
check = ''
for i in range(0, 11):
if check:
pg = self._usr.get_page(check)
else:
pg = self._usr.get_page(self.link[0])
f = open('test.html', 'w', encoding=... | execute | identifier_name |
HealPetPet.py | from neolib.plots.Step import Step
from neolib.NST import NST
import time
class HealPetPet(Step):
_paths = {
'links': '//*[@id="content"]/table/tr/td[2]//a/@href',
'img': '//*[@id="content"]/table/tr/td[2]/div/img/@src',
'cert': '//area/@href',
}
_HEALS = {
'http://images... | 'http://images.neopets.com/altador/misc/petpet_act_d_42b934a33b.gif': 3,
}
def __init__(self, usr):
super().__init__(usr, '', '', False)
# Setup link
self.link = ['http://www.neopets.com/altador/petpet.phtml?ppheal=1',
'http://www.neopets.com/altador/petpet... | 'http://images.neopets.com/altador/misc/petpet_act_c_5f4438778c.gif': 2, | random_line_split |
hanna.persona.ts | import { HttpErrorResponse } from '@angular/common/http';
import { Injector } from '@angular/core';
import { Scope } from '@dev/translatr-model';
import {
AccessTokenService,
errorMessage,
KeyService,
LocaleService,
MessageService,
ProjectService,
UserService
} from '@dev/translatr-sdk';
import { pickRand... | extends Persona {
private readonly accessTokenService: AccessTokenService;
private readonly userService: UserService;
private readonly projectService: ProjectService;
private readonly localeService: LocaleService;
private readonly keyService: KeyService;
private readonly messageService: MessageService;
... | HannaPersona | identifier_name |
hanna.persona.ts | import { HttpErrorResponse } from '@angular/common/http';
import { Injector } from '@angular/core';
import { Scope } from '@dev/translatr-model'; | KeyService,
LocaleService,
MessageService,
ProjectService,
UserService
} from '@dev/translatr-sdk';
import { pickRandomly } from '@translatr/utils';
import { Observable, of } from 'rxjs';
import { catchError, concatMap, filter, map } from 'rxjs/operators';
import { chooseAccessToken } from '../access-token';
... | import {
AccessTokenService,
errorMessage, | random_line_split |
util.rs | use fastrand;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::{io, iter::repeat_with};
use crate::error::IoResultExt;
fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
buf.push(pref... | <F, R>(
base: &Path,
prefix: &OsStr,
suffix: &OsStr,
random_len: usize,
f: F,
) -> io::Result<R>
where
F: Fn(PathBuf) -> io::Result<R>,
{
let num_retries = if random_len != 0 {
crate::NUM_RETRIES
} else {
1
};
for _ in 0..num_retries {
let path = base.joi... | create_helper | identifier_name |
util.rs | use fastrand;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::{io, iter::repeat_with};
use crate::error::IoResultExt;
fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
buf.push(pref... | ;
for _ in 0..num_retries {
let path = base.join(tmpname(prefix, suffix, random_len));
return match f(path) {
Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
res => res,
};
}
Err(io::Error::new(
io::ErrorKind::AlreadyExists,
... | {
1
} | conditional_block |
util.rs | use fastrand;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::{io, iter::repeat_with};
use crate::error::IoResultExt;
fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
buf.push(pref... | io::ErrorKind::AlreadyExists,
"too many temporary files exist",
))
.with_err_path(|| base)
} | };
}
Err(io::Error::new( | random_line_split |
util.rs | use fastrand;
use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use std::{io, iter::repeat_with};
use crate::error::IoResultExt;
fn tmpname(prefix: &OsStr, suffix: &OsStr, rand_len: usize) -> OsString {
let mut buf = OsString::with_capacity(prefix.len() + suffix.len() + rand_len);
buf.push(pref... | {
let num_retries = if random_len != 0 {
crate::NUM_RETRIES
} else {
1
};
for _ in 0..num_retries {
let path = base.join(tmpname(prefix, suffix, random_len));
return match f(path) {
Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
... | identifier_body | |
378_kth_smallest_element_in_a_sorted_matrix.py | # 378. Kth Smallest Element in a Sorted Matrix
#
# Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
#
# Note that it is the kth smallest element in the sorted order, not the kth distinct element.
#
# Example:
#
# matrix = [
# [ 1, 5,... | (self, matrix, k):
"""
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
# heapq.merge: Merge multiple sorted inputs into a single sorted output
# (for example, merge timestamped entries from multiple log files).
# Returns an iterator over the sor... | kthSmallest | identifier_name |
378_kth_smallest_element_in_a_sorted_matrix.py | # 378. Kth Smallest Element in a Sorted Matrix
#
# Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
#
# Note that it is the kth smallest element in the sorted order, not the kth distinct element.
#
# Example:
#
# matrix = [
# [ 1, 5,... |
# Maintain a min-heap with k element, initialized by the elements of the first row.
# Since it is a min-heap, and note the property that rows and columns are already sorted in ascending order,
# the heap root after popping k-1 times is the k-th smallest element of the whole matrix.
# When popping the ... | """
:type matrix: List[List[int]]
:type k: int
:rtype: int
"""
# heapq.merge: Merge multiple sorted inputs into a single sorted output
# (for example, merge timestamped entries from multiple log files).
# Returns an iterator over the sorted values.
return ... | identifier_body |
378_kth_smallest_element_in_a_sorted_matrix.py | # 378. Kth Smallest Element in a Sorted Matrix
#
# Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
#
# Note that it is the kth smallest element in the sorted order, not the kth distinct element.
#
# Example:
#
# matrix = [
# [ 1, 5,... |
return L
sol = Solution()
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
k = 8
print(sol.kthSmallest(matrix, k))
| L = mid + 1 | conditional_block |
378_kth_smallest_element_in_a_sorted_matrix.py | # 378. Kth Smallest Element in a Sorted Matrix
#
# Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix.
#
# Note that it is the kth smallest element in the sorted order, not the kth distinct element.
#
# Example:
#
# matrix = [
# [ 1, 5,... | j -= 1
count += j+1
if count >= k:
R = mid
else:
L = mid + 1
return L
sol = Solution()
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
]
k = 8
print(sol.kthSmallest(matrix, k)) | random_line_split | |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | (&self) -> @ast::Expr {
if self.prog.prefix.len() == 0 {
self.empty_block()
} else {
quote_expr!(self.cx,
if clist.size == 0 {
let haystack = self.input.as_bytes().slice_from(self.ic);
match find_prefix(prefix_bytes, haystac... | check_prefix | identifier_name |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let arms = self.prog.insts.iter().enumerate().map(|(pc, inst)| {
let nextpc = pc + 1;
let body = match *inst {
Match => {
quote_expr!(self.cx, {
match self.which {
Exists => {
... | random_line_split | |
lib.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... |
}
/// Looks for a single string literal and returns it.
/// Otherwise, logs an error with cx.span_err and returns None.
fn parse(cx: &mut ExtCtxt, tts: &[ast::TokenTree]) -> Option<~str> {
let mut parser = parse::new_parser_from_tts(cx.parse_sess(), cx.cfg(),
Vec::f... | {
let exprs = xs.map(|x| to_expr(self.cx, x)).collect();
self.cx.expr_vec(self.sp, exprs)
} | identifier_body |
soccer_ball.py | # Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
self.initialize_entity_trackers()
def after_substep(self, physics, unused_random_state):
"""Resolve contacts and update ball-player contact trackers."""
if self._hit:
# Ball has already registered a valid contact within step (during one of
# previous after_substep calls).
return
... | geom_id = physics.model.name2id(geom.full_identifier, 'geom')
self._geom_id_to_player[geom_id] = player | conditional_block |
soccer_ball.py | # Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
def after_substep(self, physics, unused_random_state):
"""Resolve contacts and update ball-player contact trackers."""
if self._hit:
# Ball has already registered a valid contact within step (during one of
# previous after_substep calls).
return
# Iterate through all contacts to find ... | self._geom_id = physics.model.name2id(self._geom.full_identifier, 'geom')
self._geom_id_to_player = {}
for player in self._players:
geoms = player.walker.mjcf_model.find_all('geom')
for geom in geoms:
geom_id = physics.model.name2id(geom.full_identifier, 'geom')
self._geom_id_to_play... | identifier_body |
soccer_ball.py | # Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | return self._hit
@property
def repossessed(self):
"""Indicates if the ball has been repossessed by a different player.
For a timeline shown below:
..., agent.step, simulation, agent.step, ...
Returns:
True if the ball is hit by a registered player during simulation step
and th... | """ | random_line_split |
soccer_ball.py | # Copyright 2019 The dm_control Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... | (self, physics, random_state):
super().after_step(physics, random_state)
pos = physics.bind(self._geom).xpos
if self._hit:
# SoccerBall is hit on this step. Update dist_between_last_hits
# to dist_since_last_hit before resetting dist_since_last_hit.
self._dist_between_last_hits = self._dis... | after_step | identifier_name |
test_lms_matlab_problem.py | # -*- coding: utf-8 -*-
"""
Test for matlab problems
"""
import time
from ...pages.lms.matlab_problem import MatlabProblemPage
from ...fixtures.course import XBlockFixtureDesc
from ...fixtures.xqueue import XQueueResponseFixture
from .test_lms_problems import ProblemsTest
from textwrap import dedent
class | (ProblemsTest):
"""
Tests that verify matlab problem "Run Code".
"""
def get_problem(self):
"""
Create a matlab problem for the test.
"""
problem_data = dedent("""
<problem markdown="null">
<text>
<p>
... | MatlabProblemTest | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.