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 |
|---|---|---|---|---|
dataWriter.ts | * as uuidLib from 'uuid';
const topLogPrefix = 'larvituser: dataWriter.ts -';
export type DataWriterOptions = {
log?: LogInstance,
db: any,
};
export class DataWriter {
private lUtils: Utils;
private helpers: Helpers;
private log: LogInstance;
private db: any;
constructor(options: DataWriterOptions) {
if ... |
async setUsername(userUuid: string, username: string): Promise<void> {
const | {
const { helpers, lUtils } = this;
const logPrefix = `${topLogPrefix} setPassword() -`;
const userUuidBuffer = helpers.valueOrThrow(lUtils.uuidToBuffer(userUuid), logPrefix, 'Invalid user uuid');
const dbFields: Array<string | Buffer> = [];
dbFields.push(password);
dbFields.push(userUuidBuffer);
const... | identifier_body |
dataWriter.ts | import * as uuidLib from 'uuid';
const topLogPrefix = 'larvituser: dataWriter.ts -';
export type DataWriterOptions = {
log?: LogInstance,
db: any,
};
export class DataWriter {
private lUtils: Utils;
private helpers: Helpers;
private log: LogInstance;
private db: any;
constructor(options: DataWriterOptions) {... | const { helpers, lUtils } = this;
const logPrefix = `${topLogPrefix} rmUser() -`;
const uuidBuffer = helpers.valueOrThrow(lUtils.uuidToBuffer(userUuid), logPrefix, 'Invalid user uuid');
let sql = 'DELETE FROM user_users_data WHERE userUuid = ?;';
await this.db.query(sql, [uuidBuffer]);
sql = 'DELETE FROM... | async rmUser(userUuid: string): Promise<void> { | random_line_split |
TipDoc.js | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Tip from 'grommet/components/Tip';
import Menu from 'grommet/components/Menu';
import Anchor from 'grommet/components/Anchor';
import DocsArticle from '../../components/DocsArticle';
import Code from '... | extends Component {
constructor () {
super();
this.state = { active: true };
}
render () {
const { active } = this.state;
let tip;
if (active) {
tip = (
<Tip target='actions'
onClose={() => this.setState({ active: false })}>
Available actions
</Tip>... | TipDoc | identifier_name |
TipDoc.js | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Tip from 'grommet/components/Tip';
import Menu from 'grommet/components/Menu';
import Anchor from 'grommet/components/Anchor';
import DocsArticle from '../../components/DocsArticle';
import Code from '... | need or try imminitely.</p>
<Menu id='actions' inline={false}>
<Anchor href=''>action 1</Anchor>
<Anchor href=''>action 2</Anchor>
</Menu>
{tip}
<p>The caller is responsible for determining when to show a Tip.
The tip should be re... | {
const { active } = this.state;
let tip;
if (active) {
tip = (
<Tip target='actions'
onClose={() => this.setState({ active: false })}>
Available actions
</Tip>
);
}
return (
<DocsArticle title='Tip'>
<section>
<p>An attention... | identifier_body |
TipDoc.js | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Tip from 'grommet/components/Tip';
import Menu from 'grommet/components/Menu';
import Anchor from 'grommet/components/Anchor';
import DocsArticle from '../../components/DocsArticle';
import Code from '... |
return (
<DocsArticle title='Tip'>
<section>
<p>An attention getter used to highlight an aspect of the interface
that might not be apparent at first glance. This should be used
sparingly. Only one Tip should ever be shown on the screen at a time
and onl... | {
tip = (
<Tip target='actions'
onClose={() => this.setState({ active: false })}>
Available actions
</Tip>
);
} | conditional_block |
filter.js | /**
* Module dependencies.
*/
var Emitter = require('emitter');
var render = require('render');
var events = require('events');
var empty = require('empty');
var filter = require('laws-filter');
var template = require('./filter-container');
var o = require('query');
var closest = require('closest');
var classes = re... |
Emitter(FilterView.prototype);
FilterView.prototype.build = function() {
this.el = render.dom(template, { filter: filter });
};
FilterView.prototype.switchOn = function() {
// View events
this.events = events(this.el, this);
this.events.bind('click #status-filter a.btn', 'onstatusclick');
this.events.bind... | {
if (!(this instanceof FilterView)) {
return new FilterView();
};
// Prep event handlers
this.refresh = this.refresh.bind(this);
this.build();
this.switchOn();
} | identifier_body |
filter.js | /**
* Module dependencies.
*/
var Emitter = require('emitter');
var render = require('render');
var events = require('events');
var empty = require('empty');
var filter = require('laws-filter');
var template = require('./filter-container');
var o = require('query');
var closest = require('closest');
var classes = re... | ;
// Prep event handlers
this.refresh = this.refresh.bind(this);
this.build();
this.switchOn();
}
Emitter(FilterView.prototype);
FilterView.prototype.build = function() {
this.el = render.dom(template, { filter: filter });
};
FilterView.prototype.switchOn = function() {
// View events
this.events = e... | {
return new FilterView();
} | conditional_block |
filter.js | /**
* Module dependencies.
*/
var Emitter = require('emitter');
var render = require('render');
var events = require('events');
var empty = require('empty');
var filter = require('laws-filter');
var template = require('./filter-container');
var o = require('query');
var closest = require('closest');
var classes = re... | () {
if (!(this instanceof FilterView)) {
return new FilterView();
};
// Prep event handlers
this.refresh = this.refresh.bind(this);
this.build();
this.switchOn();
}
Emitter(FilterView.prototype);
FilterView.prototype.build = function() {
this.el = render.dom(template, { filter: filter });
};
Fil... | FilterView | identifier_name |
filter.js | /**
* Module dependencies.
*/
var Emitter = require('emitter');
var render = require('render');
var events = require('events');
var empty = require('empty');
var filter = require('laws-filter');
var template = require('./filter-container');
var o = require('query');
var closest = require('closest');
var classes = re... | FilterView.prototype.ready = function(fn) {
filter.ready(fn);
filter.ready(this.refresh);
}
FilterView.prototype.render = function(el) {
if (1 === arguments.length) {
// if string, then query element
if ('string' === typeof el) {
el = o(el);
};
// if it's not currently inserted
// at ... | random_line_split | |
issue_16723_multiple_items_syntax_ext.rs | // Copyright 2012 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 ... | {
MacItems::new(vec![
quote_item!(cx, struct Struct1;).unwrap(),
quote_item!(cx, struct Struct2;).unwrap()
].into_iter())
} | identifier_body | |
issue_16723_multiple_items_syntax_ext.rs | // Copyright 2012 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 |
// ignore-stage1
// force-host
#![feature(plugin_registrar, quote)]
#![crate_type = "dylib"]
extern crate syntax;
extern crate rustc;
use syntax::ast;
use syntax::codemap;
use syntax::ext::base::{ExtCtxt, MacResult, MacItems};
use rustc::plugin::Registry;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Regis... | // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms. | random_line_split |
issue_16723_multiple_items_syntax_ext.rs | // Copyright 2012 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 ... | (reg: &mut Registry) {
reg.register_macro("multiple_items", expand)
}
fn expand(cx: &mut ExtCtxt, _: codemap::Span, _: &[ast::TokenTree]) -> Box<MacResult+'static> {
MacItems::new(vec![
quote_item!(cx, struct Struct1;).unwrap(),
quote_item!(cx, struct Struct2;).unwrap()
].into_iter())
}
| plugin_registrar | identifier_name |
test-ignore-cfg.rs | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// compile-flags: -... | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
// | random_line_split | |
test-ignore-cfg.rs | // Copyright 2012 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 ... |
#[test]
fn checktests() {
// Pull the tests out of the secreturn test module
let tests = __test::tests;
assert!(vec::any(
tests,
|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore));
assert!(vec::any(
tests,
|t| t.desc.name.to_str() == ~"shouldnotignore" && ... | {
} | identifier_body |
test-ignore-cfg.rs | // Copyright 2012 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 ... | () {
// Pull the tests out of the secreturn test module
let tests = __test::tests;
assert!(vec::any(
tests,
|t| t.desc.name.to_str() == ~"shouldignore" && t.desc.ignore));
assert!(vec::any(
tests,
|t| t.desc.name.to_str() == ~"shouldnotignore" && !t.desc.ignore));
}
| checktests | identifier_name |
filesponge.py | #!/usr/bin/env python
import subprocess, os, sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument("directory", help="First target directory for evaluation")
parser.add_argument("directories", nargs='+', help="All other directories to be evaluated")
parser.add_argument("-o", "--output", help="Output des... | (dirs):
prev = None
for index in dirs:
if prev is None:
prev = index
else:
diff = "diff --brief -Nrs %s %s" % (prev, index)
egrepPattern = "^Files .+ and .+ are identical$"
awkPattern = "(Files | and | are identical)"
diffProcess = su... | findIdentical | identifier_name |
filesponge.py | #!/usr/bin/env python
import subprocess, os, sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument("directory", help="First target directory for evaluation")
parser.add_argument("directories", nargs='+', help="All other directories to be evaluated")
parser.add_argument("-o", "--output", help="Output des... |
args = parser.parse_args()
def fileSponge(dirs, outputDir):
commonList = findIdentical(dirs).rstrip()
outputCommon(commonList, outputDir)
def findIdentical(dirs):
prev = None
for index in dirs:
if prev is None:
prev = index
else:
diff = "diff --brief -Nrs %s %... | random_line_split | |
filesponge.py | #!/usr/bin/env python
import subprocess, os, sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument("directory", help="First target directory for evaluation")
parser.add_argument("directories", nargs='+', help="All other directories to be evaluated")
parser.add_argument("-o", "--output", help="Output des... |
def outputCommon(commonList, outputDir):
if outputDir is not None:
options = "-av"
exclusions = "--exclude='*'"
srcPath = "./"
destPath = "%s/" % (outputDir)
targetFiles = isolateTargetFiles(commonList)
inclusions = "--files-from=./commonFiles.txt"#generateRsyncIncl... | if prev is None:
prev = index
else:
diff = "diff --brief -Nrs %s %s" % (prev, index)
egrepPattern = "^Files .+ and .+ are identical$"
awkPattern = "(Files | and | are identical)"
diffProcess = subprocess.Popen(diff.split(), stdout=subprocess.PIPE)
... | conditional_block |
filesponge.py | #!/usr/bin/env python
import subprocess, os, sys, argparse
parser = argparse.ArgumentParser()
parser.add_argument("directory", help="First target directory for evaluation")
parser.add_argument("directories", nargs='+', help="All other directories to be evaluated")
parser.add_argument("-o", "--output", help="Output des... |
def outputCommon(commonList, outputDir):
if outputDir is not None:
options = "-av"
exclusions = "--exclude='*'"
srcPath = "./"
destPath = "%s/" % (outputDir)
targetFiles = isolateTargetFiles(commonList)
inclusions = "--files-from=./commonFiles.txt"#generateRsyncIncl... | prev = None
for index in dirs:
if prev is None:
prev = index
else:
diff = "diff --brief -Nrs %s %s" % (prev, index)
egrepPattern = "^Files .+ and .+ are identical$"
awkPattern = "(Files | and | are identical)"
diffProcess = subprocess.Pop... | identifier_body |
mod.rs | #[macro_use]
pub mod macros;
pub mod reg;
pub mod mmu;
pub mod semihosting;
use core::ops::Drop;
pub fn local_irqs_disable() {
unsafe {
asm!("msr daifset, #2"
:
:
: "cc", "memory"
: "volatile")
}
}
pub fn | () {
unsafe {
asm!("msr daifclr, #2"
:
:
: "cc", "memory"
: "volatile")
}
}
fn cpu_flags_read() -> u64 {
reg::daif::read()
}
fn cpu_flags_write(flag : u64) {
reg::daif::write(flag);
}
pub struct CriticalSectionGuard {
flags : u64,
}
im... | local_irqs_enable | identifier_name |
mod.rs | #[macro_use]
pub mod macros;
pub mod reg;
pub mod mmu;
pub mod semihosting;
use core::ops::Drop;
pub fn local_irqs_disable() {
unsafe {
asm!("msr daifset, #2"
:
:
: "cc", "memory"
: "volatile")
}
}
pub fn local_irqs_enable() {
unsafe {
a... |
fn cpu_flags_write(flag : u64) {
reg::daif::write(flag);
}
pub struct CriticalSectionGuard {
flags : u64,
}
impl Drop for CriticalSectionGuard {
fn drop(&mut self) {
cpu_flags_write(self.flags);
}
}
pub fn critical_section_start() -> CriticalSectionGuard {
let ret = CriticalSectionGuar... | {
reg::daif::read()
} | identifier_body |
mod.rs | pub mod semihosting;
use core::ops::Drop;
pub fn local_irqs_disable() {
unsafe {
asm!("msr daifset, #2"
:
:
: "cc", "memory"
: "volatile")
}
}
pub fn local_irqs_enable() {
unsafe {
asm!("msr daifclr, #2"
:
:
... | #[macro_use]
pub mod macros;
pub mod reg;
pub mod mmu; | random_line_split | |
system.py | """
System plugin
Copyright (C) 2016 Walid Benghabrit
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distribu... | (self, request):
res = super(System, self).handle_request(request)
if res is not None: return res
| handle_request | identifier_name |
system.py | """
System plugin
Copyright (C) 2016 Walid Benghabrit
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distribu... | def __init__(self):
super().__init__()
def handle_request(self, request):
res = super(System, self).handle_request(request)
if res is not None: return res | identifier_body | |
system.py | """
System plugin
Copyright (C) 2016 Walid Benghabrit
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distribu... | return res | conditional_block | |
location.py | from rec import CourseRecord
from score import RoomScore
from evaluation import ScheduleEvaluation
FULL_HOURS = 8 # 8:00AM - 4:00PM utilization
PARTIAL_HOURS = FULL_HOURS * 0.75 #75%
HALF_HOURS = FULL_HOURS * 0.50 #50%
SPARSE_HOURS = FULL_HOURS * 0.25 #25%
class LocationScore:
def __init__(self, evals=No... |
def get_score_rank(self):
return self.weight_rank
def get_evals(self):
return self.evals
| return self.final_weighted | identifier_body |
location.py | from rec import CourseRecord
from score import RoomScore
from evaluation import ScheduleEvaluation
FULL_HOURS = 8 # 8:00AM - 4:00PM utilization
PARTIAL_HOURS = FULL_HOURS * 0.75 #75%
HALF_HOURS = FULL_HOURS * 0.50 #50%
SPARSE_HOURS = FULL_HOURS * 0.25 #25%
class LocationScore:
def __init__(self, evals=No... | (self):
return self.final_weighted
def get_score_rank(self):
return self.weight_rank
def get_evals(self):
return self.evals
| get_final_weighted_score | identifier_name |
location.py | from rec import CourseRecord
from score import RoomScore
from evaluation import ScheduleEvaluation
FULL_HOURS = 8 # 8:00AM - 4:00PM utilization
PARTIAL_HOURS = FULL_HOURS * 0.75 #75%
HALF_HOURS = FULL_HOURS * 0.50 #50%
SPARSE_HOURS = FULL_HOURS * 0.25 #25%
class LocationScore:
def __init__(self, evals=No... | self.reset_daily_weights()
for course, score in self.courses:
days = course.rec["DAYS_OF_WEEK"]
#score_sum += score.get_weighted_score(course)
score_total += 1.00
for day in ["M", "T", "W", "R", "F", "S"]:
if day in days:
... |
#reset daily stuff | random_line_split |
location.py | from rec import CourseRecord
from score import RoomScore
from evaluation import ScheduleEvaluation
FULL_HOURS = 8 # 8:00AM - 4:00PM utilization
PARTIAL_HOURS = FULL_HOURS * 0.75 #75%
HALF_HOURS = FULL_HOURS * 0.50 #50%
SPARSE_HOURS = FULL_HOURS * 0.25 #25%
class LocationScore:
def __init__(self, evals=No... |
return location
def get_final_weighted_score(self):
return self.final_weighted
def get_score_rank(self):
return self.weight_rank
def get_evals(self):
return self.evals
| location = str( course.rec["BUILDING"] )+ " " + str( course.rec["ROOM"] )
# just need to find the first one, so break after this happens
break | conditional_block |
repeat.py | from django import template
register = template.Library()
class RepeatNode(template.Node):
def | (self, nodelist, count):
self.nodelist = nodelist
self.count = template.Variable(count)
def render(self, context):
output = self.nodelist.render(context)
return output * int(self.count.resolve(context) + 1)
def repeat(parser, token):
"""
Repeats the containing text a c... | __init__ | identifier_name |
repeat.py | from django import template
register = template.Library()
class RepeatNode(template.Node):
def __init__(self, nodelist, count):
self.nodelist = nodelist
self.count = template.Variable(count)
def render(self, context):
output = self.nodelist.render(context)
return output * ... |
count = bits[1]
nodelist = parser.parse(('endrepeat',))
parser.delete_first_token()
return RepeatNode(nodelist, count)
repeat = register.tag(repeat) | random_line_split | |
repeat.py | from django import template
register = template.Library()
class RepeatNode(template.Node):
def __init__(self, nodelist, count):
self.nodelist = nodelist
self.count = template.Variable(count)
def render(self, context):
output = self.nodelist.render(context)
return output * ... |
count = bits[1]
nodelist = parser.parse(('endrepeat',))
parser.delete_first_token()
return RepeatNode(nodelist, count)
repeat = register.tag(repeat)
| raise template.TemplateSyntaxError('%r tag requires 1 argument.' % bits[0]) | conditional_block |
repeat.py | from django import template
register = template.Library()
class RepeatNode(template.Node):
def __init__(self, nodelist, count):
self.nodelist = nodelist
self.count = template.Variable(count)
def render(self, context):
|
def repeat(parser, token):
"""
Repeats the containing text a certain number of times.
Requires a single argument, an integer, to indicate the number of times to
repeat the enclosing content.
Example::
{% repeat 3 %}foo{% endrepeat %}
Yields::
foofoofoo... | output = self.nodelist.render(context)
return output * int(self.count.resolve(context) + 1) | identifier_body |
example_date_featurizer.py | """
=================================================
Modeling quasi-seasonal trends with date features
=================================================
Some trends are common enough to appear seasonal, yet sporadic enough that
approaching them from a seasonal perspective may not be valid. An example of
this is the ... |
n_train = y_train.shape[0]
x = np.arange(n_train + forecasts.shape[0])
ax.plot(x[:n_train], y_train, color='blue', label='Training Data')
ax.plot(x[n_train:], forecasts, color='green', marker='o',
label='Predicted')
ax.plot(x[n_train:], y_test, color='red', label='Actual')
ax.legend(loc='lower left', borderax... |
fig = plt.figure(figsize=(16, 8))
ax = fig.add_subplot(1, 1, 1) | random_line_split |
cli-options.ts | import { Map, List, fromJS } from "immutable";
import { addToFilesOption } from "./transforms/addToFilesOption"; | import { handleFilesOption } from "./transforms/handleFilesOption";
import { handleGhostModeOption } from "./transforms/handleGhostModeOption";
import { handlePortsOption } from "./transforms/handlePortsOption";
import { handleProxyOption } from "./transforms/handleProxyOption";
import { handleServerOption } from "./tr... | import { addDefaultIgnorePatterns } from "./transforms/addDefaultIgnorePatterns";
import { copyCLIIgnoreToWatchOptions } from "./transforms/copyCLIIgnoreToWatchOptions";
import { handleExtensionsOption } from "./transforms/handleExtensionsOption"; | random_line_split |
cli-options.ts | import { Map, List, fromJS } from "immutable";
import { addToFilesOption } from "./transforms/addToFilesOption";
import { addDefaultIgnorePatterns } from "./transforms/addDefaultIgnorePatterns";
import { copyCLIIgnoreToWatchOptions } from "./transforms/copyCLIIgnoreToWatchOptions";
import { handleExtensionsOption } fro... | (errors: BsErrors) {
return errors
.map(error =>
[
`Error Type: ${error.type}`,
`Error Level: ${error.level}`,
error.errors.map(item =>
[
`Error Message: ${item.error.message}`,
... | printErrors | identifier_name |
cli-options.ts | import { Map, List, fromJS } from "immutable";
import { addToFilesOption } from "./transforms/addToFilesOption";
import { addDefaultIgnorePatterns } from "./transforms/addDefaultIgnorePatterns";
import { copyCLIIgnoreToWatchOptions } from "./transforms/copyCLIIgnoreToWatchOptions";
import { handleExtensionsOption } fro... | {
return errors
.map(error =>
[
`Error Type: ${error.type}`,
`Error Level: ${error.level}`,
error.errors.map(item =>
[
`Error Message: ${item.error.message}`,
item.meta ? item... | identifier_body | |
cli-options.ts | import { Map, List, fromJS } from "immutable";
import { addToFilesOption } from "./transforms/addToFilesOption";
import { addDefaultIgnorePatterns } from "./transforms/addDefaultIgnorePatterns";
import { copyCLIIgnoreToWatchOptions } from "./transforms/copyCLIIgnoreToWatchOptions";
import { handleExtensionsOption } fro... |
return {
globs: globs,
objs: objs
};
}
export function printErrors(errors: BsErrors) {
return errors
.map(error =>
[
`Error Type: ${error.type}`,
`Error Level: ${error.level}`,
error.errors.map(item =>
... | {
value.forEach(function(value) {
if (_.isString(value)) {
globs.push(value);
} else {
if (Map.isMap(value)) {
objs.push(value);
}
}
});
} | conditional_block |
models.py | from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
from random import randint
author = 'Your name here'
doc = """
Your app description
"""
class Constants(BaseConstants):
name_in_url = 'T1'
players_per_group = None
num_... | self.charity_account -= Constants.c_charity_deduction | conditional_block | |
models.py | from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
from random import randint
author = 'Your name here'
doc = """
Your app description
"""
class Constants(BaseConstants):
name_in_url = 'T1'
players_per_group = None
num_... | if self.reported_number == Constants.c_winning_number:
self.payoff += Constants.c_winning_payoff
if self.reported_number != self.random_number:
# Deduct the punishment to the charity account
self.charity_account -= Constants.c_charity_deduction | identifier_body | |
models.py | from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
from random import randint
author = 'Your name here'
doc = """
Your app description
"""
class Constants(BaseConstants):
name_in_url = 'T1'
players_per_group = None
num_... | self.charity_account -= Constants.c_charity_deduction | random_line_split | |
models.py | from otree.api import (
models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,
Currency as c, currency_range
)
from random import randint
author = 'Your name here'
doc = """
Your app description
"""
class Constants(BaseConstants):
name_in_url = 'T1'
players_per_group = None
num_... | (BaseSubsession):
def creating_session(self):
for p in self.get_players():
p.charity_account = Constants.c_charity_endowment
p.payoff = Constants.c_player_endowment # "In addition to your show-up fee, you start with an endowment of 100 tokens"
p.random_number = randint(1... | Subsession | identifier_name |
demo.py | import os
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, ... |
@app.route('/uploads/<filename>')
def uploaded_file(filename):
#return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
#detect.doDetect(file)
if file is None:
return "File is none"
# if file is not None:
# # present_student = face_recognizer.doFaceRecognition()
# return "file is not ... | filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload folder we setup
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
detect.doDetect(file)
present_student_list = face_recognizer.doFaceRecognition()
return jsonif... | conditional_block |
demo.py | import os
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, ... | file =None
# Route that will process the file upload
@app.route('/upload', methods=['GET','POST'])
def upload():
# Get the name of the uploaded file
file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filena... | # value of the operation
@app.route('/')
def index():
return render_template('index.html')
| random_line_split |
demo.py | import os
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, ... | (filename):
return '.' in filename and \
filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']
# This route will show a form to perform an AJAX request
# jQuery is loaded to execute the request and update the
# value of the operation
@app.route('/')
def index():
return render_template('inde... | allowed_file | identifier_name |
demo.py | import os
# We'll render HTML templates and access data sent by POST
# using the request object from flask. Redirect and url_for
# will be used to redirect the user once the upload is done
# and send_from_directory will help us to send/show on the
# browser the file that the user just uploaded
from flask import Flask, ... |
@app.route('/uploads/<filename>')
def uploaded_file(filename):
#return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
#detect.doDetect(file)
if file is None:
return "File is none"
# if file is not None:
# # present_student = face_recognizer.doFaceRecognition()
# return "file is not ... | file = request.files['file']
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
# Move the file form the temporal folder to
# the upload f... | identifier_body |
test_init_code.py | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | (self):
url = "https://foo.com/test"
assert get_clone_url(url=url) == url
os.environ[POLYAXON_KEYS_GIT_CREDENTIALS] = "foo:bar"
assert get_clone_url(url=url) == "https://foo:bar@foo.com/test"
del os.environ[POLYAXON_KEYS_GIT_CREDENTIALS]
with patch("polyaxon.init.git.has... | test_get_clone_url | identifier_name |
test_init_code.py | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | url = "https://foo.com/test"
assert get_clone_url(url=url) == url
os.environ[POLYAXON_KEYS_GIT_CREDENTIALS] = "foo:bar"
assert get_clone_url(url=url) == "https://foo:bar@foo.com/test"
del os.environ[POLYAXON_KEYS_GIT_CREDENTIALS]
with patch("polyaxon.init.git.has_ssh_acc... | def test_raise_if_env_var_not_found(self):
with self.assertRaises(PolyaxonContainerException):
create_code_repo(repo_path="", url="", revision="")
def test_raise_if_env_var_not_correct(self):
os.environ[POLYAXON_KEYS_RUN_INSTANCE] = "foo"
with self.assertRaises(PolyaxonContainer... | identifier_body |
test_init_code.py | #!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | from polyaxon.exceptions import PolyaxonContainerException
from polyaxon.init.git import (
create_code_repo,
get_clone_url,
has_cred_access,
has_ssh_access,
)
from polyaxon.utils.test_utils import BaseTestCase
@pytest.mark.init_mark
class TestInitCode(BaseTestCase):
def test_raise_if_env_var_not_f... | POLYAXON_KEYS_RUN_INSTANCE,
) | random_line_split |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#[macro_use]
mod macros;
mod error;
pub use error::{Error, Result, WaitForTransactionError};
cfg_blocking! {
mod blocking;
pub use blocking::BlockingClient;
}
cfg_async! {
mod client;
pub use client::Client;
}
mod re... | {
#[serde(rename = "2.0")]
V2,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Method {
Submit,
GetMetadata,
GetAccount,
GetTransactions,
GetAccountTransaction,
GetAccountTransactions,
GetEvents,
GetCurrencies,
GetNetworkStatus,
... | JsonRpcVersion | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#[macro_use]
mod macros;
mod error;
pub use error::{Error, Result, WaitForTransactionError};
cfg_blocking! {
mod blocking;
pub use blocking::BlockingClient;
}
cfg_async! {
mod client;
pub use client::Client;
}
mod re... | V2,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Method {
Submit,
GetMetadata,
GetAccount,
GetTransactions,
GetAccountTransaction,
GetAccountTransactions,
GetEvents,
GetCurrencies,
GetNetworkStatus,
//
// Experimental APIs
... | random_line_split | |
test_pdf_reader.py | # This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
import pytest
from io import BytesIO
from rinoh.backen... | << /Type /Example
/Subtype /DictionaryExample
/Version 0.01
/IntegerItem 12
/StringItem (a string)
/Subdictionary << /Item1 0.4
/Item2 true
/LastItem (not!)
... | random_line_split | |
test_pdf_reader.py | # This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
import pytest
from io import BytesIO
from rinoh.backen... |
test_name(b'/Adobe#20Green', 'Adobe Green')
test_name(b'/PANTONE#205757#20CV', 'PANTONE 5757 CV')
test_name(b'/paired#28#29parentheses', 'paired()parentheses')
test_name(b'/The_Key_of_F#23_Minor', 'The_Key_of_F#_Minor')
test_name(b'/A#42', 'AB')
def test_read_dictionary():
input = b"""
<... | reader = PDFObjectReader(BytesIO(bytes_name))
result = reader.next_item()
assert isinstance(result, cos.Name) and str(result) == unicode_name | identifier_body |
test_pdf_reader.py | # This file is part of rinohtype, the Python document preparation system.
#
# Copyright (c) Brecht Machiels.
#
# Use of this source code is subject to the terms of the GNU Affero General
# Public License v3. See the LICENSE file or http://www.gnu.org/licenses/.
import pytest
from io import BytesIO
from rinoh.backen... | ():
def test_integer(bytes_integer, integer):
reader = PDFObjectReader(BytesIO(bytes_integer))
result = reader.next_item()
assert isinstance(result, cos.Integer) and result == integer
test_integer(b'123', 123)
test_integer(b'43445', 43445)
test_integer(b'+17', 17)
test_integ... | test_read_integer | identifier_name |
ReactDebugTool.js | string,
updateCount: number,
childIDs: Array<DebugID>,
ownerID: DebugID,
parentID: DebugID,
}
};
type HistoryItem = {
duration: number,
measurements: Array<Measurement>,
operations: Array<Operation>,
treeSnapshot: TreeSnapshot,
};
export type FlushHistory = Array<HistoryItem>;
var hooks = ... |
var isHostElement = typeof element.type === 'string';
if (isHostElement) {
return false;
}
return true;
}
function markBegin(debugID, markType) {
if (!shouldMark(debugID)) {
return;
}
var markName = `${debugID}::${markType}`;
lastMarkTimeStamp = performanceNow();
performance.mark(markName);... | {
return false;
} | conditional_block |
ReactDebugTool.js | string,
updateCount: number,
childIDs: Array<DebugID>,
ownerID: DebugID,
parentID: DebugID,
}
};
type HistoryItem = {
duration: number,
measurements: Array<Measurement>,
operations: Array<Operation>,
treeSnapshot: TreeSnapshot,
};
export type FlushHistory = Array<HistoryItem>;
var hooks = ... | performance.clearMarks(markName);
performance.clearMeasures(measurementName);
}
var ReactDebugTool = {
addHook(hook: Hook): void {
hooks.push(hook);
},
removeHook(hook: Hook): void {
for (var i = 0; i < hooks.length; i++) {
if (hooks[i] === hook) {
hooks.splice(i, 1);
i--;
... | {
if (!shouldMark(debugID)) {
return;
}
var markName = `${debugID}::${markType}`;
var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown';
// Chrome has an issue of dropping markers recorded too fast:
// https://bugs.chromium.org/p/chromium/issues/detail?id=640652
// To work ar... | identifier_body |
ReactDebugTool.js | string,
updateCount: number,
childIDs: Array<DebugID>,
ownerID: DebugID,
parentID: DebugID,
}
};
type HistoryItem = {
duration: number,
measurements: Array<Measurement>,
operations: Array<Operation>,
treeSnapshot: TreeSnapshot,
};
export type FlushHistory = Array<HistoryItem>;
var hooks = ... | if (allowRoot && debugID === 0) {
return;
}
if (!debugID) {
warning(false, 'ReactDebugTool: debugID may not be empty.');
}
}
function beginLifeCycleTimer(debugID, timerType) {
if (currentFlushNesting === 0) {
return;
}
if (currentTimerType && !lifeCycleTimerHasWarned) {
warning(
fal... | currentFlushStartTime = performanceNow();
currentFlushMeasurements = [];
}
function checkDebugID(debugID, allowRoot = false) { | random_line_split |
ReactDebugTool.js | string,
updateCount: number,
childIDs: Array<DebugID>,
ownerID: DebugID,
parentID: DebugID,
}
};
type HistoryItem = {
duration: number,
measurements: Array<Measurement>,
operations: Array<Operation>,
treeSnapshot: TreeSnapshot,
};
export type FlushHistory = Array<HistoryItem>;
var hooks = ... | (debugID, markType) {
if (!shouldMark(debugID)) {
return;
}
var markName = `${debugID}::${markType}`;
var displayName = ReactComponentTreeHook.getDisplayName(debugID) || 'Unknown';
// Chrome has an issue of dropping markers recorded too fast:
// https://bugs.chromium.org/p/chromium/issues/detail?id=64... | markEnd | identifier_name |
profile.service.js | angular.module('job')
.factory('ProfileService', ['async', '$resource', '$http', 'cmsConfig', function (async, $resource, $http, cmsConfig) {
var ProfileResource = $resource('', {}, {
// serverUrl
getProfile: {method: 'GET', url: cmsConfig.serverApi + '/profile'},
updateProfile: {method: 'POST',... |
ProfileService.prototype.preparationInitData = function (callback) {
async.parallel({
profile: function (cb) {
ProfileResource.getProfile(function (res) {
return cb(res.error, res.data);
});
},
countries: function (cb) {
ProfileResource.getCo... | {
} | identifier_body |
profile.service.js | angular.module('job')
.factory('ProfileService', ['async', '$resource', '$http', 'cmsConfig', function (async, $resource, $http, cmsConfig) {
var ProfileResource = $resource('', {}, {
// serverUrl
getProfile: {method: 'GET', url: cmsConfig.serverApi + '/profile'},
updateProfile: {method: 'POST',... | () {
}
ProfileService.prototype.preparationInitData = function (callback) {
async.parallel({
profile: function (cb) {
ProfileResource.getProfile(function (res) {
return cb(res.error, res.data);
});
},
countries: function (cb) {
ProfileReso... | ProfileService | identifier_name |
profile.service.js | angular.module('job')
.factory('ProfileService', ['async', '$resource', '$http', 'cmsConfig', function (async, $resource, $http, cmsConfig) {
var ProfileResource = $resource('', {}, {
// serverUrl
getProfile: {method: 'GET', url: cmsConfig.serverApi + '/profile'},
updateProfile: {method: 'POST',... | };
ProfileService.prototype.wrapDataToRequest = function (data) {
var formData = new FormData();
formData.append('x', data.x);
formData.append('y', data.y);
formData.append('width', data.width);
formData.append('height', data.height);
formData.append('file', data.file);
... | }).success(function (res) {
cb(res.error, res.data);
}); | random_line_split |
map.js | (function() {
var width = 960,
height = 480;
var projection = d3.geo.equirectangular()
.scale(153)
.translate([width / 2, height / 2]) | var graticule = d3.geo.graticule();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
svg.append("path")
.datum(graticule)
.attr("class", "graticule")
.attr("d", path);
d3.json("world-50m.json", function(error, world) {
if (error) throw error;
svg.inse... | .precision(.1);
var path = d3.geo.path()
.projection(projection);
| random_line_split |
test_submain_package.py | from mock import patch
from nose.tools import eq_
from helper import TestCase
import appvalidator.submain as submain
class TestSubmainPackage(TestCase):
@patch("appvalidator.submain.test_inner_package",
lambda x, z: "success")
def | (self):
"Tests the test_package function with simple data"
self.setup_err()
name = "tests/resources/submain/install_rdf.xpi"
with open(name) as pack:
result = submain.test_package(self.err, pack, name)
self.assert_silent()
eq_(result, "success")
@patch... | test_package_pass | identifier_name |
test_submain_package.py | from mock import patch
from nose.tools import eq_
from helper import TestCase
import appvalidator.submain as submain
class TestSubmainPackage(TestCase):
|
name = "tests/resources/junk.xpi"
with open(name) as pack:
result = submain.test_package(self.err, pack, name)
self.assert_failed()
def test_package_corrupt(self):
"Tests the test_package function fails with a corrupt file"
self.setup_err()
name = "te... | @patch("appvalidator.submain.test_inner_package",
lambda x, z: "success")
def test_package_pass(self):
"Tests the test_package function with simple data"
self.setup_err()
name = "tests/resources/submain/install_rdf.xpi"
with open(name) as pack:
result = subma... | identifier_body |
test_submain_package.py | from mock import patch
from nose.tools import eq_
from helper import TestCase | class TestSubmainPackage(TestCase):
@patch("appvalidator.submain.test_inner_package",
lambda x, z: "success")
def test_package_pass(self):
"Tests the test_package function with simple data"
self.setup_err()
name = "tests/resources/submain/install_rdf.xpi"
with open(n... |
import appvalidator.submain as submain
| random_line_split |
dependency_graph.rs | //! Functions related to working with dependency graphs
//!
//! For example, given a set of maybe recursive functions, you want
//! to order them such that the type signatures can be determined completely.
//! If you put mutually recursive functions together in groups, these groups
//! can then be placed in a DAG of de... | .ids()
.flat_map(|member| &siblings_out_refs[member])
.filter(|out_ref| !group.contains(out_ref))
.map(|out_ref| {
groups
.iter()
.find(|&(_, ref group2)| group2.contains(out_ref))
.map(|(n, _)| *n)
.unwrap()
... | random_line_split | |
dependency_graph.rs | //! Functions related to working with dependency graphs
//!
//! For example, given a set of maybe recursive functions, you want
//! to order them such that the type signatures can be determined completely.
//! If you put mutually recursive functions together in groups, these groups
//! can then be placed in a DAG of de... | <'src>(
start: &'src str,
current: &'src str,
siblings_out_refs: &BTreeMap<&str, BTreeSet<&'src str>>,
visited: &mut BTreeSet<&'src str>,
) -> BTreeSet<&'src str> {
if current == start && visited.contains(current) {
once(current).collect()
} else if visited.contains(current) {
BT... | circular_def_members_ | identifier_name |
dependency_graph.rs | //! Functions related to working with dependency graphs
//!
//! For example, given a set of maybe recursive functions, you want
//! to order them such that the type signatures can be determined completely.
//! If you put mutually recursive functions together in groups, these groups
//! can then be placed in a DAG of de... |
refs
}
Let(ref l) => {
let shadoweds = l.bindings
.ids()
.filter_map(|id| if siblings.remove(id) { Some(id) } else { None })
.collect::<Vec<_>>();
let refs = l.bindings
.bindings()
.map(|... | {
siblings.insert(l.param_ident.s);
} | conditional_block |
dependency_graph.rs | //! Functions related to working with dependency graphs
//!
//! For example, given a set of maybe recursive functions, you want
//! to order them such that the type signatures can be determined completely.
//! If you put mutually recursive functions together in groups, these groups
//! can then be placed in a DAG of de... |
/// Group sets of circularly referencing bindings together, to make
/// the inter-group relation acyclic.
fn group_by_circularity<'src>(
mut bindings: BTreeMap<&'src str, Binding<'src>>,
siblings_out_refs: &BTreeMap<&'src str, BTreeSet<&'src str>>,
) -> BTreeMap<usize, Group<'src>> {
let mut n = 0;
le... | {
let mut visited = BTreeSet::new();
circular_def_members_(s, s, siblings_out_refs, &mut visited)
} | identifier_body |
button.ts | import {NgModule,Directive,ElementRef,AfterViewInit,OnDestroy,HostBinding,HostListener,Input} from '@angular/core';
import {DomHandler} from '../dom/domhandler';
import {CommonModule} from '@angular/common';
@Directive({
selector: '[pButton]',
host: {
'[class.ui-state-hover]': 'hover&&!isDisabled()',
... |
public active: boolean;
public initialized: boolean;
constructor(public el: ElementRef, public domHandler: DomHandler) {}
ngAfterViewInit() {
this.domHandler.addMultipleClasses(this.el.nativeElement, this.getStyleClass());
if(this.icon) {
let iconElement = doc... |
public focus: boolean; | random_line_split |
button.ts | import {NgModule,Directive,ElementRef,AfterViewInit,OnDestroy,HostBinding,HostListener,Input} from '@angular/core';
import {DomHandler} from '../dom/domhandler';
import {CommonModule} from '@angular/common';
@Directive({
selector: '[pButton]',
host: {
'[class.ui-state-hover]': 'hover&&!isDisabled()',
... | (val: string) {
this._label = val;
if(this.initialized) {
this.domHandler.findSingle(this.el.nativeElement, '.ui-button-text').textContent = this._label;
}
}
ngOnDestroy() {
while(this.el.nativeElement.hasChildNodes()) {
this.el.nativeEle... | label | identifier_name |
block-ui-instance.service.ts | import { Injectable } from '@angular/core';
import { Observable, ReplaySubject } from 'rxjs';
import { BlockUIActions } from '../constants/block-ui-actions.constant';
import { BlockUIDefaultName } from '../constants/block-ui-default-name.constant';
import { NgBlockUI } from '../models/block-ui.model';
import { BlockUIS... | };
}
} | action,
message
}); | random_line_split |
block-ui-instance.service.ts | import { Injectable } from '@angular/core';
import { Observable, ReplaySubject } from 'rxjs';
import { BlockUIActions } from '../constants/block-ui-actions.constant';
import { BlockUIDefaultName } from '../constants/block-ui-default-name.constant';
import { NgBlockUI } from '../models/block-ui.model';
import { BlockUIS... |
}
private dispatch(subject: ReplaySubject<any>, action: BlockUIActions, name: string = BlockUIDefaultName): Function {
return (message?: any): void => {
subject.next({
name,
action,
message
});
};
}
}
| {
this.blockUIInstances[name].isActive = isActive;
} | conditional_block |
block-ui-instance.service.ts | import { Injectable } from '@angular/core';
import { Observable, ReplaySubject } from 'rxjs';
import { BlockUIActions } from '../constants/block-ui-actions.constant';
import { BlockUIDefaultName } from '../constants/block-ui-default-name.constant';
import { NgBlockUI } from '../models/block-ui.model';
import { BlockUIS... |
}
| {
return (message?: any): void => {
subject.next({
name,
action,
message
});
};
} | identifier_body |
block-ui-instance.service.ts | import { Injectable } from '@angular/core';
import { Observable, ReplaySubject } from 'rxjs';
import { BlockUIActions } from '../constants/block-ui-actions.constant';
import { BlockUIDefaultName } from '../constants/block-ui-default-name.constant';
import { NgBlockUI } from '../models/block-ui.model';
import { BlockUIS... | ({ action, name }: BlockUIEvent): void {
let isActive: boolean = null;
switch (action) {
case (BlockUIActions.START):
isActive = true;
break;
case (BlockUIActions.STOP):
case (BlockUIActions.RESET):
isActive = false;
break;
}
if (isActive !== null) {
... | blockUIMiddleware | identifier_name |
progress_test.py | # coding=utf8
import time
import random
import unittest
from qiniuManager.progress import *
class Pro(object):
def __init__(self):
self.progressed = 0
self.total = 100
self.title = 'test'
self.chunked = False
self.chunk_recved = 0
self.start = time.time() |
@bar(fill='x')
def loader_x(self):
self._normal_loader()
self.title = "x"
@bar()
def auto_loader(self):
self._normal_loader()
self.title = "长度占满宽度"
def _normal_loader(self):
time.sleep(0.01)
self.progressed += 1
def _chunked_loader(self):
... |
@bar(100, '=')
def loader(self):
self._normal_loader()
self.title = "固定长度" | random_line_split |
progress_test.py | # coding=utf8
import time
import random
import unittest
from qiniuManager.progress import *
class Pro(object):
def __init__(self):
self.progressed = 0
self.total = 100
self.title = 'test'
self.chunked = False
self.chunk_recved = 0
self.start = time.time()
@bar... | chunked_loader(self):
self._chunked_loader()
self.title = "full width"
@bar(100)
def fixed_chunked_loader(self):
self._chunked_loader()
self.title = "fixed width"
class ProgressTester(unittest.TestCase):
def test_100_progress(self):
print("进度条换行")
Pro().lo... | lf.total
@bar()
def | conditional_block |
progress_test.py | # coding=utf8
import time
import random
import unittest
from qiniuManager.progress import *
class Pro(object):
def __init__(self):
self.progressed = 0
self.total = 100
self.title = 'test'
self.chunked = False
self.chunk_recved = 0
self.start = time.time()
@bar... | ader(self):
time.sleep(0.01)
self.progressed += 1
def _chunked_loader(self):
self.chunked = True
time.sleep(0.01)
self.chunk_recved += random.randrange(3, 1000000)
if time.time() - self.start > 5:
self.progressed = self.total
@bar()
def chunked... | rmal_loader()
self.title = "长度占满宽度"
def _normal_lo | identifier_body |
progress_test.py | # coding=utf8
import time
import random
import unittest
from qiniuManager.progress import *
class Pro(object):
def __init__(self):
self.progressed = 0
self.total = 100
self.title = 'test'
self.chunked = False
self.chunk_recved = 0
self.start = time.time()
@bar... | .sleep(0.01)
self.progressed += 1
def _chunked_loader(self):
self.chunked = True
time.sleep(0.01)
self.chunk_recved += random.randrange(3, 1000000)
if time.time() - self.start > 5:
self.progressed = self.total
@bar()
def chunked_loader(self):
s... | :
time | identifier_name |
atsc_rx_filter.py | #!/usr/bin/env /usr/bin/python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your o... | pfb = filter.pfb_arb_resampler_ccf(interp, rrc_taps, nfilts)
# Connect pipeline
self.connect(self, pfb, self)
| gr.hier_block2.__init__(self, "atsc_rx_filter",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
# Create matched RX filter with RRC response for fractional
# in... | identifier_body |
atsc_rx_filter.py | #!/usr/bin/env /usr/bin/python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your o... | pfb = filter.pfb_arb_resampler_ccf(interp, rrc_taps, nfilts)
# Connect pipeline
self.connect(self, pfb, self) | excess_bw, # ATSC RRC excess bandwidth
ntaps) # Length of filter
| random_line_split |
atsc_rx_filter.py | #!/usr/bin/env /usr/bin/python
#
# Copyright 2014 Free Software Foundation, Inc.
#
# This file is part of GNU Radio
#
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your o... | (self, input_rate, sps):
gr.hier_block2.__init__(self, "atsc_rx_filter",
gr.io_signature(1, 1, gr.sizeof_gr_complex), # Input signature
gr.io_signature(1, 1, gr.sizeof_gr_complex)) # Output signature
# Create matched RX filter with RRC res... | __init__ | identifier_name |
milestones.py | #!/usr/bin/env vpython3
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script for updating the active milestones for the chromium project.
To activate a new chromium branch, run the following from the ... |
return args
class MilestonesException(Exception):
pass
_NUMBER_RE = re.compile('([0-9]+)')
def numeric_sort_key(s):
# The capture group in the regex means that the numeric portions are returned,
# odd indices will be the numeric portions of the string (the 0th or last
# element will be empty if the strin... | parser.error('no sub-command specified') | conditional_block |
milestones.py | #!/usr/bin/env vpython3
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script for updating the active milestones for the chromium project.
To activate a new chromium branch, run the following from the ... | (milestones, milestone):
if milestone not in milestones:
raise MilestonesException(
f'{milestone!r} does not refer to an active milestone: '
f'{list(milestones.keys())}')
del milestones[milestone]
milestones = {
k: milestones[k] for k in sorted(milestones, key=numeric_sort_key)
}
... | remove_milestone | identifier_name |
milestones.py | #!/usr/bin/env vpython3
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script for updating the active milestones for the chromium project.
To activate a new chromium branch, run the following from the ... |
milestones = {
k: milestones[k] for k in sorted(milestones, key=numeric_sort_key)
}
return json.dumps(milestones, indent=4) + '\n'
def activate_cmd(args):
with open(args.milestones_json) as f:
milestones = json.load(f)
milestones = add_milestone(milestones, args.milestone, args.branch)
with o... | 'name': f'm{milestone}',
'project': f'chromium-m{milestone}',
'ref': f'refs/branch-heads/{branch}',
} | random_line_split |
milestones.py | #!/usr/bin/env vpython3
# Copyright 2020 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Script for updating the active milestones for the chromium project.
To activate a new chromium branch, run the following from the ... |
def main():
args = parse_args()
try:
args.func(args)
except MilestonesException as e:
print(str(e), file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main() | with open(args.milestones_json) as f:
milestones = json.load(f)
milestones = remove_milestone(milestones, args.milestone)
with open(args.milestones_json, 'w') as f:
f.write(milestones) | identifier_body |
load.rs | use cpython::{PyDict, PyList, PyObject, PyResult, PyString, Python, PythonObject, ToPyObject};
use linked_hash_map::LinkedHashMap;
use yaml_rust::{Yaml, YamlLoader};
fn convert_yaml_to_dict(py: Python, yaml: &LinkedHashMap<Yaml, Yaml>) -> PyDict {
yaml.iter().fold(PyDict::new(py), |acc, (k, v)| {
let key =... | (py: Python, yaml: &Yaml) -> PyObject {
match &yaml {
Yaml::Null => py.None(),
Yaml::Hash(_) => convert_yaml_to_dict(py, yaml.as_hash().unwrap()).into_object(),
Yaml::String(_) => PyString::new(py, yaml.as_str().unwrap()).into_object(),
Yaml::Integer(_) => yaml.as_i64().unwrap().to_p... | from_yaml_to_python | identifier_name |
load.rs | use cpython::{PyDict, PyList, PyObject, PyResult, PyString, Python, PythonObject, ToPyObject};
use linked_hash_map::LinkedHashMap;
use yaml_rust::{Yaml, YamlLoader};
fn convert_yaml_to_dict(py: Python, yaml: &LinkedHashMap<Yaml, Yaml>) -> PyDict {
yaml.iter().fold(PyDict::new(py), |acc, (k, v)| {
let key =... | Err(e) => panic!("Cannot convert Python string into &str: {:?}", e),
};
// Load first doc from stream
let docs = match YamlLoader::load_from_str(&native_stream) {
Ok(d) => d,
Err(e) => panic!("{:?}", e),
};
let doc = &docs[0];
// Convert into proper Python's objects
... | random_line_split | |
load.rs | use cpython::{PyDict, PyList, PyObject, PyResult, PyString, Python, PythonObject, ToPyObject};
use linked_hash_map::LinkedHashMap;
use yaml_rust::{Yaml, YamlLoader};
fn convert_yaml_to_dict(py: Python, yaml: &LinkedHashMap<Yaml, Yaml>) -> PyDict {
yaml.iter().fold(PyDict::new(py), |acc, (k, v)| {
let key =... |
pub fn safe_load(py: Python, stream: &PyString) -> PyResult<PyObject> {
// Convert stream into Rust string
let native_stream = match stream.to_string(py) {
Ok(s) => s,
Err(e) => panic!("Cannot convert Python string into &str: {:?}", e),
};
// Load first doc from stream
let docs = ... | {
match &yaml {
Yaml::Null => py.None(),
Yaml::Hash(_) => convert_yaml_to_dict(py, yaml.as_hash().unwrap()).into_object(),
Yaml::String(_) => PyString::new(py, yaml.as_str().unwrap()).into_object(),
Yaml::Integer(_) => yaml.as_i64().unwrap().to_py_object(py).into_object(),
Ya... | identifier_body |
load.rs | use cpython::{PyDict, PyList, PyObject, PyResult, PyString, Python, PythonObject, ToPyObject};
use linked_hash_map::LinkedHashMap;
use yaml_rust::{Yaml, YamlLoader};
fn convert_yaml_to_dict(py: Python, yaml: &LinkedHashMap<Yaml, Yaml>) -> PyDict {
yaml.iter().fold(PyDict::new(py), |acc, (k, v)| {
let key =... | ,
Yaml::Alias(_) => unimplemented!(), // Not supported yet http://chyh1990.github.io/yaml-rust/doc/yaml_rust/yaml/enum.Yaml.html#variant.Alias
Yaml::BadValue => panic!("Bad value converting {:?}", yaml),
}
}
pub fn safe_load(py: Python, stream: &PyString) -> PyResult<PyObject> {
// Convert stre... | {
py.False().into_object()
} | conditional_block |
test_msgbox.py | # Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Sof... | #
# You should have received a copy of the GNU General Public License
# along with qutebrowser. If not, see <http://www.gnu.org/licenses/>.
"""Tests for qutebrowser.misc.msgbox."""
import pytest
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QMessageBox, QWidget
from qutebrowser.misc import msgbox
from qu... | # but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details. | random_line_split |
test_msgbox.py | # Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Sof... |
assert box.icon() == icon
assert box.standardButtons() == buttons
assert box.text() == text
assert box.parent() is parent
@pytest.mark.parametrize('plain_text, expected', [
(True, Qt.PlainText),
(False, Qt.RichText),
(None, Qt.AutoText),
])
def test_plain_text(qtbot, plain_text, expected)... | assert box.windowTitle() == title | conditional_block |
test_msgbox.py | # Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Sof... |
def test_finished_signal(qtbot):
"""Make sure we can pass a slot to be called when the dialog finished."""
signal_triggered = False
def on_finished():
nonlocal signal_triggered
signal_triggered = True
box = msgbox.msgbox(parent=None, title='foo', text='foo',
... | box = msgbox.msgbox(parent=None, title='foo', text='foo',
icon=QMessageBox.Information, plain_text=plain_text)
qtbot.add_widget(box)
assert box.textFormat() == expected | identifier_body |
test_msgbox.py | # Copyright 2015-2021 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# This file is part of qutebrowser.
#
# qutebrowser is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Sof... | (qtbot):
"""Test basic QMessageBox attributes."""
title = 'title'
text = 'text'
parent = QWidget()
qtbot.add_widget(parent)
icon = QMessageBox.Critical
buttons = QMessageBox.Ok | QMessageBox.Cancel
box = msgbox.msgbox(parent=parent, title=title, text=text, icon=icon,
... | test_attributes | identifier_name |
web.py | from flask import *
from pyZPL import *
from printLabel import printLabel
import xml.etree.ElementTree as ET
import os
app = Flask(__name__)
dn = os.path.dirname(os.path.realpath(__file__))+"/"
tree = ET.parse(dn+"pace.xml")
customElements = tree.findall(".//*[@id]")
customItems = []
for element in customElements:
... |
@app.route('/print', methods=['POST'])
def print_():
customItemsModified = []
if request.method == 'POST':
for key,value in request.form.iteritems():
newItem = ZPLCustomItem()
split = key.split('_')
newItem.type = split[len(split)-1]
newItem.ID = str... | return render_template("index.html",items=customItems) | identifier_body |
web.py | from flask import *
from pyZPL import *
from printLabel import printLabel
import xml.etree.ElementTree as ET
import os
app = Flask(__name__)
dn = os.path.dirname(os.path.realpath(__file__))+"/"
tree = ET.parse(dn+"pace.xml")
customElements = tree.findall(".//*[@id]")
customItems = []
for element in customElements:
... | app.debug = True
app.run() | else:
return "can has post?"
if __name__ == '__main__': | random_line_split |
web.py | from flask import *
from pyZPL import *
from printLabel import printLabel
import xml.etree.ElementTree as ET
import os
app = Flask(__name__)
dn = os.path.dirname(os.path.realpath(__file__))+"/"
tree = ET.parse(dn+"pace.xml")
customElements = tree.findall(".//*[@id]")
customItems = []
for element in customElements:
... |
customItems.append(newItem)
@app.route('/')
def root():
return render_template("index.html",items=customItems)
@app.route('/print', methods=['POST'])
def print_():
customItemsModified = []
if request.method == 'POST':
for key,value in request.form.iteritems():
newItem = ZPLCus... | newItem.fixed = "readonly" | conditional_block |
web.py | from flask import *
from pyZPL import *
from printLabel import printLabel
import xml.etree.ElementTree as ET
import os
app = Flask(__name__)
dn = os.path.dirname(os.path.realpath(__file__))+"/"
tree = ET.parse(dn+"pace.xml")
customElements = tree.findall(".//*[@id]")
customItems = []
for element in customElements:
... | ():
return render_template("index.html",items=customItems)
@app.route('/print', methods=['POST'])
def print_():
customItemsModified = []
if request.method == 'POST':
for key,value in request.form.iteritems():
newItem = ZPLCustomItem()
split = key.split('_')
n... | root | identifier_name |
graphite.py | """
homeassistant.components.graphite
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component that records all events and state changes and feeds the data to
a graphite installation.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/graphite/
"""
import logging
import... |
def _send_to_graphite(self, data):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect((self._host, self._port))
sock.sendall(data.encode('ascii'))
sock.send('\n'.encode('ascii'))
sock.close()
def _report_attributes(self, e... | """ Queue an event for processing. """
if self.is_alive() or not self._we_started:
_LOGGER.debug('Received event')
self._queue.put(event)
else:
_LOGGER.error('Graphite feeder thread has died, not '
'queuing event!') | identifier_body |
graphite.py | """
homeassistant.components.graphite
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component that records all events and state changes and feeds the data to
a graphite installation.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/graphite/
"""
import logging
import... | sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(10)
sock.connect((self._host, self._port))
sock.sendall(data.encode('ascii'))
sock.send('\n'.encode('ascii'))
sock.close()
def _report_attributes(self, entity_id, new_state):
now = time.... | def _send_to_graphite(self, data): | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.