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 |
|---|---|---|---|---|
cli.py |
from flexget import options
from flexget.event import event
from flexget.terminal import TerminalTable, TerminalTableError, table_parser, console
from flexget.utils.database import Session
from . import db
def do_cli(manager, options):
"""Handle regexp-list cli"""
action_map = {
'all': action_all,
... | from __future__ import unicode_literals, division, absolute_import
import re
from argparse import ArgumentParser, ArgumentTypeError
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin | random_line_split | |
cli.py | from __future__ import unicode_literals, division, absolute_import
import re
from argparse import ArgumentParser, ArgumentTypeError
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from flexget import options
from flexget.event import event
from flexget.terminal import TerminalTable, Te... |
else:
console("Regexp {} already exists in list {}".format(options.regexp, regexp_list.name))
def action_del(options):
with Session() as session:
regexp_list = db.get_list_by_exact_name(options.list_name)
if not regexp_list:
console('Could not find regexp list with... | console("Adding regexp {} to list {}".format(options.regexp, regexp_list.name))
db.add_to_list_by_name(regexp_list.name, options.regexp, session=session)
console(
'Successfully added regexp {} to regexp list {} '.format(
options.regexp, regexp_list.name
... | conditional_block |
cli.py | from __future__ import unicode_literals, division, absolute_import
import re
from argparse import ArgumentParser, ArgumentTypeError
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from flexget import options
from flexget.event import event
from flexget.terminal import TerminalTable, Te... | (options):
with Session() as session:
regexp_list = db.get_list_by_exact_name(options.list_name)
if not regexp_list:
console('Could not find regexp list with name {}'.format(options.list_name))
return
regexp = db.get_regexp(list_id=regexp_list.id, regexp=options.regex... | action_del | identifier_name |
cli.py | from __future__ import unicode_literals, division, absolute_import
import re
from argparse import ArgumentParser, ArgumentTypeError
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
from flexget import options
from flexget.event import event
from flexget.terminal import TerminalTable, Te... |
def action_list(options):
"""List regexp list"""
with Session() as session:
regexp_list = db.get_list_by_exact_name(options.list_name)
if not regexp_list:
console('Could not find regexp list with name {}'.format(options.list_name))
return
header = ['Regexp']
... | """ Show all regexp lists """
lists = db.get_regexp_lists()
header = ['#', 'List Name']
table_data = [header]
for regexp_list in lists:
table_data.append([regexp_list.id, regexp_list.name])
table = TerminalTable(options.table_type, table_data)
try:
console(table.output)
excep... | identifier_body |
framed_rectangle.rs | use {
Backend,
Color,
Colorable,
Dimensions,
Frameable,
Scalar,
Sizeable,
Widget,
};
use widget;
/// A filled rectangle widget that may or may not have some frame.
#[derive(Copy, Clone, Debug)]
pub struct | {
/// Data necessary and common for all widget builder types.
pub common: widget::CommonBuilder,
/// Unique styling for the **FramedRectangle**.
pub style: Style,
}
/// Unique kind for the Widget.
pub const KIND: widget::Kind = "FramedRectangle";
widget_style!{
KIND;
/// Unique styling for th... | FramedRectangle | identifier_name |
framed_rectangle.rs | use {
Backend,
Color,
Colorable,
Dimensions,
Frameable,
Scalar,
Sizeable,
Widget,
};
use widget;
/// A filled rectangle widget that may or may not have some frame.
#[derive(Copy, Clone, Debug)]
pub struct FramedRectangle {
/// Data necessary and common for all widget builder types.... | /// Shape styling for the inner rectangle.
- color: Color { theme.shape_color }
/// The thickness of the frame.
- frame: Scalar { theme.frame_width }
/// The color of the frame.
- frame_color: Color { theme.frame_color }
}
}
impl FramedRectangle {
/// Build a ne... | widget_style!{
KIND;
/// Unique styling for the **FramedRectangle** widget.
style Style { | random_line_split |
lib.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | else {
cx.bug("Incorrect number of arguments to `rand` in `derive(Rand)`")
};
let rand_ident = vec!(
cx.ident_of("rand"),
cx.ident_of("Rand"),
cx.ident_of("rand")
);
let rand_call = |cx: &mut ExtCtxt, span| {
cx.expr_call_global(span,
... | {
&substr.nonself_args[0]
} | conditional_block |
lib.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <F>(cx: &mut ExtCtxt,
trait_span: Span,
ctor_path: ast::Path,
summary: &StaticFields,
mut rand_call: F)
-> P<Expr> where
F: FnMut(&mut ExtCtxt, Span) -> P<Expr>,
{
let path = cx.expr_path(ctor_pa... | rand_thing | identifier_name |
lib.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | push: &mut FnMut(Annotatable)) {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("rand", "Rand")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
methods: vec!... |
pub fn expand_deriving_rand(cx: &mut ExtCtxt,
span: Span,
mitem: &MetaItem,
item: &Annotatable, | random_line_split |
lib.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | Borrowed(None, ast::Mutability::Mutable))
),
ret_ty: Self_,
attributes: Vec::new(),
combine_substructure: combine_substructure(Box::new(|a, b, c| {
rand_substructure(a, b, c)
}))
}
... | {
let trait_def = TraitDef {
span: span,
attributes: Vec::new(),
path: Path::new(vec!("rand", "Rand")),
additional_bounds: Vec::new(),
generics: LifetimeBounds::empty(),
is_unsafe: false,
methods: vec!(
MethodDef {
name: "rand",
... | identifier_body |
manage.py | #!/usr/bin/env python
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
... | (coverage=False):
"""Run the unit tests."""
if coverage and not os.environ.get('FLASK_COVERAGE'):
import sys
os.environ['FLASK_COVERAGE'] = '1'
os.execvp(sys.executable, [sys.executable] + sys.argv)
import unittest
import xmlrunner
tests = unittest.TestLoader().discover('test... | test | identifier_name |
manage.py | #!/usr/bin/env python
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
... | Shell(make_context=make_shell_context))
manager.add_command('db', MigrateCommand)
@manager.command
def test(coverage=False):
"""Run the unit tests."""
if coverage and not os.environ.get('FLASK_COVERAGE'):
import sys
os.environ['FLASK_COVERAGE'] = '1'
os.execvp(sys.executable, [sys.... | "shell", | random_line_split |
manage.py | #!/usr/bin/env python
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
... |
@manager.command
def deploy():
"""Run deployment tasks."""
from flask.ext.migrate import upgrade
# migrate database to latest revision
upgrade()
if __name__ == '__main__':
manager.run()
| """Start the application under the code profiler."""
from werkzeug.contrib.profiler import ProfilerMiddleware
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length],
profile_dir=profile_dir)
app.run() | identifier_body |
manage.py | #!/usr/bin/env python
import os
COV = None
if os.environ.get('FLASK_COVERAGE'):
import coverage
COV = coverage.coverage(branch=True, include='app/*')
COV.start()
if os.path.exists('.env'):
print('Importing environment from .env...')
for line in open('.env'):
var = line.strip().split('=')
... |
@manager.command
def profile(length=25, profile_dir=None):
"""Start the application under the code profiler."""
from werkzeug.contrib.profiler import ProfilerMiddleware
app.wsgi_app = ProfilerMiddleware(app.wsgi_app, restrictions=[length],
profile_dir=profile_dir)
... | COV.stop()
COV.save()
print('Coverage Summary:')
COV.report()
basedir = os.path.abspath(os.path.dirname(__file__))
covdir = os.path.join(basedir, 'test-reports/coverage')
COV.html_report(directory=covdir)
print('HTML version: file://%s/index.html' % covdir)
... | conditional_block |
policy_enforcement.py | License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the ... | if is_single:
resp = resp[0]
state.response.json = {key: resp}
def _get_filtered_item(self, request, controller, resource, collection,
data):
neutron_context = request.context.get('neutron_context')
to_exclude = self._exclude_attributes_by_poli... | # we have to set the status_code here to prevent the catch_errors
# middleware from turning this into a 500.
state.response.status_code = 404
return
| random_line_split |
policy_enforcement.py | License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the ... | (self, request, controller, resource, collection,
data):
neutron_context = request.context.get('neutron_context')
to_exclude = self._exclude_attributes_by_policy(
neutron_context, controller, resource, collection, data)
return self._filter_attributes(reques... | _get_filtered_item | identifier_name |
policy_enforcement.py | License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the ... |
msg = _('The resource could not be found.')
raise webob.exc.HTTPNotFound(msg)
def after(self, state):
neutron_context = state.request.context.get('neutron_context')
resource = state.request.context.get('resource')
collection = state.request.context.get('coll... | ctxt.reraise = False | conditional_block |
policy_enforcement.py | License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the ... | action_type = pecan_constants.ACTION_MAP[state.request.method]
if action_type == 'get':
action = controller.plugin_handlers[controller.SHOW]
else:
action = controller.plugin_handlers[action_type]
key = resource if is_single else collection
to_process = [da... | neutron_context = state.request.context.get('neutron_context')
resource = state.request.context.get('resource')
collection = state.request.context.get('collection')
controller = utils.get_controller(state)
if not resource:
# can't filter a resource we don't recognize
... | identifier_body |
scrolleffect.js | // Copyright 2012 Viewfinder Inc. All Rights Reserved.
/**
* @fileoverview efficient vertical scrolling callback. Allows visible scrolling behavior for a very large number
* of objects in the DOM.
*
* @author matt@emailscrubbed.com (Matt Tracy)
*/
(function($, _) {
$.scrollEffect = function ($obj) {
thi... |
});
})(jQuery, _);
| {
$.fn[n] = function() {
var r = old.apply(this, arguments);
debounceRaS();
return r;
};
} | conditional_block |
scrolleffect.js | // Copyright 2012 Viewfinder Inc. All Rights Reserved.
/**
* @fileoverview efficient vertical scrolling callback. Allows visible scrolling behavior for a very large number
* of objects in the DOM.
*
* @author matt@emailscrubbed.com (Matt Tracy)
*/
(function($, _) {
$.scrollEffect = function ($obj) {
thi... | };
var recacheAndScroll = function () {
$.scrollEffect.recacheChildren();
$.scrollEffect.scrollContainers();
};
// During load there is a flurry of DOM modifications - a simple debounce is
// enough to smooth it out completely.
var debounceRaS = _.simpleDebounce(recacheAndScroll);
$(window)... | } else {
se.save(option || {});
}
}); | random_line_split |
index.js | const concat = require('concat-stream')
const test = require('tape')
const fs = require('fs')
const gherkin = require('../')
test('should assert input types', function (t) {
t.plan(3)
const rs = fs.createReadStream(__dirname + '/file.feature')
const ts = gherkin()
const ws = concat({ object: true }, function ... | reason: 'to satisfy my thirst',
scenarios: [ {
given: [ '100 bottles of beer on the wall' ],
scenario: 'Can take a single beer',
then: [ 'there are 99 bottles of beer on the wall' ],
when: [ 'a bottle is taken down' ]
} ]
} ])
})
ts.on('end', t.pass.bind('null'... | t.deepEqual(ast, [ {
perspective: 'drinker',
feature: 'Can drink beer when thirsty',
desire: 'to take beer off the wall', | random_line_split |
access_groups.py | ###################################################################################
#
# Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Documents Access
# (see https://mukit.at).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Le... | #----------------------------------------------------------
@api.depends('directories')
def _compute_count_directories(self):
for record in self:
record.count_directories = len(record.directories) | _inherit = 'muk_security.access_groups'
#----------------------------------------------------------
# Database
#----------------------------------------------------------
directories = fields.Many2many(
comodel_name='muk_dms.directory',
relation='muk_dms_directory_group... | identifier_body |
access_groups.py | ###################################################################################
#
# Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Documents Access
# (see https://mukit.at).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Le... | (self):
for record in self:
record.count_directories = len(record.directories) | _compute_count_directories | identifier_name |
access_groups.py | ###################################################################################
#
# Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Documents Access
# (see https://mukit.at).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Le... | record.count_directories = len(record.directories) | conditional_block | |
access_groups.py | # Copyright (c) 2017-2019 MuK IT GmbH.
#
# This file is part of MuK Documents Access
# (see https://mukit.at).
#
# 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 ... | ###################################################################################
# | random_line_split | |
ex1.py | #Working with variables
import pyaudiogame
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("My Application")
#Here are some variables
#Lets first write one line of text
my_name = "Frastlin"
#now lets write a number
my_age = 42
#now lets write several lines of text
my_song = """
My application tis to be,
the coolest ... |
elif key == "s":
#Here is our number, it will speak when we press s
spk(my_age)
elif key == "d":
#Here is our multiline text example. It will speak when we press d
spk(my_song)
MyApp.logic = logic
MyApp.run() | spk(my_name) | conditional_block |
ex1.py | #Working with variables
import pyaudiogame
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("My Application")
#Here are some variables
#Lets first write one line of text
my_name = "Frastlin"
#now lets write a number
my_age = 42
#now lets write several lines of text
my_song = """
My application tis to be,
the coolest ... | MyApp.logic = logic
MyApp.run() | random_line_split | |
ex1.py | #Working with variables
import pyaudiogame
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("My Application")
#Here are some variables
#Lets first write one line of text
my_name = "Frastlin"
#now lets write a number
my_age = 42
#now lets write several lines of text
my_song = """
My application tis to be,
the coolest ... |
MyApp.logic = logic
MyApp.run() | key = actions['key']
if key == "a":
#Here is our one line of text, it will speak when we press a
spk(my_name)
elif key == "s":
#Here is our number, it will speak when we press s
spk(my_age)
elif key == "d":
#Here is our multiline text example. It will speak when we press d
spk(my_song) | identifier_body |
ex1.py | #Working with variables
import pyaudiogame
spk = pyaudiogame.speak
MyApp = pyaudiogame.App("My Application")
#Here are some variables
#Lets first write one line of text
my_name = "Frastlin"
#now lets write a number
my_age = 42
#now lets write several lines of text
my_song = """
My application tis to be,
the coolest ... | (actions):
key = actions['key']
if key == "a":
#Here is our one line of text, it will speak when we press a
spk(my_name)
elif key == "s":
#Here is our number, it will speak when we press s
spk(my_age)
elif key == "d":
#Here is our multiline text example. It will speak when we press d
spk(my_song)
MyApp... | logic | identifier_name |
index.js | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, defineMessages, injectIntl } from 'react-intl';
import { Card, CardText } from 'material-ui/Card';
import Divider from 'material-ui/Divider';
import Shortcuts from './Shortcuts';
import GeneralSettings from './GeneralSettings';
im... | />
</CardText>
</Card>
<div className="header">
<h2 className="title">
<FormattedMessage {...messages.title} />
</h2>
</div>
<Card>
<CardText>
<GeneralSettings {...props} onChange={onSettingChange} />
<Divider />
... | <ClipboardLink href="chrome://extensions/configureCommands" />
)
}} | random_line_split |
SwitchPhase.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | #: Phase of this SwitchPhase on the “to” (Switch.Terminal.sequenceNumber=2) side. Should be a phase contained in that terminal’s Terminal.phases attribute. Values are: "C", "N", "s1", "B", "s2", "A"
self.phaseSide2 = phaseSide2
#: Used in cases when no Measurement for the sta... | #: Phase of this SwitchPhase on the “from” (Switch.Terminal.sequenceNumber=1) side. Should be a phase contained in that terminal’s Terminal.phases attribute. Values are: "C", "N", "s1", "B", "s2", "A"
self.phaseSide1 = phaseSide1
| random_line_split |
SwitchPhase.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... |
_attrs = ["phaseSide1", "phaseSide2", "normalOpen"]
_attr_types = {"phaseSide1": str, "phaseSide2": str, "normalOpen": bool}
_defaults = {"phaseSide1": "C", "phaseSide2": "C", "normalOpen": False}
_enums = {"phaseSide1": "SinglePhaseKind", "phaseSide2": "SinglePhaseKind"}
_refs = ["Switch"]
_m... | """Initialises a new 'SwitchPhase' instance.
@param phaseSide1: Phase of this SwitchPhase on the “from” (Switch.Terminal.sequenceNumber=1) side. Should be a phase contained in that terminal’s Terminal.phases attribute. Values are: "C", "N", "s1", "B", "s2", "A"
@param phaseSide2: Phas... | identifier_body |
SwitchPhase.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... | (PowerSystemResource):
"""Single phase of a multi-phase switch when its attributes might be different per phase.Single phase of a multi-phase switch when its attributes might be different per phase.
"""
def __init__(self, phaseSide1="C", phaseSide2="C", normalOpen=False, Switch=None, *args, **kw_args):
... | SwitchPhase | identifier_name |
SwitchPhase.py | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... |
Switch = property(getSwitch, setSwitch)
| if self not in self._Switch._SwitchPhases:
self._Switch._SwitchPhases.append(self) | conditional_block |
sanity.rs | use WinVersion;
use super::Cache;
pub fn | (cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might mess up the expansion. This currently means:
- Featur... | sanity_check_features | identifier_name |
sanity.rs | use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might... | } | } | random_line_split |
sanity.rs | use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache) {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might... |
}
if let Some(ref winver) = feat.winver {
if !winver.is_simple() {
for &ref range in winver.ranges() {
weird_vers.insert(range.end);
}
suspect.push("complex-winver");
}
}
if suspect.len() != 0 ... | {
suspect.push("non-desktop-app");
} | conditional_block |
sanity.rs | use WinVersion;
use super::Cache;
pub fn sanity_check_features(cache: &mut Cache) | }
}
if let Some(ref winver) = feat.winver {
if !winver.is_simple() {
for &ref range in winver.ranges() {
weird_vers.insert(range.end);
}
suspect.push("complex-winver");
}
}
if suspec... | {
use std::collections::BTreeSet;
let mut weird_vers = BTreeSet::new();
cache.iter_features(|path, line, &ref feat| {
use features::Partitions;
/*
What we're looking for are any features that might mess up the expansion. This currently means:
- Features with upper limits... | identifier_body |
nodemailer-trap-plugin.js | 'use strict';
const addressParser = require('./utils').addressParser;
const addressFormatter = require('./utils').addressFormatter;
const format = require('string-format');
const escapeStringRegexp = require('escape-string-regexp');
function isValidPassthroughType(passthrough) {
return typeof passthrough === 'funct... | (passthrough, toAddr) {
if (typeof passthrough === 'function') {
return passthrough(toAddr);
}
if (typeof passthrough === 'string') {
passthrough = new RegExp(escapeStringRegexp(passthrough));
}
return passthrough.test(toAddr);
}
function trap(options) {
options = options || {};
const subject ... | shouldPassthrough | identifier_name |
nodemailer-trap-plugin.js | 'use strict';
const addressParser = require('./utils').addressParser;
const addressFormatter = require('./utils').addressFormatter;
const format = require('string-format'); | typeof passthrough === 'string' ||
passthrough instanceof RegExp;
}
function shouldPassthrough(passthrough, toAddr) {
if (typeof passthrough === 'function') {
return passthrough(toAddr);
}
if (typeof passthrough === 'string') {
passthrough = new RegExp(escapeStringRegexp(passthrough));
}
re... | const escapeStringRegexp = require('escape-string-regexp');
function isValidPassthroughType(passthrough) {
return typeof passthrough === 'function' || | random_line_split |
nodemailer-trap-plugin.js | 'use strict';
const addressParser = require('./utils').addressParser;
const addressFormatter = require('./utils').addressFormatter;
const format = require('string-format');
const escapeStringRegexp = require('escape-string-regexp');
function isValidPassthroughType(passthrough) |
function shouldPassthrough(passthrough, toAddr) {
if (typeof passthrough === 'function') {
return passthrough(toAddr);
}
if (typeof passthrough === 'string') {
passthrough = new RegExp(escapeStringRegexp(passthrough));
}
return passthrough.test(toAddr);
}
function trap(options) {
options = opti... | {
return typeof passthrough === 'function' ||
typeof passthrough === 'string' ||
passthrough instanceof RegExp;
} | identifier_body |
nodemailer-trap-plugin.js | 'use strict';
const addressParser = require('./utils').addressParser;
const addressFormatter = require('./utils').addressFormatter;
const format = require('string-format');
const escapeStringRegexp = require('escape-string-regexp');
function isValidPassthroughType(passthrough) {
return typeof passthrough === 'funct... |
// TODO: intercept cc
// TODO: intercept bcc
mail.data.subject = format(subject, toAddrs.join(','), mail.data.subject);
mail.data.to = to;
callback();
};
}
module.exports = trap;
| {
if (!isValidPassthroughType(passthrough)) {
return callback(new Error('options.passthrough can be only a string, regex or function.'));
}
if (toAddrs.length > 1) {
return callback(new Error('options.passthrough can be used with a single recipient only.'));
}
if (shouldP... | conditional_block |
events.js | 'use strict';
import delegate from 'delegate';
import activateTab from './utils/activate-tab';
import getPanel from './utils/get-panel';
module.exports = () => {
/**
* Clicks on tabs | delegate(document.body, '.dqpl-tablist .dqpl-tab', 'click', (e) => {
activateTab(e.delegateTarget);
});
/**
* Keydowns on tabs
*/
delegate(document.body, '.dqpl-tablist .dqpl-tab', 'keydown', (e) => {
const which = e.which;
const tab = e.target;
switch (which) {
case 37:
cas... | */
| random_line_split |
events.js | 'use strict';
import delegate from 'delegate';
import activateTab from './utils/activate-tab';
import getPanel from './utils/get-panel';
module.exports = () => {
/**
* Clicks on tabs
*/
delegate(document.body, '.dqpl-tablist .dqpl-tab', 'click', (e) => {
activateTab(e.delegateTarget);
});
/**
*... |
break;
}
});
/**
* Keydowns on panel
* shortcut for page up to focus panel's tab
*/
delegate(document.body, '.dqpl-panel', 'keydown', (e) => {
if (e.which !== 33) { return; }
const panel = e.target;
const tab = document.querySelector(`[aria-controls="${panel.id}"]`);
if (ta... | {
panel.tabIndex = -1; // ensure its focusable
panel.focus();
} | conditional_block |
cli.py | import click
import requests
@click.command()
@click.argument('url')
@click.option('--show-headers', '-H', is_flag=True, default=False)
@click.option('--show-status', '-S', is_flag=True, default=False)
@click.option('--quiet', '-Q', is_flag=True, default=False)
@click.option('--allow-redirects/--no-allow-redirects', d... | if show_headers:
click.echo(format_headers(response.headers), err=True)
# Show the response body
if not quiet:
click.echo(response.text)
if __name__ == '__main__':
cli()
def format_headers(headers):
formatted = ['{0}: {1}'.format(k, v) for k, v in headers.items()]
return '\n'.... | status_color = status_colors.get(int(response.status_code) / 100)
click.secho('Status: {0}'.format(response.status_code), err=True, fg=status_color)
# Show the response headers | random_line_split |
cli.py | import click
import requests
@click.command()
@click.argument('url')
@click.option('--show-headers', '-H', is_flag=True, default=False)
@click.option('--show-status', '-S', is_flag=True, default=False)
@click.option('--quiet', '-Q', is_flag=True, default=False)
@click.option('--allow-redirects/--no-allow-redirects', d... | (headers):
formatted = ['{0}: {1}'.format(k, v) for k, v in headers.items()]
return '\n'.join(formatted)
| format_headers | identifier_name |
cli.py | import click
import requests
@click.command()
@click.argument('url')
@click.option('--show-headers', '-H', is_flag=True, default=False)
@click.option('--show-status', '-S', is_flag=True, default=False)
@click.option('--quiet', '-Q', is_flag=True, default=False)
@click.option('--allow-redirects/--no-allow-redirects', d... |
# Show the response body
if not quiet:
click.echo(response.text)
if __name__ == '__main__':
cli()
def format_headers(headers):
formatted = ['{0}: {1}'.format(k, v) for k, v in headers.items()]
return '\n'.join(formatted)
| click.echo(format_headers(response.headers), err=True) | conditional_block |
cli.py | import click
import requests
@click.command()
@click.argument('url')
@click.option('--show-headers', '-H', is_flag=True, default=False)
@click.option('--show-status', '-S', is_flag=True, default=False)
@click.option('--quiet', '-Q', is_flag=True, default=False)
@click.option('--allow-redirects/--no-allow-redirects', d... | formatted = ['{0}: {1}'.format(k, v) for k, v in headers.items()]
return '\n'.join(formatted) | identifier_body | |
__init__.py | import walk
except ImportError:
from scandir import walk
import bson
import datetime
import io
import os
import pymongo.errors
import re
import redis
import types
import models
import models.build as mbuild
import models.job as mjob
import utils
import utils.database.redisdb as redisdb
import utils.db
import uti... | (Exception):
def __init__(self, code, *args, **kwargs):
self.code = code
self.from_exc = kwargs.pop('from_exc', None)
super(BuildError, self).__init__(*args, **kwargs)
def _update_job_doc(job_doc, job_id, status, build_doc, database):
"""Update the JobDocument with values from a BuildD... | BuildError | identifier_name |
__init__.py | os import walk
except ImportError:
from scandir import walk
import bson
import datetime
import io
import os
import pymongo.errors
import re
import redis
import types
import models
import models.build as mbuild
import models.job as mjob
import utils
import utils.database.redisdb as redisdb
import utils.db
import ... | no_git = all([
not job_doc.git_url,
not job_doc.git_commit,
not job_doc.git_describe,
not job_doc.git_describe_v
])
no_compiler = all([
not job_doc.compiler,
not job_doc.compiler_version,
not job_doc.compiler_version_ext,
not job_doc.compiler_... | """Update the JobDocument with values from a BuildDocument.
:param job_doc: The job document to update.
:type job_doc: JobDocument
:param status: The job status value.
:type status: string
:param build_doc: A BuildDocument object.
:type build_doc: BuildDocument
"""
to_update = False
... | identifier_body |
__init__.py | os import walk
except ImportError:
from scandir import walk
import bson
import datetime
import io
import os
import pymongo.errors
import re
import redis
import types
import models
import models.build as mbuild
import models.job as mjob
import utils
import utils.database.redisdb as redisdb
import utils.db
import ... | models.KERNEL_KEY: descr,
models.GIT_BRANCH_KEY: branch,
})
if p_doc:
job_doc = mjob.JobDocument.from_json(p_doc)
job_id = job_doc.id
else:
job_doc = mjob.JobDocument(tree, descr, branch)
job_doc.status = models... | database[models.JOB_COLLECTION],
{
models.JOB_KEY: tree, | random_line_split |
__init__.py | import walk
except ImportError:
from scandir import walk
import bson
import datetime
import io
import os
import pymongo.errors
import re
import redis
import types
import models
import models.build as mbuild
import models.job as mjob
import utils
import utils.database.redisdb as redisdb
import utils.db
import uti... |
return doc_id, c_date
class BuildError(Exception):
def __init__(self, code, *args, **kwargs):
self.code = code
self.from_exc = kwargs.pop('from_exc', None)
super(BuildError, self).__init__(*args, **kwargs)
def _update_job_doc(job_doc, job_id, status, build_doc, database):
"""Up... | if prev_doc_count == 1:
prev_doc = utils.db.find_one2(collection, spec)
doc_id = prev_doc.get(models.ID_KEY)
c_date = prev_doc.get(models.CREATED_KEY)
else:
utils.LOG.warn(
"Found multiple defconfig docs matching: {}".format... | conditional_block |
lib.rs | API, similar to epoll on Linux
//! * Design to allow for stack allocated buffers when possible (avoid double buffering).
//! * Provide utilities such as a timers, a notification channel, buffer abstractions, and a slab.
//!
//! # Usage
//!
//! Using mio starts by creating a [`Poll`], which reads events from the OS and... | //! CLIENT => {
//! // The server just shuts down the socket, let's just exit
//! // from our event loop.
//! return;
//! }
//! _ => unreachable!(),
//! }
//! }
//! }
//!
//! ```
#![doc(html_root_url = "https://docs.rs/mio/... | //! } | random_line_split |
lib.rs | SERVER: Token = Token(0);
//! const CLIENT: Token = Token(1);
//!
//! let addr = "127.0.0.1:13265".parse().unwrap();
//!
//! // Setup the server socket
//! let server = TcpListener::bind(&addr).unwrap();
//!
//! // Create a poll instance
//! let poll = Poll::new().unwrap();
//!
//! // Start listening for incoming conn... | {
// Round up.
let millis = (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI;
duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64)
} | identifier_body | |
lib.rs | [`Poll`].
//!
//! [`Poll`]: struct.Poll.html
//! [`Events`]: struct.Events.html
//!
//! # Example
//!
//! ```
//! use mio::*;
//! use mio::net::{TcpListener, TcpStream};
//!
//! // Setup some tokens to allow us to identify which event is
//! // for which socket.
//! const SERVER: Token = Token(0);
//! const CLIENT: To... | millis | identifier_name | |
files.js | var express = require("express");
var router = express.Router();
var sqlite3 = require("sqlite3").verbose();
var fs = require('fs');
var db = new sqlite3.Database("admin/package.sqlite3");
/* GET home page. */
router.get("/", function(req, res, next) {
db.serialize(function() {
var repo = req.originalUrl.split("/")... | }
});
});
});
module.exports = router; | }
}, function(err, count){
if (count == 0){
next(err); | random_line_split |
files.js | var express = require("express");
var router = express.Router();
var sqlite3 = require("sqlite3").verbose();
var fs = require('fs');
var db = new sqlite3.Database("admin/package.sqlite3");
/* GET home page. */
router.get("/", function(req, res, next) {
db.serialize(function() {
var repo = req.originalUrl.split("/")... | ;
module.exports = router;
| );
}
});
});
}) | conditional_block |
forms.py | from flask.ext.wtf import Form
from wtforms import TextField, TextAreaField, SubmitField, PasswordField, validators, ValidationError, SelectField
class | (Form):
deviceId = TextField(u'Device ID', validators=[validators.required()])
notificationEmail = TextField("Notification Email", [validators.email("Please enter 7 characters to search")])
region = SelectField(u'Region', choices=[('us-east-1', 'us-east-1'), ('us-west-1', 'us-west-1'),
... | AWSIEFormFields | identifier_name |
forms.py | from flask.ext.wtf import Form
from wtforms import TextField, TextAreaField, SubmitField, PasswordField, validators, ValidationError, SelectField
class AWSIEFormFields(Form):
deviceId = TextField(u'Device ID', validators=[validators.required()])
notificationEmail = TextField("Notification Email", [validators... | substitutions2b = TextField("Ignore directories")
logBucket = TextField("Log Bucket", [validators.required("Please enter the bucket name for job logs")])
trueCryptPassword = TextField("TrueCrypt Password")
pinCode = TextField("Pin Code")
cacheControl = TextField("Cache Control")
contentDispositi... | substitutionsb = TextField("Ignore directories")
substitutions2 = TextField("Replace box1 with box2") | random_line_split |
forms.py | from flask.ext.wtf import Form
from wtforms import TextField, TextAreaField, SubmitField, PasswordField, validators, ValidationError, SelectField
class AWSIEFormFields(Form):
| expires = TextField("Expires")
ignore = SelectField(u'Exclude Lost+Found', choices=[('', ''), ('yes', 'yes')])
ignore2 = SelectField(u'Exclude Recycle Bin', choices=[('', ''), ('yes', 'yes')])
ignore3 = SelectField(u'Exclude ~ and .swp files', choices=[('', ''), ('yes', 'yes')])
ignore4 = TextField(... | deviceId = TextField(u'Device ID', validators=[validators.required()])
notificationEmail = TextField("Notification Email", [validators.email("Please enter 7 characters to search")])
region = SelectField(u'Region', choices=[('us-east-1', 'us-east-1'), ('us-west-1', 'us-west-1'),
('us-west-2'... | identifier_body |
InstallWizard.py | from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen, ConfigList
from Components.ActionMap import ActionMap
from Components.Sources.StaticText import StaticText
from Components.config import config, ConfigSubsection, ConfigBoolean, getConfigListEntry, ConfigSelection, ConfigYesNo, Config... |
def checkNetworkLinkCB(self, retval):
if retval:
iNetwork.checkNetworkState(self.checkNetworkCB)
else:
self.createMenu()
def createMenu(self):
try:
test = self.index
except:
return
self.list = []
if self.index == self.STATE_UPDATE:
if config.misc.installwizard.hasnetwork.value:
self.... | if data < 3:
config.misc.installwizard.hasnetwork.value = True
self.createMenu() | identifier_body |
InstallWizard.py | from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen, ConfigList
from Components.ActionMap import ActionMap
from Components.Sources.StaticText import StaticText
from Components.config import config, ConfigSubsection, ConfigBoolean, getConfigListEntry, ConfigSelection, ConfigYesNo, Config... |
if is_found is False:
self.createMenu()
elif self.index == self.STATE_CHOISE_CHANNELLIST:
self.enabled = ConfigYesNo(default = True)
modes = {"openxta": "XTA(13e-19e)", "19e": "Astra 1", "23e": "Astra 3", "19e-23e": "Astra 1 Astra 3", "19e-23e-28e": "Astra 1 Astra 2 Astra 3", "13e-19e-23e-28e": "Astra 1... | if x[1] == 'eth0' or x[1] == 'eth1':
if iNetwork.getAdapterAttribute(x[1], 'up'):
self.ipConfigEntry = ConfigIP(default = iNetwork.getAdapterAttribute(x[1], "ip"))
iNetwork.checkNetworkState(self.checkNetworkCB)
if_found = True
else:
iNetwork.restartNetwork(self.checkNetworkLinkCB)
... | conditional_block |
InstallWizard.py | from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen, ConfigList
from Components.ActionMap import ActionMap
from Components.Sources.StaticText import StaticText
from Components.config import config, ConfigSubsection, ConfigBoolean, getConfigListEntry, ConfigSelection, ConfigYesNo, Config... | iNetwork.restartNetwork(self.checkNetworkLinkCB)
break
if is_found is False:
self.createMenu()
elif self.index == self.STATE_CHOISE_CHANNELLIST:
self.enabled = ConfigYesNo(default = True)
modes = {"openxta": "XTA(13e-19e)", "19e": "Astra 1", "23e": "Astra 3", "19e-23e": "Astra 1 Astra 3", "19e... | random_line_split | |
InstallWizard.py | from Screens.Screen import Screen
from Components.ConfigList import ConfigListScreen, ConfigList
from Components.ActionMap import ActionMap
from Components.Sources.StaticText import StaticText
from Components.config import config, ConfigSubsection, ConfigBoolean, getConfigListEntry, ConfigSelection, ConfigYesNo, Config... | (Screen):
skin = """
<screen position="c-300,c-25" size="600,50" title=" ">
<widget source="statusbar" render="Label" position="10,5" zPosition="10" size="e-10,30" halign="center" valign="center" font="Regular;22" transparent="1" shadowColor="black" shadowOffset="-1,-1" />
</screen>"""
def __init__(self, session... | InstallWizardIpkgUpdater | identifier_name |
settings.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { AuthService } from '../core/auth.service';
import { UserService } from '../shared/user.service';
import { User } from '../classes/user';
import { NotificationService } from '../shared/notif... | () {
return this.userService.editSettings(this.form.value).subscribe(
response => {
this.authService.setLoggedUser(User.newInstance(response.data));
this.notificationService.fireSuccess('Settings saved!');
}
);
}
}
| handleSubmit | identifier_name |
settings.component.ts | import { Component, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormGroup } from '@angular/forms';
import { AuthService } from '../core/auth.service';
import { UserService } from '../shared/user.service';
import { User } from '../classes/user';
import { NotificationService } from '../shared/notif... | form: FormGroup;
constructor(
private formBuilder: FormBuilder,
private authService: AuthService,
private userService: UserService,
private notificationService: NotificationService,
) { }
ngOnInit() {
let user = this.authService.getLoggedUser();
this.fo... | templateUrl: './settings.component.html',
styleUrls: ['./settings.component.scss']
})
export class SettingsComponent implements OnInit { | random_line_split |
ExportDialogTest.tsx | import React from 'react'
import { createDefaultExportOptions } from 'app/state/reducers/export'
import { ExportDialog, Props } from 'app/ui/export/ExportDialog'
import { addSection, action, TestContext } from 'test-ui/core/UiTester'
import { PhotoExportOptions } from 'common/CommonTypes'
function createDefaultProp... | )
})
.add('progress', context => (
<ExportDialog
{...createDefaultProps(context)}
progress={{ processed: 2, total: 7 }}
/>
)) | showRemoveInfoDesc={true}
/> | random_line_split |
ExportDialogTest.tsx | import React from 'react'
import { createDefaultExportOptions } from 'app/state/reducers/export'
import { ExportDialog, Props } from 'app/ui/export/ExportDialog'
import { addSection, action, TestContext } from 'test-ui/core/UiTester'
import { PhotoExportOptions } from 'common/CommonTypes'
function createDefaultProp... |
return {
usePortal: false,
photos: {
totalSelectedCount: 7,
sectionSelectionById: {}
},
exportOptions: context.state.exportOptions,
showRemoveInfoDesc: context.state.showRemoveInfoDesc || false,
progress: null,
onExportOptionsChange:... | {
context.state.exportOptions = {
...createDefaultExportOptions(),
folderPath: '/Users/me/Temp/vacation-photos'
} as PhotoExportOptions
} | conditional_block |
ExportDialogTest.tsx | import React from 'react'
import { createDefaultExportOptions } from 'app/state/reducers/export'
import { ExportDialog, Props } from 'app/ui/export/ExportDialog'
import { addSection, action, TestContext } from 'test-ui/core/UiTester'
import { PhotoExportOptions } from 'common/CommonTypes'
function | (context: TestContext): Props {
if (!context.state.exportOptions) {
context.state.exportOptions = {
...createDefaultExportOptions(),
folderPath: '/Users/me/Temp/vacation-photos'
} as PhotoExportOptions
}
return {
usePortal: false,
photos: {
... | createDefaultProps | identifier_name |
ExportDialogTest.tsx | import React from 'react'
import { createDefaultExportOptions } from 'app/state/reducers/export'
import { ExportDialog, Props } from 'app/ui/export/ExportDialog'
import { addSection, action, TestContext } from 'test-ui/core/UiTester'
import { PhotoExportOptions } from 'common/CommonTypes'
function createDefaultProp... | context.forceUpdate()
},
onToggleShowRemoveInfoDesc: () => {
context.state.showRemoveInfoDesc = !context.state.showRemoveInfoDesc
context.forceUpdate()
},
onStartExport: action('onStartExport'),
onClosed: action('onClosed'),
}
}
addSecti... | {
if (!context.state.exportOptions) {
context.state.exportOptions = {
...createDefaultExportOptions(),
folderPath: '/Users/me/Temp/vacation-photos'
} as PhotoExportOptions
}
return {
usePortal: false,
photos: {
totalSelectedCount: 7,
... | identifier_body |
properties_2.js | var searchData=
[
['data',['Data',['../classowncloudsharp_1_1_types_1_1_o_c_s.html#ad64d4fa0e0f73ba19a0eb97b9d30f2bd',1,'owncloudsharp::Types::OCS']]],
['defaultenable',['DefaultEnable',['../classowncloudsharp_1_1_types_1_1_app_info.html#a21fbeb14bcd6b6783ef68231f9230f42',1,'owncloudsharp::Types::AppInfo']]],
['d... | ['displayname',['DisplayName',['../classowncloudsharp_1_1_types_1_1_user.html#a9b885e34f7c1e695e5d9867931b64d9c',1,'owncloudsharp::Types::User']]],
['displaynameowner',['DisplaynameOwner',['../classowncloudsharp_1_1_types_1_1_advanced_share_properties.html#add275aead35226f84b36e447e4104f0d',1,'owncloudsharp::Types:... | random_line_split | |
main.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(... | #[macro_use]
extern crate log;
mod app;
mod audio;
mod debug;
mod device;
mod exception;
mod macros;
mod memory;
mod null_output;
mod palette;
mod sound_buffer;
mod util;
mod video_buffer;
mod video_renderer;
use core::alloc::Layout;
use core::panic::PanicInfo;
use cortex_a::asm;
use linked_list_allocator::LockedHeap... | #![feature(range_contains)]
extern crate alloc; | random_line_split |
main.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(... | (info: &PanicInfo) -> ! {
//interrupt::disable();
print!("ERROR: {}\n", info);
loop {
asm::wfe()
}
}
raspi3_boot::entry!(start);
| on_panic | identifier_name |
main.rs | // This file is part of zinc64.
// Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved.
// Licensed under the GPLv3. See LICENSE file in the project root for full license text.
#![no_std]
#![no_main]
#![feature(alloc)]
#![feature(alloc_error_handler)]
#![feature(asm)]
#![feature(global_asm)]
#![feature(... | let vectors = &__exception_vectors_start as *const _ as u64;
VBAR_EL1.set(vectors);
barrier::isb(barrier::SY);
}
print!("Initializing MMU ...\n");
unsafe {
memory::mmu::init_page_table();
memory::mmu::init();
}
print!("Initializing heap ...\n");
unsafe {... | {
extern "C" {
//noinspection RsStaticConstNaming
static __exception_vectors_start: u64;
}
print!("Initializing console ...\n");
{
let dma_range = memory::dma_heap_range();
let gpio = device::gpio::GPIO::new(memory::map::GPIO_BASE);
let mut mbox = device::mbox::Mb... | identifier_body |
tools.py | import sys, os
def timeSplit( ETR ):
h = int(ETR/3600)
m = int(ETR - 3600*h)/60
s = int(ETR - 3600*h - 60*m)
return h, m, s
def printProgress( current, total, deltaIter, deltaTime ):
terminalString = "\rProgress: "
if total==0: total+=1
percent = 100.*current/total
nDots = int(percent/5)
dotsStri... | os.makedirs(dirName) |
def ensureDirectory( dirName ):
if not os.path.exists(dirName): | random_line_split |
tools.py | import sys, os
def timeSplit( ETR ):
h = int(ETR/3600)
m = int(ETR - 3600*h)/60
s = int(ETR - 3600*h - 60*m)
return h, m, s
def printProgress( current, total, deltaIter, deltaTime ):
terminalString = "\rProgress: "
if total==0: total+=1
percent = 100.*current/total
nDots = int(percent/5)
dotsStri... |
terminalString += dotsString + percentString + ETRstring
sys.stdout. write(terminalString)
sys.stdout.flush()
def ensureDirectory( dirName ):
if not os.path.exists(dirName):
os.makedirs(dirName) | ETRstring = " ETR= " | conditional_block |
tools.py | import sys, os
def timeSplit( ETR ):
h = int(ETR/3600)
m = int(ETR - 3600*h)/60
s = int(ETR - 3600*h - 60*m)
return h, m, s
def printProgress( current, total, deltaIter, deltaTime ):
terminalString = "\rProgress: "
if total==0: total+=1
percent = 100.*current/total
nDots = int(percent/5)
dotsStri... | if not os.path.exists(dirName):
os.makedirs(dirName) | identifier_body | |
tools.py | import sys, os
def timeSplit( ETR ):
h = int(ETR/3600)
m = int(ETR - 3600*h)/60
s = int(ETR - 3600*h - 60*m)
return h, m, s
def printProgress( current, total, deltaIter, deltaTime ):
terminalString = "\rProgress: "
if total==0: total+=1
percent = 100.*current/total
nDots = int(percent/5)
dotsStri... | ( current, total, deltaTime ):
terminalString = "\rProgress: "
if total==0: total+=1
percent = 100.*current/total
nDots = int(percent/5)
dotsString = "[" + nDots*"." + (20-nDots)*" " + "]"
percentString = "{0:.0f}%".format(percent)
if current != 0:
ETR = (deltaTime*(total - current))/float(current)
... | printProgressTime | identifier_name |
AsyncQueue.d.ts | /**
* A queue for async task execution.
*/
export default class | {
_queue: any;
_stopped: boolean;
/**
* Removes any pending tasks from the queue.
*/
clear(): void;
/**
* Internal task processing implementation which makes things work.
*/
_processQueueTasks(task: any, finishedCallback: any): void;
/**
* The 'task' function will b... | AsyncQueue | identifier_name |
AsyncQueue.d.ts | /**
* A queue for async task execution.
*/
export default class AsyncQueue {
_queue: any;
_stopped: boolean;
/**
* Removes any pending tasks from the queue. | clear(): void;
/**
* Internal task processing implementation which makes things work.
*/
_processQueueTasks(task: any, finishedCallback: any): void;
/**
* The 'task' function will be given a callback it MUST call with either:
* 1) No arguments if it was successful or
* 2) An e... | */ | random_line_split |
subprocess_timeout.py | ##########################################################################
# Copyright (c) 2009-2016 ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, Universitaetstr 6, CH... | p.wait()
finally:
timer.cancel() | random_line_split | |
subprocess_timeout.py | ##########################################################################
# Copyright (c) 2009-2016 ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, Universitaetstr 6, CH... | timer = Timer(timeout, lambda x: x.kill(), [p])
try:
timer.start()
p.wait()
finally:
timer.cancel() | identifier_body | |
subprocess_timeout.py | ##########################################################################
# Copyright (c) 2009-2016 ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, Universitaetstr 6, CH... | (p, timeout=5):
# Kill process if it doesn't voluntarily exit in `timeout` seconds
timer = Timer(timeout, lambda x: x.kill(), [p])
try:
timer.start()
p.wait()
finally:
timer.cancel()
| wait_or_kill | identifier_name |
url.ts | /*
* Copyright (c) 2018 by Filestack
* Some 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 required b... |
const serialized = urlfy(params);
const hashIndex = url.indexOf('#');
if (hashIndex !== -1) {
url = url.slice(0, hashIndex);
}
return url + (url.indexOf('?') === -1 ? '?' : '&') + serialized;
};
/**
* Change request json params to url search ones
*
* @param {Object} obj Object to transform
*/
exp... | {
return url;
} | conditional_block |
url.ts | /*
* Copyright (c) 2018 by Filestack
* Some 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 required b... | .map(k => `${encodeURIComponent(k)}=${encodeURIComponent(val[k])}`)
.join('&'); | * @param {Object} obj Object to transform
*/
export const urlfy = val =>
Object.keys(val)
.filter(k => k && typeof val[k] !== 'undefined') | random_line_split |
lockss-manifest-validate.py | #!/usr/bin/python
"""
This is a tool to verify checksum hashes produced by LOCKSS against hashes
provided by a BagIt manifest document.
Invoke with -h for usage help.
Written by Stephen Eisenhauer
At University of North Texas Libraries
On 2013-04-17
Notes:
* The LOCKSS hash list will have more entries than we ac... |
f.close()
print "Compared %d records, encountered %d errors." % (records, errors)
def _make_arg_parser():
parser = argparse.ArgumentParser(
description='Compare a LOCKSS hash list to a bag manifest.')
parser.add_argument('HashCUS',
help="path to the HashCUS.txt file downloaded from LO... | records += 1
path = urllib.quote(m.group(1), safe="%/:=&?~#+!$,;'@()*[]")
if not path in hashes:
print "No LOCKSS hash found for path: %s" % path
errors += 1
elif line[:32].upper() != hashes[path]:
print "Hash mismatch: %s != %s for pat... | conditional_block |
lockss-manifest-validate.py | #!/usr/bin/python
"""
This is a tool to verify checksum hashes produced by LOCKSS against hashes
provided by a BagIt manifest document.
Invoke with -h for usage help.
Written by Stephen Eisenhauer
At University of North Texas Libraries
On 2013-04-17
Notes:
* The LOCKSS hash list will have more entries than we ac... |
def _make_arg_parser():
parser = argparse.ArgumentParser(
description='Compare a LOCKSS hash list to a bag manifest.')
parser.add_argument('HashCUS',
help="path to the HashCUS.txt file downloaded from LOCKSS")
parser.add_argument('manifest',
help="path to the bag manifest (e.g. myba... | print "Compared %d records, encountered %d errors." % (records, errors)
| random_line_split |
lockss-manifest-validate.py | #!/usr/bin/python
"""
This is a tool to verify checksum hashes produced by LOCKSS against hashes
provided by a BagIt manifest document.
Invoke with -h for usage help.
Written by Stephen Eisenhauer
At University of North Texas Libraries
On 2013-04-17
Notes:
* The LOCKSS hash list will have more entries than we ac... | ():
parser = argparse.ArgumentParser(
description='Compare a LOCKSS hash list to a bag manifest.')
parser.add_argument('HashCUS',
help="path to the HashCUS.txt file downloaded from LOCKSS")
parser.add_argument('manifest',
help="path to the bag manifest (e.g. mybag/manifest-md5.txt")
... | _make_arg_parser | identifier_name |
lockss-manifest-validate.py | #!/usr/bin/python
"""
This is a tool to verify checksum hashes produced by LOCKSS against hashes
provided by a BagIt manifest document.
Invoke with -h for usage help.
Written by Stephen Eisenhauer
At University of North Texas Libraries
On 2013-04-17
Notes:
* The LOCKSS hash list will have more entries than we ac... |
def _make_arg_parser():
parser = argparse.ArgumentParser(
description='Compare a LOCKSS hash list to a bag manifest.')
parser.add_argument('HashCUS',
help="path to the HashCUS.txt file downloaded from LOCKSS")
parser.add_argument('manifest',
help="path to the bag manifest (e.g. my... | records = 0
errors = 0
f = open(manifest_path, 'r')
for line in f:
m = re.match('[0-9a-f]{32} (.+)', line)
if m:
records += 1
path = urllib.quote(m.group(1), safe="%/:=&?~#+!$,;'@()*[]")
if not path in hashes:
print "No LOCKSS hash found f... | identifier_body |
database.py | """Database resource."""
import re
from acapi.resources.acquiaresource import AcquiaResource
from acapi.resources.backup import Backup
from acapi.resources.backuplist import BackupList
class Database(AcquiaResource):
"""Environment database."""
#: Valid keys for environment object.
valid_keys = ["db_cl... | (self, backup_id):
"""Fetch a backup.
Parameters
----------
backup_id : int
The id of the database backup to fetch.
Returns
-------
Backup
The backup object.
"""
uri = "{uri}/backups/{backup_id}".format(uri=self.uri, backu... | backup | identifier_name |
database.py | """Database resource."""
import re
from acapi.resources.acquiaresource import AcquiaResource
from acapi.resources.backup import Backup
from acapi.resources.backuplist import BackupList
class Database(AcquiaResource):
"""Environment database."""
#: Valid keys for environment object.
valid_keys = ["db_cl... |
def copy(self, target, wait=True):
"""Copy a database to another environment.
Parameters
----------
target : string
Name of the target environment.
wait : bool
Wait until task is complete.
Returns
-------
Database or Task
... | """Fetch a list of database backups."""
backups = BackupList(self.uri, self.auth)
return backups | identifier_body |
database.py | """Database resource."""
import re
from acapi.resources.acquiaresource import AcquiaResource
from acapi.resources.backup import Backup
from acapi.resources.backuplist import BackupList
class Database(AcquiaResource):
"""Environment database."""
#: Valid keys for environment object.
valid_keys = ["db_cl... | The backup object.
"""
uri = "{uri}/backups/{backup_id}".format(uri=self.uri, backup_id=backup_id)
return Backup(uri, self.auth)
def backups(self):
"""Fetch a list of database backups."""
backups = BackupList(self.uri, self.auth)
return backups
def c... | -------
Backup | random_line_split |
database.py | """Database resource."""
import re
from acapi.resources.acquiaresource import AcquiaResource
from acapi.resources.backup import Backup
from acapi.resources.backuplist import BackupList
class Database(AcquiaResource):
"""Environment database."""
#: Valid keys for environment object.
valid_keys = ["db_cl... |
task.wait()
# Another hack, this time to get the URI for the domain.
env_search = "/{}/".format(current_env)
env_target = "/{}/".format(target)
new_uri = self.uri.replace(env_search, env_target)
return Database(new_uri, self.auth)
| return task | conditional_block |
models.py | from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
import jsonfield
from .signals import event_logged
class Log(models.Model):
user = models.... |
content_type = None
object_id = None
if obj is not None:
content_type = ContentType.objects.get_for_model(obj)
object_id = obj.pk
event = Log.objects.create(
user=user,
action=action,
extra=extra,
content_type=content_type,
object_id=object_id
... | extra = {} | conditional_block |
models.py | from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
import jsonfield
from .signals import event_logged
class | (models.Model):
user = models.ForeignKey(
getattr(settings, "AUTH_USER_MODEL", "auth.User"),
null=True,
on_delete=models.SET_NULL
)
timestamp = models.DateTimeField(default=timezone.now, db_index=True)
action = models.CharField(max_length=50, db_index=True)
content_type = mo... | Log | identifier_name |
models.py | from django.conf import settings
from django.db import models
from django.utils import timezone
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
import jsonfield
from .signals import event_logged
class Log(models.Model):
user = models.... |
class Meta:
ordering = ["-timestamp"]
def log(user, action, extra=None, obj=None):
if (user is not None and not user.is_authenticated()):
user = None
if extra is None:
extra = {}
content_type = None
object_id = None
if obj is not None:
content_type = ContentTy... | return "eventlog/{}.html".format(self.action.lower()) | identifier_body |
models.py | from django.conf import settings
from django.db import models |
from django.contrib.contenttypes.models import ContentType
import jsonfield
from .signals import event_logged
class Log(models.Model):
user = models.ForeignKey(
getattr(settings, "AUTH_USER_MODEL", "auth.User"),
null=True,
on_delete=models.SET_NULL
)
timestamp = models.DateTime... | from django.utils import timezone
from django.contrib.contenttypes.fields import GenericForeignKey | random_line_split |
site-browser.service.ts | import {Injectable} from "@angular/core";
import {Response} from "@angular/http";
import {HttpClient} from "./http.service";
import {Observable} from "rxjs";
import {Treeable} from "../treeable/shared/treeable.model";
import {Folder} from "../treeable/shared/folder.model";
import {File} from "../treeable/shared/file.mo... |
/**
* Returns the Treeable assets (files, folders) under a host/folder
* @param siteName dotCMS Site to load assets for
* @param uri Path to load assets from
* @returns {Observable<R>} Gets the Treeable objects. If a file the Treeable will be File as File extends Treeable
*/
getTreeab... | {
return this.httpClient.get('/api/v1/browsertree/sitename/' + siteName + '/uri//')
.map((res: Response) => this.extractDataFilter(res))
.catch(error => this.handleError(error));
} | identifier_body |
site-browser.service.ts | import {Injectable} from "@angular/core";
import {Response} from "@angular/http";
import {HttpClient} from "./http.service";
import {Observable} from "rxjs";
import {Treeable} from "../treeable/shared/treeable.model";
import {Folder} from "../treeable/shared/folder.model";
import {File} from "../treeable/shared/file.mo... | {
constructor
(
private httpClient: HttpClient,
private notificationService: NotificationService
)
{}
/**
* Returns the Treeable assets (files, folders) under a host/folder
* @param siteName dotCMS Site to load assets for
* @returns {Observable<R>} Gets the Treeable... | SiteBrowserService | identifier_name |
site-browser.service.ts | import {Injectable} from "@angular/core";
import {Response} from "@angular/http";
import {HttpClient} from "./http.service";
import {Observable} from "rxjs";
import {Treeable} from "../treeable/shared/treeable.model";
import {Folder} from "../treeable/shared/folder.model";
import {File} from "../treeable/shared/file.mo... | .catch(error => this.handleError(error));
}
private extractDataFilter(res: Response): Treeable[] {
let treeables: Treeable[] = [];
let obj = JSON.parse(res.text());
let results: any[] = obj.entity.result;
for (let i = 0; i < results.length; i++) {
let r: ... | */
getTreeableAssetsUnderFolder(siteName: String, uri: String): Observable < Treeable[] > {
return this.httpClient.get('/api/v1/browsertree/sitename/' + siteName + '/uri/' + uri)
.map((res: Response) => this.extractDataFilter(res)) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.