file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
day_6.rs | use std::borrow::Cow;
use std::iter::Peekable;
use std::num::ParseFloatError;
use std::str::Chars;
pub fn calculate<'s>(src: Cow<'s, str>) -> Result<f64, ParseFloatError> |
fn parse_expression(iter: &mut Peekable<Chars>) -> Result<f64, ParseFloatError> {
let mut ret = parse_term(iter.by_ref());
loop {
match iter.peek().cloned() {
Some('+') => {
iter.next();
ret = ret.and_then(|ret| parse_term(iter.by_ref()).map(|num| ret + num)... | {
let mut iter = src.chars().peekable();
parse_expression(&mut iter)
} | identifier_body |
test_collection_times.py | from concurrency.get_websites import get_number_of_links
import time
# Run get_number_of_links and compare it to a serial version
# stub out load_url with a sleep function so the time is always the same
# Show that the concurrent version takes less time than the serial
import unittest
from unittest.mock import patch... | unittest.main() | conditional_block | |
test_collection_times.py | from concurrency.get_websites import get_number_of_links
import time
# Run get_number_of_links and compare it to a serial version
# stub out load_url with a sleep function so the time is always the same
# Show that the concurrent version takes less time than the serial
import unittest
from unittest.mock import patch... | (unittest.TestCase):
def setUp(self):
self.loadtime = 1
self.fake_urls = ['url1','url2', 'url3']
@patch('concurrency.get_websites.BeautifulSoup')
@patch('concurrency.get_websites.load_url')
def test_concurrent_slower_than_serial(self, mock_load_url, bs_mock):
""" Time the colle... | TestConcurrency | identifier_name |
test_collection_times.py | from concurrency.get_websites import get_number_of_links
import time
# Run get_number_of_links and compare it to a serial version
# stub out load_url with a sleep function so the time is always the same
# Show that the concurrent version takes less time than the serial
import unittest
from unittest.mock import patch... | self.loadtime = 1
self.fake_urls = ['url1','url2', 'url3']
@patch('concurrency.get_websites.BeautifulSoup')
@patch('concurrency.get_websites.load_url')
def test_concurrent_slower_than_serial(self, mock_load_url, bs_mock):
""" Time the collection of data from websites """
bs_... | random_line_split | |
test_collection_times.py | from concurrency.get_websites import get_number_of_links
import time
# Run get_number_of_links and compare it to a serial version
# stub out load_url with a sleep function so the time is always the same
# Show that the concurrent version takes less time than the serial
import unittest
from unittest.mock import patch... |
if __name__ == "__main__":
unittest.main() | def setUp(self):
self.loadtime = 1
self.fake_urls = ['url1','url2', 'url3']
@patch('concurrency.get_websites.BeautifulSoup')
@patch('concurrency.get_websites.load_url')
def test_concurrent_slower_than_serial(self, mock_load_url, bs_mock):
""" Time the collection of data from website... | identifier_body |
util.py | import subprocess
import os
import errno
def | (url, local_fname=None, force_write=False):
# requests is not default installed
import requests
if local_fname is None:
local_fname = url.split('/')[-1]
if not force_write and os.path.exists(local_fname):
return local_fname
dir_name = os.path.dirname(local_fname)
if dir_name != "":
if not os.p... | download_file | identifier_name |
util.py | import subprocess
import os
import errno
def download_file(url, local_fname=None, force_write=False):
# requests is not default installed
import requests
if local_fname is None:
local_fname = url.split('/')[-1]
if not force_write and os.path.exists(local_fname):
return local_fname
dir_name = os.pat... | """
return a list of GPUs
"""
try:
re = subprocess.check_output(["nvidia-smi", "-L"], universal_newlines=True)
except OSError:
return []
return range(len([i for i in re.split('\n') if 'GPU' in i])) | identifier_body | |
util.py | import subprocess
import os
import errno
def download_file(url, local_fname=None, force_write=False):
# requests is not default installed
import requests
if local_fname is None:
local_fname = url.split('/')[-1]
if not force_write and os.path.exists(local_fname):
return local_fname
dir_name = os.pat... |
r = requests.get(url, stream=True)
assert r.status_code == 200, "failed to open %s" % url
with open(local_fname, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
return local_fname
def get_gpus():
"""
return a list o... | raise | conditional_block |
util.py | import subprocess
import os
import errno
def download_file(url, local_fname=None, force_write=False):
# requests is not default installed
import requests
if local_fname is None:
local_fname = url.split('/')[-1]
if not force_write and os.path.exists(local_fname):
return local_fname
dir_name = os.pat... | if not os.path.exists(dir_name):
try: # try to create the directory if it doesn't exists
os.makedirs(dir_name)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
r = requests.get(url, stream=True)
assert r.status_code == 200, "failed to open %s" % url
with open(... | random_line_split | |
pi.py | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import... |
def output(d):
# Use write() to avoid spaces between the digits
# Use str() to avoid the 'L'
sys.stdout.write(str(d))
# Flush so the output is seen immediately
sys.stdout.flush()
if __name__ == "__main__":
main()
| output(d)
a, a1 = 10L*(a%b), 10L*(a1%b1)
d, d1 = a//b, a1//b1 | conditional_block |
pi.py | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import... | def main():
k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
while 1:
# Next approximation
p, q, k = k*k, 2L*k+1L, k+1L
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a//b, a1//b1
while d == d1:
output(d)
a, a1 = 10L*(a%b), 10... | random_line_split | |
pi.py | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import... |
def output(d):
# Use write() to avoid spaces between the digits
# Use str() to avoid the 'L'
sys.stdout.write(str(d))
# Flush so the output is seen immediately
sys.stdout.flush()
if __name__ == "__main__":
main()
| k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
while 1:
# Next approximation
p, q, k = k*k, 2L*k+1L, k+1L
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a//b, a1//b1
while d == d1:
output(d)
a, a1 = 10L*(a%b), 10L*(a1%b1)
... | identifier_body |
pi.py | #! /usr/bin/env python
# Print digits of pi forever.
#
# The algorithm, using Python's 'long' integers ("bignums"), works
# with continued fractions, and was conceived by Lambert Meertens.
#
# See also the ABC Programmer's Handbook, by Geurts, Meertens & Pemberton,
# published by Prentice-Hall (UK) Ltd., 1990.
import... | ():
k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
while 1:
# Next approximation
p, q, k = k*k, 2L*k+1L, k+1L
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d, d1 = a//b, a1//b1
while d == d1:
output(d)
a, a1 = 10L*(a%b), 10L*(a1%b1... | main | identifier_name |
common.rs | //! This module contains various infrastructure that is common across all assembler backends
use proc_macro2::{Span, TokenTree};
use quote::ToTokens;
use quote::quote;
use syn::spanned::Spanned;
use syn::parse;
use syn::Token;
use crate::parse_helpers::{ParseOpt, eat_pseudo_keyword};
use crate::serialize;
/// Enum re... | (value: u16) -> Stmt {
Stmt::Const(u64::from(value), Size::WORD)
}
pub fn u32(value: u32) -> Stmt {
Stmt::Const(u64::from(value), Size::DWORD)
}
pub fn u64(value: u64) -> Stmt {
Stmt::Const(value, Size::QWORD)
}
}
// Makes a None-delimited TokenTree item out of anything t... | u16 | identifier_name |
common.rs | //! This module contains various infrastructure that is common across all assembler backends
use proc_macro2::{Span, TokenTree};
use quote::ToTokens;
use quote::quote;
use syn::spanned::Spanned;
use syn::parse;
use syn::Token;
use crate::parse_helpers::{ParseOpt, eat_pseudo_keyword};
use crate::serialize;
/// Enum re... | }
}
/**
* Jump types
*/
#[derive(Debug, Clone)]
pub struct Jump {
pub kind: JumpKind,
pub offset: Option<syn::Expr>
}
#[derive(Debug, Clone)]
pub enum JumpKind {
// note: these symbol choices try to avoid stuff that is a valid starting symbol for parse_expr
// in order to allow the full range o... | Size::QWORD => "i64",
Size::PWORD => "i80",
Size::OWORD => "i128",
Size::HWORD => "i256"
}, Span::mixed_site()) | random_line_split |
sha.ts | import { sha_variant_error } from "./common";
import {
CSHAKEOptionsEncodingType,
CSHAKEOptionsNoEncodingType,
SHAKEOptionsEncodingType,
SHAKEOptionsNoEncodingType,
EncodingType,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
KMACOptionsNoEncodingType,
KMACOption... | else {
throw new Error(sha_variant_error);
}
}
/**
* Takes `input` and hashes as many blocks as possible. Stores the rest for either a future `update` or `getHash` call.
*
* @param input The input to be hashed
*/
update(input: string | ArrayBuffer | Uint8Array): void {
this.shaObj.upda... | {
this.shaObj = new jsSHA3(variant, inputFormat, options);
} | conditional_block |
sha.ts | import { sha_variant_error } from "./common";
import {
CSHAKEOptionsEncodingType,
CSHAKEOptionsNoEncodingType,
SHAKEOptionsEncodingType,
SHAKEOptionsNoEncodingType,
EncodingType,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
KMACOptionsNoEncodingType,
KMACOption... | (format: any, options?: any): any {
return this.shaObj.getHMAC(format, options);
}
}
| getHMAC | identifier_name |
sha.ts | import { sha_variant_error } from "./common";
import {
CSHAKEOptionsEncodingType,
CSHAKEOptionsNoEncodingType,
SHAKEOptionsEncodingType,
SHAKEOptionsNoEncodingType,
EncodingType,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
KMACOptionsNoEncodingType,
KMACOption... |
/**
* Returns the the HMAC in the specified format using the key given by a previous `setHMACKey` call. Now deprecated
* in favor of just calling `getHash`.
*
* @param format The desired output formatting (B64, HEX, BYTES, ARRAYBUFFER, or UINT8ARRAY) as a string.
* @param options Options in the form ... | {
this.shaObj.setHMACKey(key, inputFormat, options);
} | identifier_body |
sha.ts | import { sha_variant_error } from "./common";
import {
CSHAKEOptionsEncodingType,
CSHAKEOptionsNoEncodingType,
SHAKEOptionsEncodingType,
SHAKEOptionsNoEncodingType,
EncodingType,
FixedLengthOptionsEncodingType,
FixedLengthOptionsNoEncodingType,
FormatNoTextType,
KMACOptionsNoEncodingType,
KMACOption... | * {value: <INPUT>, format: <FORMAT>, encoding?: "UTF8" | "UTF16BE" | "UTF16LE"} where <FORMAT> takes the same
* values as `inputFormat` and <INPUT> can be a `string | ArrayBuffer | Uint8Array` depending on <FORMAT>.
* Supplying this key switches to HMAC calculation and replaces the now deprecated c... | * or UINT8ARRAY) as a string.
* @param options Options in the form of { encoding?: "UTF8" | "UTF16BE" | "UTF16LE"; numRounds?: number }.
* `encoding` is for only TEXT input (defaults to UTF8) and `numRounds` defaults to 1.
* `numRounds` is not valid for any of the MAC or CSHAKE variants.
* * If t... | random_line_split |
react-user-tour-tests.tsx | // Tests for type definitions for react-user-tour
// Project: https://github.com/socialtables/react-user-tour
// Definitions by: Carlo Cancellieri <https://github.com/ccancellieri>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types='react-dom' />
import * as React from 'react';
im... | (p:any){
super(p);
this.setState({
isTourActive:true,
tourStep:1
});
}
render() {
const Tour = <ReactUserTour active={this.state.isTourActive}
step={this.state.tourStep}
onNext={(step:number) => this.setState({tourStep: step, isT... | constructor | identifier_name |
react-user-tour-tests.tsx | // Tests for type definitions for react-user-tour
// Project: https://github.com/socialtables/react-user-tour
// Definitions by: Carlo Cancellieri <https://github.com/ccancellieri>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types='react-dom' />
import * as React from 'react';
im... |
render() {
const Tour = <ReactUserTour active={this.state.isTourActive}
step={this.state.tourStep}
onNext={(step:number) => this.setState({tourStep: step, isTourActive: true})}
onBack={(step:number) => this.setState({tourStep: step, isTourActive: true})}
on... | {
super(p);
this.setState({
isTourActive:true,
tourStep:1
});
} | identifier_body |
react-user-tour-tests.tsx | // Tests for type definitions for react-user-tour
// Project: https://github.com/socialtables/react-user-tour
// Definitions by: Carlo Cancellieri <https://github.com/ccancellieri>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types='react-dom' />
import * as React from 'react';
im... | onBack={(step:number) => this.setState({tourStep: step, isTourActive: true})}
onCancel={() => this.setState({tourStep: this.state.tourStep, isTourActive: false})}
steps={[
{
step: 1,
selector: '.MyClass',
tit... | step={this.state.tourStep}
onNext={(step:number) => this.setState({tourStep: step, isTourActive: true})} | random_line_split |
vector.rs | /*
* Copyright 2018 Google Inc. 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 applica... | <'a, T: 'a>(&'a [u8], usize, PhantomData<T>);
impl<'a, T: 'a> Vector<'a, T> {
#[inline(always)]
pub fn new(buf: &'a [u8], loc: usize) -> Self {
Vector {
0: buf,
1: loc,
2: PhantomData,
}
}
#[inline(always)]
pub fn len(&self) -> usize {
re... | Vector | identifier_name |
vector.rs | /*
* Copyright 2018 Google Inc. 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 applica... |
impl<'a> Follow<'a> for &'a str {
type Inner = &'a str;
fn follow(buf: &'a [u8], loc: usize) -> Self::Inner {
let len = read_scalar::<UOffsetT>(&buf[loc..loc + SIZE_UOFFSET]) as usize;
let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len];
let s = unsafe { from_utf8_unchecked(... | {
let sz = size_of::<T>();
let buf = &buf[loc..loc + sz];
let ptr = buf.as_ptr() as *const T;
unsafe { &*ptr }
} | identifier_body |
vector.rs | /*
* Copyright 2018 Google Inc. 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 applica... | use primitives::*;
#[derive(Debug)]
pub struct Vector<'a, T: 'a>(&'a [u8], usize, PhantomData<T>);
impl<'a, T: 'a> Vector<'a, T> {
#[inline(always)]
pub fn new(buf: &'a [u8], loc: usize) -> Self {
Vector {
0: buf,
1: loc,
2: PhantomData,
}
}
#[inlin... |
use endian_scalar::{EndianScalar, read_scalar};
use follow::Follow; | random_line_split |
fakepuppy.py | #!/usr/bin/python
import sys
import getopt
import time
import os
| DATA_DIR='/local/devel/guppy/testing/'
opts, args = getopt.getopt(sys.argv[1:], 'c:t')
transfer = False
listdir = False
for opt, optarg in opts:
if opt == '-c':
if optarg == 'get' or optarg == 'put':
transfer = True
if optarg == 'dir':
listdir = True
if optarg == 'cancel':
os.system("pkill -f 'fakepu... | random_line_split | |
fakepuppy.py | #!/usr/bin/python
import sys
import getopt
import time
import os
DATA_DIR='/local/devel/guppy/testing/'
opts, args = getopt.getopt(sys.argv[1:], 'c:t')
transfer = False
listdir = False
for opt, optarg in opts:
|
if transfer:
inc = 10
percent = 0.0
for i in xrange(100/inc):
percent = percent + inc
print >> sys.stderr, "\r%6.2f%%, %5.2f Mbits/s, %02d:%02d:%02d elapsed, %d:%02d:%02d remaining" % (percent, 2.2, 1, 1, 1, 2, 2, 2),
time.sleep(0.5)
print
elif listdir:
listing = open(DATA_DIR + 'puppy-listdir.txt')
for l... | if opt == '-c':
if optarg == 'get' or optarg == 'put':
transfer = True
if optarg == 'dir':
listdir = True
if optarg == 'cancel':
os.system("pkill -f 'fakepuppy.py -c get.*'")
if optarg == 'size':
size = True | conditional_block |
middleware.py |
try:
from django.conf import settings
STRACKS_CONNECTOR = settings.STRACKS_CONNECTOR
except (ImportError, AttributeError):
STRACKS_CONNECTOR = None
STRACKS_API = None
from stracks_api.api import API
from stracks_api import client
import django.http
STRACKS_API = None
if STRACKS_CONNECTOR:
STRACK... |
def process_exception(self, request, exception):
if not STRACKS_API:
return
## do not log 404 exceptions, see issue #356
if isinstance(exception, django.http.Http404):
return
client.exception("Crash: %s" % exception)
| if not STRACKS_API:
return response
r = client.get_request()
if r:
if not request.user.is_anonymous():
## if there's an active user then he owns
## the request. We need to map it to an
## entity
from django.utils.i... | identifier_body |
middleware.py | try:
from django.conf import settings
STRACKS_CONNECTOR = settings.STRACKS_CONNECTOR
except (ImportError, AttributeError):
STRACKS_CONNECTOR = None
STRACKS_API = None
from stracks_api.api import API
from stracks_api import client
import django.http
STRACKS_API = None
if STRACKS_CONNECTOR:
STRACKS... | client.exception("Crash: %s" % exception) | random_line_split | |
middleware.py |
try:
from django.conf import settings
STRACKS_CONNECTOR = settings.STRACKS_CONNECTOR
except (ImportError, AttributeError):
STRACKS_CONNECTOR = None
STRACKS_API = None
from stracks_api.api import API
from stracks_api import client
import django.http
STRACKS_API = None
if STRACKS_CONNECTOR:
STRACK... |
request = sess.request(ip, useragent, path)
client.set_request(request)
def process_response(self, request, response):
if not STRACKS_API:
return response
r = client.get_request()
if r:
if not request.user.is_anonymous():
## if ther... | sess = STRACKS_API.session()
request.session['stracks-session'] = sess | conditional_block |
middleware.py |
try:
from django.conf import settings
STRACKS_CONNECTOR = settings.STRACKS_CONNECTOR
except (ImportError, AttributeError):
STRACKS_CONNECTOR = None
STRACKS_API = None
from stracks_api.api import API
from stracks_api import client
import django.http
STRACKS_API = None
if STRACKS_CONNECTOR:
STRACK... | (object):
def process_request(self, request):
if not STRACKS_API:
return
##
## get useragent, ip, path
## fetch session, create one if necessary
## create request, store it in local thread storage
useragent = request.META.get('HTTP_USER_AGENT', 'unknown')... | StracksMiddleware | identifier_name |
MARock.py | import os as os
import numpy as np
import scipy as sp
from pathlib import Path
from openpnm.utils import logging, Project
from openpnm.network import GenericNetwork
from openpnm.io import GenericIO
from openpnm.topotools import trim
logger = logging.getLogger(__name__)
class | (GenericIO):
r"""
3DMA-Rock is a network extraction algorithm developed by Brent Lindquist
and his group
It uses Medial Axis thinning to find the skeleton of the pore space, then
extracts geometrical features such as pore volume and throat
cross-sectional area.
[1] Lindquist, W. Brent, S. ... | MARock | identifier_name |
MARock.py | import os as os
import numpy as np
import scipy as sp
from pathlib import Path
from openpnm.utils import logging, Project
from openpnm.network import GenericNetwork
from openpnm.io import GenericIO
from openpnm.topotools import trim
logger = logging.getLogger(__name__)
class MARock(GenericIO):
r"""
3DMA-Rock ... |
with open(np2th_file, mode='rb') as f:
[Np, Nt] = np.fromfile(file=f, count=2, dtype='u4')
net['pore.boundary_type'] = sp.ndarray([Np, ], int)
net['throat.conns'] = np.ones([Nt, 2], int)*(-1)
net['pore.coordination'] = sp.ndarray([Np, ], int)
net['po... | if file.endswith(".np2th"):
np2th_file = os.path.join(path, file)
elif file.endswith(".th2np"):
th2np_file = os.path.join(path, file) | conditional_block |
MARock.py | import os as os
import numpy as np
import scipy as sp
from pathlib import Path
from openpnm.utils import logging, Project
from openpnm.network import GenericNetwork
from openpnm.io import GenericIO
from openpnm.topotools import trim
logger = logging.getLogger(__name__)
class MARock(GenericIO):
r"""
3DMA-Rock ... | r"""
Load data from a 3DMA-Rock extracted network. This format consists of
two files: 'rockname.np2th' and 'rockname.th2pn'. They should be
stored together in a folder which is referred to by the path argument.
These files are binary and therefore not human readable.
Parameter... | identifier_body | |
MARock.py | import os as os
import numpy as np
import scipy as sp
from pathlib import Path
from openpnm.utils import logging, Project
from openpnm.network import GenericNetwork
from openpnm.io import GenericIO
from openpnm.topotools import trim
logger = logging.getLogger(__name__)
| class MARock(GenericIO):
r"""
3DMA-Rock is a network extraction algorithm developed by Brent Lindquist
and his group
It uses Medial Axis thinning to find the skeleton of the pore space, then
extracts geometrical features such as pore volume and throat
cross-sectional area.
[1] Lindquist, W... | random_line_split | |
sudokus-tests.ts | import { solve, ProgressFn, Cell } from 'sudokus';
const onProgress: ProgressFn = (cell: Cell[][]) => {
cell[0][0].fixed;
cell[0][0].value;
}; | [
[0, 0, 0, 2, 9, 0, 1, 0, 0],
[6, 0, 0, 5, 0, 1, 0, 7, 0],
[0, 0, 0, 0, 0, 0, 0, 3, 4],
[0, 0, 0, 0, 0, 0, 9, 4, 0],
[4, 5, 0, 3, 0, 0, 0, 6, 2],
[2, 0, 9, 0, 0, 4, 3, 1, 0],
[0, 2, 0, 0, 0, 0, 4, 9, 0],
[0, 0, 6, 0, 0, 8, 0, 0, 0],
[0, 4, 3, ... |
solve( | random_line_split |
BodyDOMSource.ts | import xs, {Stream, MemoryStream} from 'xstream';
import {adapt} from '@cycle/run/lib/adapt';
import {DevToolEnabledSource} from '@cycle/run';
import {EventsFnOptions, DOMSource} from './DOMSource';
import {fromEvent} from './fromEvent';
export class BodyDOMSource {
constructor(private _name: string) {}
public se... | out._isCycleSource = this._name;
return out;
}
public events<K extends keyof HTMLBodyElementEventMap>(
eventType: K,
options?: EventsFnOptions,
bubbles?: boolean
): Stream<HTMLBodyElementEventMap[K]>;
public events(
eventType: string,
options: EventsFnOptions = {},
bubbles?: boo... | const out: DevToolEnabledSource & MemoryStream<HTMLBodyElement> = adapt(
xs.of(document.body)
); | random_line_split |
BodyDOMSource.ts | import xs, {Stream, MemoryStream} from 'xstream';
import {adapt} from '@cycle/run/lib/adapt';
import {DevToolEnabledSource} from '@cycle/run';
import {EventsFnOptions, DOMSource} from './DOMSource';
import {fromEvent} from './fromEvent';
export class BodyDOMSource {
constructor(private _name: string) {}
public se... | (): MemoryStream<Array<HTMLBodyElement>> {
const out: DevToolEnabledSource &
MemoryStream<Array<HTMLBodyElement>> = adapt(xs.of([document.body]));
out._isCycleSource = this._name;
return out;
}
public element(): MemoryStream<HTMLBodyElement> {
const out: DevToolEnabledSource & MemoryStream<HT... | elements | identifier_name |
BodyDOMSource.ts | import xs, {Stream, MemoryStream} from 'xstream';
import {adapt} from '@cycle/run/lib/adapt';
import {DevToolEnabledSource} from '@cycle/run';
import {EventsFnOptions, DOMSource} from './DOMSource';
import {fromEvent} from './fromEvent';
export class BodyDOMSource {
constructor(private _name: string) {}
public se... |
public events<K extends keyof HTMLBodyElementEventMap>(
eventType: K,
options?: EventsFnOptions,
bubbles?: boolean
): Stream<HTMLBodyElementEventMap[K]>;
public events(
eventType: string,
options: EventsFnOptions = {},
bubbles?: boolean
): Stream<Event> {
let stream: Stream<Event>;... | {
const out: DevToolEnabledSource & MemoryStream<HTMLBodyElement> = adapt(
xs.of(document.body)
);
out._isCycleSource = this._name;
return out;
} | identifier_body |
app.js | var authrocket = new AuthRocket({
jsUrl: 'https://tessellate.e1.loginrocket.com/v1/',
accountId: 'org_0vFdP9Zc11Y7yucwRTSCg8',
apiKey: 'key_AAAe02TUpGzBNgkrLkXYi6j57tmaiU0ll27NEvDRjBq',
realmId: 'rl_0vFhopfukY34r8EPGmKVpb'
});
console.log('authrocket:', authrocket);
//Set logged in status when dom is loaded
doc... | logoutButton.style.display='none';
}
}
function login(loginData){
if(!loginData){
var loginData = {};
loginData.username = document.getElementById('login-username').value;
loginData.password = document.getElementById('login-password').value;
}
authrocket.login(loginData).then(function(loginInfo... | } else {
statusEl.innerHTML = "False";
statusEl.style.color = 'red'; | random_line_split |
app.js | var authrocket = new AuthRocket({
jsUrl: 'https://tessellate.e1.loginrocket.com/v1/',
accountId: 'org_0vFdP9Zc11Y7yucwRTSCg8',
apiKey: 'key_AAAe02TUpGzBNgkrLkXYi6j57tmaiU0ll27NEvDRjBq',
realmId: 'rl_0vFhopfukY34r8EPGmKVpb'
});
console.log('authrocket:', authrocket);
//Set logged in status when dom is loaded
doc... | {
authrocket.Users.get().then(function(usersList){
console.log('users loaded', usersList);
}, function(err){
console.error('error getting users', err);
});
} | identifier_body | |
app.js | var authrocket = new AuthRocket({
jsUrl: 'https://tessellate.e1.loginrocket.com/v1/',
accountId: 'org_0vFdP9Zc11Y7yucwRTSCg8',
apiKey: 'key_AAAe02TUpGzBNgkrLkXYi6j57tmaiU0ll27NEvDRjBq',
realmId: 'rl_0vFhopfukY34r8EPGmKVpb'
});
console.log('authrocket:', authrocket);
//Set logged in status when dom is loaded
doc... | else {
statusEl.innerHTML = "False";
statusEl.style.color = 'red';
logoutButton.style.display='none';
}
}
function login(loginData){
if(!loginData){
var loginData = {};
loginData.username = document.getElementById('login-username').value;
loginData.password = document.getElementById('login... | {
statusEl.innerHTML = "True";
statusEl.style.color = 'green';
// statusEl.className = statusEl.className ? ' status-loggedIn' : 'status-loggedIn';
logoutButton.style.display='inline';
} | conditional_block |
app.js | var authrocket = new AuthRocket({
jsUrl: 'https://tessellate.e1.loginrocket.com/v1/',
accountId: 'org_0vFdP9Zc11Y7yucwRTSCg8',
apiKey: 'key_AAAe02TUpGzBNgkrLkXYi6j57tmaiU0ll27NEvDRjBq',
realmId: 'rl_0vFhopfukY34r8EPGmKVpb'
});
console.log('authrocket:', authrocket);
//Set logged in status when dom is loaded
doc... | () {
var statusEl = document.getElementById("status");
var logoutButton = document.getElementById("logout-btn");
if(authrocket.isLoggedIn){
statusEl.innerHTML = "True";
statusEl.style.color = 'green';
// statusEl.className = statusEl.className ? ' status-loggedIn' : 'status-loggedIn';
logoutButto... | setStatus | identifier_name |
grab_xml_processing.py | # coding: utf-8
from tests.util import build_grab
from tests.util import BaseGrabTestCase
class | (BaseGrabTestCase):
def setUp(self):
self.server.reset()
def test_xml_with_declaration(self):
self.server.response['get.data'] =\
b'<?xml version="1.0" encoding="UTF-8"?>'\
b'<root><foo>foo</foo></root>'
grab = build_grab()
grab.go(self.server.get_url())
... | GrabXMLProcessingTestCase | identifier_name |
grab_xml_processing.py | # coding: utf-8
from tests.util import build_grab
from tests.util import BaseGrabTestCase
class GrabXMLProcessingTestCase(BaseGrabTestCase):
def setUp(self):
self.server.reset()
def test_xml_with_declaration(self): | self.assertTrue(grab.doc.select('//foo').text() == 'foo')
def test_declaration_bug(self):
"""
1. Build Grab instance with XML with xml declaration
2. Call search method
3. Call xpath
4. Get ValueError: Unicode strings with encoding
declaration are not sup... | self.server.response['get.data'] =\
b'<?xml version="1.0" encoding="UTF-8"?>'\
b'<root><foo>foo</foo></root>'
grab = build_grab()
grab.go(self.server.get_url()) | random_line_split |
grab_xml_processing.py | # coding: utf-8
from tests.util import build_grab
from tests.util import BaseGrabTestCase
class GrabXMLProcessingTestCase(BaseGrabTestCase):
def setUp(self):
self.server.reset()
def test_xml_with_declaration(self):
self.server.response['get.data'] =\
b'<?xml version="1.0" encoding... | """
1. Build Grab instance with XML with xml declaration
2. Call search method
3. Call xpath
4. Get ValueError: Unicode strings with encoding
declaration are not supported.
"""
xml = b'<?xml version="1.0" encoding="UTF-8"?>'\
b'<tree><leaf>text</... | identifier_body | |
numbers.rs | //! Functions operating on numbers.
use std::sync::Mutex;
use rand::{StdRng, Rng, SeedableRng};
use lisp::LispObject;
use remacs_sys::{EmacsInt, INTMASK};
use remacs_macros::lisp_fn;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT is a floating point ... | #[lisp_fn]
fn numberp(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_number())
}
/// Return t if OBJECT is a number or a marker (editor pointer).
#[lisp_fn]
fn number_or_marker_p(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_number() || object.is_marker())
}
/// Retu... | fn natnump(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_natnum())
}
/// Return t if OBJECT is a number (floating point or integer). | random_line_split |
numbers.rs | //! Functions operating on numbers.
use std::sync::Mutex;
use rand::{StdRng, Rng, SeedableRng};
use lisp::LispObject;
use remacs_sys::{EmacsInt, INTMASK};
use remacs_macros::lisp_fn;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT is a floating point ... | (object: LispObject) -> LispObject {
LispObject::from_bool(object.is_float())
}
/// Return t if OBJECT is an integer.
#[lisp_fn]
fn integerp(object: LispObject) -> LispObject {
LispObject::from_bool(object.is_integer())
}
/// Return t if OBJECT is an integer or a marker (editor pointer).
#[lisp_fn]
fn integer... | floatp | identifier_name |
numbers.rs | //! Functions operating on numbers.
use std::sync::Mutex;
use rand::{StdRng, Rng, SeedableRng};
use lisp::LispObject;
use remacs_sys::{EmacsInt, INTMASK};
use remacs_macros::lisp_fn;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT is a floating point ... | {
let mut rng = RNG.lock().unwrap();
if limit == LispObject::constant_t() {
*rng = StdRng::new().unwrap();
} else if let Some(s) = limit.as_string() {
let values: Vec<usize> = s.as_slice().iter().map(|&x| x as usize).collect();
rng.reseed(&values);
}
if let Some(limit) = lim... | identifier_body | |
numbers.rs | //! Functions operating on numbers.
use std::sync::Mutex;
use rand::{StdRng, Rng, SeedableRng};
use lisp::LispObject;
use remacs_sys::{EmacsInt, INTMASK};
use remacs_macros::lisp_fn;
lazy_static! {
static ref RNG: Mutex<StdRng> = Mutex::new(StdRng::new().unwrap());
}
/// Return t if OBJECT is a floating point ... |
}
| {
LispObject::from_fixnum_truncated(rng.gen())
} | conditional_block |
auxpow_testing.py | #!/usr/bin/env python3
# Copyright(c) 2014-2019 Daniel Kraft
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Utility routines for auxpow that are needed specifically by the regtests.
# This is mostly about actually *solving* an ... |
return (hexData, blockhash)
| break | conditional_block |
auxpow_testing.py | #!/usr/bin/env python3
# Copyright(c) 2014-2019 Daniel Kraft
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Utility routines for auxpow that are needed specifically by the regtests.
# This is mostly about actually *solving* an ... |
(tx, header) = auxpow.constructAuxpow(block)
(header, _) = mineBlock(header, target, ok)
return auxpow.finishAuxpow(tx, header)
def mineAuxpowBlock(node):
"""
Mine an auxpow block on the given RPC connection. This uses the
createauxblock and submitauxblock command pair.
"""
def create():
addr = ... | Build an auxpow object(serialised as hex string) that solves
(ok = True) or doesn't solve(ok = False) the block.
""" | random_line_split |
auxpow_testing.py | #!/usr/bin/env python3
# Copyright(c) 2014-2019 Daniel Kraft
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Utility routines for auxpow that are needed specifically by the regtests.
# This is mostly about actually *solving* an ... | (node):
"""
Mine an auxpow block on the given RPC connection. This uses the
createauxblock and submitauxblock command pair.
"""
def create():
addr = node.getnewaddress()
return node.createauxblock(addr)
return mineAuxpowBlockWithMethods(create, node.submitauxblock)
def mineAuxpowBlockWithMethods... | mineAuxpowBlock | identifier_name |
auxpow_testing.py | #!/usr/bin/env python3
# Copyright(c) 2014-2019 Daniel Kraft
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
# Utility routines for auxpow that are needed specifically by the regtests.
# This is mostly about actually *solving* an ... |
def getCoinbaseAddr(node, blockHash):
"""
Extract the coinbase tx' payout address for the given block.
"""
blockData = node.getblock(blockHash)
txn = blockData['tx']
assert len(txn) >= 1
txData = node.getrawtransaction(txn[0], True, blockHash)
assert len(txData['vout']) >= 1 and len(... | """
Mine an auxpow block, using the given methods for creation and submission.
"""
auxblock = create()
target = auxpow.reverseHex(auxblock['_target'])
apow = computeAuxpow(auxblock['hash'], target, True)
res = submit(auxblock['hash'], apow)
assert res
return auxblock['hash'] | identifier_body |
BOK.js | goog.provide('bok.BOK');
//reassign Window Event class as BOK event will pollute its name
var DOMEvent = window.Event;
var BOK = {};
BOK.enableTrace = true;
BOK.enableWarning = true;
/**
* @param {Function} childClass
* @param {Function} baseClass
* */
BOK.inherits = function(childClass, baseClass) {
//do a dee... | () {}
tempCtor.prototype = baseClass.prototype;
childClass.superClass_ = baseClass.prototype;
childClass.prototype = new tempCtor();
childClass.prototype.constructor = childClass;
};
/**
* @param {Function} childClass
* Sub class implements the interface
* @param {Function} interfaceClass
* interface... | tempCtor | identifier_name |
BOK.js | goog.provide('bok.BOK');
//reassign Window Event class as BOK event will pollute its name
var DOMEvent = window.Event;
var BOK = {};
BOK.enableTrace = true;
BOK.enableWarning = true;
/**
* @param {Function} childClass
* @param {Function} baseClass
* */
BOK.inherits = function(childClass, baseClass) {
//do a dee... | };
/**
* @public add a ClassName to an element
* */
BOK.addClassName = function(elem, name)
{
if(!BOK.hasClassName(elem, name))
elem.className += ' '+name;
};
/**
* @public remove a ClassName to an element
* */
BOK.removeClassName = function(elem, name)
{
var classes = elem.className.split(' ');
BOK.each(cla... | return Loc + '/' + url; | random_line_split |
BOK.js | goog.provide('bok.BOK');
//reassign Window Event class as BOK event will pollute its name
var DOMEvent = window.Event;
var BOK = {};
BOK.enableTrace = true;
BOK.enableWarning = true;
/**
* @param {Function} childClass
* @param {Function} baseClass
* */
BOK.inherits = function(childClass, baseClass) {
//do a dee... |
tempCtor.prototype = baseClass.prototype;
childClass.superClass_ = baseClass.prototype;
childClass.prototype = new tempCtor();
childClass.prototype.constructor = childClass;
};
/**
* @param {Function} childClass
* Sub class implements the interface
* @param {Function} interfaceClass
* interface clas... | {} | identifier_body |
dgeni-definitions.ts | import {ClassExportDoc} from 'dgeni-packages/typescript/api-doc-types/ClassExportDoc';
import {ClassLikeExportDoc} from 'dgeni-packages/typescript/api-doc-types/ClassLikeExportDoc';
import {PropertyMemberDoc} from 'dgeni-packages/typescript/api-doc-types/PropertyMemberDoc';
import {NormalizedMethodMemberDoc} from './no... | directiveOutputAlias: string;
}
/** Extended Dgeni method-member document that simplifies logic for the Dgeni template. */
export interface CategorizedMethodMemberDoc extends NormalizedMethodMemberDoc {
showReturns: boolean;
isDeprecated: boolean;
} | random_line_split | |
StressTest.ts | import ITestImpl = require('../ITestImpl');
class StressTest implements ITestImpl {
run (runCount: number, onStatus: (status: any) => any, onOutput: (output: any) => any) {
if (!this.prepare(() => this.$$finishRun(runCount, onStatus, onOutput)))
| return this.$$finishRun(runCount, onStatus, onOutput);
}
private $$finishRun (runCount: number, onStatus: (status: any) => any, onOutput: (output: any) => any) {
var all: number[] = [];
//Pre-run
for (var i = 0; i < 5; i++) {
this.prepareIteration();
... | random_line_split | |
StressTest.ts | import ITestImpl = require('../ITestImpl');
class StressTest implements ITestImpl {
run (runCount: number, onStatus: (status: any) => any, onOutput: (output: any) => any) {
if (!this.prepare(() => this.$$finishRun(runCount, onStatus, onOutput)))
return this.$$finishRun(runCount, onStatus, ... |
var total = performance.now() - start;
console.profileEnd();
var min = all.reduce((agg, ms) => Math.min(agg, ms), Number.POSITIVE_INFINITY);
var max = all.reduce((agg, ms) => Math.max(agg, ms), Number.NEGATIVE_INFINITY);
var sum = all.reduce((agg, ms) => agg + ms, 0);
... | {
var s = performance.now();
this.prepareIteration();
this.runIteration();
all.push(performance.now() - s);
} | conditional_block |
StressTest.ts | import ITestImpl = require('../ITestImpl');
class StressTest implements ITestImpl {
run (runCount: number, onStatus: (status: any) => any, onOutput: (output: any) => any) {
if (!this.prepare(() => this.$$finishRun(runCount, onStatus, onOutput)))
return this.$$finishRun(runCount, onStatus, ... | () {
}
}
function createTimingString (ms: number): string {
return ms.toString()
+ "ms ("
+ (ms / 1000).toFixed(1)
+ "s)";
}
function calcStdDev (all: number[], total: number): number {
var avg = total / all.length;
return Math.sqrt(all.reduce((agg, ms) => agg + M... | runIteration | identifier_name |
StressTest.ts | import ITestImpl = require('../ITestImpl');
class StressTest implements ITestImpl {
run (runCount: number, onStatus: (status: any) => any, onOutput: (output: any) => any) {
if (!this.prepare(() => this.$$finishRun(runCount, onStatus, onOutput)))
return this.$$finishRun(runCount, onStatus, ... |
}
function createTimingString (ms: number): string {
return ms.toString()
+ "ms ("
+ (ms / 1000).toFixed(1)
+ "s)";
}
function calcStdDev (all: number[], total: number): number {
var avg = total / all.length;
return Math.sqrt(all.reduce((agg, ms) => agg + Math.pow(ms -... | {
} | identifier_body |
imp.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... | "Decoder/Video",
"CDG decoder",
"Guillaume Desmottes <guillaume.desmottes@collabora.com>",
);
let sink_caps = gst::Caps::new_simple("video/x-cdg", &[("parsed", &true)]);
let sink_pad_template = gst::PadTemplate::new(
"sink",
gst::PadDi... | "CDG decoder", | random_line_split |
imp.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... | (&self, element: &Self::Type) -> bool {
gst_debug!(CAT, obj: element, "flushing, reset CDG interpreter");
let mut cdg_inter = self.cdg_inter.lock().unwrap();
cdg_inter.reset(false);
true
}
}
| flush | identifier_name |
imp.rs | // Copyright (C) 2019 Guillaume Desmottes <guillaume.desmottes@collabora.com>
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, ... |
}
impl ObjectImpl for CdgDec {}
impl ElementImpl for CdgDec {}
impl VideoDecoderImpl for CdgDec {
fn start(&self, element: &Self::Type) -> Result<(), gst::ErrorMessage> {
let mut out_info = self.output_info.lock().unwrap();
*out_info = None;
self.parent_start(element)
}
fn stop... | {
klass.set_metadata(
"CDG decoder",
"Decoder/Video",
"CDG decoder",
"Guillaume Desmottes <guillaume.desmottes@collabora.com>",
);
let sink_caps = gst::Caps::new_simple("video/x-cdg", &[("parsed", &true)]);
let sink_pad_template = gst::Pad... | identifier_body |
projectStore.ts | import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { File } from '../../types'
import { fetchProject } from './projectActions'
import { NormalizedProjectStore } from './ProjectStoreTypes'
const initialState: NormalizedProjectStore = {
entities: {
projects: {},
files: {},
},
ids: [],
}
... | extraReducers: (builder) => {
builder.addCase(fetchProject.fulfilled, (state, { payload }) => {
state.entities = payload.entities
state.ids =
typeof payload.result === 'string' ? [payload.result] : payload.result
})
},
})
export const projectActions = projectSlice.actions
export type Pr... | { payload }: PayloadAction<Record<string, File>>
) => {
state.entities.files = payload
},
}, | random_line_split |
base.py | # Peerz - P2P python library using ZeroMQ sockets and gevent
# Copyright (C) 2014-2015 Steve Henderson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... |
def __init__(self, engine, txid, msg, callback=None, max_duration=5000, max_concurrency=3):
self.engine = engine
self.callback = callback
self.machine = Machine(model=self,
states=self.states,
transitions=self.transitions,
... | transitions = [
{'trigger': 'query', 'source': 'initialised', 'dest': 'waiting response', 'before': '_update', 'after': '_send_query'},
{'trigger': 'response', 'source': 'waiting response', 'dest': 'complete', 'before': '_update', 'after': '_completed'},
{'trigger': 'timeout', 'source': '*',... | random_line_split |
base.py | # Peerz - P2P python library using ZeroMQ sockets and gevent
# Copyright (C) 2014-2015 Steve Henderson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... | (self):
now = time.time() * 1000
self.times.setdefault(self.state, 0.0)
self.times[self.state] += (now - self.last_change)
self.last_change = now
def duration(self):
return time.time() * 1000 - self.start
def latency(self):
return self.times.setdefault('waiting ... | _update | identifier_name |
base.py | # Peerz - P2P python library using ZeroMQ sockets and gevent
# Copyright (C) 2014-2015 Steve Henderson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at... |
def pack_request(self):
return None
@staticmethod
def unpack_response(content):
return None
@staticmethod
def pack_response(content):
return None
def _update(self):
now = time.time() * 1000
self.times.setdefault(self.state, 0.0)
self.times... | return self.state in ['complete', 'timedout'] | identifier_body |
url.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMe... |
}
// https://url.spec.whatwg.org/#dom-url-searchparams
fn SearchParams(&self) -> DomRoot<URLSearchParams> {
self.search_params
.or_init(|| URLSearchParams::new(&self.global(), Some(self)))
}
// https://url.spec.whatwg.org/#dom-url-href
fn Stringifier(&self) -> DOMString {
... | {
search_params.set_list(self.query_pairs());
} | conditional_block |
url.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMe... | Err(error) => {
// Step 2.2.
return Err(Error::Type(format!("could not parse base: {}", error)));
},
}
}
};
// Step 3.
let parsed_url = match ServoUrl::parse_with_base(parsed_base.... | {
match ServoUrl::parse(&base.0) {
Ok(base) => Some(base), | random_line_split |
url.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMe... | (&self, value: USVString) {
UrlHelper::SetHost(&mut self.url.borrow_mut(), value);
}
// https://url.spec.whatwg.org/#dom-url-hostname
fn Hostname(&self) -> USVString {
UrlHelper::Hostname(&self.url.borrow())
}
// https://url.spec.whatwg.org/#dom-url-hostname
fn SetHostname(&sel... | SetHost | identifier_name |
url.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 https://mozilla.org/MPL/2.0/. */
use crate::dom::bindings::cell::DomRefCell;
use crate::dom::bindings::codegen::Bindings::URLBinding::{self, URLMe... |
pub fn new(global: &GlobalScope, url: ServoUrl) -> DomRoot<URL> {
reflect_dom_object(Box::new(URL::new_inherited(url)), global, URLBinding::Wrap)
}
pub fn query_pairs(&self) -> Vec<(String, String)> {
self.url
.borrow()
.as_url()
.query_pairs()
... | {
URL {
reflector_: Reflector::new(),
url: DomRefCell::new(url),
search_params: Default::default(),
}
} | identifier_body |
fetch-auth-token.ts | import { exec, execaCommand, IResponse } from './util';
import * as common from './';
import * as util from './util';
import config from './config';
const REFRESH_URL = `https://${config.AUTH0_DOMAIN}/delegation`;
interface IAuth0Response {
id_token: string;
}
export async function fetchToken(
params: { refreshTok... |
const payload = {
client_id: config.AUTH0_CLIENT_ID,
refresh_token: refreshToken,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
api_type: 'app',
};
let response: IResponse<IAuth0Response>;
try {
response = await util.http.post<IAuth0Response>(REFRESH_URL, payload);
if (response.status =... | {
throw new Error('Need a refresh token. Is your .env set up correctly?');
} | conditional_block |
fetch-auth-token.ts | import { exec, execaCommand, IResponse } from './util';
import * as common from './';
import * as util from './util';
import config from './config';
const REFRESH_URL = `https://${config.AUTH0_DOMAIN}/delegation`;
interface IAuth0Response {
id_token: string;
}
export async function fetchToken(
params: { refreshTok... | {
const refreshToken =
(params && params.refreshToken) || config.AUTH0_REFRESH_TOKEN;
if (!refreshToken) {
throw new Error('Need a refresh token. Is your .env set up correctly?');
}
const payload = {
client_id: config.AUTH0_CLIENT_ID,
refresh_token: refreshToken,
grant_type: 'urn:ietf:params:oauth:grant-... | identifier_body | |
fetch-auth-token.ts | import { exec, execaCommand, IResponse } from './util';
import * as common from './';
import * as util from './util';
import config from './config';
const REFRESH_URL = `https://${config.AUTH0_DOMAIN}/delegation`;
interface IAuth0Response {
id_token: string;
}
export async function | (
params: { refreshToken?: string } = {},
): Promise<string | null> {
const refreshToken =
(params && params.refreshToken) || config.AUTH0_REFRESH_TOKEN;
if (!refreshToken) {
throw new Error('Need a refresh token. Is your .env set up correctly?');
}
const payload = {
client_id: config.AUTH0_CLIENT_ID,
ref... | fetchToken | identifier_name |
fetch-auth-token.ts | import { exec, execaCommand, IResponse } from './util';
import * as common from './';
import * as util from './util';
import config from './config';
const REFRESH_URL = `https://${config.AUTH0_DOMAIN}/delegation`;
interface IAuth0Response {
id_token: string;
}
export async function fetchToken(
params: { refreshTok... | client_id: config.AUTH0_CLIENT_ID,
refresh_token: refreshToken,
grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
api_type: 'app',
};
let response: IResponse<IAuth0Response>;
try {
response = await util.http.post<IAuth0Response>(REFRESH_URL, payload);
if (response.status === 200 && response.da... | const payload = { | random_line_split |
lot.py | # -*- coding: utf-8 -*-
from openprocurement.auctions.core.utils import (
apply_patch,
context_unpack,
get_now,
json_view,
opresource,
save_auction,
)
from openprocurement.auctions.core.validation import (
validate_lot_data,
validate_patch_lot_data,
)
from openprocurement.auctions.core.v... | (self):
"""Update of lot
"""
auction = self.request.validated['auction']
if auction.status not in ['active.tendering']:
self.request.errors.add('body', 'data', 'Can\'t update lot in current ({}) auction status'.format(auction.status))
self.request.errors.status = ... | patch | identifier_name |
lot.py | # -*- coding: utf-8 -*-
from openprocurement.auctions.core.utils import (
apply_patch,
context_unpack,
get_now,
json_view,
opresource,
save_auction,
)
from openprocurement.auctions.core.validation import (
validate_lot_data,
validate_patch_lot_data,
)
from openprocurement.auctions.core.v... | return {'data': self.request.context.serialize("view")}
@json_view(permission='edit_auction')
def delete(self):
"""Lot deleting
"""
auction = self.request.validated['auction']
if auction.status not in ['active.tendering']:
self.request.errors.add('body', ... | random_line_split | |
lot.py | # -*- coding: utf-8 -*-
from openprocurement.auctions.core.utils import (
apply_patch,
context_unpack,
get_now,
json_view,
opresource,
save_auction,
)
from openprocurement.auctions.core.validation import (
validate_lot_data,
validate_patch_lot_data,
)
from openprocurement.auctions.core.v... |
if apply_patch(self.request, src=self.request.context.serialize()):
self.LOGGER.info('Updated auction lot {}'.format(self.request.context.id),
extra=context_unpack(self.request, {'MESSAGE_ID': 'auction_lot_patch'}))
return {'data': self.request.context.serialize(... | self.request.errors.add('body', 'data', 'Can\'t update lot in current ({}) auction status'.format(auction.status))
self.request.errors.status = 403
return | conditional_block |
lot.py | # -*- coding: utf-8 -*-
from openprocurement.auctions.core.utils import (
apply_patch,
context_unpack,
get_now,
json_view,
opresource,
save_auction,
)
from openprocurement.auctions.core.validation import (
validate_lot_data,
validate_patch_lot_data,
)
from openprocurement.auctions.core.v... | """Lot deleting
"""
auction = self.request.validated['auction']
if auction.status not in ['active.tendering']:
self.request.errors.add('body', 'data', 'Can\'t delete lot in current ({}) auction status'.format(auction.status))
self.request.errors.status = 403
r... | identifier_body | |
create_trace_graphviz.py | """
Read in the output from the trace-inputlocator script and create a GraphViz file.
Pass as input the path to the yaml output of the trace-inputlocator script via config file.
The output is written to the trace-inputlocator location.
WHY? because the trace-inputlocator only has the GraphViz output of the last call ... |
if __name__ == '__main__':
main(cea.config.Configuration()) | with open(config.trace_inputlocator.yaml_output_file, 'r') as f:
yaml_data = yaml.safe_load(f)
trace_data = []
for script in yaml_data.keys():
for direction in ('input', 'output'):
for locator, file in yaml_data[script][direction]:
trace_data.append((direction, scrip... | identifier_body |
create_trace_graphviz.py | """
Read in the output from the trace-inputlocator script and create a GraphViz file.
Pass as input the path to the yaml output of the trace-inputlocator script via config file.
The output is written to the trace-inputlocator location.
WHY? because the trace-inputlocator only has the GraphViz output of the last call ... |
trace_data = []
for script in yaml_data.keys():
for direction in ('input', 'output'):
for locator, file in yaml_data[script][direction]:
trace_data.append((direction, script, locator, file))
create_graphviz_output(trace_data, config.trace_inputlocator.graphviz_output_fi... | def main(config):
with open(config.trace_inputlocator.yaml_output_file, 'r') as f:
yaml_data = yaml.safe_load(f) | random_line_split |
create_trace_graphviz.py | """
Read in the output from the trace-inputlocator script and create a GraphViz file.
Pass as input the path to the yaml output of the trace-inputlocator script via config file.
The output is written to the trace-inputlocator location.
WHY? because the trace-inputlocator only has the GraphViz output of the last call ... | (config):
with open(config.trace_inputlocator.yaml_output_file, 'r') as f:
yaml_data = yaml.safe_load(f)
trace_data = []
for script in yaml_data.keys():
for direction in ('input', 'output'):
for locator, file in yaml_data[script][direction]:
trace_data.append((di... | main | identifier_name |
create_trace_graphviz.py | """
Read in the output from the trace-inputlocator script and create a GraphViz file.
Pass as input the path to the yaml output of the trace-inputlocator script via config file.
The output is written to the trace-inputlocator location.
WHY? because the trace-inputlocator only has the GraphViz output of the last call ... |
create_graphviz_output(trace_data, config.trace_inputlocator.graphviz_output_file)
if __name__ == '__main__':
main(cea.config.Configuration()) | trace_data.append((direction, script, locator, file)) | conditional_block |
keyboardInteractiveAuthPanel.component.ts | import { Component, Input, Output, EventEmitter, ViewChild, ElementRef, ChangeDetectionStrategy } from '@angular/core'
import { KeyboardInteractivePrompt } from '../session/ssh'
@Component({
selector: 'keyboard-interactive-auth-panel',
template: require('./keyboardInteractiveAuthPanel.component.pug'),
sty... | {
@Input() prompt: KeyboardInteractivePrompt
@Input() step = 0
@Output() done = new EventEmitter()
@ViewChild('input') input: ElementRef
isPassword (): boolean {
return this.prompt.prompts[this.step].prompt.toLowerCase().includes('password') || !this.prompt.prompts[this.step].echo
}
... | KeyboardInteractiveAuthComponent | identifier_name |
keyboardInteractiveAuthPanel.component.ts | import { Component, Input, Output, EventEmitter, ViewChild, ElementRef, ChangeDetectionStrategy } from '@angular/core'
import { KeyboardInteractivePrompt } from '../session/ssh'
@Component({
selector: 'keyboard-interactive-auth-panel',
template: require('./keyboardInteractiveAuthPanel.component.pug'),
sty... |
this.input.nativeElement.focus()
}
next (): void {
if (this.step === this.prompt.prompts.length - 1) {
this.prompt.respond()
this.done.emit()
return
}
this.step++
this.input.nativeElement.focus()
}
}
| {
this.step--
} | conditional_block |
keyboardInteractiveAuthPanel.component.ts | import { Component, Input, Output, EventEmitter, ViewChild, ElementRef, ChangeDetectionStrategy } from '@angular/core'
import { KeyboardInteractivePrompt } from '../session/ssh'
@Component({ | })
export class KeyboardInteractiveAuthComponent {
@Input() prompt: KeyboardInteractivePrompt
@Input() step = 0
@Output() done = new EventEmitter()
@ViewChild('input') input: ElementRef
isPassword (): boolean {
return this.prompt.prompts[this.step].prompt.toLowerCase().includes('password') ... | selector: 'keyboard-interactive-auth-panel',
template: require('./keyboardInteractiveAuthPanel.component.pug'),
styles: [require('./keyboardInteractiveAuthPanel.component.scss')],
changeDetection: ChangeDetectionStrategy.OnPush, | random_line_split |
keyboardInteractiveAuthPanel.component.ts | import { Component, Input, Output, EventEmitter, ViewChild, ElementRef, ChangeDetectionStrategy } from '@angular/core'
import { KeyboardInteractivePrompt } from '../session/ssh'
@Component({
selector: 'keyboard-interactive-auth-panel',
template: require('./keyboardInteractiveAuthPanel.component.pug'),
sty... |
next (): void {
if (this.step === this.prompt.prompts.length - 1) {
this.prompt.respond()
this.done.emit()
return
}
this.step++
this.input.nativeElement.focus()
}
}
| {
if (this.step > 0) {
this.step--
}
this.input.nativeElement.focus()
} | identifier_body |
mod.rs | //! Generators for file formats that can be derived from the intercom
//! libraries.
use std::collections::HashMap;
use intercom::type_system::TypeSystemName;
use intercom::typelib::{Interface, TypeInfo, TypeLib};
/// A common error type for all the generators.
#[derive(Fail, Debug)]
pub enum GeneratorError
{
#[... | pub mod idl; |
pub mod cpp; | random_line_split |
mod.rs | //! Generators for file formats that can be derived from the intercom
//! libraries.
use std::collections::HashMap;
use intercom::type_system::TypeSystemName;
use intercom::typelib::{Interface, TypeInfo, TypeLib};
/// A common error type for all the generators.
#[derive(Fail, Debug)]
pub enum GeneratorError
{
#[... | <'a>
{
pub itfs_by_ref: HashMap<String, &'a Interface>,
pub itfs_by_name: HashMap<String, &'a Interface>,
}
impl<'a> LibraryContext<'a>
{
fn try_from(lib: &'a TypeLib) -> Result<LibraryContext<'a>, GeneratorError>
{
let itfs_by_name: HashMap<String, &Interface> = lib
.types
... | LibraryContext | identifier_name |
mainSocket.js | $(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInp... | (message, options) {
var $el = $('<li>').addClass('log').text(message);
addMessageElement($el, options);
}
// Adds the visual chat message to the message list
function addChatMessage (data, options) {
// Don't fade the message in if there is an 'X was typing'
var $typingMessages = getTypingMessa... | log | identifier_name |
mainSocket.js | $(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInp... | log('you have been disconnected');
});
socket.on('reconnect', function () {
log('you have been reconnected');
if (username) {
socket.emit('add user', username);
}
});
socket.on('reconnect_error', function () {
log('attempt to reconnect has failed');
});
}); |
socket.on('disconnect', function () { | random_line_split |
mainSocket.js | $(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInp... |
}
// Sends a chat message
function sendMessage () {
var message = $inputMessage.val();
// Prevent markup from being injected into the message
message = cleanInput(message);
// if there is a non-empty message and a socket connection
if (message && connected) {
$inputMessage.val('');
... | {
$loginPage.fadeOut();
$chatPage.show();
$loginPage.off('click');
$currentInput = $inputMessage.focus();
// Tell the server your username
socket.emit('add user', username);
} | conditional_block |
mainSocket.js | $(function() {
var FADE_TIME = 150; // ms
var TYPING_TIMER_LENGTH = 400; // ms
var COLORS = [
'#e21400', '#91580f', '#f8a700', '#f78b00',
'#58dc00', '#287b00', '#a8f07a', '#4ae8c4',
'#3b88eb', '#3824aa', '#a700ff', '#d300e7'
];
// Initialize variables
var $window = $(window);
var $usernameInp... |
// Keyboard events
$window.keydown(function (event) {
// Auto-focus the current input when a key is typed
if (!(event.ctrlKey || event.metaKey || event.altKey)) {
$currentInput.focus();
}
// When the client hits ENTER on their keyboard
if (event.which === 13) {
if (username) {
... | {
// Compute hash code
var hash = 7;
for (var i = 0; i < username.length; i++) {
hash = username.charCodeAt(i) + (hash << 5) - hash;
}
// Calculate color
var index = Math.abs(hash % COLORS.length);
return COLORS[index];
} | identifier_body |
hDBSessionMaker.py | # create a Session object by sessionmaker
import os
import ConfigParser
import sqlalchemy.orm
# get path to taskmanager. it is assumed that this script is in the lib directory of
# the taskmanager package.
tmpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/..' ) )
etcpath =... |
# read config file
if os.path.exists( configFileName ):
config = ConfigParser.ConfigParser()
config.read( configFileName )
else:
sys.stderr.write( "ERROR: Could not find Config file {c}!".format( c=configFileName) )
sys.exit( -1 )
databa... | etcpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/../etc' ) )
# default config file for database connection
configFileName = "{etcPath}/serversettings.cfg".format(etcPath=etcpath) | conditional_block |
hDBSessionMaker.py | # create a Session object by sessionmaker
import os
import ConfigParser
import sqlalchemy.orm
# get path to taskmanager. it is assumed that this script is in the lib directory of
# the taskmanager package.
tmpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/..' ) )
etcpath =... | pool_size=50, # number of connections to keep open inside the connection pool
max_overflow=100, # number of connections to allow in connection pool "overflow", that is connections that can be opened above and beyond the pool... | host=databaseHost,
port=databasePort,
... | random_line_split |
hDBSessionMaker.py | # create a Session object by sessionmaker
import os
import ConfigParser
import sqlalchemy.orm
# get path to taskmanager. it is assumed that this script is in the lib directory of
# the taskmanager package.
tmpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/..' ) )
etcpath =... | ( self, configFileName=None, createTables=False, echo=False ):
if not configFileName:
# use default config file
etcpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/../etc' ) )
# default config file for database connection
... | __init__ | identifier_name |
hDBSessionMaker.py | # create a Session object by sessionmaker
import os
import ConfigParser
import sqlalchemy.orm
# get path to taskmanager. it is assumed that this script is in the lib directory of
# the taskmanager package.
tmpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/..' ) )
etcpath =... | if not configFileName:
# use default config file
etcpath = os.path.normpath( os.path.join( os.path.dirname( os.path.realpath(__file__) ) + '/../etc' ) )
# default config file for database connection
configFileName = "{etcPath}/serversettings.cfg".format(etcPa... | identifier_body | |
index.js | import { createFilter, makeLegalIdentifier } from 'rollup-pluginutils';
export default function json(options = {}) | {
const filter = createFilter(options.include, options.exclude);
return {
name: 'json',
transform(json, id) {
if (id.slice(-5) !== '.json') return null;
if (!filter(id)) return null;
const data = JSON.parse(json);
let code = '';
const ast = {
type: 'Program',
sourceType: 'module',
s... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.