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 |
|---|---|---|---|---|
hash.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use digest::{Digest, FixedOutput};
use sha2::Sha256;
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use hex;
const FINGERPRINT_SIZE: usize = 32;
#[derive(Clone, Cop... | () {
assert_eq!(
Fingerprint::from_bytes_unsafe(&vec![
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
0xab,
... | from_bytes_unsafe | identifier_name |
hash.rs | // Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use digest::{Digest, FixedOutput};
use sha2::Sha256;
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use hex;
const FINGERPRINT_SIZE: usize = 32;
#[derive(Clone, Cop... |
let mut fingerprint = [0; FINGERPRINT_SIZE];
fingerprint.clone_from_slice(&bytes[0..FINGERPRINT_SIZE]);
Fingerprint(fingerprint)
}
pub fn from_hex_string(hex_string: &str) -> Result<Fingerprint, String> {
<[u8; FINGERPRINT_SIZE] as hex::FromHex>::from_hex(hex_string)
.map(|v| Fingerprint(v)... | {
panic!(
"Input value was not a fingerprint; had length: {}",
bytes.len()
);
} | conditional_block |
browsingcontext.rs | /. */
| use dom::bindings::utils::WindowProxyHandler;
use dom::bindings::utils::get_array_index_from_id;
use dom::document::Document;
use dom::element::Element;
use dom::window::Window;
use js::JSCLASS_IS_GLOBAL;
use js::glue::{CreateWrapperProxyHandler, ProxyTraps, NewWindowProxy};
use js::glue::{GetProxyPrivate, SetProxyExtr... | use dom::bindings::cell::DOMRefCell;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, Reflector}; | random_line_split |
browsingcontext.rs | /. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, Reflector};
use ... | (document: &Document) -> SessionHistoryEntry {
SessionHistoryEntry {
document: JS::from_ref(document),
children: vec![],
}
}
}
#[allow(unsafe_code)]
unsafe fn GetSubframeWindow(cx: *mut JSContext,
proxy: HandleObject,
i... | new | identifier_name |
browsingcontext.rs | /. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, Reflector};
use ... |
pub fn frame_element(&self) -> Option<&Element> {
self.frame_element.r()
}
pub fn window_proxy(&self) -> *mut JSObject {
let window_proxy = self.reflector.get_jsobject();
assert!(!window_proxy.get().is_null());
window_proxy.get()
}
}
// This isn't a DOM struct, just a... | {
Root::from_ref(self.active_document().window())
} | identifier_body |
browsingcontext.rs | /. */
use dom::bindings::cell::DOMRefCell;
use dom::bindings::conversions::{ToJSValConvertible, root_from_handleobject};
use dom::bindings::js::{JS, Root, RootedReference};
use dom::bindings::proxyhandler::{fill_property_descriptor, get_property_descriptor};
use dom::bindings::reflector::{Reflectable, Reflector};
use ... |
*bp = found;
true
}
#[allow(unsafe_code)]
unsafe extern "C" fn get(cx: *mut JSContext,
proxy: HandleObject,
receiver: HandleObject,
id: HandleId,
vp: MutableHandleValue)
-> bool {
... | {
return false;
} | conditional_block |
tonality.js | import React from 'react'
import Icon from 'react-icon-base'
const MdTonality = props => ( | <g><path d="m32.9 23.4c0.1-0.6 0.2-1.2 0.3-1.8h-11.6v1.8h11.3z m-2.5 5c0.4-0.6 0.9-1.2 1.2-1.8h-10v1.8h8.8z m-8.8 4.8c1.8-0.2 3.4-0.8 4.9-1.6h-4.9v1.6z m0-16.6v1.8h11.6c-0.1-0.6-0.2-1.2-0.3-1.8h-11.3z m0-5v1.8h10c-0.4-0.6-0.8-1.2-1.2-1.8h-8.8z m0-4.8v1.6h4.9c-1.5-0.8-3.1-1.4-4.9-1.6z m-3.2 26.4v-26.4c-6.6 0.8-1... | <Icon viewBox="0 0 40 40" {...props}> | random_line_split |
committees.py | import csv
import re
import unicodedata
from utils import *
def initialise(name):
return re.sub('[^A-Z]', '', name)
def asciify(name):
return unicodedata.normalize('NFKD', unicode(name)).encode('ascii', 'ignore')
def parse(data):
orgs_by_id = dict([ (x['id'], x) for x in data['organizations'].values() ])... |
add_membership(person, mship)
return data
| mship['role'] = 'Chairperson' | conditional_block |
committees.py | import csv
import re
import unicodedata
from utils import *
def | (name):
return re.sub('[^A-Z]', '', name)
def asciify(name):
return unicodedata.normalize('NFKD', unicode(name)).encode('ascii', 'ignore')
def parse(data):
orgs_by_id = dict([ (x['id'], x) for x in data['organizations'].values() ])
# TODO: Perhaps check old/new committees, then stop using parl.py
... | initialise | identifier_name |
committees.py | import csv
import re
import unicodedata
from utils import *
def initialise(name):
return re.sub('[^A-Z]', '', name) | def parse(data):
orgs_by_id = dict([ (x['id'], x) for x in data['organizations'].values() ])
# TODO: Perhaps check old/new committees, then stop using parl.py
# committees. Or just assume these new ones are accurate.
for row in csv.DictReader(open(data_path + 'committees.csv')):
if row['Name'] ... |
def asciify(name):
return unicodedata.normalize('NFKD', unicode(name)).encode('ascii', 'ignore')
| random_line_split |
committees.py | import csv
import re
import unicodedata
from utils import *
def initialise(name):
|
def asciify(name):
return unicodedata.normalize('NFKD', unicode(name)).encode('ascii', 'ignore')
def parse(data):
orgs_by_id = dict([ (x['id'], x) for x in data['organizations'].values() ])
# TODO: Perhaps check old/new committees, then stop using parl.py
# committees. Or just assume these new ones ... | return re.sub('[^A-Z]', '', name) | identifier_body |
hextobase64.rs | extern crate matasano;
use self::matasano::common::{base64, err};
fn test_hex_to_base64(input: &str, output: &str) {
let r: Result<String, err::Error> = base64::hex_to_base64(input);
let base64 = match r {
Ok(v) => v,
Err(e) => {
println!("{}", e);
String::from("N.A.")
}
};
assert_eq!(base64, ... |
#[test]
fn test_more() {
test_hex_to_base64("00", "AA==");
test_hex_to_base64("00FF", "AP8=");
test_hex_to_base64("00FFed", "AP/t");
test_hex_to_base64("00F3ed45", "APPtRQ==");
test_hex_to_base64("00F3ed455727efd982a8b340", "APPtRVcn79mCqLNA");
test_hex_to_base64("", "");
}
| {
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
test_hex_to_base64(input, output);
} | identifier_body |
hextobase64.rs | extern crate matasano;
use self::matasano::common::{base64, err};
fn test_hex_to_base64(input: &str, output: &str) {
let r: Result<String, err::Error> = base64::hex_to_base64(input);
let base64 = match r {
Ok(v) => v,
Err(e) => {
println!("{}", e);
String::from("N.A.")
}
};
assert_eq!(base64, ... | () {
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
test_hex_to_base64(input, output);
}
#[test]
fn test_more() {
test_hex_to_base64("00", "AA==");
test_hex_to_base64(... | test_cryptopals_case | identifier_name |
hextobase64.rs | extern crate matasano;
use self::matasano::common::{base64, err};
fn test_hex_to_base64(input: &str, output: &str) {
let r: Result<String, err::Error> = base64::hex_to_base64(input);
let base64 = match r {
Ok(v) => v,
Err(e) => {
println!("{}", e);
String::from("N.A.")
}
};
| #[test]
fn test_cryptopals_case() {
let input = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";
let output = "SSdtIGtpbGxpbmcgeW91ciBicmFpbiBsaWtlIGEgcG9pc29ub3VzIG11c2hyb29t";
test_hex_to_base64(input, output);
}
#[test]
fn test_more() {
test_hex_to_base64("00"... | assert_eq!(base64, output);
}
| random_line_split |
mod.rs | 6-GCM-SHA384:\
ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\
ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:\
AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:\
ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eN... | })
.to_owned();
let ciphers = config
.lookup("input.tls_ciphers")
.map_or(DEFAULT_CIPHERS, |x| {
x.as_str()
.expect("input.tls_ciphers must be a string with a cipher suite")
})
.to_owned();
let tls_modern = match config
.lookup... | {
let listen = config
.lookup("input.listen")
.map_or(DEFAULT_LISTEN, |x| {
x.as_str().expect("input.listen must be an ip:port string")
})
.to_owned();
let threads = get_default_threads(config);
let cert = config
.lookup("input.tls_cert")
.map_or(D... | identifier_body |
mod.rs | 6-GCM-SHA384:\
ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\
ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:\
AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:\
ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eN... | const DEFAULT_COMPRESSION: bool = false;
const DEFAULT_FRAMING: &str = "line";
const DEFAULT_KEY: &str = "flowgger.pem";
const DEFAULT_LISTEN: &str = "0.0.0.0:6514";
#[cfg(feature = "coroutines")]
const DEFAULT_THREADS: usize = 1;
const DEFAULT_TIMEOUT: u64 = 3600;
const DEFAULT_TLS_COMPATIBILITY_LEVEL: &str = "default... | !EDH-DSS-DES-CBC3-SHA:!EDH-RSA-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"; | random_line_split |
mod.rs | 6-GCM-SHA384:\
ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:\
ECDHE-ECDSA-AES256-SHA:ECDHE-RSA-AES256-SHA:AES128-GCM-SHA256:AES256-GCM-SHA384:\
AES128-SHA256:AES256-SHA256:AES128-SHA:AES256-SHA:ECDHE-ECDSA-DES-CBC3-SHA:\
ECDHE-RSA-DES-CBC3-SHA:DES-CBC3-SHA:!aNULL:!eN... | {
framing: String,
threads: usize,
acceptor: SslAcceptor,
}
fn set_fs(ctx: &mut SslContextBuilder) {
let p = BigNum::from_hex_str("87A8E61DB4B6663CFFBBD19C651959998CEEF608660DD0F25D2CEED4435E3B00E00DF8F1D61957D4FAF7DF4561B2AA3016C3D91134096FAA3BF4296D830E9A7C209E0C6497517ABD5A8A9D306BCF67ED91F9E6725B4... | TlsConfig | identifier_name |
mod.rs | -DES-CBC3-SHA";
const DEFAULT_COMPRESSION: bool = false;
const DEFAULT_FRAMING: &str = "line";
const DEFAULT_KEY: &str = "flowgger.pem";
const DEFAULT_LISTEN: &str = "0.0.0.0:6514";
#[cfg(feature = "coroutines")]
const DEFAULT_THREADS: usize = 1;
const DEFAULT_TIMEOUT: u64 = 3600;
const DEFAULT_TLS_COMPATIBILITY_LEVEL:... | {
SslAcceptor::mozilla_modern(SslMethod::tls())
} | conditional_block | |
test_vector_operations.py | import unittest
import env
from linalg.vector import Vector
class TestVectorOperations(unittest.TestCase):
def test_vector_equality(self):
a = Vector([1, 2, 3])
b = Vector([1, 2, 3])
self.assertEqual(a, b)
def test_vector_inequality(self):
a = Vector([1, 2, 3])
b = V... | unittest.main() | conditional_block | |
test_vector_operations.py | import unittest
import env
from linalg.vector import Vector
class | (unittest.TestCase):
def test_vector_equality(self):
a = Vector([1, 2, 3])
b = Vector([1, 2, 3])
self.assertEqual(a, b)
def test_vector_inequality(self):
a = Vector([1, 2, 3])
b = Vector([4, 5, 6])
self.assertNotEqual(a, b)
def test_vector_addition(self):
... | TestVectorOperations | identifier_name |
test_vector_operations.py | import unittest
import env
from linalg.vector import Vector
class TestVectorOperations(unittest.TestCase):
def test_vector_equality(self):
a = Vector([1, 2, 3])
b = Vector([1, 2, 3])
self.assertEqual(a, b)
def test_vector_inequality(self):
a = Vector([1, 2, 3])
b = V... | v = Vector([3.039, 1.879])
b = Vector([0.825, 2.036])
proj = v.project(b)
self.assertEqual(proj.round(3), Vector([1.083, 2.672]))
v = Vector([-9.88, -3.264, -8.159])
b = Vector([-2.155, -9.353, -9.473])
orth = v.orthogonal_component(b)
try:
se... | Testing vector projection, orthogonal components, and
decomposition.
""" | random_line_split |
test_vector_operations.py | import unittest
import env
from linalg.vector import Vector
class TestVectorOperations(unittest.TestCase):
def test_vector_equality(self):
a = Vector([1, 2, 3])
b = Vector([1, 2, 3])
self.assertEqual(a, b)
def test_vector_inequality(self):
a = Vector([1, 2, 3])
b = V... |
if __name__ == '__main__':
unittest.main()
| """
Testing the calculation of cross products, as well as the areas
of parallelograms and triangles spanned by different vectors.
"""
v = Vector([8.462, 7.893, -8.187])
w = Vector([6.984, -5.975, 4.778])
cross = v.cross(w)
self.assertEqual(cross.round(3), Vector([... | identifier_body |
party.component.ts | import { Component } from '@angular/core';
import { ColyseusGameService } from '../colyseus.game.service';
import { startCase } from 'lodash';
import { LocalStorage } from 'ngx-webstorage';
@Component({
selector: 'app-party',
templateUrl: './party.component.html',
styleUrls: ['./party.component.scss']
})
export... | passLeader() {
this.colyseusGame.sendCommandString(`party give ${this.partyPass}`);
this.partyPass = '';
}
}
| this.colyseusGame.sendCommandString(`party kick ${this.partyPass}`);
this.partyPass = '';
}
| identifier_body |
party.component.ts | import { Component } from '@angular/core';
import { ColyseusGameService } from '../colyseus.game.service';
import { startCase } from 'lodash';
import { LocalStorage } from 'ngx-webstorage';
@Component({ |
@LocalStorage()
public partyName: string;
public partyPass: string;
get party() {
if(!this.colyseusGame.character) return null;
return (<any>this.colyseusGame.character)._party;
}
get partyExp() {
if(!this.colyseusGame.character) return null;
return (<any>this.colyseusGame.character).par... | selector: 'app-party',
templateUrl: './party.component.html',
styleUrls: ['./party.component.scss']
})
export class PartyComponent { | random_line_split |
party.component.ts | import { Component } from '@angular/core';
import { ColyseusGameService } from '../colyseus.game.service';
import { startCase } from 'lodash';
import { LocalStorage } from 'ngx-webstorage';
@Component({
selector: 'app-party',
templateUrl: './party.component.html',
styleUrls: ['./party.component.scss']
})
export... |
this.colyseusGame.sendCommandString('party leave');
this.partyPass = '';
}
kick() {
this.colyseusGame.sendCommandString(`party kick ${this.partyPass}`);
this.partyPass = '';
}
passLeader() {
this.colyseusGame.sendCommandString(`party give ${this.partyPass}`);
this.partyPass = '';
}
... | e() { | identifier_name |
local_rate_limit.rs | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | t.run_server_with_config(server_config);
let (mut recv_chan, socket) = t.open_socket_and_recv_multiple_packets().await;
let server_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), server_port);
for _ in 0..3 {
socket.send_to(b"hello", &server_addr).await.unwrap();
}
fo... | {
let mut t = TestHelper::default();
let yaml = "
max_packets: 2
period: 1
";
let echo = t.run_echo_server().await;
let server_port = 12346;
let server_config = ConfigBuilder::empty()
.with_port(server_port)
.with_static(
vec![Filter {
name: local_rate_l... | identifier_body |
local_rate_limit.rs | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to i... | () {
let mut t = TestHelper::default();
let yaml = "
max_packets: 2
period: 1
";
let echo = t.run_echo_server().await;
let server_port = 12346;
let server_config = ConfigBuilder::empty()
.with_port(server_port)
.with_static(
vec![Filter {
name: local_rat... | local_rate_limit_filter | identifier_name |
local_rate_limit.rs | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at | * http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language govern... | * | random_line_split |
picup.server.model.tests.js | 'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Picup = mongoose.model('Picup');
/**
* Globals
*/
var user, picup; | /**
* Unit tests
*/
describe('Picup Model Unit Tests:', function() {
beforeEach(function(done) {
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: 'username',
password: 'password'
});
user.save(function... | random_line_split | |
common.js | /**********************************************************
* Common JS function calls. *
* Copyright © 2001-2007 E-Blah. *
* Part of the E-Blah Software. Released under the GPL. *
* Last Update: September 17, 2007 *
**************... | else { req.send('TEMP'); }
} else { alert('There was an error loading this page.'); }
}
function processReqChange() {
if(req.readyState != 4) { document.getElementById(messageid).innerHTML = '<div class="loading"> </div>'; }
if(req.readyState == 4) {
if (req.status == 200) {
document.getEle... |
req.send(savemessage);
} | conditional_block |
common.js | /**********************************************************
* Common JS function calls. *
* Copyright © 2001-2007 E-Blah. *
* Part of the E-Blah Software. Released under the GPL. *
* Last Update: September 17, 2007 *
**************... |
function ConstructLinks(JSinput) {
GetLinks(JSinput);
var link = '';
for(x in MenuItems) {
link += '<div style="padding: 5px;" class="win3">' + MenuItems[x] + '</div>';
}
return(link);
}
// Image Resize; from Martin's Mod for E-Blah
function resizeImg() {
var _resizeWidth = 750;
var ResizeM... |
document.getElementById('menu-eblah').innerHTML = '';
document.getElementById('menu-eblah').style.visibility = 'hidden';
}
| identifier_body |
common.js | /**********************************************************
* Common JS function calls. *
* Copyright © 2001-2007 E-Blah. *
* Part of the E-Blah Software. Released under the GPL. *
* Last Update: September 17, 2007 *
**************... | JSinput) {
GetLinks(JSinput);
var link = '';
for(x in MenuItems) {
link += '<div style="padding: 5px;" class="win3">' + MenuItems[x] + '</div>';
}
return(link);
}
// Image Resize; from Martin's Mod for E-Blah
function resizeImg() {
var _resizeWidth = 750;
var ResizeMsg = 'Click to view origina... | onstructLinks( | identifier_name |
common.js | /**********************************************************
* Common JS function calls. *
* Copyright © 2001-2007 E-Blah. *
* Part of the E-Blah Software. Released under the GPL. *
* Last Update: September 17, 2007 *
**************... | catch(e) {
try { req = new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e) { req = false; }
}
}
if(req) {
req.onreadystatechange = processReqChange;
req.open("POST", url, true); // Use POST so we don't get CACHED items!
if(saveopen == 1) { req.send("message="+encodeURIComponent(savem... | try { req = new ActiveXObject("Msxml2.XMLHTTP"); }
| random_line_split |
cssmediarule.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 cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings::codegen::Bind... | fn Media(&self) -> Root<MediaList> {
self.medialist()
}
} |
impl CSSMediaRuleMethods for CSSMediaRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media | random_line_split |
cssmediarule.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 cssparser::Parser;
use dom::bindings::codegen::Bindings::CSSMediaRuleBinding;
use dom::bindings::codegen::Bind... | self) -> DOMString {
let guard = self.cssconditionrule.shared_lock().read();
self.mediarule.read_with(&guard).to_css_string(&guard).into()
}
}
impl CSSMediaRuleMethods for CSSMediaRule {
// https://drafts.csswg.org/cssom/#dom-cssgroupingrule-media
fn Media(&self) -> Root<MediaList> {
... | t_css(& | identifier_name |
mim-video-playlist.js | define(['knockout', 'Q', 'model',
'css!mediaelement-css', 'css!dataTables-bootstrap-css', 'css!datatables-scroller-css', 'text!./mim-video-playlist.html',
'datatables', 'knockout.punches', 'mediaelement', 'datatables-bootstrap', 'datatables-scroller'],
function (ko, Q, model, css, dataTablesBootstrapCss,dat... | self.player =
$('#videoContent').mediaelementplayer({
alwaysShowControls: false,
features: ['playpause', 'volume'],
success: function (mediaElement, domObject) {
if (self.mustPlay()) mediaElement.play();
... | {
var self = this;
self.urlBaseVideo = 'videoDirectory/';
self.urlApi = 'Api/';
self.videoSuffix = '.mp4';
self.videoSuffix = '.jpg';
self.isVideoDataLoaded = ko.observable(false);
self.url = {
getVideoList: self.urlA... | identifier_body |
mim-video-playlist.js | define(['knockout', 'Q', 'model',
'css!mediaelement-css', 'css!dataTables-bootstrap-css', 'css!datatables-scroller-css', 'text!./mim-video-playlist.html',
'datatables', 'knockout.punches', 'mediaelement', 'datatables-bootstrap', 'datatables-scroller'],
function (ko, Q, model, css, dataTablesBootstrapCss,dat... | (params) {
var self = this;
self.urlBaseVideo = 'videoDirectory/';
self.urlApi = 'Api/';
self.videoSuffix = '.mp4';
self.videoSuffix = '.jpg';
self.isVideoDataLoaded = ko.observable(false);
self.url = {
getVideoList: ... | MimVideoPlaylist | identifier_name |
mim-video-playlist.js | define(['knockout', 'Q', 'model',
'css!mediaelement-css', 'css!dataTables-bootstrap-css', 'css!datatables-scroller-css', 'text!./mim-video-playlist.html',
'datatables', 'knockout.punches', 'mediaelement', 'datatables-bootstrap', 'datatables-scroller'],
function (ko, Q, model, css, dataTablesBootstrapCss,dat... | vmCreate.video = self.urlBaseVideo + options.data.Video + self.videoSuffix;
vmCreate.title = options.data.Title;
return vmCreate;
}
};
self.initModel = function () {
Q(model.post(self.url.getVideoList))
... | random_line_split | |
index.d.ts | import TuiGrid from '../index';
import { RowKey, CellValue, ListItem } from '../store/data';
import { ColumnInfo } from '../store/column';
import { Dictionary } from '../options';
export type CheckboxOptions = ListItemOptions & {
type: 'checkbox' | 'radio';
};
export type PortalEditingKeydown = (ev: KeyboardEvent) ... |
export interface CellEditor {
getElement(): HTMLElement | undefined;
getValue(): CellValue;
mounted?(): void;
beforeDestroy?(): void;
el?: HTMLElement;
}
export interface ListItemOptions {
listItems: ListItem[];
relationListItemMap?: Dictionary<ListItem[]>;
}
export interface CellEditorClass {
new (p... | random_line_split | |
GoogleSignInScreen.tsx | import * as GoogleSignIn from 'expo-google-sign-in';
import React from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import { getGUID } from '../api/guid';
import GoogleSignInButton from '../components/GoogleSignInButton';
GoogleSignIn.allowInClient();
interface State {
user?: {
[key: ... |
render() {
const { user } = this.state;
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{user && <GoogleProfile {...user} />}
<GoogleSignInButton onPress={this._toggleAuth}>{this.buttonTitle}</GoogleSignInButton>
</View>
);
}
_toggleAu... | {
return this.state.user ? 'Sign-Out of Google' : 'Sign-In with Google';
} | identifier_body |
GoogleSignInScreen.tsx | import * as GoogleSignIn from 'expo-google-sign-in';
import React from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import { getGUID } from '../api/guid';
import GoogleSignInButton from '../components/GoogleSignInButton';
GoogleSignIn.allowInClient();
interface State {
user?: {
[key: ... |
_configureAsync = async () => {
try {
await GoogleSignIn.initAsync({
isOfflineEnabled: false,
isPromptEnabled: true,
clientId: `${getGUID()}.apps.googleusercontent.com`,
});
} catch ({ message }) {
console.error('Demo: Error: init: ' + message);
}
this._syncU... | readonly state: State = {};
componentDidMount() {
this._configureAsync();
} | random_line_split |
GoogleSignInScreen.tsx | import * as GoogleSignIn from 'expo-google-sign-in';
import React from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import { getGUID } from '../api/guid';
import GoogleSignInButton from '../components/GoogleSignInButton';
GoogleSignIn.allowInClient();
interface State {
user?: {
[key: ... | () {
this._configureAsync();
}
_configureAsync = async () => {
try {
await GoogleSignIn.initAsync({
isOfflineEnabled: false,
isPromptEnabled: true,
clientId: `${getGUID()}.apps.googleusercontent.com`,
});
} catch ({ message }) {
console.error('Demo: Error: init... | componentDidMount | identifier_name |
GoogleSignInScreen.tsx | import * as GoogleSignIn from 'expo-google-sign-in';
import React from 'react';
import { Image, StyleSheet, Text, View } from 'react-native';
import { getGUID } from '../api/guid';
import GoogleSignInButton from '../components/GoogleSignInButton';
GoogleSignIn.allowInClient();
interface State {
user?: {
[key: ... |
} else {
this.setState({ user: undefined });
}
};
get buttonTitle() {
return this.state.user ? 'Sign-Out of Google' : 'Sign-In with Google';
}
render() {
const { user } = this.state;
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
{u... | {
this.setState({
user: {
...(user.toJSON() as { displayName: string; email: string }),
photoURL: photoURL || user.photoURL!,
},
});
} | conditional_block |
__init__.py | """Support for INSTEON Modems (PLM and Hub)."""
import asyncio
from contextlib import suppress
import logging
from pyinsteon import async_close, async_connect, devices
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_PLATFORM, EVENT_HOMEASSISTANT_STOP
from homeassistant.exce... | workdir=hass.config.config_dir, id_devices=0, load_modem_aldb=0
)
# If options existed in YAML and have not already been saved to the config entry
# add them now
if (
not entry.options
and entry.source == SOURCE_IMPORT
and hass.data.get(DOMAIN)
and hass.data[DOMA... | )
await devices.async_load( | random_line_split |
__init__.py | """Support for INSTEON Modems (PLM and Hub)."""
import asyncio
from contextlib import suppress
import logging
from pyinsteon import async_close, async_connect, devices
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_PLATFORM, EVENT_HOMEASSISTANT_STOP
from homeassistant.exce... | (hass, entry):
"""Set up an Insteon entry."""
if not devices.modem:
try:
await async_connect(**entry.data)
except ConnectionError as exception:
_LOGGER.error("Could not connect to Insteon modem")
raise ConfigEntryNotReady from exception
entry.async_on_un... | async_setup_entry | identifier_name |
__init__.py | """Support for INSTEON Modems (PLM and Hub)."""
import asyncio
from contextlib import suppress
import logging
from pyinsteon import async_close, async_connect, devices
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_PLATFORM, EVENT_HOMEASSISTANT_STOP
from homeassistant.exce... | not entry.options
and entry.source == SOURCE_IMPORT
and hass.data.get(DOMAIN)
and hass.data[DOMAIN].get(OPTIONS)
):
hass.config_entries.async_update_entry(
entry=entry,
options=hass.data[DOMAIN][OPTIONS],
)
for device_override in entry.opt... | """Set up an Insteon entry."""
if not devices.modem:
try:
await async_connect(**entry.data)
except ConnectionError as exception:
_LOGGER.error("Could not connect to Insteon modem")
raise ConfigEntryNotReady from exception
entry.async_on_unload(
hass.... | identifier_body |
__init__.py | """Support for INSTEON Modems (PLM and Hub)."""
import asyncio
from contextlib import suppress
import logging
from pyinsteon import async_close, async_connect, devices
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_PLATFORM, EVENT_HOMEASSISTANT_STOP
from homeassistant.exce... |
for device in entry.options.get(CONF_X10, []):
housecode = device.get(CONF_HOUSECODE)
unitcode = device.get(CONF_UNITCODE)
x10_type = "on_off"
steps = device.get(CONF_DIM_STEPS, 22)
if device.get(CONF_PLATFORM) == "light":
x10_type = "dimmable"
elif devi... | cat = device_override[CONF_CAT]
subcat = device_override[CONF_SUBCAT]
devices.set_id(address, cat, subcat, 0) | conditional_block |
plotIndices.py | import os
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import cm
import atmath
# Define the observable
srcDir = '../runPlasim/postprocessor/indices/'
# SRng = np.array([1260, 1360, 1380, 1400, 1415, 1425, 1430, 1433,
# 1263, 1265, 1270, 1280, 1300, 1330, ... | # figFormat = 'eps'
figFormat = 'png'
dpi = 300
varRng = np.empty((SRng.shape[0],))
skewRng = np.empty((SRng.shape[0],))
kurtRng = np.empty((SRng.shape[0],))
lagMax = 80
#lagMax = daysPerYear * 5
ccfRng = np.empty((SRng.shape[0], lagMax*2+1))
for k in np.arange(SRng.shape[0]):
S = SRng[k]
restartSt... | fs_cbar_label = fs_default | random_line_split |
plotIndices.py | import os
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import cm
import atmath
# Define the observable
srcDir = '../runPlasim/postprocessor/indices/'
# SRng = np.array([1260, 1360, 1380, 1400, 1415, 1425, 1430, 1433,
# 1263, 1265, 1270, 1280, 1300, 1330, ... | nt = ntFull - spinup
observable = observable[spinup:]
seasonal = np.empty((daysPerYear,))
anom = np.empty((nt,))
for day in np.arange(daysPerYear):
seasonal[day] = observable[day::daysPerYear].mean()
anom[day::daysPerYear] = observable[day::daysPerYear] - seasonal[day]
varRng[k]... | S = SRng[k]
restartState = restartStateRng[k]
# Create directories
resDir = '%s_%s/' % (restartState, S)
dstDir = resDir
indicesPath = '%s/%s/' % (srcDir, resDir)
os.system('mkdir stats %s %s/seasonal %s/anom 2> /dev/null' % (dstDir, dstDir, dstDir))
# Read datasets
obsName = '%s_%... | conditional_block |
__init__.py | #
#
# Copyright 2011,2013 Luis Ariel Vega Soliz, Uremix (http://www.uremix.org) and contributors.
#
#
# This file is part of UADH (Uremix App Developer Helper).
#
# UADH is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by | # (at your option) any later version.
#
# UADH is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received... | # the Free Software Foundation, either version 3 of the License, or | random_line_split |
stable3d.py | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
else:
raise AttributeError("You cannot add class attributes to %s" % cls)
return set_class_attr
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
def wrapper(cls):
return metac... | set(cls, name, value) | conditional_block |
stable3d.py | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
return set_instance_attr
def _swig_setattr_nondynamic_class_variable(set):
def set_class_attr(cls, name, value):
if hasattr(cls, name) and not isinstance(getattr(cls, name), property):
set(cls, name, value)
else:
raise AttributeError("You cannot add class attributes to... | if name == "thisown":
self.this.own(value)
elif name == "this":
set(self, name, value)
elif hasattr(self, name) and isinstance(getattr(type(self), name), property):
set(self, name, value)
else:
raise AttributeError("You cannot add instance attribut... | identifier_body |
stable3d.py | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... | else:
raise AttributeError("You cannot add class attributes to %s" % cls)
return set_class_attr
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass"""
def wrapper(cls):
return metacl... | random_line_split | |
stable3d.py | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... | (object):
r"""Proxy of C++ mfem::STable3D class."""
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag")
__repr__ = _swig_repr
def __init__(self, nr):
r"""__init__(STable3D self, int nr) -> STable3D"""
_stable3d.STable3D_swiginit(self, _stab... | STable3D | identifier_name |
controller.js | // Copyright 2017 The Kubernetes Dashboard Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicabl... | {
/**
* @param {!backendApi.ReplicaSetList} replicaSetList
* @param {!angular.Resource} kdReplicaSetListResource
* @ngInject
*/
constructor(replicaSetList, kdReplicaSetListResource) {
/** @export {!backendApi.ReplicaSetList} */
this.replicaSetList = replicaSetList;
/** @export {!angular.Re... | ReplicaSetListController | identifier_name |
controller.js | // Copyright 2017 The Kubernetes Dashboard Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicabl... |
}
| {
/** @export {!backendApi.ReplicaSetList} */
this.replicaSetList = replicaSetList;
/** @export {!angular.Resource} */
this.replicaSetListResource = kdReplicaSetListResource;
} | identifier_body |
controller.js | // Copyright 2017 The Kubernetes Dashboard Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicabl... | * @param {!backendApi.ReplicaSetList} replicaSetList
* @param {!angular.Resource} kdReplicaSetListResource
* @ngInject
*/
constructor(replicaSetList, kdReplicaSetListResource) {
/** @export {!backendApi.ReplicaSetList} */
this.replicaSetList = replicaSetList;
/** @export {!angular.Resource} *... | * @final
*/
export class ReplicaSetListController {
/** | random_line_split |
logical_ast.rs | use query::Occur;
use schema::Field;
use schema::Term;
use schema::Type;
use std::fmt;
use std::ops::Bound;
#[derive(Clone)]
pub enum LogicalLiteral {
Term(Term),
Phrase(Vec<(usize, Term)>),
Range {
field: Field,
value_type: Type,
lower: Bound<Term>,
upper: Bound<Term>,
... |
}
impl From<LogicalLiteral> for LogicalAST {
fn from(literal: LogicalLiteral) -> LogicalAST {
LogicalAST::Leaf(Box::new(literal))
}
}
impl fmt::Debug for LogicalLiteral {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
LogicalLiteral::Te... | {
match *self {
LogicalAST::Clause(ref clause) => {
if clause.is_empty() {
write!(formatter, "<emptyclause>")?;
} else {
let (ref occur, ref subquery) = clause[0];
write!(formatter, "({}{:?}", occur_letter(*o... | identifier_body |
logical_ast.rs | use query::Occur;
use schema::Field;
use schema::Term;
use schema::Type;
use std::fmt;
use std::ops::Bound;
#[derive(Clone)]
pub enum LogicalLiteral {
Term(Term),
Phrase(Vec<(usize, Term)>),
Range {
field: Field,
value_type: Type,
lower: Bound<Term>,
upper: Bound<Term>,
... |
LogicalAST::Leaf(ref literal) => write!(formatter, "{:?}", literal),
}
}
}
impl From<LogicalLiteral> for LogicalAST {
fn from(literal: LogicalLiteral) -> LogicalAST {
LogicalAST::Leaf(Box::new(literal))
}
}
impl fmt::Debug for LogicalLiteral {
fn fmt(&self, formatter: &mut... | {
if clause.is_empty() {
write!(formatter, "<emptyclause>")?;
} else {
let (ref occur, ref subquery) = clause[0];
write!(formatter, "({}{:?}", occur_letter(*occur), subquery)?;
for &(ref occur, ref subquery) ... | conditional_block |
logical_ast.rs | use query::Occur;
use schema::Field;
use schema::Term;
use schema::Type;
use std::fmt;
use std::ops::Bound;
#[derive(Clone)]
pub enum LogicalLiteral {
Term(Term),
Phrase(Vec<(usize, Term)>),
Range {
field: Field,
value_type: Type,
lower: Bound<Term>,
upper: Bound<Term>,
... | Clause(Vec<(Occur, LogicalAST)>),
Leaf(Box<LogicalLiteral>),
}
fn occur_letter(occur: Occur) -> &'static str {
match occur {
Occur::Must => "+",
Occur::MustNot => "-",
Occur::Should => "",
}
}
impl fmt::Debug for LogicalAST {
fn fmt(&self, formatter: &mut fmt::Formatter) ->... | }
#[derive(Clone)]
pub enum LogicalAST { | random_line_split |
logical_ast.rs | use query::Occur;
use schema::Field;
use schema::Term;
use schema::Type;
use std::fmt;
use std::ops::Bound;
#[derive(Clone)]
pub enum | {
Term(Term),
Phrase(Vec<(usize, Term)>),
Range {
field: Field,
value_type: Type,
lower: Bound<Term>,
upper: Bound<Term>,
},
All,
}
#[derive(Clone)]
pub enum LogicalAST {
Clause(Vec<(Occur, LogicalAST)>),
Leaf(Box<LogicalLiteral>),
}
fn occur_letter(occur: ... | LogicalLiteral | identifier_name |
memprof.py | x),2(a,1x),2(i0,1x))')&
# trim(vname), trim(act), addr, isize, trim(basename(file)), trim(func), line, memtot_abi%memory
return super(cls, Entry).__new__(cls,
vname=args[0],
action=args[1],
ptr=int(args[2]),
size=int(args[3]),
file=args[4],
func=args... |
return peaks
@catchall
def plot_memory_usage(self, show=True):
memory = [e.tot_memory for e in self.yield_all_entries()]
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot(memory)
if show: plt.show()
return fi... | print(peak) | conditional_block |
memprof.py | x),2(a,1x),2(i0,1x))')&
# trim(vname), trim(act), addr, isize, trim(basename(file)), trim(func), line, memtot_abi%memory
return super(cls, Entry).__new__(cls,
vname=args[0],
action=args[1],
ptr=int(args[2]),
size=int(args[3]),
file=args[4],
func=args... | (self):
with open(self.path, "rt") as fh:
for lineno, line in enumerate(fh):
if lineno == 0: continue
yield Entry.from_line(line, lineno)
@catchall
def find_peaks(self, maxlen=20):
# the deque is bounded to the specified maximum length. Once a bounded... | yield_all_entries | identifier_name |
memprof.py | 1x),2(a,1x),2(i0,1x))')&
# trim(vname), trim(act), addr, isize, trim(basename(file)), trim(func), line, memtot_abi%memory
return super(cls, Entry).__new__(cls,
vname=args[0],
action=args[1],
ptr=int(args[2]),
size=int(args[3]),
file=args[4],
func=arg... | # when new items are added, a corresponding number of items are discarded from the opposite end.
peaks = deque(maxlen=maxlen)
for e in self.yield_all_entries():
size = e.size
if size == 0 or not e.isalloc: continue
if len(peaks) == 0:
peaks.a... | yield Entry.from_line(line, lineno)
@catchall
def find_peaks(self, maxlen=20):
# the deque is bounded to the specified maximum length. Once a bounded length deque is full, | random_line_split |
memprof.py | 1x),2(a,1x),2(i0,1x))')&
# trim(vname), trim(act), addr, isize, trim(basename(file)), trim(func), line, memtot_abi%memory
return super(cls, Entry).__new__(cls,
vname=args[0],
action=args[1],
ptr=int(args[2]),
size=int(args[3]),
file=args[4],
func=arg... | if lineno == 0: continue
e = Entry.from_line(line, lineno)
if not e.isalloc: continue
if 0 < e.size <= nbytes: smalles.append(e)
pprint(smalles)
return smalles
@catchall
def find_intensive(self, threshold=2000):
d = {}
... | def __init__(self, path):
self.path = path
#def __str__(self):
# lines = []
# app = lines.append
# return "\n".join(lines)
@catchall
def summarize(self):
with open(self.path, "rt") as fh:
l = fh.read()
print(l)
@catchall
def find_small_... | identifier_body |
run_extract_epochs.py | # Author: Denis A. Engemann <denis.engemann@gmail.com>
# License: BSD (3-clause)
import mkl
import sys
import os.path as op
import numpy as np
import mne
from mne.io import Raw
from mne.preprocessing import read_ica
from mne.viz import plot_drop_log
from meeg_preprocessing.utils import setup_provenance, set_eog_ecg_c... | 1.*(epochs._data[:, ch, :] < 8192))
# evoked before mask subtraction
evoked = epochs.average()
fig = evoked.plot(show=False)
report.add_figs_to_section(fig, '%s (%s): butterfly' % (subject, name),
'Butterfly: ' + name)
... | % (subject, name), 'Drop: ' + name)
# trigger channel
ch = mne.pick_channels(epochs.ch_names, ['STI101'])
epochs._data[:, ch, :] = (2.*(epochs._data[:, ch, :] > 1) + | random_line_split |
run_extract_epochs.py | # Author: Denis A. Engemann <denis.engemann@gmail.com>
# License: BSD (3-clause)
import mkl
import sys
import os.path as op
import numpy as np
import mne
from mne.io import Raw
from mne.preprocessing import read_ica
from mne.viz import plot_drop_log
from meeg_preprocessing.utils import setup_provenance, set_eog_ecg_c... |
fig = evoked.plot_topomap(times, ch_type=ch_type, show=False)
report.add_figs_to_section(
fig, '%s (%s): UNMASKED: topo %s' % (subject, name, ch_type),
'Topo: ' + name)
report.save(open_browser=open_browser)
| ch_type = 'mag' | conditional_block |
translations.js | var translations = {
'Mostri spaziali': {
en: 'Space monsters',
},
'Dettagli': {
en: 'Details',
},
'Testa': {
en: 'Head', | 'Occhi': {
en: 'Eyes',
},
'Naso': {
en: 'Nose',
},
'Bocca': {
en: 'Mouth',
},
'Orecchie': {
en: 'Ears',
},
'Fantasmatico': {
en: 'InHideum',
},
'Allegro': {
en: 'Happy',
},
'Orribile': {
en: 'Franken',
},
... | }, | random_line_split |
deferred.rs |
use std::ops;
use std::str;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Deferred<T> {
StaticStr(&'static str),
Actual(T),
}
impl<T> Deferred<T> where T: From<&'static str> {
pub(crate) fn into_actual(self) -> T |
pub(crate) fn actual(&mut self) -> &mut T {
if let Deferred::StaticStr(value) = *self {
*self = Deferred::Actual(value.into());
}
match *self {
Deferred::StaticStr(_) => panic!("unexpected static storage"),
Deferred::Actual(ref mut value) => value,
... | {
match self {
Deferred::StaticStr(value) => value.into(),
Deferred::Actual(value) => value,
}
} | identifier_body |
deferred.rs | use std::ops;
use std::str;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Deferred<T> {
StaticStr(&'static str), | }
impl<T> Deferred<T> where T: From<&'static str> {
pub(crate) fn into_actual(self) -> T {
match self {
Deferred::StaticStr(value) => value.into(),
Deferred::Actual(value) => value,
}
}
pub(crate) fn actual(&mut self) -> &mut T {
if let Deferred::StaticStr(... | Actual(T), | random_line_split |
deferred.rs |
use std::ops;
use std::str;
use std::fmt;
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Deferred<T> {
StaticStr(&'static str),
Actual(T),
}
impl<T> Deferred<T> where T: From<&'static str> {
pub(crate) fn into_actual(self) -> T {
match self {
Deferred::StaticStr(value) => val... | (&mut self) -> &mut T {
if let Deferred::StaticStr(value) = *self {
*self = Deferred::Actual(value.into());
}
match *self {
Deferred::StaticStr(_) => panic!("unexpected static storage"),
Deferred::Actual(ref mut value) => value,
}
}
}
impl<T> fmt:... | actual | identifier_name |
embed.service.ts | import { Injectable } from '@angular/core';
import {
ShareService,
ShareEmbedCreateRequest,
OutputAccess,
ShareContent,
Content,
BusinessProcessService,
} from '@picturepark/sdk-v1-angular';
@Injectable({
providedIn: 'root',
})
export class EmbedService {
constructor(private shareService: ShareService,... | const contentItems = selectedItems.map(
(i) =>
new ShareContent({
contentId: i.id,
outputFormatIds: ['Original'],
})
);
try {
const result = await this.shareService
.create(
new ShareEmbedCreateRequest({
n... |
async embed(selectedItems: Content[], postUrl: string) {
if (selectedItems.length > 0) { | random_line_split |
embed.service.ts | import { Injectable } from '@angular/core';
import {
ShareService,
ShareEmbedCreateRequest,
OutputAccess,
ShareContent,
Content,
BusinessProcessService,
} from '@picturepark/sdk-v1-angular';
@Injectable({
providedIn: 'root',
})
export class EmbedService {
constructor(private shareService: ShareService,... | if (result) {
await this.businessProcessService.waitForCompletion(result.id, '02:00:00', true).toPromise();
const share = await this.shareService.get(result.referenceId!, null, null).toPromise();
const postMessage = JSON.stringify(share);
if (window.opener) {
... | {
const contentItems = selectedItems.map(
(i) =>
new ShareContent({
contentId: i.id,
outputFormatIds: ['Original'],
})
);
try {
const result = await this.shareService
.create(
new ShareEmbedCreateRequest({
... | conditional_block |
embed.service.ts | import { Injectable } from '@angular/core';
import {
ShareService,
ShareEmbedCreateRequest,
OutputAccess,
ShareContent,
Content,
BusinessProcessService,
} from '@picturepark/sdk-v1-angular';
@Injectable({
providedIn: 'root',
})
export class EmbedService {
constructor(private shareService: ShareService,... | (selectedItems: Content[], postUrl: string) {
if (selectedItems.length > 0) {
const contentItems = selectedItems.map(
(i) =>
new ShareContent({
contentId: i.id,
outputFormatIds: ['Original'],
})
);
try {
const result = await this.shareSe... | embed | identifier_name |
implementations.rs | //! Implementations of `Header` and `ToHeader` for various types.
use std::str;
use std::fmt;
use super::{Header, ToHeader};
impl ToHeader for usize {
fn parse(raw: &[u8]) -> Option<usize> {
str::from_utf8(raw).ok().and_then(|s| s.parse().ok())
}
}
impl Header for usize {
fn fmt(&self, f: &mut f... | }
} | bad::<usize>(b"1234567890123467901245790");
bad::<usize>(b"1,000"); | random_line_split |
implementations.rs | //! Implementations of `Header` and `ToHeader` for various types.
use std::str;
use std::fmt;
use super::{Header, ToHeader};
impl ToHeader for usize {
fn parse(raw: &[u8]) -> Option<usize> |
}
impl Header for usize {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", *self)
}
}
#[cfg(test)]
mod tests {
use std::fmt;
use headers::{Header, ToHeader, HeaderDisplayAdapter};
fn eq<H: Header + ToHeader + Eq + fmt::Debug>(raw: &[u8], typed: H) {
assert_e... | {
str::from_utf8(raw).ok().and_then(|s| s.parse().ok())
} | identifier_body |
implementations.rs | //! Implementations of `Header` and `ToHeader` for various types.
use std::str;
use std::fmt;
use super::{Header, ToHeader};
impl ToHeader for usize {
fn parse(raw: &[u8]) -> Option<usize> {
str::from_utf8(raw).ok().and_then(|s| s.parse().ok())
}
}
impl Header for usize {
fn fmt(&self, f: &mut f... | () {
eq(b"0", 0usize);
eq(b"1", 1usize);
eq(b"123456789", 123456789usize);
bad::<usize>(b"-1");
bad::<usize>(b"0xdeadbeef");
bad::<usize>(b"deadbeef");
bad::<usize>(b"1234567890123467901245790");
bad::<usize>(b"1,000");
}
}
| test_usize | identifier_name |
models.py | from django.db import models
from django.contrib.auth.models import User | from django.contrib.localflavor.us.us_states import STATE_CHOICES
# https://docs.djangoproject.com/en/1.3/ref/contrib/localflavor/#united-states-of-america-us
# TODO: django scheduler
# TODO: confirm what's in User model
# User model?
# first name
# last name
# auth_mode (custom, facebook, tumblr?)
class Profile(m... | from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django_countries import CountryField
from django.contrib.localflavor.us.models import * | random_line_split |
models.py | from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django_countries import CountryField
from django.contrib.localflavor.us.models import *
from django.contrib.localflavor.us.us_states im... |
class Category(models.Model):
"""
Moderated set of categories for events
"""
name = models.CharField(max_length=60, unique=True)
def __unicode__(self):
return self.name
class Tag(models.Model):
"""
Moderated set of subcats for events
"""
name = models.CharField(max_len... | if self.email:
return self.email
if self.phone:
return self.phone
if self.web:
return self.web
return '<Contact at 0x%x>' % (id(self)) | identifier_body |
models.py | from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django_countries import CountryField
from django.contrib.localflavor.us.models import *
from django.contrib.localflavor.us.us_states im... |
if self.phone:
return self.phone
if self.web:
return self.web
return '<Contact at 0x%x>' % (id(self))
class Category(models.Model):
"""
Moderated set of categories for events
"""
name = models.CharField(max_length=60, unique=True)
def __unicode__(... | return self.email | conditional_block |
models.py | from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django_countries import CountryField
from django.contrib.localflavor.us.models import *
from django.contrib.localflavor.us.us_states im... | (self):
return self.date.isoformat()
class Meta:
ordering = ['date']
class Contact(models.Model):
"""
Contact info for projects and events
"""
first_name = models.CharField(max_length=40, blank=True, null=True)
last_name = models.CharField(max_length=40, blank=True, null=... | __unicode__ | identifier_name |
navleft.js | /*分页JS*/
var rsss = false;
$(function () {
$(".leftNav_side").css("min-height", $(".leftNav_side").height());
$(window).resize(function () {
$(".leftNav_side").height($(window).height());
}).trigger("resize");//左侧菜单高度自适应,但是保留内容最小高度
//切换左导航一级菜单
$(".Nav_lvl dt").click(function () {
... | $("#pagerForm").submit();
});
$(".pager").find("a.prev").click(function(){
num = Number($("[name='currentPage']").val()) - 1 < 0 ? 0 :Number($("[name='currentPage']").val()) - 1;
$("[name='currentPage']").val(num);
$("#pagerForm").submit();
});
$(".pager").find("a.next... | });
$(".pager").find("a.first").click(function(){
num = 1;
$("[name='currentPage']").val(num);
| random_line_split |
navleft.js | /*分页JS*/
var rsss = false;
$(function () {
$(".leftNav_side").css("min-height", $(".leftNav_side").height());
$(window).resize(function () {
$(".leftNav_side").height($(window).height());
}).trigger("resize");//左侧菜单高度自适应,但是保留内容最小高度
//切换左导航一级菜单
$(".Nav_lvl dt").click(function () {
... | f="#">尾页</a>';
}
else {
pages[pages.length] = '<span>下一页</span><span>尾页</span>';
}
pages[pages.length] = '<input type="text" name="page" value="'+currentPage+'"/>';
pages[pages.length] = '<input type="button" value="跳转" class="btn_violet" />';
$(".pager").html(pages.join("")).... | e
pages[pages.length] = '<a href="#">' + i + '</a>';
}
}
if (currentPage < totalPage) {
pages[pages.length] = '<a class="next" href="#">下一页</a><a class="last" hre | conditional_block |
thread.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
handle: Handle
}
impl Thread {
pub unsafe fn new<'a>(stack: usize, p: Box<FnBox() + 'a>)
-> io::Result<Thread> {
let p = box p;
// FIXME On UNIX, we guard against stack sizes that are too small but
// that's because pthreads enforces that stacks are at leas... | Thread | identifier_name |
thread.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | 0
}
}
pub fn set_name(_name: &str) {
// Windows threads are nameless
// The names in MSVC debugger are obtained using a "magic" exception,
// which requires a use of MS C++ extensions.
// See https://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
}
p... | unsafe { start_thread(main); } | random_line_split |
thread.rs | // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | else {
mem::forget(p); // ownership passed to CreateThread
Ok(Thread { handle: Handle::new(ret) })
};
#[no_stack_check]
extern "system" fn thread_start(main: *mut libc::c_void) -> DWORD {
unsafe { start_thread(main); }
0
}
}
pub ... | {
Err(io::Error::last_os_error())
} | conditional_block |
resources.py | from tastypie import fields
from tastypie.bundle import Bundle
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from api.authorization import DateaBaseAuthorization
from api.authentication import ApiKeyPlusWebAuthentication
from api.base_resources import JSONDefaultMixin
from api.serializers import... |
return super(CommentResource, self).apply_sorting(obj_list, options)
class Meta:
queryset = Comment.objects.all()
resource_name = 'comment'
allowed_methods = ['get', 'post', 'patch', 'delete']
serializer = UTCSerializer(formats=['json'])
filtering={
... | options['order_by'] = 'created' | conditional_block |
resources.py | from tastypie import fields
from tastypie.bundle import Bundle
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from api.authorization import DateaBaseAuthorization
from api.authentication import ApiKeyPlusWebAuthentication
from api.base_resources import JSONDefaultMixin
from api.serializers import... | ():
return CommentResource
| get_comment_resource_class | identifier_name |
resources.py | from tastypie import fields
from tastypie.bundle import Bundle
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from api.authorization import DateaBaseAuthorization
from api.authentication import ApiKeyPlusWebAuthentication
from api.base_resources import JSONDefaultMixin
from api.serializers import... | orig_obj = Comment.objects.get(pk=int(bundle.data['id']))
for f in fields:
if f in request.data:
request.data[f] = getattr(orig_obj, f)
elif bundle.request.method == 'POST':
# enforce post user
bundle.obj.user = bun... | user = fields.ToOneField('account.resources.UserResource',
attribute='user', full=True, readonly=True)
def dehydrate(self, bundle):
user_data = {
'username': bundle.data['user'].data['username'],
'image_small': bundle.data['user'].data['im... | identifier_body |
resources.py | from tastypie import fields | from api.authentication import ApiKeyPlusWebAuthentication
from api.base_resources import JSONDefaultMixin
from api.serializers import UTCSerializer
from django.template.defaultfilters import linebreaksbr
from tastypie.cache import SimpleCache
from tastypie.throttle import CacheThrottle
from django.contrib.contenttypes... | from tastypie.bundle import Bundle
from tastypie.resources import ModelResource, ALL, ALL_WITH_RELATIONS
from api.authorization import DateaBaseAuthorization | random_line_split |
ez_setup.py | setuptools.
"""
import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlib
from distutils import log
try:
# noinspection PyCompatibility
from urllib.request import urlopen
except ImportError:
# noinspection PyCompa... | (cmd, target):
"""
Run the command to download target. If the command fails, clean up before
re-raising the error.
"""
try:
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
if os.access(target, os.F_OK):
os.unlink(target)
raise
def download_f... | _clean_check | identifier_name |
ez_setup.py | .warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2
def _build_egg(egg, archive_filename, to_dir):
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools... | version=options.version,
download_base=options.download_base,
downloader_factory=options.downloader_factory, | random_line_split | |
ez_setup.py | setuptools.
"""
import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlib
from distutils import log
try:
# noinspection PyCompatibility
from urllib.request import urlopen
except ImportError:
# noinspection PyCompa... |
def _build_egg(egg, archive_filename, to_dir):
with archive_context(archive_filename):
# building an egg
log.warn('Building a Setuptools egg in %s', to_dir)
_python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir)
# returning the result
log.warn(egg)
if not os.path.exi... | log.warn('Something went wrong during the installation.')
log.warn('See the error message above.')
# exitcode will be 2
return 2 | conditional_block |
ez_setup.py | setuptools.
"""
import os
import shutil
import sys
import tempfile
import zipfile
import optparse
import subprocess
import platform
import textwrap
import contextlib
from distutils import log
try:
# noinspection PyCompatibility
from urllib.request import urlopen
except ImportError:
# noinspection PyCompa... |
def _parse_args():
"""
Parse the command line for options
"""
parser = optparse.OptionParser()
parser.add_option(
'--user | """
Build the arguments to 'python setup.py install' on the setuptools package
"""
return ['--user'] if options.user_install else [] | identifier_body |
change_set.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::ledger_counters::LedgerCounterBumps;
use diem_types::transaction::Version;
use schemadb::SchemaBatch;
use std::collections::HashMap;
/// Structure that collects changes to be made to the DB in one transaction.
///
/// To be ... | pub(crate) struct SealedChangeSet {
/// A batch of db alternations.
pub batch: SchemaBatch,
} | /// This is a wrapper type just to make sure `ChangeSet` to be committed is sealed properly. | random_line_split |
change_set.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::ledger_counters::LedgerCounterBumps;
use diem_types::transaction::Version;
use schemadb::SchemaBatch;
use std::collections::HashMap;
/// Structure that collects changes to be made to the DB in one transaction.
///
/// To be ... | {
/// A batch of db alternations.
pub batch: SchemaBatch,
}
| SealedChangeSet | identifier_name |
change_set.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::ledger_counters::LedgerCounterBumps;
use diem_types::transaction::Version;
use schemadb::SchemaBatch;
use std::collections::HashMap;
/// Structure that collects changes to be made to the DB in one transaction.
///
/// To be ... |
pub fn counter_bumps(&mut self, version: Version) -> &mut LedgerCounterBumps {
self.counter_bumps
.entry(version)
.or_insert_with(LedgerCounterBumps::new)
}
#[cfg(test)]
pub fn new_with_bumps(counter_bumps: HashMap<Version, LedgerCounterBumps>) -> Self {
Self {... | {
Self {
batch: SchemaBatch::new(),
counter_bumps: HashMap::new(),
}
} | identifier_body |
enums.py | """
Enums.
"""
try:
from enum import Enum
except ImportError:
Enum = object
class MailTypes(Enum):
|
class DependencyTypes(Enum):
"""
DependencyTypes enum
"""
# This job can begin execution after the specified jobs have begun
# execution.
# SUPPORT: Slurm
AFTER = 0
# This job can begin execution after the specified jobs have terminated.
# SUPPORT: Slurm, PBS
AFTER_ANY = 1
... | """
MailTypes enum
"""
ALL = 0
BEGIN = 1
END = 2
FAIL = 3
REQUEUE = 4 | identifier_body |
enums.py | """
Enums.
"""
try:
from enum import Enum
except ImportError:
Enum = object
class | (Enum):
"""
MailTypes enum
"""
ALL = 0
BEGIN = 1
END = 2
FAIL = 3
REQUEUE = 4
class DependencyTypes(Enum):
"""
DependencyTypes enum
"""
# This job can begin execution after the specified jobs have begun
# execution.
# SUPPORT: Slurm
AFTER = 0
# This jo... | MailTypes | identifier_name |
enums.py | """
Enums.
""" |
try:
from enum import Enum
except ImportError:
Enum = object
class MailTypes(Enum):
"""
MailTypes enum
"""
ALL = 0
BEGIN = 1
END = 2
FAIL = 3
REQUEUE = 4
class DependencyTypes(Enum):
"""
DependencyTypes enum
"""
# This job can begin execution after the speci... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.