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 |
|---|---|---|---|---|
share.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import base64 | import json
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from behave import *
@step('I share first element in the history list')
def step_impl(context):
context.execute_steps(u'''
given I ope... | random_line_split | |
0002_auto_20150708_1158.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class | (migrations.Migration):
dependencies = [
('taskmanager', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
... | Migration | identifier_name |
0002_auto_20150708_1158.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
| name='project',
unique_together=set([('user', 'name')]),
),
]
| dependencies = [
('taskmanager', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('name', models.CharFiel... | identifier_body |
0002_auto_20150708_1158.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import django.core.validators
class Migration(migrations.Migration):
dependencies = [
('taskmanager', '0001_initial'), | ]
operations = [
migrations.CreateModel(
name='Project',
fields=[
('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),
('name', models.CharField(verbose_name='name', max_length=100, help_text='Enter th... | random_line_split | |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum HttpMethod {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlo... | HttpMethod::Checkout => "CHECKOUT".to_string(),
HttpMethod::Merge => "MERGE".to_string(),
HttpMethod::MSearch => "M-SEARCH".to_string(),
HttpMethod::Notify => "NOTIFY".to_string(),
HttpMethod::Subscribe => "SUBSCRIBE".to_string(),
... | {
match *self {
HttpMethod::Delete => "DELETE".to_string(),
HttpMethod::Get => "GET".to_string(),
HttpMethod::Head => "HEAD".to_string(),
HttpMethod::Post => "POST".to_string(),
HttpMethod::Put => "Put".to_string(),
... | identifier_body |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum | {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlock,
// subversion
Report,
MKActivity,
Checkout,
Merge,
// upnp
MSearch,
No... | HttpMethod | identifier_name |
http_method.rs | /// `HttpMethod` defines supported HTTP methods.
#[derive(PartialEq, Eq, Clone, Copy)]
pub enum HttpMethod {
Delete,
Get,
Head,
Post,
Put,
// pathological
Connect,
Options,
Trace,
// webdav
Copy,
Lock,
MKCol,
Move,
PropFind,
PropPatch,
Search,
Unlo... | Report,
MKActivity,
Checkout,
Merge,
// upnp
MSearch,
Notify,
Subscribe,
Unsubscribe,
// RFC-5789
Patch,
Purge,
// CalDAV
MKCalendar,
}
impl ToString for HttpMethod {
fn to_string(&self) -> String {
match *self {
HttpMethod::Delete =>... | random_line_split | |
lib.rs | //! `bincode` is a crate for encoding and decoding using a tiny binary
//! serialization strategy.
//!
//! There are simple functions for encoding to `Vec<u8>` and decoding from
//! `&[u8]`, but the meat of the library is the `encode_into` and `decode_from`
//! functions which respectively allow encoding into a `std::i... | {
Infinite,
Bounded(u64)
}
| SizeLimit | identifier_name |
lib.rs | //! `bincode` is a crate for encoding and decoding using a tiny binary
//! serialization strategy.
//!
//! There are simple functions for encoding to `Vec<u8>` and decoding from
//! `&[u8]`, but the meat of the library is the `encode_into` and `decode_from`
//! functions which respectively allow encoding into a `std::i... | pub use refbox::{RefBox, StrBox, SliceBox};
mod refbox;
pub mod rustc_serialize;
pub mod serde;
/// A limit on the amount of bytes that can be read or written.
///
/// Size limits are an incredibly important part of both encoding and decoding.
///
/// In order to prevent DOS attacks on a decoder, it is important to l... | random_line_split | |
base.command.ts | import { Observable } from 'rxjs/Observable';
import { CommandPayload } from './payloads/base.command.payload';
import { Gateway } from '../gateways/base.gateway';
import { Observer } from 'rxjs/Observer';
export enum CommandState {
IDLE,
EXECUTING,
INVOKED
};
export interface CommandResult {
command: Command... |
concat(command: Command): void {
this._payload.concat(command.payload);
}
serialize(): string | Blob | ArrayBuffer {
return this._payload.serialize();
}
parse(response: any): any {
return this._payload.parse(response);
};
invoke(context?: Command): Observable<CommandResult> {
context ... | {
return this._payload.mimeType;
} | identifier_body |
base.command.ts | import { Observable } from 'rxjs/Observable';
import { CommandPayload } from './payloads/base.command.payload';
import { Gateway } from '../gateways/base.gateway';
import { Observer } from 'rxjs/Observer';
export enum CommandState {
IDLE,
EXECUTING,
INVOKED
};
export interface CommandResult {
command: Command... | (): any {
return this._method;
}
set method(value: any) {
this._method = value;
}
set gateway(value: Gateway) {
this._gateway = value;
}
get mimeType() {
return this._payload.mimeType;
}
concat(command: Command): void {
this._payload.concat(command.payload);
}
serialize(): s... | method | identifier_name |
base.command.ts | import { Observable } from 'rxjs/Observable';
import { CommandPayload } from './payloads/base.command.payload';
import { Gateway } from '../gateways/base.gateway';
import { Observer } from 'rxjs/Observer';
export enum CommandState {
IDLE,
EXECUTING,
INVOKED
};
export interface CommandResult {
command: Command... | static _id: number = 0;
protected _state: CommandState;
protected _payload: CommandPayload;
protected _commands: Command[] = [];
protected _method: any;
protected _gateway: Gateway;
protected _id: number = 0;
constructor(payload?: CommandPayload) {
this._payload = payload;
Command._id += 1;
... |
export abstract class Command { | random_line_split |
index.js | module.exports = function(el, state, container) {
var ul = el.getElementsByTagName('ul')[0]
var lastFlags = []
var controlsTouch = -1
var containerTouch = {"id":-1, "x":-1, "y":-1}
el.addEventListener('touchstart', startTouchControls)
el.addEventListener('touchmove', handleTouchControls)
el.addEventListen... | (event) {
event.preventDefault()
var touch = null
if (event.targetTouches.length > 1) {
for (t in event.targetTouches) {
if (event.targetTouches[t].identifier === controlsTouch) {
touch = event.targetTouches[t]
break
}
}
} else {
touch = event.target... | handleTouchControls | identifier_name |
index.js | module.exports = function(el, state, container) {
var ul = el.getElementsByTagName('ul')[0]
var lastFlags = []
var controlsTouch = -1
var containerTouch = {"id":-1, "x":-1, "y":-1}
el.addEventListener('touchstart', startTouchControls)
el.addEventListener('touchmove', handleTouchControls)
el.addEventListen... | controlsTouch = event.targetTouches[0].identifier
}
handleTouchControls(event)
}
function handleTouchControls(event) {
event.preventDefault()
var touch = null
if (event.targetTouches.length > 1) {
for (t in event.targetTouches) {
if (event.targetTouches[t].identifier === cont... | container.addEventListener('touchmove', handleTouchContainer)
container.addEventListener('touchend', unTouchContainer)
function startTouchControls(event) {
if (controlsTouch === -1) { | random_line_split |
index.js | module.exports = function(el, state, container) {
var ul = el.getElementsByTagName('ul')[0]
var lastFlags = []
var controlsTouch = -1
var containerTouch = {"id":-1, "x":-1, "y":-1}
el.addEventListener('touchstart', startTouchControls)
el.addEventListener('touchmove', handleTouchControls)
el.addEventListen... |
}
function unTouchControls() {
setState(lastFlags, 0)
lastFlags = []
controlsTouch = -1
}
function setState(states, value) {
var delta = {}
for(s in states) {
delta[states[s]] = value
}
state.write(delta)
}
function startTouchContainer(event) {
if (containerTouch.id ==... | {
// Start jumping (in additional to existing movement)
lastFlags.push('jump')
setState(['jump'], 1)
} | conditional_block |
index.js | module.exports = function(el, state, container) {
var ul = el.getElementsByTagName('ul')[0]
var lastFlags = []
var controlsTouch = -1
var containerTouch = {"id":-1, "x":-1, "y":-1}
el.addEventListener('touchstart', startTouchControls)
el.addEventListener('touchmove', handleTouchControls)
el.addEventListen... |
function handleTouchContainer(event) {
event.preventDefault()
var touch = null, x = y = -1, delta = {}
for (t in event.targetTouches) {
if (event.targetTouches[t].identifier === containerTouch.id) {
touch = event.targetTouches[t]
break
}
}
if (touch === null) return
... | {
if (containerTouch.id === -1) {
containerTouch.id = event.targetTouches[0].identifier
containerTouch.x = event.targetTouches[0].clientX
containerTouch.y = event.targetTouches[0].clientY
}
handleTouchContainer(event)
} | identifier_body |
trait-attributes.rs | // Copyright 2018 The Rust Project Developers. See the COPYRIGHT | // http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except accordin... | // file at the top-level directory of this distribution and at | random_line_split |
trait-attributes.rs | // Copyright 2018 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 ... |
}
| {} | identifier_body |
trait-attributes.rs | // Copyright 2018 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 ... | ;
impl Bar {
// @has foo/struct.Bar.html '//h4[@id="method.bar"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar() {}
// @has foo/struct.Bar.html '//h4[@id="method.bar2"]//div[@class="docblock attributes"]' '#[must_use]'
#[must_use]
pub fn bar2() {}
}
| Bar | identifier_name |
locale.js | /**
* Shopware 4.0
* Copyright © 2012 shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permi... | /**
* Shopware Backend - ErrorReporter Main Model
*
* todo@all: Documentation
*/
Ext.define('Shopware.apps.UserManager.model.Locale', {
extend: 'Ext.data.Model',
fields: [ 'id', 'name' ]
}); | * @version $Id$
* @author shopware AG
*/
| random_line_split |
attributes.rs | #!/she-bang line
//inner attributes
#![crate_type = "lib"]
#![crate_name = "rary"]
mod empty {}
fn main() {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() |
struct S<#[foo]'a, #[may_dangle] T> {}
#[macro_export]
macro_rules! give_me_struct {
($name:ident) => {
#[allow(non_camel_case_types)]
struct $name;
}
}
#[cfg(not(test))]
give_me_struct! {
hello_world
}
#[post("/", data = "<todo_form>")]
fn string_value() {}
| {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
} | identifier_body |
attributes.rs | #!/she-bang line
//inner attributes | #![crate_name = "rary"]
mod empty {}
fn main() {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
}
stru... | #![crate_type = "lib"] | random_line_split |
attributes.rs | #!/she-bang line
//inner attributes
#![crate_type = "lib"]
#![crate_name = "rary"]
mod empty {}
fn | () {
#![crate_type = "lib"]
}
enum E {
#[cfg(test)] F(#[cfg(test)] i32)
}
#[empty_attr()]
const T: i32 = 92;
fn attrs_on_statements() {
#[cfg(test)]
let x = 92;
#[cfg(test)]
loop {}
#[cfg(test)]
1 + 1;
S { #[foo] foo: 92 };
}
struct S<#[foo]'a, #[may_dangle] T> {}
#[macro_exp... | main | identifier_name |
rule.js | /* Authors:
* Endi Sukma Dewata <edewata@redhat.com>
*
* Copyright (C) 2010 Red Hat
* see file 'COPYING' for use and warranty information
*
* 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 Founda... |
var exclude = that.values;
if (that.external) {
exclude = [];
for (var i=0; i<that.values.length; i++) {
exclude.push(that.values[i][that.name]);
}
}
return IPA.rule_association_adder_dialog({
title: title,
pke... | var title = that.add_title;
title = title.replace('${entity}', entity_label);
title = title.replace('${primary_key}', pkey);
title = title.replace('${other_entity}', other_entity_label); | random_line_split |
rule.js | /* Authors:
* Endi Sukma Dewata <edewata@redhat.com>
*
* Copyright (C) 2010 Red Hat
* see file 'COPYING' for use and warranty information
*
* 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 Founda... |
}
};
that.init();
return that;
};
/**
* Rule radio widget
*
* Intended to be used especially by rule widget.
*
* @class IPA.rule_radio_widget
* @extends IPA.radio_widget
*/
IPA.rule_radio_widget = function(spec) {
spec = spec || {};
var that = IPA.radio_widget(spec);
/**
... | {
var table = that.tables[i];
var table_widget = that.widgets.get_widget(table.name);
table_widget.set_enabled(enabled);
} | conditional_block |
imageadmin.py | # -*- coding: utf-8 -*-
from django import forms
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.translation import ugettext as _
from filer.admin.fileadmin import FileAdmin
from filer.models import Image
class ImageAdminForm(forms.ModelForm):
subject_location = forms.Ch... |
class ImageAdmin(FileAdmin):
form = ImageAdminForm
ImageAdmin.fieldsets = ImageAdmin.build_fieldsets(
extra_main_fields=('author', 'default_alt_text', 'default_caption',),
extra_fieldsets=(
('Subject Location', {
'fields': ('subject_location',),
'classes': ('collapse',),... | css = {
# 'all': (settings.MEDIA_URL + 'filer/css/focal_point.css',)
}
js = (
static('filer/js/raphael.js'),
static('filer/js/focal_point.js'),
) | identifier_body |
imageadmin.py | # -*- coding: utf-8 -*-
from django import forms
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.translation import ugettext as _ | from filer.models import Image
class ImageAdminForm(forms.ModelForm):
subject_location = forms.CharField(
max_length=64, required=False,
label=_('Subject location'),
help_text=_('Location of the main subject of the scene.'))
def sidebar_image_ratio(self):
if self.instance:
... |
from filer.admin.fileadmin import FileAdmin | random_line_split |
imageadmin.py | # -*- coding: utf-8 -*-
from django import forms
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.translation import ugettext as _
from filer.admin.fileadmin import FileAdmin
from filer.models import Image
class | (forms.ModelForm):
subject_location = forms.CharField(
max_length=64, required=False,
label=_('Subject location'),
help_text=_('Location of the main subject of the scene.'))
def sidebar_image_ratio(self):
if self.instance:
# this is very important. It forces the valu... | ImageAdminForm | identifier_name |
imageadmin.py | # -*- coding: utf-8 -*-
from django import forms
from django.contrib.staticfiles.templatetags.staticfiles import static
from django.utils.translation import ugettext as _
from filer.admin.fileadmin import FileAdmin
from filer.models import Image
class ImageAdminForm(forms.ModelForm):
subject_location = forms.Ch... |
else:
return ''
class Meta:
model = Image
exclude = ()
class Media:
css = {
# 'all': (settings.MEDIA_URL + 'filer/css/focal_point.css',)
}
js = (
static('filer/js/raphael.js'),
static('filer/js/focal_point.js'),
... | return '%.6F' % self.instance.sidebar_image_ratio() | conditional_block |
reporter.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Config} from '@jest/types';
import {AssertionResult, TestResult} from '@jest/test-result';
import {fo... | failureMessage: formatResultsErrors(
testResults,
this._config,
this._globalConfig,
this._testPath,
),
numFailingTests,
numPassingTests,
numPendingTests,
numTodoTests,
perfStats: {
end: 0,
start: 0,
},
snapshot: {
... | {
let numFailingTests = 0;
let numPassingTests = 0;
let numPendingTests = 0;
let numTodoTests = 0;
const testResults = this._testResults;
testResults.forEach(testResult => {
if (testResult.status === 'failed') {
numFailingTests++;
} else if (testResult.status === 'pending') {... | identifier_body |
reporter.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Config} from '@jest/types';
import {AssertionResult, TestResult} from '@jest/test-result';
import {fo... | this._globalConfig = globalConfig;
this._config = config;
this._testPath = testPath;
this._testResults = [];
this._currentSuites = [];
this._resolve = null;
this._resultsPromise = new Promise(resolve => (this._resolve = resolve));
this._startTimes = new Map();
}
jasmineStarted(_runD... | constructor(
globalConfig: Config.GlobalConfig,
config: Config.ProjectConfig,
testPath: Config.Path,
) { | random_line_split |
reporter.ts | /**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import {Config} from '@jest/types';
import {AssertionResult, TestResult} from '@jest/test-result';
import {fo... | implements Reporter {
private _testResults: Array<AssertionResult>;
private _globalConfig: Config.GlobalConfig;
private _config: Config.ProjectConfig;
private _currentSuites: Array<string>;
private _resolve: any;
private _resultsPromise: Promise<TestResult>;
private _startTimes: Map<string, Microseconds>... | Jasmine2Reporter | identifier_name |
lib.rs | // The MIT License (MIT)
//
// Copyright (c) 2014 Jeremy Letang
//
// 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, c... | #![crate_type = "dylib"]
#![allow(dead_code, non_camel_case_types, missing_doc)]
#![feature(struct_variant)]
#![feature(globs)]
#![unstable]
extern crate libc;
pub use self::window::Window;
pub use self::video_mode::VideoMode;
pub use self::window_builder::WindowBuilder;
pub use self::context_settings::ContextSetting... |
#![crate_name = "verdigris"]
#![desc = "Multi plateform opengl windowing for Rust"]
#![license = "MIT"]
#![crate_type = "rlib"] | random_line_split |
angular-locale_en-lc.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n... | return PLURAL_CATEGORY.OTHER;}
});
}]);
| { return PLURAL_CATEGORY.ONE; } | conditional_block |
angular-locale_en-lc.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n... | "January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
],
"SHORTDAY": [
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
... | "AD"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
| random_line_split |
angular-locale_en-lc.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) |
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
... | {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
} | identifier_body |
angular-locale_en-lc.js | 'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function | (n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f... | getDecimals | identifier_name |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf... | (
&mut self,
id: U256,
new_gas: Option<U256>,
new_gas_price: Option<U256>,
new_min_block: Option<Option<BlockNumber>>,
pwd: &str
) -> BoxFuture<Result<U256, RpcError>, Canceled>
{
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { g... | confirm_request | identifier_name |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf... |
pub fn reject_request(&mut self, id: U256) ->
BoxFuture<Result<bool, RpcError>, Canceled>
{
self.rpc.request("signer_rejectRequest", vec![
JsonValue::String(format!("{:#x}", id))
])
}
}
| {
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { gas_price: new_gas_price, gas: new_gas, min_block: new_min_block }),
to_value(&pwd),
])
} | identifier_body |
signer_client.rs | use client::{Rpc, RpcError};
use rpc::v1::types::{ConfirmationRequest, TransactionModification, U256, BlockNumber};
use serde_json::{Value as JsonValue, to_value};
use std::path::PathBuf;
use futures::{BoxFuture, Canceled};
pub struct SignerRpc {
rpc: Rpc,
}
impl SignerRpc {
pub fn new(url: &str, authfile: &PathBuf... | id: U256,
new_gas: Option<U256>,
new_gas_price: Option<U256>,
new_min_block: Option<Option<BlockNumber>>,
pwd: &str
) -> BoxFuture<Result<U256, RpcError>, Canceled>
{
self.rpc.request("signer_confirmRequest", vec![
to_value(&format!("{:#x}", id)),
to_value(&TransactionModification { gas_price: new_g... | }
pub fn confirm_request(
&mut self, | random_line_split |
lazytox.py | #!/usr/bin/env python3
"""
Lazy 'tox' to quickly check if branch is up to PR standards.
This is NOT a tox replacement, only a quick check during development.
"""
import os
import asyncio
import sys
import re
import shlex
from collections import namedtuple
try:
from colorlog.escape_codes import escape_codes
except... | files = await git()
if not files:
print(
"No changed files found. Please ensure you have added your "
"changes with git add & git commit"
)
return
pyfile = re.compile(r".+\.py$")
pyfiles = [file for file in files if pyfile.match(file)]
print("=======... | async def main():
"""Run the main loop."""
# Ensure we are in the homeassistant root
os.chdir(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
| random_line_split |
lazytox.py | #!/usr/bin/env python3
"""
Lazy 'tox' to quickly check if branch is up to PR standards.
This is NOT a tox replacement, only a quick check during development.
"""
import os
import asyncio
import sys
import re
import shlex
from collections import namedtuple
try:
from colorlog.escape_codes import escape_codes
except... | (stream, display):
"""Read from stream line by line until EOF, display, and capture lines."""
output = []
while True:
line = await stream.readline()
if not line:
break
output.append(line)
display(line.decode()) # assume it doesn't block
return b"".join(output... | read_stream | identifier_name |
lazytox.py | #!/usr/bin/env python3
"""
Lazy 'tox' to quickly check if branch is up to PR standards.
This is NOT a tox replacement, only a quick check during development.
"""
import os
import asyncio
import sys
import re
import shlex
from collections import namedtuple
try:
from colorlog.escape_codes import escape_codes
except... |
lint_ok = True
for err in res:
err_msg = "{} {}:{} {}".format(err.file, err.line, err.col, err.msg)
# tests/* does not have to pass lint
if err.skip:
print(err_msg)
else:
printc(FAIL, err_msg)
lint_ok = False
return lint_ok
async def ... | printc(PASS, "Pylint and Flake8 passed") | conditional_block |
lazytox.py | #!/usr/bin/env python3
"""
Lazy 'tox' to quickly check if branch is up to PR standards.
This is NOT a tox replacement, only a quick check during development.
"""
import os
import asyncio
import sys
import re
import shlex
from collections import namedtuple
try:
from colorlog.escape_codes import escape_codes
except... |
async def flake8(files):
"""Exec flake8."""
_, log = await async_exec("flake8", "--doctests", *files)
res = []
for line in log.splitlines():
line = line.split(":")
if len(line) < 4:
continue
_fn = line[0].replace("\\", "/")
res.append(Error(_fn, line[1], li... | """Exec pylint."""
_, log = await async_exec("pylint", "-f", "parseable", "--persistent=n", *files)
res = []
for line in log.splitlines():
line = line.split(":")
if len(line) < 3:
continue
_fn = line[0].replace("\\", "/")
res.append(Error(_fn, line[1], "", line[2]... | identifier_body |
flat-map-observable-scalar.js | var oldFlatMapWithCurrentThreadScheduler = RxOld.Observable.range(0, 25, RxOld.Scheduler.currentThread).flatMap(RxOld.Observable.return(0, RxOld.Scheduler.currentThread));
var newFlatMapWithCurrentThreadScheduler = RxNew.Observable.range(0, 25, RxNew.Scheduler.immediate).flatMapTo(RxNew.Observable.return(0, RxN... | var RxOld = require("rx");
var RxNew = require("../../../../index");
module.exports = function (suite) {
| random_line_split | |
flat-map-observable-scalar.js | var RxOld = require("rx");
var RxNew = require("../../../../index");
module.exports = function (suite) {
var oldFlatMapWithCurrentThreadScheduler = RxOld.Observable.range(0, 25, RxOld.Scheduler.currentThread).flatMap(RxOld.Observable.return(0, RxOld.Scheduler.currentThread));
var newFlatMapWithCurrentThreadSc... | (){ }
}; | _complete | identifier_name |
flat-map-observable-scalar.js | var RxOld = require("rx");
var RxNew = require("../../../../index");
module.exports = function (suite) {
var oldFlatMapWithCurrentThreadScheduler = RxOld.Observable.range(0, 25, RxOld.Scheduler.currentThread).flatMap(RxOld.Observable.return(0, RxOld.Scheduler.currentThread));
var newFlatMapWithCurrentThreadSc... |
function _complete(){ }
}; | { } | identifier_body |
__init__.py | # -*- coding: utf-8 -*-
import json
from vilya.libs import api_errors
from vilya.models.project import CodeDoubanProject
from vilya.views.api.utils import RestAPIUI, api_require_login, jsonize
from vilya.views.api.repos.product import ProductUI
from vilya.views.api.repos.summary import SummaryUI
from vilya.views.api.... | def lang_stats(self, request):
if not self.repo:
raise api_errors.NotFoundError
if self.method == 'POST':
language = request.get_form_var('language', '')
languages = request.get_form_var('languages', '[]')
try:
languages = json.loads(la... | return RepositoryUI(name)
@jsonize | random_line_split |
__init__.py | # -*- coding: utf-8 -*-
import json
from vilya.libs import api_errors
from vilya.models.project import CodeDoubanProject
from vilya.views.api.utils import RestAPIUI, api_require_login, jsonize
from vilya.views.api.repos.product import ProductUI
from vilya.views.api.repos.summary import SummaryUI
from vilya.views.api.... | (self):
return CommitsUI(self.repo)
@property
def post_receive(self):
return PostReceiveUI(self.repo)
@property
def svn2git(self):
return SVN2GITUI(self.repo)
@property
def git2svn(self):
return GIT2SVNUI(self.repo)
@property
def issues(self):
... | commits | identifier_name |
__init__.py | # -*- coding: utf-8 -*-
import json
from vilya.libs import api_errors
from vilya.models.project import CodeDoubanProject
from vilya.views.api.utils import RestAPIUI, api_require_login, jsonize
from vilya.views.api.repos.product import ProductUI
from vilya.views.api.repos.summary import SummaryUI
from vilya.views.api.... |
else:
return dict(language=self.repo.language,
languages=self.repo.languages)
@property
def forks(self):
return ForksUI(self.repo)
@property
def pulls(self):
return PullsUI(self.repo)
@property
def product(self):
return Prod... | language = request.get_form_var('language', '')
languages = request.get_form_var('languages', '[]')
try:
languages = json.loads(languages)
except ValueError:
raise api_errors.NotJSONError
self.repo.language = language
self.repo.... | conditional_block |
__init__.py | # -*- coding: utf-8 -*-
import json
from vilya.libs import api_errors
from vilya.models.project import CodeDoubanProject
from vilya.views.api.utils import RestAPIUI, api_require_login, jsonize
from vilya.views.api.repos.product import ProductUI
from vilya.views.api.repos.summary import SummaryUI
from vilya.views.api.... |
def _q_access(request):
request.response.set_content_type('application/json; charset=utf-8')
class RepositoryUI(object):
_q_exports = [
'lang_stats', 'forks', 'pulls', 'summary',
'committers', 'name', 'owner', 'product',
'intern_banned', 'default_branch', 'commits',
'post_re... | return RepositoryUI(name) | identifier_body |
models.py | .lang,
"type_name": self.type_name,
"value_name": self.value_name,
}
if not nested:
data["concepts"] = [concept.to_json(nested=True) for concept in self.concepts.all()]
return data
def __str__(self):
return "{}: {}".format(self.type, self.value)... | "name": self.name,
"query": self.query,
"lang": self.lang,
}
if not nested:
data["tags"] = [tag.to_json(nested=True) for tag in self.tags.all()]
data["actions"] = [action.to_json(nested=True) for action in self.actions.all()]
return da... | """
Model concepts for open learner model
"""
identifier = models.CharField(max_length=20, blank=True)
query = models.TextField()
name = models.CharField(max_length=200)
lang = models.CharField(max_length=2)
tags = models.ManyToManyField(Tag, related_name="concepts", blank=True)
active =... | identifier_body |
models.py | .lang,
"type_name": self.type_name,
"value_name": self.value_name,
}
if not nested:
data["concepts"] = [concept.to_json(nested=True) for concept in self.concepts.all()]
return data
def __str__(self):
return "{}: {}".format(self.type, self.value)... |
else:
items = Concept.objects.get_concept_item_mapping(lang=lang)
environment = get_environment()
mastery_threshold = get_mastery_trashold()
for user, concepts in concepts.items():
all_items = list(set(flatten([items[c] for c in concepts])))
answer_c... | items = Concept.objects.get_concept_item_mapping(concepts=Concept.objects.filter(pk__in=set(flatten(concepts.values())))) | conditional_block |
models.py | .lang,
"type_name": self.type_name,
"value_name": self.value_name,
}
if not nested:
data["concepts"] = [concept.to_json(nested=True) for concept in self.concepts.all()]
return data
def __str__(self):
return "{}: {}".format(self.type, self.value)... | (models.Manager):
def prepare_related(self):
return self.prefetch_related('tags', 'actions')
@cache_pure()
def get_concept_item_mapping(self, concepts=None, lang=None):
"""
Get mapping of concepts to items belonging to concept.
Args:
concepts (list of Concept): ... | ConceptManager | identifier_name |
models.py | only_one_user = True
users = [users]
mapping = self.get_item_concept_mapping(lang)
current_user_stats = defaultdict(lambda: {})
user_stats_qs = UserStat.objects.filter(user__in=users, stat="answer_count") # we need only one type
if concepts is not None:
... | class UserStat(models.Model):
"""
Represent arbitrary statistic (float) of the user on concept
""" | random_line_split | |
logout.controller.tests.js | /*
This file is part of MyConference.
MyConference is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY;... | ctrl = $controller('LogoutCtrl', {
$scope: scope,
backendService: backendServiceMock,
$state: stateMock,
$ionicPopup: ionicPopupMock,
$translate: translateMock,
})
}))
// tests
it('should call backendService.logout function', function () {
expect(backendServiceMock.logout... | translateMock = jasmine.createSpy('$translate spy').and.returnValue(translateDfd.promise)
ionicPopupMock = jasmine.createSpyObj('$ionicPopup spy', ['alert'])
ionicPopupMock.alert.and.returnValue(alertDfd.promise)
stateMock = jasmine.createSpyObj('$state spy', ['go']) | random_line_split |
feature-gate-unboxed-closures.rs | // Copyright 2016 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 ... |
//~^^^ ERROR rust-call ABI is subject to change (see issue #29625)
}
fn main() {
assert_eq!(Test(1u32, 2u32), 3u32);
}
| {
a + b
} | identifier_body |
feature-gate-unboxed-closures.rs | // Copyright 2016 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 ... | () {
assert_eq!(Test(1u32, 2u32), 3u32);
}
| main | identifier_name |
feature-gate-unboxed-closures.rs | // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at | // <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.
struct Test;
impl FnOnce<(u32, u32)> for Test {
type Output = u32;
extern "rust-call" fn call_once(self, (a, b): (u32, u32)) -> u32 {
a ... | // 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 | random_line_split |
fastqc.py | ##
# Copyright 2009-2013 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | """Overwrite install_step from PackedBinary"""
os.chdir(self.builddir)
os.chmod("FastQC/fastqc", os.stat("FastQC/fastqc").st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
super(EB_FastQC, self).install_step() | identifier_body | |
fastqc.py | ##
# Copyright 2009-2013 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | this is just give execution permission to the `fastqc` binary before installing.
"""
def install_step(self):
"""Overwrite install_step from PackedBinary"""
os.chdir(self.builddir)
os.chmod("FastQC/fastqc", os.stat("FastQC/fastqc").st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH... |
class EB_FastQC(PackedBinary):
"""Easyblock implementing the build step for FastQC, | random_line_split |
fastqc.py | ##
# Copyright 2009-2013 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (htt... | (PackedBinary):
"""Easyblock implementing the build step for FastQC,
this is just give execution permission to the `fastqc` binary before installing.
"""
def install_step(self):
"""Overwrite install_step from PackedBinary"""
os.chdir(self.builddir)
os.chmod("FastQC/fastqc", os.s... | EB_FastQC | identifier_name |
commands_clear_tests.py | import os
from unittest import TestCase
from click.testing import CliRunner
from regparser.commands.clear import clear
from regparser.index import entry
class CommandsClearTests(TestCase):
def setUp(self):
self.cli = CliRunner()
def test_no_errors_when_clear(self):
"""Should raise no errors... |
def test_deletes_index(self):
with self.cli.isolated_filesystem():
entry.Entry('aaa', 'bbb').write('ccc')
entry.Entry('bbb', 'ccc').write('ddd')
self.assertEqual(1, len(entry.Entry("aaa")))
self.assertEqual(1, len(entry.Entry("bbb")))
self.cli.in... | self.assertTrue(os.path.exists('fr_cache.sqlite'))
self.cli.invoke(clear, ['--http-cache'])
self.assertFalse(os.path.exists('fr_cache.sqlite')) | random_line_split |
commands_clear_tests.py | import os
from unittest import TestCase
from click.testing import CliRunner
from regparser.commands.clear import clear
from regparser.index import entry
class CommandsClearTests(TestCase):
def setUp(self):
self.cli = CliRunner()
def test_no_errors_when_clear(self):
"""Should raise no errors... |
def test_deletes_index(self):
with self.cli.isolated_filesystem():
entry.Entry('aaa', 'bbb').write('ccc')
entry.Entry('bbb', 'ccc').write('ddd')
self.assertEqual(1, len(entry.Entry("aaa")))
self.assertEqual(1, len(entry.Entry("bbb")))
self.cli.i... | with self.cli.isolated_filesystem():
open('fr_cache.sqlite', 'w').close()
self.assertTrue(os.path.exists('fr_cache.sqlite'))
# flag must be present
self.cli.invoke(clear)
self.assertTrue(os.path.exists('fr_cache.sqlite'))
self.cli.invoke(clear, [... | identifier_body |
commands_clear_tests.py | import os
from unittest import TestCase
from click.testing import CliRunner
from regparser.commands.clear import clear
from regparser.index import entry
class CommandsClearTests(TestCase):
def setUp(self):
self.cli = CliRunner()
def test_no_errors_when_clear(self):
"""Should raise no errors... |
self.cli.invoke(clear, ['delroot', 'root/delsub'])
self.assertItemsEqual(['top-level-file', 'root', 'other-root'],
list(entry.Entry()))
self.assertItemsEqual(['othersub', 'aaa'],
list(entry.Entry('root')))
... | entry.Entry(*path.split('/')).write('') | conditional_block |
commands_clear_tests.py | import os
from unittest import TestCase
from click.testing import CliRunner
from regparser.commands.clear import clear
from regparser.index import entry
class | (TestCase):
def setUp(self):
self.cli = CliRunner()
def test_no_errors_when_clear(self):
"""Should raise no errors when no cached files are present"""
with self.cli.isolated_filesystem():
self.cli.invoke(clear)
def test_deletes_fr_cache(self):
with self.cli.isol... | CommandsClearTests | identifier_name |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn | () {
let conn = rocket().1;
let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
assert_eq!(expected_keys, actual_keys);
}
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
le... | db_connection | identifier_name |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn db_connection() {
let conn = rocket().1;
| assert_eq!(expected_keys, actual_keys);
}
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
let (rocket, conn, _) = rocket();
let client = Client::new(rocket).expect("valid rocket instance");
let mut response = client.get("/oration/session").dispa... | let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
| random_line_split |
tests.rs | use super::rocket;
use diesel::prelude::*;
use rocket::http::Status;
use rocket::local::Client;
use schema::preferences::dsl::*;
#[test]
/// Tests connection to the database through the pool managed by rocket.
fn db_connection() |
#[test]
/// Compares the session hash in the database to the one returned by /session
fn session_hash() {
let (rocket, conn, _) = rocket();
let client = Client::new(rocket).expect("valid rocket instance");
let mut response = client.get("/oration/session").dispatch();
let session_key: Vec<String> = pr... | {
let conn = rocket().1;
let expected_keys = vec!["session-key"];
let actual_keys: Vec<String> = preferences.select(key).load(&*conn).unwrap();
assert_eq!(expected_keys, actual_keys);
} | identifier_body |
PowerInputRounded.js | import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon( | <path d="M3 10c0 .55.45 1 1 1h17c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1zm1 5h3c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1zm7 0h3c.55 0 1-.45 1-1s-.45-1-1-1h-3c-.55 0-1 .45-1 1s.45 1 1 1zm7 0h3c.55 0 1-.45 1-1s-.45-1-1-1h-3c-.55 0-1 .45-1 1s.45 1 1 1z" />
, 'PowerInputRounded'); | random_line_split | |
CoverageDescription.ts | /*
* This file is part of rasdaman community.
*
* Rasdaman community 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.
*
* Rasdam... | this.ServiceParameters = new wcs.ServiceParameters(source.getChildAsSerializedObject("wcs:ServiceParameters"));
}
}
} | {
super(source);
rasdaman.common.ArgumentValidator.isNotNull(source, "source");
this.CoverageId = source.getChildAsSerializedObject("wcs:CoverageId").getValueAsString();
if (source.doesElementExist("gml:coverageFunction")) {
this.CoverageFunction = new ... | identifier_body |
CoverageDescription.ts | /*
* This file is part of rasdaman community.
*
* Rasdaman community 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.
*
* Rasdam... | (source:rasdaman.common.ISerializedObject) {
super(source);
rasdaman.common.ArgumentValidator.isNotNull(source, "source");
this.CoverageId = source.getChildAsSerializedObject("wcs:CoverageId").getValueAsString();
if (source.doesElementExist("gml:coverageFunction")) {
... | constructor | identifier_name |
CoverageDescription.ts | /*
* This file is part of rasdaman community.
*
* Rasdaman community 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.
*
* Rasdam... | source.getChildrenAsSerializedObjects("gmlcov:metadata").forEach(o=> {
this.Metadata.push(new gmlcov.Metadata(o));
});
this.DomainSet = new gml.DomainSet(source.getChildAsSerializedObject("gml:domainSet"));
this.RangeType = new gmlcov.RangeType(source.ge... | random_line_split | |
CoverageDescription.ts | /*
* This file is part of rasdaman community.
*
* Rasdaman community 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.
*
* Rasdam... |
this.Metadata = [];
source.getChildrenAsSerializedObjects("gmlcov:metadata").forEach(o=> {
this.Metadata.push(new gmlcov.Metadata(o));
});
this.DomainSet = new gml.DomainSet(source.getChildAsSerializedObject("gml:domainSet"));
this.RangeTyp... | {
this.CoverageFunction = new gml.CoverageFunction(source.getChildAsSerializedObject("gml:coverageFunction"));
} | conditional_block |
plugin.js | ),
colorBoxId = CKEDITOR.tools.getNextId() + '_colorBox',
panelBlock;
options = options || {};
editor.ui.add( name, CKEDITOR.UI_PANELBUTTON, {
label: title,
title: title,
modes: { wysiwyg: 1 },
editorFocus: 0,
toolbar: 'colors,' + order,
allowedContent: style,
requiredConten... | this.on( 'cancel', onColorDialogClose );
} );
return;
}
editor.focus();
panel.hide();
editor.fire( 'saveSnapshot' );
// Clean up any conflicting style within the range.
editor.removeStyle( new CKEDITOR.style( config[ 'colorButton_' + type + 'Style' ], { color: 'inherit' } ) ... | var output = [],
colors = config.colorButton_colors.split( ',' ),
colorsPerRow = config.colorButton_colorsPerRow || 6,
// Tells if we should include "More Colors..." button.
moreColorsEnabled = editor.plugins.colordialog && config.colorButton_enableMore !== false,
// aria-setsize and aria-posinse... | identifier_body |
plugin.js | ),
colorBoxId = CKEDITOR.tools.getNextId() + '_colorBox',
panelBlock;
options = options || {};
editor.ui.add( name, CKEDITOR.UI_PANELBUTTON, {
label: title,
title: title,
modes: { wysiwyg: 1 },
editorFocus: 0,
toolbar: 'colors,' + order,
allowedContent: style,
requiredConten... | ' title="', colorLabel, '"' +
' onclick="CKEDITOR.tools.callFunction(', clickFn, ',\'', colorName, '\',\'', type, '\'); return false;"' +
' href="javascript:void(\'', colorLabel, '\')"' +
' data-value="' + colorCode + '"' +
' role="option" aria-posinset="', ( i + 2 ), '" aria-setsize |
var colorLabel = editor.lang.colorbutton.colors[ colorCode ] || colorCode;
output.push( '<td>' +
'<a class="cke_colorbox" _cke_focus=1 hidefocus=true' + | random_line_split |
plugin.js | ),
colorBoxId = CKEDITOR.tools.getNextId() + '_colorBox',
panelBlock;
options = options || {};
editor.ui.add( name, CKEDITOR.UI_PANELBUTTON, {
label: title,
title: title,
modes: { wysiwyg: 1 },
editorFocus: 0,
toolbar: 'colors,' + order,
allowedContent: style,
requiredConten... | while ( type == 'back' && automaticColor == 'transparent' && block && ( block = block.getParent() ) );
// The box should never be transparent.
if ( !automaticColor || automaticColor == 'transparent' )
automaticColor = '#ffffff';
if ( config.colorButton_enableAutomatic !== false ) {
this... | automaticColor = block && block.getComputedStyle( type == 'back' ? 'background-color' : 'color' ) || 'transparent';
}
| conditional_block |
plugin.js | ),
colorBoxId = CKEDITOR.tools.getNextId() + '_colorBox',
panelBlock;
options = options || {};
editor.ui.add( name, CKEDITOR.UI_PANELBUTTON, {
label: title,
title: title,
modes: { wysiwyg: 1 },
editorFocus: 0,
toolbar: 'colors,' + order,
allowedContent: style,
requiredConten... | panel, type, colorBoxId ) {
var output = [],
colors = config.colorButton_colors.split( ',' ),
colorsPerRow = config.colorButton_colorsPerRow || 6,
// Tells if we should include "More Colors..." button.
moreColorsEnabled = editor.plugins.colordialog && config.colorButton_enableMore !== false,
// a... | nderColors( | identifier_name |
borrowck-let-suggestion-suffixes.rs | // Copyright 2015 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 ... | () {
f();
}
| main | identifier_name |
borrowck-let-suggestion-suffixes.rs | // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | let young = ['y']; // statement 3
//~^ NOTE ...but borrowed value is only valid for the block suffix following statement 3
v2.push(&young[0]); // statement 4
//~^ ERROR `young[..]` does not live long enough
let mut v3 = Vec::new(); // statement 5
//~^ NOTE reference must be valid fo... | //~^ NOTE reference must be valid for the block suffix following statement 2
| random_line_split |
borrowck-let-suggestion-suffixes.rs | // Copyright 2015 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 ... | {
f();
} | identifier_body | |
test_builddict.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.c... | (BaseTest):
@property
def alias_groups(self):
return register_core().merge(register_jvm().merge(register_python()))
def setUp(self):
super(ExtractedContentSanityTests, self).setUp()
self._syms = reflect.assemble_buildsyms(build_file_parser=self.build_file_parser)
def test_sub_tocls(self):
pyth... | ExtractedContentSanityTests | identifier_name |
test_builddict.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.c... |
def test_sub_tocls(self):
python_symbols = builddictionary.python_sub_tocl(self._syms).e
# python_requirements goes through build_file_aliases.curry_context.
# It's in the "Python" sub_tocl, but tenuously
self.assertTrue('python_requirements' in python_symbols)
# Some less-tenuous sanity check... | super(ExtractedContentSanityTests, self).setUp()
self._syms = reflect.assemble_buildsyms(build_file_parser=self.build_file_parser) | identifier_body |
test_builddict.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.c... |
class ExtractedContentSanityTests(BaseTest):
@property
def alias_groups(self):
return register_core().merge(register_jvm().merge(register_python()))
def setUp(self):
super(ExtractedContentSanityTests, self).setUp()
self._syms = reflect.assemble_buildsyms(build_file_parser=self.build_file_parser)
... | random_line_split | |
test_builddict.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.c... |
jvm_symbols = builddictionary.jvm_sub_tocl(self._syms).e
for sym in ['java_library', 'scala_library']:
self.assertTrue(sym in jvm_symbols)
| self.assertTrue(sym in python_symbols) | conditional_block |
__init__.py | __all__ = ["sqlite_dump", "sqlite_merge"]
from random import Random
import math
def random_expectations(depth=0, breadth=3, low=1, high=10, random=Random()):
"""
Generate depth x breadth array of random numbers where each row sums to
high, with a minimum of low.
"""
result = []
if depth == 0:... | result = [random_expectations(depth - 1, breadth, low, high, random) for x in range(breadth)]
return result
def rescale(new_low, new_high, low, diff, x):
scaled = (new_high-new_low)*(x - low)
scaled /= diff
return scaled + new_low
def weighted_random_choice(choices, weights, random=Random())... | else: | random_line_split |
__init__.py | __all__ = ["sqlite_dump", "sqlite_merge"]
from random import Random
import math
def random_expectations(depth=0, breadth=3, low=1, high=10, random=Random()):
"""
Generate depth x breadth array of random numbers where each row sums to
high, with a minimum of low.
"""
result = []
if depth == 0:... | (probabilities, draws=1, random=Random()):
"""
Draw from a multinomial distribution
"""
def pick():
draw = random.random()
bracket = 0.
for i in range(len(probabilities)):
bracket += probabilities[i]
if draw < bracket:
return i
... | multinomial | identifier_name |
__init__.py | __all__ = ["sqlite_dump", "sqlite_merge"]
from random import Random
import math
def random_expectations(depth=0, breadth=3, low=1, high=10, random=Random()):
"""
Generate depth x breadth array of random numbers where each row sums to
high, with a minimum of low.
"""
result = []
if depth == 0:... | run_script = ["#!/bin/bash -vx", "#PBS -l walltime=%d:%d:00" % (hours, mins), "#PBS -l nodes=1:ppn=%d" % ppn,
"module load python"]
# Doesn't work on multiple nodes, sadly
# Set up the call
run_call = "%s -m disclosuregame.run %s" % (interpreter, args)
run_script.append(run_call)... | """
Generate a PBS run script to be submitted.
"""
from disclosuregame.Util.sqlite_merge import list_matching
from os.path import split
args_dir, name = split(kwargs.kwargs[0])
kwargs_files = list_matching(args_dir, name)
count = len(kwargs_files)
import sys
args = sys.argv[1:]
... | identifier_body |
__init__.py | __all__ = ["sqlite_dump", "sqlite_merge"]
from random import Random
import math
def random_expectations(depth=0, breadth=3, low=1, high=10, random=Random()):
"""
Generate depth x breadth array of random numbers where each row sums to
high, with a minimum of low.
"""
result = []
if depth == 0:... |
return result
def rescale(new_low, new_high, low, diff, x):
scaled = (new_high-new_low)*(x - low)
scaled /= diff
return scaled + new_low
def weighted_random_choice(choices, weights, random=Random()):
population = [val for val, cnt in zip(choices, weights) for i in range(int(cnt))]
return ra... | result = [random_expectations(depth - 1, breadth, low, high, random) for x in range(breadth)] | conditional_block |
auth_backends.py | from __future__ import unicode_literals
import re
from django.db.models import Q
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
email_re = re.compile(
r"(^[-!#$%&'*+/=... |
class HybridAuthenticationBackend(ModelBackend):
"""User can login via email OR username"""
def authenticate(self, **credentials):
User = get_user_model()
if email_re.search(credentials["username"]):
qs = EmailAddress.objects.filter(Q(primary=True) | Q(verified=True))
t... | qs = EmailAddress.objects.filter(Q(primary=True) | Q(verified=True))
try:
email_address = qs.get(email__iexact=credentials["username"])
except (EmailAddress.DoesNotExist, KeyError):
return None
else:
user = email_address.user
try:
i... | identifier_body |
auth_backends.py | from __future__ import unicode_literals
import re
from django.db.models import Q
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
email_re = re.compile(
r"(^[-!#$%&'*+/=... | (self, **credentials):
User = get_user_model()
lookup_kwargs = get_user_lookup_kwargs({
"{username}__iexact": credentials["username"]
})
try:
user = User.objects.get(**lookup_kwargs)
except (User.DoesNotExist, KeyError):
return None
els... | authenticate | identifier_name |
auth_backends.py | from __future__ import unicode_literals
import re
from django.db.models import Q
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
email_re = re.compile(
r"(^[-!#$%&'*+/=... |
except KeyError:
return None
class EmailAuthenticationBackend(ModelBackend):
def authenticate(self, **credentials):
qs = EmailAddress.objects.filter(Q(primary=True) | Q(verified=True))
try:
email_address = qs.get(email__iexact=credentials["username"])
... | return user | conditional_block |
auth_backends.py | from __future__ import unicode_literals
import re
from django.db.models import Q
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
from account.models import EmailAddress
from account.utils import get_user_lookup_kwargs
email_re = re.compile(
r"(^[-!#$%&'*+/=... |
def authenticate(self, **credentials):
qs = EmailAddress.objects.filter(Q(primary=True) | Q(verified=True))
try:
email_address = qs.get(email__iexact=credentials["username"])
except (EmailAddress.DoesNotExist, KeyError):
return None
else:
user = e... | except KeyError:
return None
class EmailAuthenticationBackend(ModelBackend): | random_line_split |
partially-ordered-set_spec.ts | /**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { PartiallyOrderedSet } from './partially-ordered-set';
describe('PartiallyOrderedSet', () => {
it('can add... | it('list items in determistic order of dependency', () => {
const set = new PartiallyOrderedSet<string>();
set.add('red');
set.add('yellow', ['red']);
set.add('green', ['red']);
set.add('blue');
set.add('purple', ['red', 'blue']);
expect([...set]).toEqual(['red', 'blue', 'yellow', 'green... |
expect([...set]).toEqual(['hello']);
});
| random_line_split |
regress-306738.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... |
});
expect = '({get foo() {return "foo";}})';
compareSource(expect, actual, summary);
| {
return "foo";
} | identifier_body |
regress-306738.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | ()
{
return "foo";
}
});
expect = '({get foo() {return "foo";}})';
compareSource(expect, actual, summary);
| foo | identifier_name |
regress-306738.js | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the Lic... | compareSource(expect, actual, summary); | random_line_split | |
TestNativeRsqrt.rs | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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 app... | * See the License for the specific language governing permissions and
* limitations under the License.
*/
// Don't edit this file! It is auto-generated by frameworks/rs/api/generate.sh.
#pragma version(1)
#pragma rs java_package_name(android.renderscript.cts)
float __attribute__((kernel)) testNativeRsqrtFloatFl... | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
messages.py | NOT_GIT_REPO_MSG = "#{red}Not a git repository (or any of the parent directories)"
HOOK_ALREADY_INSTALLED_MSG = "The pre-commit hook has already been installed."
EXISTING_HOOK_MSG = (
"#{yellow}There is an existing pre-commit hook.\n"
"#{reset_all}Therapist can preserve this legacy hook and run it before the ... | "#{yellow}The current pre-commit hook is not the Therapist pre-commit hook.\n"
"#{reset_all}Uninstallation aborted."
)
LEGACY_HOOK_EXISTS_MSG = "#{yellow}There is a legacy pre-commit hook present."
CONFIRM_RESTORE_LEGACY_HOOK_MSG = "Would you like to restore the legacy hook?"
COPYING_LEGACY_HOOK_MSG = "Copyi... |
CONFIRM_UNINSTALL_HOOK_MSG = "Are you sure you want to uninstall the current pre-commit hook?"
CURRENT_HOOK_NOT_THERAPIST_MSG = ( | random_line_split |
FFTSceneManager.py | import numpy as np
from PyQt5.QtGui import QPainterPath, QPen
from PyQt5.QtWidgets import QGraphicsPathItem
from urh import settings
from urh.cythonext import path_creator
from urh.ui.painting.GridScene import GridScene
from urh.ui.painting.SceneManager import SceneManager
class FFTSceneManager(SceneManager):
de... |
def clear_peak(self):
self.peak = []
if self.peak_item:
self.peak_item.setPath(QPainterPath())
def eliminate(self):
super().eliminate()
self.peak = None
self.peak_item = None
| self.scene.removeItem(item)
item.setParentItem(None)
del item | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.