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 |
|---|---|---|---|---|
tests.py | from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase
from .provider import MicrosoftGraphProvider
class MicrosoftGraphTests(OAuth2TestsMixin, TestCase):
provider_id = MicrosoftGraphProvider.id
def get_mocked_response(self):
| response_data = """
{
"@odata.context": "https://graph.microsoft.com/v1.0/$metadata#users/$entity",
"id": "16f5a7b6-5a15-4568-aa5a-31bb117e9967",
"businessPhones": [],
"displayName": "Anne Weiler",
"givenName": "Anne",
"jobTitle": "Manufact... | identifier_body | |
tests.py | from allauth.socialaccount.tests import OAuth2TestsMixin
from allauth.tests import MockedResponse, TestCase
from .provider import MicrosoftGraphProvider
class MicrosoftGraphTests(OAuth2TestsMixin, TestCase):
provider_id = MicrosoftGraphProvider.id
def get_mocked_response(self):
response_data = """
... | "givenName": "Anne",
"jobTitle": "Manufacturing Lead",
"mail": "annew@CIE493742.onmicrosoft.com",
"mobilePhone": "+1 3528700812",
"officeLocation": null,
"preferredLanguage": "en-US",
"surname": "Weiler",
"userPrincipalName"... | "displayName": "Anne Weiler", | random_line_split |
mod.rs | performed.
#[stable]
pub struct Arguments<'a> {
// Format string pieces to print.
pieces: &'a [&'a str],
// Placeholder specs, or `None` if all specs are default (as in "{}{}").
fmt: Option<&'a [rt::Argument<'a>]>,
// Dynamic arguments for interpolation, to be interleaved with string
// piece... |
}
/// When a format is not otherwise specified, types are formatted by ascribing
/// to this trait. There is not an explicit way of selecting this trait to be
/// used for formatting, it is only if no other format is specified.
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Show for Sized? {
///... | {
write(fmt.buf, self)
} | identifier_body |
mod.rs | #[unstable = "I/O and core have yet to be reconciled"]
pub trait Show for Sized? {
/// Formats the value using the given formatter.
fn fmt(&self, &mut Formatter) -> Result;
}
/// Format trait for the `o` character
#[unstable = "I/O and core have yet to be reconciled"]
pub trait Octal for Sized? {
/// Form... | pad | identifier_name | |
mod.rs | self, fmt: &mut Formatter) -> Result {
write(fmt.buf, self)
}
}
/// When a format is not otherwise specified, types are formatted by ascribing
/// to this trait. There is not an explicit way of selecting this trait to be
/// used for formatting, it is only if no other format is specified.
#[unstable = "I/O... | /// * width - the minimum width of what to emit
/// * fill/align - what to emit and where to emit it if the string | random_line_split | |
conf.py | # -*- coding: utf-8 -*-
#
# Python-Starter documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 13 16:29:44 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file... | # If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc',
'sphinx.ext.viewcode']
# Add any p... | random_line_split | |
attributes_test.js | var assert = require('chai').assert;
var ss = require('../../../script_sanitize');
var describe = require('mocha/lib/mocha.js').describe;
var it = require('mocha/lib/mocha.js').it;
var script_sanitize = ss.sanitize;
module.exports = function () {
describe("attributes", function () {
it('should replace the attrib... | var a = script_sanitize("<h1 onload='' onmouseover=''></h1>", { attributes: ["onload", "onmouseover"], tags: [] });
assert.isOk(!a.includes("onload"));
assert.isOk(!a.includes("onmouseover"));
});
it('should remove nested attributes', function () {
var a = script_sanitize("<h1 onload='o... | var a = script_sanitize("<h1 onload=''></h1>", { attributes: ["onload"], tags: [] });
assert.isOk(!a.includes("onload"));
});
it('should support multiple attributes', function() { | random_line_split |
luoo_Download.py | import urllib2
import os
import re
import time
print '---------------------------------------------------------------'
print 'Name: Luoo.net-Mp3 crawler '
print 'version: v1.0'
print 'author: ChenYao'
print 'data: 2013/9/4'
print 'Introductions: the music will Downloaded to path D:\\Luoo.net\\'
print '------------... | # print the download time
timeEnd = time.time()
spendTime = time.strftime('%M:%S',time.localtime(timeEnd - timeStart))
print '### Download Time: [%s]' % spendTime
# file exist
elif(os.path.isfile(sourcePath)):
# then check wether file is empty
if((o... | timeStart = time.time()
req = urllib2.Request(
url = url,
headers = headers
)
try:
# catch the exception, example HTTP_404
response = urllib2.urlopen(req, timeout = 10)
except urllib2.URLError, e:
if hasattr(e, 'reason'):
... | conditional_block |
luoo_Download.py | import urllib2
import os
import re
import time
print '---------------------------------------------------------------'
print 'Name: Luoo.net-Mp3 crawler '
print 'version: v1.0'
print 'author: ChenYao'
print 'data: 2013/9/4'
print 'Introductions: the music will Downloaded to path D:\\Luoo.net\\'
print '------------... | (sourcePath, url):
# file do not exist, download
if (os.path.isfile(sourcePath) == False):
timeStart = time.time()
req = urllib2.Request(
url = url,
headers = headers
)
try:
# catch the exception, example HTTP_404
response = urlli... | requestResource | identifier_name |
luoo_Download.py | import urllib2
import os
import re
import time
print '---------------------------------------------------------------'
print 'Name: Luoo.net-Mp3 crawler '
print 'version: v1.0'
print 'author: ChenYao'
print 'data: 2013/9/4'
print 'Introductions: the music will Downloaded to path D:\\Luoo.net\\'
print '------------... | continue
realUrl = str(a[0])
b = re.findall(r'(?<=title=").*(?="\s*/)',line)
if b == []:
continue
songName = str(b[0]).decode('utf-8')
songName = removeChar(songName)
print_info(songName,fileNum)
... | for line in lines[2:-1]:
line = line.strip()
a = re.findall(r'http.*.mp3',line)
if a == []: | random_line_split |
luoo_Download.py | import urllib2
import os
import re
import time
print '---------------------------------------------------------------'
print 'Name: Luoo.net-Mp3 crawler '
print 'version: v1.0'
print 'author: ChenYao'
print 'data: 2013/9/4'
print 'Introductions: the music will Downloaded to path D:\\Luoo.net\\'
print '------------... |
# start download
def download(start,end):
for x in range(start,end):
startTime = time.time()
if x < 296:
Url = sourUrl + str(x) +'/mp3player.xml'
else:
Url = sourUrl + str(x) +'/mp3.xml'
folderPath = rawPath + 'Luoo_' + str(x) + '\\'
#folderPath ... | for i in charInSongName:
songName = songName.replace(i,' ')
return songName | identifier_body |
app_routing_view_module.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | RouterLinkDirectiveContainer,
],
})
export class AppRoutingViewModule {} | RouterOutletContainer,
RouterOutletComponent, | random_line_split |
app_routing_view_module.ts | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or a... | {}
| AppRoutingViewModule | identifier_name |
inviteFactory.js | angular.module('inviteFactory', ['firebase'])
.factory('invite', ['$firebaseObject', '$http' , function ($firebaseObject, $http) {
var inviteFactory = {};
// mandrill API key ** free version API key only for production **
// in real use case, should store this securely
var mandrillKey = 'ul35c_Y39BxIZUIUa_HI... | "from_email": sender+"."+orgName+"@Hiver.com",
"to":[{"email":recipientEmail}],
"subject": "Hey "+recipient+" go signup at Hive!",
"html":
"<h1>"+sender+" invited you to sign up for "+orgName+" at Hive</h1><h2>Your OrgID is "+orgId+"</h2>... | "key": mandrillKey,
"message": { | random_line_split |
syntax_test_union.rs | // SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax"
union Union {
//^^^ meta.union storage.type.union
//^^^^^^^^^^^ meta.union
// ^^^^^ entity.name.union
// ^ meta.block punctuation.definition.block.begin
f: u32,
// ^ meta.union meta.block variable.other.member
// ^ meta.union meta.b... | () {}
// ^^^^^ meta.function entity.name.function
union /*comment*/ U {}
// ^^^^^^^^^^^ meta.union comment.block
| union | identifier_name |
syntax_test_union.rs | // SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax"
union Union {
//^^^ meta.union storage.type.union | // ^ meta.block punctuation.definition.block.begin
f: u32,
// ^ meta.union meta.block variable.other.member
// ^ meta.union meta.block punctuation.separator
// ^^^ meta.union meta.block storage.type
}
// <- meta.union meta.block punctuation.definition.block.end
pub union Foo<'a, Y: Baz>
// <- stora... | //^^^^^^^^^^^ meta.union
// ^^^^^ entity.name.union | random_line_split |
syntax_test_union.rs | // SYNTAX TEST "Packages/Rust Enhanced/RustEnhanced.sublime-syntax"
union Union {
//^^^ meta.union storage.type.union
//^^^^^^^^^^^ meta.union
// ^^^^^ entity.name.union
// ^ meta.block punctuation.definition.block.begin
f: u32,
// ^ meta.union meta.block variable.other.member
// ^ meta.union meta.b... |
// ^^^^^ meta.function entity.name.function
union /*comment*/ U {}
// ^^^^^^^^^^^ meta.union comment.block
| {} | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
setup(
name='mtg-deck-editor',
version='1.0.3',
url='https://github.com/buckket/mtg-deck-editor',
author='buckket',
author_email='buckket@cock.li',
packages=['mtgdeckeditor'],
package_dir={'mtgdeckeditor': 'mtgdec... | ],
) | 'Intended Audience :: End Users/Desktop',
'Topic :: Games/Entertainment', | random_line_split |
u_str.rs | 629
static UTF8_CHAR_WIDTH: [u8; 256] = [
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x1F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1... | let (low, high) = self.chars.size_hint(); | random_line_split | |
u_str.rs | a str;
fn trim_left<'a>(&'a self) -> &'a str;
fn trim_right<'a>(&'a self) -> &'a str;
}
impl UnicodeStr for str {
#[inline]
fn split_whitespace(&self) -> SplitWhitespace {
fn is_not_empty(s: &&str) -> bool { !s.is_empty() }
let is_not_empty: fn(&&str) -> bool = is_not_empty; // coerce t... | items<'a>(v | identifier_name | |
u_str.rs | 1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x3F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x5F
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // 0x7F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 0x9F
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,... | .inner.next() }
}
imp | identifier_body | |
vote_genesis.rs | ::Error;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::env;
use std::io::Write;
use std::io;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::{BufRead};
pub struct VotePersona {
voter_keys: KeyPair,
voting_round: VoteRound,
}
impl VotePersona {
pub fn import_keys() -> VotePersona {
prin... |
}
#[derive(Clone, RustcDecodable, RustcEncodable)]
pub struct VoteHash {
pub poll_hash: Vec<u8>,
pub vote_message: String,
pub vote_msgindex: i32,
pub vote_publickey: String,
}
impl VoteHash {
pub fn return_hash(&self) -> String {
let encoded = json::encode(&self).unwrap();
let the_sha = Sha256dHash::fro... | {
&self.voter_keys
} | identifier_body |
vote_genesis.rs | error::Error;
use std::fs;
use std::fs::File;
use std::path::Path;
use std::env;
use std::io::Write;
use std::io;
use std::fs::OpenOptions;
use std::io::Read;
use std::io::{BufRead};
pub struct VotePersona {
voter_keys: KeyPair,
voting_round: VoteRound,
}
impl VotePersona {
pub fn import_keys() -> VotePersona {
... | let persona = VotePersona::import_keys();
println!("please enter path of the poll you intend to vote on");
let mut path = String::new();
let stdin = io::stdin();
stdin.lock().read_line(&mut path).unwrap();
let path_trim = path.trim_right_matches("\n");
let path = Path::new(&path_trim);
... | random_line_split | |
vote_genesis.rs | ::io::{BufRead};
pub struct VotePersona {
voter_keys: KeyPair,
voting_round: VoteRound,
}
impl VotePersona {
pub fn import_keys() -> VotePersona {
println!("input your private key");
let mut input2 = String::new();
let stdin2 = io::stdin();
stdin2.lock().read_line(&mut input2).unwrap();
let tr... | return_votecount | identifier_name | |
ship.js | // Camera setup
// Ship Constructor
function ship() |
ship.prototype = new THREE.Object3D();
ship.prototype.constructor = ship;
ship.prototype.stats = {
turnRate : 220, // DEGREES PER SECOND
accelRate : 35, // METERS PER SECOND PER SECOND
maxSpeed : 40, // METERS PER SECOND
maxBankAngle : 0.3,
bankAngle: 0 // BANKING ANGLE * GRAPHIC EFFECT ONLY *
};
mod... | {
THREE.Object3D.call(this);
this.velocity = new THREE.Vector3();
var _this = this;
this.shipModel = new THREE.Mesh();
var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "assets/ship.js", function(geometry, materials) {
var material = new THREE.MeshFaceMaterial( materials );
_this.shipMod... | identifier_body |
ship.js | // Camera setup
// Ship Constructor
function ship() {
THREE.Object3D.call(this);
this.velocity = new THREE.Vector3();
var _this = this;
this.shipModel = new THREE.Mesh();
var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "assets/ship.js", function(geometry, materials) {
var material = ne... |
}
ship.prototype = new THREE.Object3D();
ship.prototype.constructor = ship;
ship.prototype.stats = {
turnRate : 220, // DEGREES PER SECOND
accelRate : 35, // METERS PER SECOND PER SECOND
maxSpeed : 40, // METERS PER SECOND
maxBankAngle : 0.3,
bankAngle: 0 // BANKING ANGLE * GRAPHIC EFFECT ONLY *
};
m... | _this.shipModel = new THREE.Mesh( geometry, material );
_this.shipModel.rotateOnAxis( new THREE.Vector3(1,0,0), Math.PI / 2);
_this.add(_this.shipModel);
}); | random_line_split |
ship.js | // Camera setup
// Ship Constructor
function | () {
THREE.Object3D.call(this);
this.velocity = new THREE.Vector3();
var _this = this;
this.shipModel = new THREE.Mesh();
var jsonLoader = new THREE.JSONLoader();
jsonLoader.load( "assets/ship.js", function(geometry, materials) {
var material = new THREE.MeshFaceMaterial( materials );
_this.ship... | ship | identifier_name |
workerlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerLocationBinding;
use dom::bindings::codegen::Bindings::WorkerLocationB... | {
reflector_: Reflector,
url: Url,
}
impl WorkerLocation {
fn new_inherited(url: Url) -> WorkerLocation {
WorkerLocation {
reflector_: Reflector::new(),
url: url,
}
}
pub fn new(global: &WorkerGlobalScope, url: Url) -> Root<WorkerLocation> {
reflect... | WorkerLocation | identifier_name |
workerlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerLocationBinding;
use dom::bindings::codegen::Bindings::WorkerLocationB... |
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-search
fn Search(&self) -> USVString {
UrlHelper::Search(&self.url)
}
// https://html.spec.whatwg.org/multipage/#dom-workerlocation-href
fn Stringifier(&self) -> DOMString {
DOMString::from(self.Href().0)
}
}
| {
UrlHelper::Protocol(&self.url)
} | identifier_body |
workerlocation.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::WorkerLocationBinding; | use dom::bindings::reflector::{Reflector, reflect_dom_object};
use dom::bindings::str::{DOMString, USVString};
use dom::urlhelper::UrlHelper;
use dom::workerglobalscope::WorkerGlobalScope;
use url::Url;
// https://html.spec.whatwg.org/multipage/#worker-locations
#[dom_struct]
pub struct WorkerLocation {
reflector_... | use dom::bindings::codegen::Bindings::WorkerLocationBinding::WorkerLocationMethods;
use dom::bindings::global::GlobalRef;
use dom::bindings::js::Root; | random_line_split |
tag_sets.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... | (_: QualName) -> bool { false }
#[inline(always)] pub fn full_set(_: QualName) -> bool { true }
// FIXME: MathML, SVG
declare_tag_set!(pub default_scope = applet caption html table td th marquee object template);
declare_tag_set!(pub list_item_scope = default_scope + ol ul);
declare_tag_set!(pub button_scope = defaul... | empty_set | identifier_name |
tag_sets.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... |
// FIXME: MathML, SVG
declare_tag_set!(pub default_scope = applet caption html table td th marquee object template);
declare_tag_set!(pub list_item_scope = default_scope + ol ul);
declare_tag_set!(pub button_scope = default_scope + button);
declare_tag_set!(pub table_scope = html table template);
declare_tag_set!(pu... | { true } | identifier_body |
tag_sets.rs | // Copyright 2014 The html5ever Project Developers. See the
// COPYRIGHT file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>,... | frame frameset h1 h2 h3 h4 h5 h6 head header hgroup hr html iframe img input isindex li
link listing main marquee menu menuitem meta nav noembed noframes noscript object ol p
param plaintext pre script section select source style summary table tbody td template
textarea tfoot th thead title tr track ul ... | random_line_split | |
serve.ts | import { BuildOptions } from '../models/webpack-config';
import { BaseBuildCommandOptions } from './build';
const PortFinder = require('portfinder');
const Command = require('../ember-cli/lib/models/command');
PortFinder.basePort = 49152;
const defaultPort = process.env.PORT || 4200;
export interface ServeTaskOptio... | name: 'host',
type: String,
default: 'localhost',
aliases: ['H'],
description: 'Listens only on localhost by default'
},
{ name: 'proxy-config', type: 'Path', aliases: ['pc'] },
{ name: 'live-reload', type: Boolean, default: true, ... | random_line_split | |
MultiRegime.py | #!/usr/bin/env python2
# multi-regime.py
# Author: Jonah Miller (jonah.maxwell.miller@gmail.com)
# Time-stamp: <2013-12-14 16:06:28 (jonah)>
# This is a library to plot and fit for omega(rho) variable. We choose
# omega so that we get the three distinct regimes for which we know
# the analytic solution with continuou... | ():
mpl.rcParams.update({'font.size': pav.fontsize})
x = np.linspace(0,RHO_RADIATION,100)
ys = [omega(x,RHO_DARK_ENERGY[i],TRANSITION_WIDTH_DE[i],
RHO_MATTER[i],TRANSITION_WIDTH_MR[i]) for i in range(len(RHO_DARK_ENERGY))]
lines = [plt.plot(x,y,linewidth=pav.my_linewidth) for y in ys]
... | plot_rho | identifier_name |
MultiRegime.py | #!/usr/bin/env python2
# multi-regime.py
# Author: Jonah Miller (jonah.maxwell.miller@gmail.com)
# Time-stamp: <2013-12-14 16:06:28 (jonah)>
# This is a library to plot and fit for omega(rho) variable. We choose
# omega so that we get the three distinct regimes for which we know
# the analytic solution with continuou... |
if __name__ == "__main__":
plot_rho()
| mpl.rcParams.update({'font.size': pav.fontsize})
x = np.linspace(0,RHO_RADIATION,100)
ys = [omega(x,RHO_DARK_ENERGY[i],TRANSITION_WIDTH_DE[i],
RHO_MATTER[i],TRANSITION_WIDTH_MR[i]) for i in range(len(RHO_DARK_ENERGY))]
lines = [plt.plot(x,y,linewidth=pav.my_linewidth) for y in ys]
plt.ax... | identifier_body |
MultiRegime.py | #!/usr/bin/env python2
# multi-regime.py
# Author: Jonah Miller (jonah.maxwell.miller@gmail.com)
# Time-stamp: <2013-12-14 16:06:28 (jonah)>
# This is a library to plot and fit for omega(rho) variable. We choose
# omega so that we get the three distinct regimes for which we know
# the analytic solution with continuou... |
if __name__ == "__main__":
plot_rho() | return | random_line_split |
MultiRegime.py | #!/usr/bin/env python2
# multi-regime.py
# Author: Jonah Miller (jonah.maxwell.miller@gmail.com)
# Time-stamp: <2013-12-14 16:06:28 (jonah)>
# This is a library to plot and fit for omega(rho) variable. We choose
# omega so that we get the three distinct regimes for which we know
# the analytic solution with continuou... | plot_rho() | conditional_block | |
test_switch.py | """Tests for 1-Wire devices connected on OWServer."""
import copy
from unittest.mock import patch
import pytest
from homeassistant.components.onewire.switch import DEVICE_SWITCHES
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TOGGLE, STATE_... | (owproxy, hass, device_id):
"""Test for 1-Wire switch.
This test forces all entities to be enabled.
"""
await async_setup_component(hass, "persistent_notification", {})
entity_registry = mock_registry(hass)
setup_owproxy_mock_devices(owproxy, SWITCH_DOMAIN, [device_id])
mock_device = MOCK... | test_owserver_switch | identifier_name |
test_switch.py | """Tests for 1-Wire devices connected on OWServer."""
import copy
from unittest.mock import patch
import pytest
from homeassistant.components.onewire.switch import DEVICE_SWITCHES
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TOGGLE, STATE_... |
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TOGGLE,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state.state == expected_entity["result"]
... | owproxy.return_value.read.side_effect = [b" 1"]
expected_entity["result"] = STATE_ON | random_line_split |
test_switch.py | """Tests for 1-Wire devices connected on OWServer."""
import copy
from unittest.mock import patch
import pytest
from homeassistant.components.onewire.switch import DEVICE_SWITCHES
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TOGGLE, STATE_... |
await hass.services.async_call(
SWITCH_DOMAIN,
SERVICE_TOGGLE,
{ATTR_ENTITY_ID: entity_id},
blocking=True,
)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state.state == expected_entity["result"]
... | owproxy.return_value.read.side_effect = [b" 1"]
expected_entity["result"] = STATE_ON | conditional_block |
test_switch.py | """Tests for 1-Wire devices connected on OWServer."""
import copy
from unittest.mock import patch
import pytest
from homeassistant.components.onewire.switch import DEVICE_SWITCHES
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import ATTR_ENTITY_ID, SERVICE_TOGGLE, STATE_... | "homeassistant.components.onewire.switch.DEVICE_SWITCHES", patch_device_switches
):
await setup_onewire_patched_owserver_integration(hass)
await hass.async_block_till_done()
assert len(entity_registry.entities) == len(expected_entities)
for expected_entity in expected_entities:
... | """Test for 1-Wire switch.
This test forces all entities to be enabled.
"""
await async_setup_component(hass, "persistent_notification", {})
entity_registry = mock_registry(hass)
setup_owproxy_mock_devices(owproxy, SWITCH_DOMAIN, [device_id])
mock_device = MOCK_SWITCHES[device_id]
expecte... | identifier_body |
make_figures.py | #name:make_figures.py
#author:Will Barnes
#Description: make some figures useful to notes on AIA response functions
import numpy as np
import matplotlib.pyplot as plt
import seaborn.apionly as sns
def display_aia_response_control_flow():
"""Show the control flow of the IDL programs used to compute AIA response fu... |
plt.tight_layout()
plt.savefig('figures/aia_response_functions.eps',format='eps')
if __name__=='__main__':
plot_aia_response_functions('aia_sample_data/aia_tresponse_raw.dat','aia_sample_data/aia_tresponse_fix.dat') | ax[1].set_ylabel(r'Normalized Temperature Response',fontsize=22)
#legend
ax[0].legend(loc='best',fontsize=14) | random_line_split |
make_figures.py | #name:make_figures.py
#author:Will Barnes
#Description: make some figures useful to notes on AIA response functions
import numpy as np
import matplotlib.pyplot as plt
import seaborn.apionly as sns
def display_aia_response_control_flow():
"""Show the control flow of the IDL programs used to compute AIA response fu... | ax[0].set_yscale('log')
ax[0].set_xlim([10**5.,10**8.])
ax[0].set_ylim([1e-28,1e-23])
ax[1].set_xlim([5,8])
ax[1].set_ylim([0,1])
#labels
ax[0].set_xlabel(r'$T\,\,\mathrm{(K)}$',fontsize=22)
ax[0].set_ylabel(r'Temperature Response $(\mathrm{DN}\,\mathrm{cm}^{-5}\,\mathrm{s}^{-1}\,\mathr... | """Plot AIA temperature response functions as computed by SSW"""
#Load data
raw_tresp,fix_tresp = np.loadtxt(raw_response_file),np.loadtxt(fix_response_file)
#set labels
aia_labs = [r'$94\,\,\AA$',r'$131\,\,\AA$',r'$171\,\,\AA$',r'$193\,\,\AA$',r'$211\,\,\AA$',r'$335\,\,\AA$']
#Create figure
... | identifier_body |
make_figures.py | #name:make_figures.py
#author:Will Barnes
#Description: make some figures useful to notes on AIA response functions
import numpy as np
import matplotlib.pyplot as plt
import seaborn.apionly as sns
def display_aia_response_control_flow():
"""Show the control flow of the IDL programs used to compute AIA response fu... |
#set plot options
ax[0].set_xscale('log')
ax[0].set_yscale('log')
ax[0].set_xlim([10**5.,10**8.])
ax[0].set_ylim([1e-28,1e-23])
ax[1].set_xlim([5,8])
ax[1].set_ylim([0,1])
#labels
ax[0].set_xlabel(r'$T\,\,\mathrm{(K)}$',fontsize=22)
ax[0].set_ylabel(r'Temperature Response $(\m... | ax[0].plot(10**raw_tresp[:,0],raw_tresp[:,i],linewidth=2,linestyle='-',color=sns.color_palette('deep')[i-1],label=aia_labs[i-1])
ax[0].plot(10**fix_tresp[:,0],fix_tresp[:,i],linewidth=2,linestyle='--',color=sns.color_palette('deep')[i-1])
#normalized
ax[1].plot(raw_tresp[:,0],raw_tresp[:,i]/np.m... | conditional_block |
make_figures.py | #name:make_figures.py
#author:Will Barnes
#Description: make some figures useful to notes on AIA response functions
import numpy as np
import matplotlib.pyplot as plt
import seaborn.apionly as sns
def display_aia_response_control_flow():
"""Show the control flow of the IDL programs used to compute AIA response fu... | (raw_response_file,fix_response_file):
"""Plot AIA temperature response functions as computed by SSW"""
#Load data
raw_tresp,fix_tresp = np.loadtxt(raw_response_file),np.loadtxt(fix_response_file)
#set labels
aia_labs = [r'$94\,\,\AA$',r'$131\,\,\AA$',r'$171\,\,\AA$',r'$193\,\,\AA$',r'$211\,\,\AA$... | plot_aia_response_functions | identifier_name |
test_urls.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import importlib
import os
import six
import ujson
import django.core.urlresolvers
from django.test import TestCase
from typing import List, Optional
from zerver.lib.test_classes import ZulipTestCase
from zerver.mode... | # 'index.md') to `get_urls['200']` list.
for doc in os.listdir('./templates/zerver/help'):
if doc.startswith(".") or '~' in doc or '#' in doc:
continue # nocoverage -- just here for convenience
if doc not in {'main.html', 'index.md', 'include'}:
g... | }
# Add all files in 'templates/zerver/help' directory (except for 'main.html' and | random_line_split |
test_urls.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import importlib
import os
import six
import ujson
import django.core.urlresolvers
from django.test import TestCase
from typing import List, Optional
from zerver.lib.test_classes import ZulipTestCase
from zerver.mode... |
# Tests function-based views declared in urls.urlpatterns for
# whether the function exists. We at present do not test the
# class-based views.
def test_non_api_url_resolution(self):
# type: () -> None
for pattern in urls.urlpatterns:
callback_str = self.get_callback_strin... | for pattern in urls.v1_api_and_json_patterns:
callback_str = self.get_callback_string(pattern)
if callback_str and hasattr(pattern, "default_args"):
for func_string in pattern.default_args.values():
if isinstance(func_string, tuple):
fu... | identifier_body |
test_urls.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import importlib
import os
import six
import ujson
import django.core.urlresolvers
from django.test import TestCase
from typing import List, Optional
from zerver.lib.test_classes import ZulipTestCase
from zerver.mode... |
if doc not in {'main.html', 'index.md', 'include'}:
get_urls[200].append('/help/' + os.path.splitext(doc)[0]) # Strip the extension.
post_urls = {200: ["/accounts/login/"],
302: ["/accounts/logout/"],
401: ["/json/messages",
... | continue # nocoverage -- just here for convenience | conditional_block |
test_urls.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import importlib
import os
import six
import ujson
import django.core.urlresolvers
from django.test import TestCase
from typing import List, Optional
from zerver.lib.test_classes import ZulipTestCase
from zerver.mode... | (ZulipTestCase):
"""
Account creation URLs are accessible even when not logged in. Authenticated
URLs redirect to a page.
"""
def fetch(self, method, urls, expected_status):
# type: (str, List[str], int) -> None
for url in urls:
# e.g. self.client_post(url) if method is ... | PublicURLTest | identifier_name |
__init__.py | """
Weather component that handles meteorological data for your location.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/weather/
"""
import asyncio
import logging
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.he... |
ENTITY_ID_FORMAT = DOMAIN + '.{}'
ATTR_CONDITION_CLASS = 'condition_class'
ATTR_FORECAST = 'forecast'
ATTR_FORECAST_CONDITION = 'condition'
ATTR_FORECAST_PRECIPITATION = 'precipitation'
ATTR_FORECAST_TEMP = 'temperature'
ATTR_FORECAST_TEMP_LOW = 'templow'
ATTR_FORECAST_TIME = 'datetime'
ATTR_WEATHER_ATTRIBUTION = 'at... |
_LOGGER = logging.getLogger(__name__)
DEPENDENCIES = []
DOMAIN = 'weather' | random_line_split |
__init__.py | """
Weather component that handles meteorological data for your location.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/weather/
"""
import asyncio
import logging
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.he... |
return data
@property
def state(self):
"""Return the current state."""
return self.condition
@property
def condition(self):
"""Return the current condition."""
raise NotImplementedError()
| forecast = []
for forecast_entry in self.forecast:
forecast_entry = dict(forecast_entry)
forecast_entry[ATTR_FORECAST_TEMP] = show_temp(
self.hass, forecast_entry[ATTR_FORECAST_TEMP],
self.temperature_unit, self.precision)
... | conditional_block |
__init__.py | """
Weather component that handles meteorological data for your location.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/weather/
"""
import asyncio
import logging
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.he... | (self):
"""Return the wind bearing."""
return None
@property
def ozone(self):
"""Return the ozone level."""
return None
@property
def attribution(self):
"""Return the attribution."""
return None
@property
def visibility(self):
"""Return ... | wind_bearing | identifier_name |
__init__.py | """
Weather component that handles meteorological data for your location.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/weather/
"""
import asyncio
import logging
from homeassistant.helpers.entity_component import EntityComponent
from homeassistant.he... |
@property
def wind_bearing(self):
"""Return the wind bearing."""
return None
@property
def ozone(self):
"""Return the ozone level."""
return None
@property
def attribution(self):
"""Return the attribution."""
return None
@property
def ... | """Return the wind speed."""
return None | identifier_body |
store.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
const { applyMiddleware, createStore, compose } = require("redux");
const { thunk } = require("../share... | // Indicates to the component that we do want to render on the next
// render cycle.
forceUpdate: true
};
}
return next(reinitializerEnhancer, initialState, enhancer);
};
}
module.exports = (props: Props) => {
const middlewares = [thunk];
if (props.injectWaitService) {
... | loadedProperties: new Map(), | random_line_split |
store.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
const { applyMiddleware, createStore, compose } = require("redux");
const { thunk } = require("../share... | (props) {
return next => (innerReducer, initialState, enhancer) => {
function reinitializerEnhancer(state, action) {
if (action.type !== "ROOTS_CHANGED") {
return innerReducer(state, action);
}
if (props.releaseActor && initialState.actors) {
initialState.actors.forEach(props.re... | enableStateReinitializer | identifier_name |
store.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
const { applyMiddleware, createStore, compose } = require("redux");
const { thunk } = require("../share... |
return createStore(
reducer,
createInitialState(props),
compose(
applyMiddleware(...middlewares),
enableStateReinitializer(props)
)
);
};
| {
middlewares.push(waitUntilService);
} | conditional_block |
store.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
const { applyMiddleware, createStore, compose } = require("redux");
const { thunk } = require("../share... |
return next(reinitializerEnhancer, initialState, enhancer);
};
}
module.exports = (props: Props) => {
const middlewares = [thunk];
if (props.injectWaitService) {
middlewares.push(waitUntilService);
}
return createStore(
reducer,
createInitialState(props),
compose(
applyMiddleware... | {
if (action.type !== "ROOTS_CHANGED") {
return innerReducer(state, action);
}
if (props.releaseActor && initialState.actors) {
initialState.actors.forEach(props.releaseActor);
}
return {
...action.data,
actors: new Set(),
expandedPaths: new Set(),... | identifier_body |
uistuff.py | -column.html
def appendAutowrapColumn(treeview, name, **kvargs):
cell = Gtk.CellRendererText()
# cell.props.wrap_mode = Pango.WrapMode.WORD
# TODO:
# changed to ellipsize instead until "never ending grow" bug gets fixed
# see https://github.com/pychess/pychess/issues/1054
cell.props.ellipsize = ... | random_line_split | ||
uistuff.py | rgb[1]) * 0.2 + 0.6)
# This algorithm ought to balance colors more precisely, but it overrates
# the lightness of yellow, and nearly makes it black
# yiq = colorsys.rgb_to_yiq(*rgb)
# rgb = colorsys.yiq_to_rgb(.125, yiq[1], yiq[2])
return rgb
def keepDown(scrolledWindow):
def changed(vadjust)... |
treeview.set_size_request(0, -1)
# treeview.connect_after("size-allocate", callback, column, cell)
scroll = treeview.get_parent()
if isinstance(scroll, Gtk.ScrolledWindow):
scroll.set_policy(Gtk.PolicyType.NEVER, scroll.get_policy()[1])
return cell
METHODS = (
# Gtk.SpinButton s... | store.row_changed(store.get_path(store_iter), store_iter)
store_iter = store.iter_next(store_iter) | conditional_block |
uistuff.py | rgb[1]) * 0.2 + 0.6)
# This algorithm ought to balance colors more precisely, but it overrates
# the lightness of yellow, and nearly makes it black
# yiq = colorsys.rgb_to_yiq(*rgb)
# rgb = colorsys.yiq_to_rgb(.125, yiq[1], yiq[2])
return rgb
def keepDown(scrolledWindow):
def changed(vadjust)... | (*args):
if not conf.hasKey(key) or conf.get(key) != get_value():
conf.set(key, get_value())
widget.connect(signal, callback)
conf.notify_add(key, lambda *args: setFromConf())
if conf.hasKey(key):
setFromConf()
elif conf.get(key) is not None:
conf.set(key, conf.get(... | callback | identifier_name |
uistuff.py | # for saving widget values for Gtk.Dialog instances that are loaded with different
# sets of values/configurations and which also aren't instant save like in
# uistuff.keep(), but rather are saved later if and when the user clicks
# the dialog's OK button
def loadDialogWidget(widget,
widget_name,
... | if sys.platform == "win32" and not conf.no_gettext:
tree = ET.parse(addDataPrefix("glade/%s" % filename))
for node in tree.iter():
if 'translatable' in node.attrib:
node.text = _(node.text)
del node.attrib['translatable']
if... | identifier_body | |
features.tests.ts | import { echoLaunchJson } from "app/utils/jsonFiles"
import { intersection } from "lodash"
import { env } from "process"
import { devToggles, features } from "./features"
Object.entries(features).forEach(([key, val]) => {
describe(`The ${key} feature`, () => {
if (val.echoFlagKey) {
it(`uses an echo flag n... | }) | }) | random_line_split |
features.tests.ts | import { echoLaunchJson } from "app/utils/jsonFiles"
import { intersection } from "lodash"
import { env } from "process"
import { devToggles, features } from "./features"
Object.entries(features).forEach(([key, val]) => {
describe(`The ${key} feature`, () => {
if (val.echoFlagKey) {
it(`uses an echo flag n... |
})
}
})
})
describe("features and devToggles", () => {
it("never have the same keys", () => {
const featureKeys = Object.keys(features)
const devToggleKeys = Object.keys(devToggles)
const common = intersection(featureKeys, devToggleKeys)
expect(common).toStrictEqual([])
})
})
describ... | {
throw new Error(
`No echo flag found for key ${val.echoFlagKey}. ` +
(env.CI === "true"
? "Make sure you added it to the echo repo"
: "Make sure you added it to the echo repo and updated your local copy of echo with ./scripts/update-echo")
... | conditional_block |
main.js | var map, boroughSearch = [],
theaterSearch = [],
museumSearch = [];
/* Basemap Layers */
var mapquestOSM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0po4e8k/{z}/{x}/{y}.png");
var mbTerrainSat = L.tileLayer("https://{s}.tiles.mapbox.com/v3/matt.hd0b27jd/{z}/{x}/{y}.png");
var mbTerrainReg = L.tileL... | else {
var y = e.pageY - 20;
}
$("#info").css({
"left": x,
"top": y
});
});
}
};
popup.init();
}) | {
var y = e.pageY - 100;
} | conditional_block |
main.js | var map, boroughSearch = [],
theaterSearch = [],
museumSearch = [];
/* Basemap Layers */
var mapquestOSM = L.tileLayer("http://{s}.tiles.mapbox.com/v3/am3081.h0po4e8k/{z}/{x}/{y}.png");
var mbTerrainSat = L.tileLayer("https://{s}.tiles.mapbox.com/v3/matt.hd0b27jd/{z}/{x}/{y}.png");
var mbTerrainReg = L.tileL... |
map = L.map("map", {
zoom: 5,
center: [39, -95],
layers: [mapquestOSM]
});
/* Larger screens get expanded layer control */
if (document.body.clientWidth <= 767) {
var isCollapsed = true;
} else {
var isCollapsed = false;
}
var baseLayers = {
"Street Map": mapquestOSM,
"Aerial Imagery": mapquestOAM,
... | subdomains: ["oatile1", "oatile2", "oatile3", "oatile4"],
})]); | random_line_split |
categories.component.ts | import { Component, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import { AppBase } from './../../app.base'
import { Security } from './../../../common/security';
import { CategoriesResource } from './../../../common/resources';
@Component({
selector: 'categories',
encapsula... | extends AppBase {
metricsTableData: Array<any>;
isLoading: boolean = false;
constructor(public _router: Router, public _security: Security, private _categories: CategoriesResource) {
super(_router, _security);
}
protected getListData() {
this.isLoading = true;
this._categories.getList(this.page... | Categories | identifier_name |
categories.component.ts | import { Component, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import { AppBase } from './../../app.base'
import { Security } from './../../../common/security';
import { CategoriesResource } from './../../../common/resources';
@Component({
selector: 'categories',
encapsula... |
protected getListData() {
this.isLoading = true;
this._categories.getList(this.page, this.pageSize, this.sort, this.order, this.data).then(
(res: any)=> {
this.metricsTableData = res.data;
this.totalItems = res.pagination.total;
this.isLoading = false;
},
()=> {
... | {
super(_router, _security);
} | identifier_body |
categories.component.ts | import { Component, ViewEncapsulation } from '@angular/core';
import { Router } from '@angular/router';
import { AppBase } from './../../app.base'
import { Security } from './../../../common/security';
import { CategoriesResource } from './../../../common/resources';
@Component({
selector: 'categories',
encapsula... | this.page = pageNo;
};
public pageChanged(event: any): void {
this.page = event.page;
this.pageSize = event.itemsPerPage;
this.getListData();
};
public addItem() {
this._router.navigateByUrl('pages/categories/create');
}
public editItem(item) {
this._router.navigateByUrl('pages/ca... | this.getListData();
}
// pagination
public setPage(pageNo: number): void { | random_line_split |
index.js | var async = require('async');
function | (schema) {
// Pre-Save Setup
schema.pre('validate', function (next) {
var self = this;
this._wasNew = this.isNew;
if (this.isNew) {
this.runPreMethods(schema.preCreateMethods, self, function(){
next();
});
} else {
this.runPreMethods(schema.preUpdateMethods, self, function... | captainHook | identifier_name |
index.js | var async = require('async');
function captainHook(schema) {
| this.runPreMethods(schema.preCreateMethods, self, function(){
next();
});
} else {
this.runPreMethods(schema.preUpdateMethods, self, function(){
next();
});
}
});
// Post-Save Setup
schema.post('save', function () {
var self = this;
if (this._wasNew) {
... | // Pre-Save Setup
schema.pre('validate', function (next) {
var self = this;
this._wasNew = this.isNew;
if (this.isNew) { | random_line_split |
index.js | var async = require('async');
function captainHook(schema) {
// Pre-Save Setup
schema.pre('validate', function (next) {
var self = this;
this._wasNew = this.isNew;
if (this.isNew) {
this.runPreMethods(schema.preCreateMethods, self, function(){
next();
});
} else {
this.ru... | else {
this.runPostMethods(schema.postUpdateMethods, self);
}
});
/**
* Pre-Hooks
* These hooks run before an instance has been created / updated
*/
schema.methods.runPreMethods = function(methods, self, callback){
async.eachSeries(methods,
function(fn, cb) {
fn(self, cb... | {
this.runPostMethods(schema.postCreateMethods, self);
} | conditional_block |
index.js | var async = require('async');
function captainHook(schema) | if (this._wasNew) {
this.runPostMethods(schema.postCreateMethods, self);
} else {
this.runPostMethods(schema.postUpdateMethods, self);
}
});
/**
* Pre-Hooks
* These hooks run before an instance has been created / updated
*/
schema.methods.runPreMethods = function(methods, sel... | {
// Pre-Save Setup
schema.pre('validate', function (next) {
var self = this;
this._wasNew = this.isNew;
if (this.isNew) {
this.runPreMethods(schema.preCreateMethods, self, function(){
next();
});
} else {
this.runPreMethods(schema.preUpdateMethods, self, function(){
... | identifier_body |
group_device_list.rs | use dioxus::prelude::*;
use dioxus_router::use_route;
use fermi::use_read;
use homectl_types::group::GroupId;
use crate::{app_state::GROUPS_ATOM, device_list::DeviceList, scene_list::SceneList};
#[allow(non_snake_case)]
pub fn GroupDeviceList(cx: Scope) -> Element | {
let group_id: GroupId = use_route(&cx).segment("group_id")?.ok()?;
let groups = use_read(&cx, GROUPS_ATOM);
let (_, group) = groups
.iter()
.find(|(candidate_group_id, _)| *candidate_group_id == &group_id)?;
let name = &group.name;
cx.render(rsx! {
DeviceList { filte... | identifier_body | |
group_device_list.rs | use dioxus::prelude::*;
use dioxus_router::use_route;
use fermi::use_read;
use homectl_types::group::GroupId;
use crate::{app_state::GROUPS_ATOM, device_list::DeviceList, scene_list::SceneList};
#[allow(non_snake_case)]
pub fn | (cx: Scope) -> Element {
let group_id: GroupId = use_route(&cx).segment("group_id")?.ok()?;
let groups = use_read(&cx, GROUPS_ATOM);
let (_, group) = groups
.iter()
.find(|(candidate_group_id, _)| *candidate_group_id == &group_id)?;
let name = &group.name;
cx.render(rsx! {
... | GroupDeviceList | identifier_name |
group_device_list.rs | use dioxus::prelude::*;
use dioxus_router::use_route; | use homectl_types::group::GroupId;
use crate::{app_state::GROUPS_ATOM, device_list::DeviceList, scene_list::SceneList};
#[allow(non_snake_case)]
pub fn GroupDeviceList(cx: Scope) -> Element {
let group_id: GroupId = use_route(&cx).segment("group_id")?.ok()?;
let groups = use_read(&cx, GROUPS_ATOM);
let (... | use fermi::use_read; | random_line_split |
tables.ts | import path from "path";
import { Option, WeightedValue } from "./index";
import { getGroups } from "./utils";
interface TableEntry {
w: number;
options: Option[];
}
interface Tables {
[name: string]: TableEntry;
}
const tables = {} as Tables;
let isInitialized = false;
function initAvailableTables(files: stri... |
}
return options as TableReferenceOption[];
}
export function getTableWeight(tableName: string) {
return getTable(tableName).w;
}
export function getTableOptions(tableName: string) {
return getTable(tableName).options;
}
| {
throw new Error(`Missing "table" property in table ${tableName} option ${opt.original}`);
} | conditional_block |
tables.ts | import path from "path";
import { Option, WeightedValue } from "./index";
import { getGroups } from "./utils";
interface TableEntry {
w: number;
options: Option[];
}
interface Tables {
[name: string]: TableEntry;
}
const tables = {} as Tables;
let isInitialized = false;
function initAvailableTables(files: stri... | (tableName: string, r: (id: string) => any) {
const name = path.basename(tableName, ".json");
const table: WeightedValue[] = r(tableName);
let totalWeight = 0;
const options = table.map((row) => {
const w = row.w > 0 ? row.w : 0;
totalWeight += w;
return {
...row,
w,
v: getGroups(r... | importTable | identifier_name |
tables.ts | import path from "path";
import { Option, WeightedValue } from "./index";
import { getGroups } from "./utils";
interface TableEntry {
w: number;
options: Option[];
}
interface Tables {
[name: string]: TableEntry;
}
const tables = {} as Tables;
let isInitialized = false;
function initAvailableTables(files: stri... | {
return getTable(tableName).options;
} | identifier_body | |
tables.ts | import path from "path";
import { Option, WeightedValue } from "./index";
import { getGroups } from "./utils";
interface TableEntry {
w: number;
options: Option[];
}
interface Tables {
[name: string]: TableEntry;
}
const tables = {} as Tables;
let isInitialized = false;
function initAvailableTables(files: stri... |
export function getTable(tableName: string) {
ensureTablesAreInitialized();
if (!(tableName in tables)) {
throw new Error(`Unable to find table [${tableName}]`);
}
return tables[tableName];
}
export interface NamedOption extends Option {
name?: string;
}
export interface TableReferenceOption extends Nam... |
export function getTableNames() {
ensureTablesAreInitialized();
return Object.keys(tables);
} | random_line_split |
test_auth.py | # Copyright (C) 2008 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at you... | (self):
"""
verify that multipart auth works.
"""
self.start_server()
self.tc.connect(hostkey=self.public_host_key)
remain = self.tc.auth_password(username='paranoid', password='paranoid')
self.assertEqual(['publickey'], remain)
key = DSSKey.from_private_k... | test_3_multipart_auth | identifier_name |
test_auth.py | # Copyright (C) 2008 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at you... |
return AUTH_FAILED
def check_auth_publickey(self, username, key):
if (username == 'paranoid') and (key == self.paranoid_key):
# 2-part auth
self.paranoid_did_public_key = True
if self.paranoid_did_password:
return AUTH_SUCCESSFUL
retu... | raise Exception("Ack!") | conditional_block |
test_auth.py | # Copyright (C) 2008 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at you... |
def tearDown(self):
self.tc.close()
self.ts.close()
self.socks.close()
self.sockc.close()
def start_server(self):
host_key = RSAKey.from_private_key_file(test_path('test_rsa.key'))
self.public_host_key = RSAKey(data=host_key.asbytes())
self.ts.add_s... | self.socks = LoopSocket()
self.sockc = LoopSocket()
self.sockc.link(self.socks)
self.tc = Transport(self.sockc)
self.ts = Transport(self.socks) | identifier_body |
test_auth.py | # Copyright (C) 2008 Robey Pointer <robeypointer@gmail.com>
#
# This file is part of paramiko.
#
# Paramiko is free software; you can redistribute it and/or modify it under the
# terms of the GNU Lesser General Public License as published by the Free
# Software Foundation; either version 2.1 of the License, or (at you... | self.event = threading.Event()
self.server = NullServer()
self.assertTrue(not self.event.isSet())
self.ts.start_server(self.event, self.server)
def verify_finished(self):
self.event.wait(1.0)
self.assertTrue(self.event.isSet())
self.assertTrue(self.ts.is_... | host_key = RSAKey.from_private_key_file(test_path('test_rsa.key'))
self.public_host_key = RSAKey(data=host_key.asbytes())
self.ts.add_server_key(host_key) | random_line_split |
spf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/spf.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of condit... |
def test_spf_evaluate_mechanism_permerror(self):
s = spf.SenderPolicyFramework('1.2.3.4', 'doesnotexist.king-phisher.com')
eval_mech = lambda m, r: s._evaluate_mechanism(s.ip_address, s.domain, s.sender, m, r)
with self.assertRaises(spf.SPFPermError):
eval_mech('ip4', 'thisisnotanetwork')
with self.assert... | s = spf.SenderPolicyFramework('1.2.3.4', 'doesnotexist.king-phisher.com')
eval_mech = lambda m, r: s._evaluate_mechanism(s.ip_address, s.domain, s.sender, m, r)
self.assertTrue(eval_mech('all', None))
self.assertTrue(eval_mech('exists', '%{d2}'))
self.assertTrue(eval_mech('ip4', '1.2.3.0/24'))
self.assertTrue... | identifier_body |
spf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/spf.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of condit... | (self):
s = spf.SenderPolicyFramework('1.2.3.4', 'king-phisher.com')
check_host_result = s.check_host()
self.assertIsNotNone(check_host_result)
self.assertEqual(check_host_result, 'fail')
self.assertEqual(spf.check_host('1.2.3.4', 'king-phisher.com'), 'fail')
@testing.skip_if_offline
def test_spf_evaluate... | test_spf_check_host | identifier_name |
spf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/spf.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of condit... | unittest.main() | conditional_block | |
spf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# tests/spf.py
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of condit... | self.assertEqual(expand_macro('%{ir}.%{v}.%{l1r-}.lp._spf.%{d2}'), '3.2.0.192.in-addr.strong.lp._spf.example.com')
self.assertEqual(expand_macro('%{d2}.trusted-domains.example.net'), 'example.com.trusted-domains.example.net')
def test_spf_record_unparse(self):
self.assertEqual(spf.record_unparse(('all', '+', No... | self.assertEqual(expand_macro('%{l1r-}'), 'strong')
self.assertEqual(expand_macro('%{ir}.%{v}._spf.%{d2}'), '3.2.0.192.in-addr._spf.example.com')
self.assertEqual(expand_macro('%{lr-}.lp._spf.%{d2}'), 'bad.strong.lp._spf.example.com')
self.assertEqual(expand_macro('%{lr-}.lp.%{ir}.%{v}._spf.%{d2}'), 'bad.stron... | random_line_split |
type_check_file.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 * as ts from 'typescript';
import {AbsoluteFsPath, join} from '../../file_system';
import {NoopImportRewriter... | (): ts.Statement[] { return []; }
}
export function typeCheckFilePath(rootDirs: AbsoluteFsPath[]): AbsoluteFsPath {
const shortest = rootDirs.concat([]).sort((a, b) => a.length - b.length)[0];
return join(shortest, '__ng_typecheck__.ts');
}
| getPreludeStatements | identifier_name |
type_check_file.ts | /** | * 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 * as ts from 'typescript';
import {AbsoluteFsPath, join} from '../../file_system';
import {NoopImportRewriter, Reference, ReferenceEmitter} from '../../imports';
import {Clas... | * @license
* Copyright Google Inc. All Rights Reserved.
* | random_line_split |
files.contribution.ts | #files.autoSaveDelay#`."),
nls.localize({ comment: ['This is the description for a setting. Values surrounded by single quotes are not to be translated.'], key: 'files.autoSave.onFocusChange' }, "A dirty editor is automatically saved when the editor loses focus."),
nls.localize({ comment: ['This is the descript... | 'type': 'boolean',
'description': nls.localize('compressSingleChildFolders', "Controls whether the explorer should render folders in a compact form. In such a form, single child folders will be compressed in a combined tree element. Useful for Java package structures, for example."),
'default': true
},
} | random_line_split | |
files.contribution.ts | 'View: Show Explorer',
nls.localize('view', "View")
);
// Register file editors
Registry.as<IEditorRegistry>(EditorExtensions.Editors).registerEditor(
EditorDescriptor.create(
BinaryFileEditor,
BinaryFileEditor.ID,
nls.localize('binaryFileEditor', "Binary File Editor")
),
[
new SyncDescriptor<EditorInput>(... |
deserialize(instantiationService: IInstantiationService, serializedEditorInput: string): FileEditorInput {
return instantiationService.invokeFunction<FileEditorInput>(accessor => {
const serializedFileEditorInput: ISerializedFileEditorInput = JSON.parse(serializedEditorInput);
const resource = URI.revive(ser... | {
const fileEditorInput = <FileEditorInput>editorInput;
const resource = fileEditorInput.resource;
const serializedFileEditorInput: ISerializedFileEditorInput = {
resourceJSON: resource.toJSON(),
encoding: fileEditorInput.getEncoding(),
modeId: fileEditorInput.getPreferredMode() // only using the preferr... | identifier_body |
files.contribution.ts | implements IWorkbenchContribution {
constructor(@ILabelService labelService: ILabelService) {
labelService.registerFormatter({
scheme: Schemas.file,
formatting: {
label: '${authority}${path}',
separator: sep,
tildify: !platform.isWindows,
normalizeDriveLetter: platform.isWindows,
authorit... | FileUriLabelContribution | identifier_name | |
test_suite.py | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... | except TApplicationException:
pass
else:
self.fail("should have gotten exception")
yield self.client.testException('Safe')
def suite():
suite = unittest.TestSuite()
loader = unittest.TestLoader()
suite.addTest(loader.loadTestsFromTestCase(ThriftTestCase))
... | try:
yield self.client.testException('throw_undeclared') | random_line_split |
test_suite.py | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... |
@gen_test
def test_void(self):
v = yield self.client.testVoid()
self.assertEqual(v, None)
@gen_test
def test_string(self):
v = yield self.client.testString('Python')
self.assertEqual(v, 'Python')
@gen_test
def test_byte(self):
v = yield self.client.tes... | super(ThriftTestCase, self).setUp()
self.port = get_unused_port()
# server
self.handler = TestHandler(self)
self.processor = ThriftTest.Processor(self.handler)
self.pfactory = TBinaryProtocol.TBinaryProtocolFactory()
self.server = TTornado.TTornadoServer(self.processor... | identifier_body |
test_suite.py | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... | unittest.TestProgram(defaultTest='suite',
testRunner=unittest.TextTestRunner(verbosity=1)) | conditional_block | |
test_suite.py | #!/usr/bin/env python
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "L... | (self):
self.client.testOneway(1)
v = yield self.client.testI32(-1)
self.assertEqual(v, -1)
@gen_test
def test_map(self):
"""
TestHandler.testMap is a coroutine, this test checks if gen.Return() from a coroutine works.
"""
expected = {1: 1}
res = ... | test_oneway | identifier_name |
page-base.component.ts | /**
* @license
* Copyright 2017 JBoss 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 | * See the License for the specific language governing permissions and
* limitations under the License.
*/
import { OnDestroy, OnInit, Directive } from "@angular/core";
import {ActivatedRoute} from "@angular/router";
import {Title} from "@angular/platform-browser";
export class DataMap {
[key: string]: boolean;... | *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | random_line_split |
page-base.component.ts | /**
* @license
* Copyright 2017 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... | (error: any): void {
console.error(" Error: %o", error);
this.pageError = error;
}
/**
* Called when page data has been loaded.
* @param key
*/
public loaded(key: string): void {
this.dataLoaded[key] = true;
}
/**
* Called to determine whether some pa... | error | identifier_name |
page-base.component.ts | /**
* @license
* Copyright 2017 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... |
/**
* Called by a subclass (page) to report an error during loading of data.
* @param error
*/
public error(error: any): void {
console.error(" Error: %o", error);
this.pageError = error;
}
/**
* Called when page data has been loaded.
* @param key
*/
... | {
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.