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 |
|---|---|---|---|---|
HelpOutlineTwoTone.js | "use strict";
| var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default... | random_line_split | |
empty.rs | use crate::Stream;
use core::marker::PhantomData;
use core::pin::Pin;
use core::task::{Context, Poll};
/// Stream for the [`empty`](fn@empty) function.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Empty<T>(PhantomData<T>);
impl<T> Unpin for Empty<T> {}
unsafe impl<T> Send for Empty<T>... | }
impl<T> Stream for Empty<T> {
type Item = T;
fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<T>> {
Poll::Ready(None)
}
fn size_hint(&self) -> (usize, Option<usize>) {
(0, Some(0))
}
} | pub const fn empty<T>() -> Empty<T> {
Empty(PhantomData) | random_line_split |
empty.rs | use crate::Stream;
use core::marker::PhantomData;
use core::pin::Pin;
use core::task::{Context, Poll};
/// Stream for the [`empty`](fn@empty) function.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct Empty<T>(PhantomData<T>);
impl<T> Unpin for Empty<T> {}
unsafe impl<T> Send for Empty<T>... | (&self) -> (usize, Option<usize>) {
(0, Some(0))
}
}
| size_hint | identifier_name |
cpu.py | # (void)walker hardware platform support
# Copyright (C) 2012-2013 David Holm <dholmster@gmail.com>
# 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 you... | (self):
raise NotImplementedError
def value(self):
raise NotImplementedError
def str(self):
if self.value() is not None:
return self._register_fmt[self.size()] % self.value()
chars_per_byte = 2
return ''.join(['-' * (self.size() * chars_per_byte)])
def cre... | size | identifier_name |
cpu.py | # (void)walker hardware platform support
# Copyright (C) 2012-2013 David Holm <dholmster@gmail.com>
# 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 you... | def registers(self):
return self._registers.iteritems()
@abc.abstractmethod
def stack_pointer(self):
raise NotImplementedError
@abc.abstractmethod
def program_counter(self):
raise NotImplementedError
class CpuFactory(object):
__metaclass__ = abc.ABCMeta
def creat... | random_line_split | |
cpu.py | # (void)walker hardware platform support
# Copyright (C) 2012-2013 David Holm <dholmster@gmail.com>
# 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 you... |
def create_static_register(register):
class StaticRegister(type(register), object):
def __init__(self, name):
super(StaticRegister, self).__init__(name)
self._size = register.size()
self._value = register.value()
def size(self):
return self._size
... | _register_fmt = {16: '0x%032lX',
10: '0x%020lX',
8: '0x%016lX',
4: '0x%08lX',
2: '0x%04lX',
1: '0x%02lX'}
def __init__(self, name):
self._name = name
def name(self):
return self._name
... | identifier_body |
cpu.py | # (void)walker hardware platform support
# Copyright (C) 2012-2013 David Holm <dholmster@gmail.com>
# 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 you... |
chars_per_byte = 2
return ''.join(['-' * (self.size() * chars_per_byte)])
def create_static_register(register):
class StaticRegister(type(register), object):
def __init__(self, name):
super(StaticRegister, self).__init__(name)
self._size = register.size()
... | return self._register_fmt[self.size()] % self.value() | conditional_block |
mod.rs | //! Platform-specific extensions to `std` for Windows.
//!
//! Provides access to platform-level information for Windows, and exposes
//! Windows-specific idioms that would otherwise be inappropriate as part
//! the core `std` library. These extensions allow developers to use
//! `std` types and idioms with Windows in ... | #[doc(no_inline)]
#[stable(feature = "file_offset", since = "1.15.0")]
pub use super::fs::FileExt;
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::fs::{MetadataExt, OpenOptionsExt};
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use... | pub mod prelude {
#[doc(no_inline)]
#[stable(feature = "rust1", since = "1.0.0")]
pub use super::ffi::{OsStrExt, OsStringExt}; | random_line_split |
validate.py | from matplotlib import pyplot
from .algo import _bs_fit
def axes_object(ax):
""" Checks if a value if an Axes. If None, a new one is created.
Both the figure and axes are returned (in that order).
"""
if ax is None:
ax = pyplot.gca()
fig = ax.figure
elif isinstance(ax, pyplot.Ax... | (options):
"""
Replaces None with an empty dict for plotting options.
"""
return dict() if options is None else options.copy()
def estimator(value):
if value.lower() in ["res", "resid", "resids", "residual", "residuals"]:
msg = "Bootstrapping the residuals is not ready yet"
raise... | other_options | identifier_name |
validate.py | from matplotlib import pyplot
from .algo import _bs_fit
def axes_object(ax):
""" Checks if a value if an Axes. If None, a new one is created.
Both the figure and axes are returned (in that order).
"""
if ax is None:
ax = pyplot.gca()
fig = ax.figure
elif isinstance(ax, pyplot.Ax... | raise ValueError('estimator must be either "resid" or "fit".')
return est | elif value.lower() in ["fit", "values"]:
est = _bs_fit
else: | random_line_split |
validate.py | from matplotlib import pyplot
from .algo import _bs_fit
def axes_object(ax):
""" Checks if a value if an Axes. If None, a new one is created.
Both the figure and axes are returned (in that order).
"""
if ax is None:
ax = pyplot.gca()
fig = ax.figure
elif isinstance(ax, pyplot.Ax... |
return est
| raise ValueError('estimator must be either "resid" or "fit".') | conditional_block |
validate.py | from matplotlib import pyplot
from .algo import _bs_fit
def axes_object(ax):
""" Checks if a value if an Axes. If None, a new one is created.
Both the figure and axes are returned (in that order).
"""
if ax is None:
ax = pyplot.gca()
fig = ax.figure
elif isinstance(ax, pyplot.Ax... |
def other_options(options):
"""
Replaces None with an empty dict for plotting options.
"""
return dict() if options is None else options.copy()
def estimator(value):
if value.lower() in ["res", "resid", "resids", "residual", "residuals"]:
msg = "Bootstrapping the residuals is not read... | """
Replaces None with an empty string for axis labels.
"""
return "" if label is None else label | identifier_body |
main.rs | extern crate itertools;
extern crate clap;
extern crate rand;
use itertools::Itertools;
use clap::{App, Arg};
use std::fs::File;
use rand::Rng;
use std::io::{Read, Write};
const DEFAULT_CROSSOVER_POINTS: usize = 3;
const DEFAULT_MUTATION_RATE: f64 = 0.001;
const DEFAULT_UNIT: usize = 1;
const DEFAULT_STRIDE: usize = 1... | }
v
},
Err(e) => {
println!("Could not open file \"{}\": {}", filenames.0, e);
return;
},
}, match File::open(filenames.1) {
Ok(mut f) => {
let mut v = Vec::new();
matc... | random_line_split | |
main.rs | extern crate itertools;
extern crate clap;
extern crate rand;
use itertools::Itertools;
use clap::{App, Arg};
use std::fs::File;
use rand::Rng;
use std::io::{Read, Write};
const DEFAULT_CROSSOVER_POINTS: usize = 3;
const DEFAULT_MUTATION_RATE: f64 = 0.001;
const DEFAULT_UNIT: usize = 1;
const DEFAULT_STRIDE: usize = 1... | {
let matches = App::new("matef")
.version("1.0")
.author("Geordon Worley <vadixidav@gmail.com>")
.about("Mates two files")
.arg(Arg::with_name("output")
.help("The output location")
.required(true)
.index(1))
.arg(Arg::with_name("file1")
... | identifier_body | |
main.rs | extern crate itertools;
extern crate clap;
extern crate rand;
use itertools::Itertools;
use clap::{App, Arg};
use std::fs::File;
use rand::Rng;
use std::io::{Read, Write};
const DEFAULT_CROSSOVER_POINTS: usize = 3;
const DEFAULT_MUTATION_RATE: f64 = 0.001;
const DEFAULT_UNIT: usize = 1;
const DEFAULT_STRIDE: usize = 1... | () {
let matches = App::new("matef")
.version("1.0")
.author("Geordon Worley <vadixidav@gmail.com>")
.about("Mates two files")
.arg(Arg::with_name("output")
.help("The output location")
.required(true)
.index(1))
.arg(Arg::with_name("file1"... | main | identifier_name |
regress-900055.js | // Copyright 2008 Google Inc. All Rights Reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions a... |
assertEquals(42, e("42"));
assertEquals(Object, e("Object"));
assertEquals(e, e("e"));
var caught = false;
try {
e('s'); // should throw exception since aliased eval is global
} catch (e) {
caught = true;
assertTrue(e instanceof ReferenceError);
}
assertTrue(caught);
| { return alias(s); } | identifier_body |
regress-900055.js | // Copyright 2008 Google Inc. All Rights Reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions a... | e('s'); // should throw exception since aliased eval is global
} catch (e) {
caught = true;
assertTrue(e instanceof ReferenceError);
}
assertTrue(caught); |
var caught = false;
try { | random_line_split |
regress-900055.js | // Copyright 2008 Google Inc. All Rights Reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions a... | (s) { return alias(s); }
assertEquals(42, e("42"));
assertEquals(Object, e("Object"));
assertEquals(e, e("e"));
var caught = false;
try {
e('s'); // should throw exception since aliased eval is global
} catch (e) {
caught = true;
assertTrue(e instanceof ReferenceError);
}
assertTrue(caught);
| e | identifier_name |
files.py | import hashlib
import os
import random
import time
from django.utils.deconstruct import deconstructible
from django.utils.text import slugify
@deconstructible
class UploadToDir(object):
"""Generates a function to give to ``upload_to`` parameter in
models.Fields, that generates an name for uploaded files bas... | elif self.prefix is not None:
readable_name = f"{self.prefix}{readable_name}"
file_name = "{}.{}".format(readable_name, ext)
return os.path.join(self.path, file_name) | "{}--{}".format(time.time(), random.random()).encode("utf-8")
)
readable_name = random_name.hexdigest() | random_line_split |
files.py | import hashlib
import os
import random
import time
from django.utils.deconstruct import deconstructible
from django.utils.text import slugify
@deconstructible
class UploadToDir(object):
"""Generates a function to give to ``upload_to`` parameter in
models.Fields, that generates an name for uploaded files bas... | (self, path, populate_from=None, prefix=None, random_name=False):
self.path = path
self.populate_from = populate_from
self.random_name = random_name
self.prefix = prefix
def __call__(self, instance, filename):
"""Generates an name for an uploaded file."""
if self.pop... | __init__ | identifier_name |
files.py | import hashlib
import os
import random
import time
from django.utils.deconstruct import deconstructible
from django.utils.text import slugify
@deconstructible
class UploadToDir(object):
"""Generates a function to give to ``upload_to`` parameter in
models.Fields, that generates an name for uploaded files bas... |
if self.random_name:
random_name = hashlib.sha256(
"{}--{}".format(time.time(), random.random()).encode("utf-8")
)
readable_name = random_name.hexdigest()
elif self.prefix is not None:
readable_name = f"{self.prefix}{readable_name}"
... | readable_name = slugify(getattr(instance, self.populate_from)) | conditional_block |
files.py | import hashlib
import os
import random
import time
from django.utils.deconstruct import deconstructible
from django.utils.text import slugify
@deconstructible
class UploadToDir(object):
"""Generates a function to give to ``upload_to`` parameter in
models.Fields, that generates an name for uploaded files bas... | """Generates an name for an uploaded file."""
if self.populate_from is not None and not hasattr(instance, self.populate_from):
raise AttributeError(
"Instance hasn't {} attribute".format(self.populate_from)
)
ext = filename.split(".")[-1]
readable_name = s... | identifier_body | |
build.js | 'use strict';
var path = require('path');
var gulp = require('gulp');
var conf = require('./conf');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
gulp.task('partials', ['clean'], function () {
return gulp.src([
path.join(conf.path... | return gulp.src(path.join(conf.paths.tmp, '/serve/*.html'))
.pipe($.inject(partialsInjectFile, partialsInjectOptions))
.pipe(assets = $.useref.assets())
//.pipe($.rev())
.pipe(jsFilter)
.pipe($.sourcemaps.init())
//.pipe($.uglify({ preserveComments: $.uglifySaveLicense })).on('error', co... | var cssFilter = $.filter('**/*.css', {restore: true});
var assets;
| random_line_split |
typeck-unsafe-always-share.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 ... | test(uns);
let ms = MySync{u: uns};
test(ms);
let ns = NoSync{m: marker::NoSync};
test(ns);
//~^ ERROR `core::kinds::Sync` is not implemented
} | fn main() {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0i)});
test(us);
let uns = UnsafeCell::new(NoSync{m: marker::NoSync}); | random_line_split |
typeck-unsafe-always-share.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 ... |
fn main() {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0i)});
test(us);
let uns = UnsafeCell::new(NoSync{m: marker::NoSync});
test(uns);
let ms = MySync{u: uns};
test(ms);
let ns = NoSync{m: marker::NoSync};
test(ns);
//~^ ERROR `core::kinds::Sync` is not implemented
}
| {
} | identifier_body |
typeck-unsafe-always-share.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 ... | <T> {
u: UnsafeCell<T>
}
struct NoSync {
m: marker::NoSync
}
fn test<T: Sync>(s: T){
}
fn main() {
let us = UnsafeCell::new(MySync{u: UnsafeCell::new(0i)});
test(us);
let uns = UnsafeCell::new(NoSync{m: marker::NoSync});
test(uns);
let ms = MySync{u: uns};
test(ms);
let ns = N... | MySync | identifier_name |
playground.js | const ScratchRender = require('../RenderWebGL');
const getMousePosition = require('./getMousePosition');
const canvas = document.getElementById('scratch-stage');
let fudge = 90;
const renderer = new ScratchRender(canvas);
renderer.setLayerGroupOrdering(['group1']);
const drawableID = renderer.createDrawable('group1')... | renderer.extractColor(mousePos.x, mousePos.y, 30);
});
canvas.addEventListener('click', event => {
const mousePos = getMousePosition(event, canvas);
const pickID = renderer.pick(mousePos.x, mousePos.y);
console.log(`You clicked on ${(pickID < 0 ? 'nothing' : `ID# ${pickID}`)}`);
if (pickID >= 0) {
... | stageScaleInput.addEventListener('change', updateStageScale);
canvas.addEventListener('mousemove', event => {
const mousePos = getMousePosition(event, canvas); | random_line_split |
playground.js | const ScratchRender = require('../RenderWebGL');
const getMousePosition = require('./getMousePosition');
const canvas = document.getElementById('scratch-stage');
let fudge = 90;
const renderer = new ScratchRender(canvas);
renderer.setLayerGroupOrdering(['group1']);
const drawableID = renderer.createDrawable('group1')... |
});
xhr.open('GET', 'https://cdn.assets.scratch.mit.edu/internalapi/asset/b7853f557e4426412e64bb3da6531a99.svg/get/');
xhr.send();
if (wantedSkin === WantedSkinType.pen) {
const penSkinID = renderer.createPenSkin();
renderer.updateDrawableProperties(drawableID2, {
skinId: penSkinID
});
canva... | {
renderer.updateDrawableProperties(drawableID2, {
skinId: skinId
});
} | conditional_block |
run_tests.py | #!/usr/bin/env python
"""Execute the tests for the samcat program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Usage: ... |
else:
failures += 1
print 'FAILED'
# Cleanup.
ph.deleteTempDir()
print '=============================='
print ' total tests: %d' % len(conf_list)
print ' failed tests: %d' % failures
print 'successful tests: %d' % (len(conf_list) - failures)
print '=... | print 'OK' | conditional_block |
run_tests.py | #!/usr/bin/env python
"""Execute the tests for the samcat program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Usage: ... | (source_base, binary_base):
"""Main entry point of the script."""
print 'Executing test for samcat'
print '========================='
print
ph = app_tests.TestPathHelper(
source_base, binary_base,
'apps/samcat/tests') # tests dir
# ============================================... | main | identifier_name |
run_tests.py | #!/usr/bin/env python
"""Execute the tests for the samcat program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Usage: ... | print 'FAILED'
# Cleanup.
ph.deleteTempDir()
print '=============================='
print ' total tests: %d' % len(conf_list)
print ' failed tests: %d' % failures
print 'successful tests: %d' % (len(conf_list) - failures)
print '=============================='
# Comp... | print ' '.join(conf.commandLineArgs())
if res:
print 'OK'
else:
failures += 1 | random_line_split |
run_tests.py | #!/usr/bin/env python
"""Execute the tests for the samcat program.
The golden test outputs are generated by the script generate_outputs.sh.
You have to give the root paths to the source and the binaries as arguments to
the program. These are the paths to the directory that contains the 'projects'
directory.
Usage: ... |
if __name__ == '__main__':
sys.exit(app_tests.main(main))
| """Main entry point of the script."""
print 'Executing test for samcat'
print '========================='
print
ph = app_tests.TestPathHelper(
source_base, binary_base,
'apps/samcat/tests') # tests dir
# ============================================================
# Auto-dete... | identifier_body |
mock_webapp.py | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | (self):
"""Indicates whether the response was an error response."""
return self.status >= 400
def clear(self):
"""Clears all data written to self.out."""
self.out.seek(0)
self.out.truncate(0)
| has_error | identifier_name |
mock_webapp.py | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
if min_value is not None:
value = max(value, min_value)
return value
def set(self, argument_name, value):
"""Sets the value of a query parameter.
Args:
argument_name: The string name of the query parameter.
value: The string value of the query parameter. Pass None to remove
... | value = min(value, max_value) | conditional_block |
mock_webapp.py | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
def set_path(self, value):
self._path = value
self.update_properties()
path = property(get_path, set_path)
def set_url(self, url):
"""Set full URL for the request.
Parses the URL and sets path, scheme, host and parameters correctly.
"""
o = urlparse.urlparse(url)
self.path = o.pat... | return self._path | identifier_body |
mock_webapp.py | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | argument_name: The string name of the query parameter.
value: The string value of the query parameter. Pass None to remove
query parameter.
"""
self.params_list = filter(lambda p: p[0] != argument_name, self.params_list)
if value is not None:
self.params[argument_name] = value
... | Args: | random_line_split |
index.d.ts | // Type definitions for react-router-redux 3.x
// Project: https://github.com/rackt/react-router-redux
// Definitions by: Isman Usoh <http://github.com/isman-usoh>, Noah Shipley <https://github.com/noah79>, Dimitri Rosenberg <https://github.com/rosendi>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped... |
function routeReducer(state?: any, options?: any): Redux.Reducer<any>;
function syncHistory(history: History.History): HistoryMiddleware;
}
export = ReactRouterRedux; | }
interface HistoryMiddleware extends Redux.Middleware {
listenForReplays(store: Redux.Store<any>, selectLocationState?: Function): void;
unsubscribe(): void;
} | random_line_split |
npm.d.ts | import { BowerJson, DistTag, IShellRunOptions, IonicEnvironment, PackageJson } from '../../definitions';
export declare const ERROR_INVALID_PACKAGE_JSON = "INVALID_PACKAGE_JSON";
export declare const ERROR_INVALID_BOWER_JSON = "INVALID_BOWER_JSON";
/**
* Lightweight version of https://github.com/npm/validate-npm-packa... | global?: boolean;
link?: boolean;
save?: boolean;
saveDev?: boolean;
saveExact?: boolean;
}
/**
* Resolves pkg manager intent with command args.
*
* @return Promise<args> If the args is an empty array, it means the pkg manager doesn't have that command.
*/
export declare function pkgManagerArgs(... | export interface PkgManagerOptions extends IShellRunOptions {
command?: 'dedupe' | 'install' | 'uninstall';
pkg?: string; | random_line_split |
exec.rs | #![feature(test)]
extern crate rasen;
extern crate rasen_dsl;
extern crate test;
use rasen_dsl::prelude::*;
use std::f32::consts::PI;
use test::Bencher;
include!("../../tests/dsl.rs");
#[bench]
fn bench_run_basic_frag(b: &mut Bencher) {
b.iter(|| {
basic_frag(
vec3(0.0f32, 1.0f32, 0.0f32),
... | {
b.iter(|| {
functions(Value::of(PI));
});
} | identifier_body | |
exec.rs | #![feature(test)]
extern crate rasen;
extern crate rasen_dsl;
extern crate test;
use rasen_dsl::prelude::*;
use std::f32::consts::PI;
use test::Bencher;
include!("../../tests/dsl.rs");
#[bench]
fn | (b: &mut Bencher) {
b.iter(|| {
basic_frag(
vec3(0.0f32, 1.0f32, 0.0f32),
vec2(0.0f32, 0.0f32),
Value::of(Sampler(Vec4([0.25f32, 0.625f32, 1.0f32, 1.0f32]))),
);
});
}
#[bench]
fn bench_run_basic_vert(b: &mut Bencher) {
b.iter(|| {
let a_pos = vec... | bench_run_basic_frag | identifier_name |
exec.rs | #![feature(test)]
extern crate rasen;
extern crate rasen_dsl;
extern crate test;
use rasen_dsl::prelude::*;
use std::f32::consts::PI;
use test::Bencher;
include!("../../tests/dsl.rs");
#[bench]
fn bench_run_basic_frag(b: &mut Bencher) {
b.iter(|| {
basic_frag(
vec3(0.0f32, 1.0f32, 0.0f32),
... | 1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
]);
#[rustfmt::skip]
let view = Mat4([
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0
... | let a_uv = vec2(0.5f32, 0.5f32);
#[rustfmt::skip]
let projection = Mat4([ | random_line_split |
init.rs | use disk::ahci::Ahci;
use disk::ide::Ide;
use env::Environment;
use schemes::file::FileScheme;
use super::config::PciConfig;
use super::common::class::*;
use super::common::subclass::*;
use super::common::programming_interface::*;
/*
use super::common::vendorid::*;
use super::common::deviceid::*;
use audio::ac97::... | }
}
}
}
} | ((id >> 16) & 0xFFFF) as u16); | random_line_split |
init.rs | use disk::ahci::Ahci;
use disk::ide::Ide;
use env::Environment;
use schemes::file::FileScheme;
use super::config::PciConfig;
use super::common::class::*;
use super::common::subclass::*;
use super::common::programming_interface::*;
/*
use super::common::vendorid::*;
use super::common::deviceid::*;
use audio::ac97::... |
(MASS_STORAGE, SATA, AHCI) => {
if let Some(module) = FileScheme::new(Ahci::disks(pci)) {
env.schemes.lock().push(module);
}
}
/*
(SERIAL_BUS, USB, UHCI) => env.schemes.lock().push(Uhci::new(pci)),
(SERIAL_BUS, USB, OHCI) => env.schemes.lo... | {
if let Some(module) = FileScheme::new(Ide::disks(pci)) {
env.schemes.lock().push(module);
}
} | conditional_block |
init.rs | use disk::ahci::Ahci;
use disk::ide::Ide;
use env::Environment;
use schemes::file::FileScheme;
use super::config::PciConfig;
use super::common::class::*;
use super::common::subclass::*;
use super::common::programming_interface::*;
/*
use super::common::vendorid::*;
use super::common::deviceid::*;
use audio::ac97::... | (env: &mut Environment,
pci: PciConfig,
class_id: u8,
subclass_id: u8,
interface_id: u8,
vendor_code: u16,
device_code: u16) {
match (class_id, subclass_id, interface... | pci_device | identifier_name |
init.rs | use disk::ahci::Ahci;
use disk::ide::Ide;
use env::Environment;
use schemes::file::FileScheme;
use super::config::PciConfig;
use super::common::class::*;
use super::common::subclass::*;
use super::common::programming_interface::*;
/*
use super::common::vendorid::*;
use super::common::deviceid::*;
use audio::ac97::... | {
for bus in 0..256 {
for slot in 0..32 {
for func in 0..8 {
let mut pci = PciConfig::new(bus as u8, slot as u8, func as u8);
let id = pci.read(0);
if (id & 0xFFFF) != 0xFFFF {
let class_id = pci.read(8);
/... | identifier_body | |
index.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Rule, SchematicsException, Tree, UpdateRecorder} from '@angular-devkit/schematics';
import {relative} from 'p... | update.insertLeft(startPos, text);
};
migrateFile(sourceFile, typeChecker, rewriter);
if (update !== null) {
tree.commitUpdate(update);
}
}
} | }
update.remove(startPos, origLength); | random_line_split |
index.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Rule, SchematicsException, Tree, UpdateRecorder} from '@angular-devkit/schematics';
import {relative} from 'p... | {
const {program} = createMigrationProgram(tree, tsconfigPath, basePath);
const typeChecker = program.getTypeChecker();
const sourceFiles =
program.getSourceFiles().filter(sourceFile => canMigrateFile(basePath, sourceFile, program));
for (const sourceFile of sourceFiles) {
let update: UpdateRecorder|... | identifier_body | |
index.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Rule, SchematicsException, Tree, UpdateRecorder} from '@angular-devkit/schematics';
import {relative} from 'p... | (tree: Tree, tsconfigPath: string, basePath: string) {
const {program} = createMigrationProgram(tree, tsconfigPath, basePath);
const typeChecker = program.getTypeChecker();
const sourceFiles =
program.getSourceFiles().filter(sourceFile => canMigrateFile(basePath, sourceFile, program));
for (const sourceF... | runTypedFormsMigration | identifier_name |
index.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Rule, SchematicsException, Tree, UpdateRecorder} from '@angular-devkit/schematics';
import {relative} from 'p... |
for (const tsconfigPath of allPaths) {
runTypedFormsMigration(tree, tsconfigPath, basePath);
}
};
}
function runTypedFormsMigration(tree: Tree, tsconfigPath: string, basePath: string) {
const {program} = createMigrationProgram(tree, tsconfigPath, basePath);
const typeChecker = program.getTypeChec... | {
throw new SchematicsException(
'Could not find any tsconfig file. Cannot migrate to Typed Forms.');
} | conditional_block |
add_to_google_spreadsheet_menu.js | odoo.define('board.AddToGoogleSpreadsheetMenu', function (require) {
"use strict";
var ActionManager = require('web.ActionManager');
var core = require('web.core');
var data = require('web.data');
var Domain = require('web.Domain');
var favorites_submenus_registry = require('web.favorites_submenus_registry');
var pyUt... |
});
},
/**
* Renders the `SearchView.addtogooglespreadsheet` template.
*
* @private
*/
_render: function () {
var $el = QWeb.render('SearchView.addtogooglespreadsheet', {widget: this});
this._replaceElement($el);
},
//--------------------------------... | {
window.open(res.url, '_blank');
} | conditional_block |
add_to_google_spreadsheet_menu.js | odoo.define('board.AddToGoogleSpreadsheetMenu', function (require) {
"use strict";
var ActionManager = require('web.ActionManager');
var core = require('web.core');
var data = require('web.data');
var Domain = require('web.Domain');
var favorites_submenus_registry = require('web.favorites_submenus_registry');
var pyUt... | //--------------------------------------------------------------------------
/**
* @private
* @param {jQueryEvent} event
*/
_onAddToSpreadsheetClick: function (event) {
event.preventDefault();
event.stopPropagation();
this._addToSpreadsheet();
},
});
favorites_... | random_line_split | |
show.js | Slipmat.Views.LabelShow = Backbone.ModularView.extend({
tagName: "main",
className: "group",
template: JST["labels/show"],
initialize: function (options) {
this.router = options.router;
this.listenTo(this.model, "sync change", this.render);
},
events: {
"submit": "addComment"
},
render: ... |
this.listContributors();
this.renderComments();
this.renderRecords();
return this;
},
renderRecords: function () {
var records = this.model.records(),
template = JST["records/_record"],
header = JST["layouts/_paginationHeader"]({ collection: records }),
footer = JST["... | {
$textarea = $('<textarea class="form comment-form">');
this.$("#new-comment").prepend($textarea);
} | conditional_block |
show.js | Slipmat.Views.LabelShow = Backbone.ModularView.extend({
tagName: "main",
className: "group",
template: JST["labels/show"],
initialize: function (options) {
this.router = options.router;
this.listenTo(this.model, "sync change", this.render);
},
events: {
"submit": "addComment"
},
render: ... | renderRecords: function () {
var records = this.model.records(),
template = JST["records/_record"],
header = JST["layouts/_paginationHeader"]({ collection: records }),
footer = JST["layouts/_paginationFooter"]({ collection: records }),
$el = this.$(".content-records");
this.$(... | },
| random_line_split |
GroupQueryTreeRequest.py | # -*- encoding: utf-8 -*-
from supriya.tools import osctools
from supriya.tools.requesttools.Request import Request
class GroupQueryTreeRequest(Request):
r'''A /g_queryTree request.
::
>>> from supriya.tools import requesttools
>>> request = requesttools.GroupQueryTreeRequest(
... ... | (self):
from supriya.tools import requesttools
return requesttools.RequestId.GROUP_QUERY_TREE | request_id | identifier_name |
GroupQueryTreeRequest.py | # -*- encoding: utf-8 -*-
from supriya.tools import osctools
from supriya.tools.requesttools.Request import Request
class GroupQueryTreeRequest(Request):
| r'''A /g_queryTree request.
::
>>> from supriya.tools import requesttools
>>> request = requesttools.GroupQueryTreeRequest(
... node_id=0,
... include_controls=True,
... )
>>> request
GroupQueryTreeRequest(
include_controls=True,
... | identifier_body | |
GroupQueryTreeRequest.py | # -*- encoding: utf-8 -*-
from supriya.tools import osctools
from supriya.tools.requesttools.Request import Request
class GroupQueryTreeRequest(Request):
r'''A /g_queryTree request.
::
>>> from supriya.tools import requesttools
>>> request = requesttools.GroupQueryTreeRequest(
... ... | )
### INITIALIZER ###
def __init__(
self,
include_controls=False,
node_id=None,
):
Request.__init__(self)
self._node_id = node_id
self._include_controls = bool(include_controls)
### PUBLIC METHODS ###
def to_osc_message(self):
r... | '_include_controls',
'_node_id', | random_line_split |
main.rs | // Copyright (c) 2015 Sergey "SnakE" Gromov
//
// See the file license.txt for copying permission.
//! # Radix Conversion Utility
extern crate num;
mod table;
mod convtable;
use std::{env, path};
use num::BigInt;
use convtable::ConvTable;
use std::error::Error;
use num::traits::Num;
fn main() {
let mut table ... | <'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
if s.starts_with(prefix) {
Some(&s[prefix.len()..])
} else {
None
}
}
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn usage(tool: &str) {
println!("\
Display numbers in multiple radii
(c) 2015 Sergey \"SnakE\" Gromov
Versi... | strip_prefix | identifier_name |
main.rs | // Copyright (c) 2015 Sergey "SnakE" Gromov
//
// See the file license.txt for copying permission.
//! # Radix Conversion Utility
extern crate num;
mod table;
mod convtable;
use std::{env, path};
use num::BigInt;
use convtable::ConvTable;
use std::error::Error;
use num::traits::Num;
fn main() {
let mut table ... |
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
fn usage(tool: &str) {
println!("\
Display numbers in multiple radii
(c) 2015 Sergey \"SnakE\" Gromov
Version {}
Usage: {} num [num ...]
num decimal, hex, octal, or binary number
decimal start with a digit
hex start with `0x`
octal s... | {
if s.starts_with(prefix) {
Some(&s[prefix.len()..])
} else {
None
}
} | identifier_body |
main.rs | // Copyright (c) 2015 Sergey "SnakE" Gromov
//
// See the file license.txt for copying permission.
//! # Radix Conversion Utility
extern crate num;
mod table;
mod convtable;
use std::{env, path};
use num::BigInt;
use convtable::ConvTable;
use std::error::Error;
use num::traits::Num;
fn main() {
let mut table ... | match BigInt::from_str_radix(&v, radix) {
Ok(x) => table.push_result(&arg, &x),
Err(e) => table.push_error(&arg, e.description()),
};
}
table.print();
}
/// Return input string without prefix if prefix matches.
fn strip_prefix<'a>(s: &'a str, prefix: &str) -> Option<&'a... | } else {
(&*arg, 10)
};
| random_line_split |
view.rs | /*!
PE view.
*/
use std::prelude::v1::*;
use std::{cmp, slice};
use crate::Result;
use super::image::*;
use super::pe::validate_headers;
use super::{Align, Pe, PeObject};
/// View into a mapped PE image.
#[derive(Copy, Clone)]
pub struct PeView<'a> {
image: &'a [u8],
}
current_target! {
impl PeView<'static> {
... | }
// Clamp to the actual image size...
file_size = cmp::min(file_size, sizeof_image);
// Zero fill the underlying file
let mut vec = vec![0u8; file_size as usize];
// Start by copying the headers
let image = self.image();
unsafe {
// Validated by constructor
let dest_headers = vec.get_unchecked_... | let mut file_size = sizeof_headers;
for section in self.section_headers() {
file_size = cmp::max(file_size, u32::wrapping_add(section.PointerToRawData, section.SizeOfRawData)); | random_line_split |
view.rs | /*!
PE view.
*/
use std::prelude::v1::*;
use std::{cmp, slice};
use crate::Result;
use super::image::*;
use super::pe::validate_headers;
use super::{Align, Pe, PeObject};
/// View into a mapped PE image.
#[derive(Copy, Clone)]
pub struct PeView<'a> {
image: &'a [u8],
}
current_target! {
impl PeView<'static> {
... |
}
vec
}
}
//----------------------------------------------------------------
unsafe impl<'a> Pe<'a> for PeView<'a> {}
unsafe impl<'a> PeObject<'a> for PeView<'a> {
fn image(&self) -> &'a [u8] {
self.image
}
fn align(&self) -> Align {
Align::Section
}
#[cfg(feature = "serde")]
fn serde_name(&self) ->... | {
dest.copy_from_slice(src);
} | conditional_block |
view.rs | /*!
PE view.
*/
use std::prelude::v1::*;
use std::{cmp, slice};
use crate::Result;
use super::image::*;
use super::pe::validate_headers;
use super::{Align, Pe, PeObject};
/// View into a mapped PE image.
#[derive(Copy, Clone)]
pub struct PeView<'a> {
image: &'a [u8],
}
current_target! {
impl PeView<'static> {
... |
}
//----------------------------------------------------------------
#[cfg(feature = "serde")]
impl<'a> serde::Serialize for PeView<'a> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
super::pe::serialize_pe(*self, serializer)
}
}
//--------------------------... | {
"PeView"
} | identifier_body |
view.rs | /*!
PE view.
*/
use std::prelude::v1::*;
use std::{cmp, slice};
use crate::Result;
use super::image::*;
use super::pe::validate_headers;
use super::{Align, Pe, PeObject};
/// View into a mapped PE image.
#[derive(Copy, Clone)]
pub struct PeView<'a> {
image: &'a [u8],
}
current_target! {
impl PeView<'static> {
... | <S: serde::Serializer>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error> {
super::pe::serialize_pe(*self, serializer)
}
}
//----------------------------------------------------------------
#[cfg(test)]
mod tests {
use crate::Error;
use super::PeView;
#[test]
fn from_byte_slice() {
assert!(match ... | serialize | identifier_name |
test_removeSign.py | #!/usr/bin/env python2
##
# autosign
# https://github.com/leosartaj/autosign.git
#
# copyright (c) 2014 sartaj singh
# licensed under the mit license.
##
import unittest
import os, shutil
import helper
from autosign.main import removeSign, isSign
from autosign.exce import UnsignedError
class TestremoveSign(unittest... | (self):
self.dire = os.path.dirname(__file__)
self.signedfile = os.path.join(self.dire, 'testData/toBeSigned.py')
self.signed = os.path.join(self.dire, 'testData/test_signedfile.py')
shutil.copyfile(self.signedfile, self.signed)
self.unsigned = os.path.join(self.dire, 'testData/t... | setUp | identifier_name |
test_removeSign.py | #!/usr/bin/env python2
##
# autosign
# https://github.com/leosartaj/autosign.git
#
# copyright (c) 2014 sartaj singh
# licensed under the mit license.
##
import unittest
import os, shutil
import helper
from autosign.main import removeSign, isSign
from autosign.exce import UnsignedError
class TestremoveSign(unittest... |
def tearDown(self):
os.remove(self.unsigned)
| self.assertTrue(isSign(self.signed, self.options_py))
removeSign(self.signed, self.options_py)
self.assertFalse(isSign(self.signed, self.options_py)) | identifier_body |
test_removeSign.py | #!/usr/bin/env python2
##
# autosign
# https://github.com/leosartaj/autosign.git
#
# copyright (c) 2014 sartaj singh
# licensed under the mit license.
##
| import unittest
import os, shutil
import helper
from autosign.main import removeSign, isSign
from autosign.exce import UnsignedError
class TestremoveSign(unittest.TestCase):
"""
tests the removeSign function in main module
"""
def setUp(self):
self.dire = os.path.dirname(__file__)
self.... | random_line_split | |
xrwebglsubimage.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::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... | fn GetImageIndex(&self) -> Option<u32> {
self.image_index
}
} | random_line_split | |
xrwebglsubimage.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::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... | (&self) -> Option<u32> {
self.image_index
}
}
| GetImageIndex | identifier_name |
xrwebglsubimage.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::codegen::Bindings::XRWebGLSubImageBinding::XRWebGLSubImageBinding::XRWebGLSubImageMetho... |
/// https://immersive-web.github.io/layers/#dom-xrwebglsubimage-imageindex
fn GetImageIndex(&self) -> Option<u32> {
self.image_index
}
}
| {
self.depth_stencil_texture.as_deref().map(DomRoot::from_ref)
} | identifier_body |
test_breakpoint-07.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/**
* Check that setting a breakpoint in a line without code in the second child
* script will skip forward.
*/
var gDebuggee;
var gClient;
var gThreadClient;
function run_test()
{
initTestDebuggerServer(... | {
gThreadClient.addOneTimeListener("paused", function (aEvent, aPacket) {
let path = getFilePath('test_breakpoint-07.js');
let location = { url: path, line: gDebuggee.line0 + 6};
gThreadClient.setBreakpoint(location, function (aResponse, bpClient) {
// Check that the breakpoint has properly skipped ... | identifier_body | |
test_breakpoint-07.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/**
* Check that setting a breakpoint in a line without code in the second child
* script will skip forward.
*/
var gDebuggee;
var gClient;
var gThreadClient;
function | ()
{
initTestDebuggerServer();
gDebuggee = addTestGlobal("test-stack");
gClient = new DebuggerClient(DebuggerServer.connectPipe());
gClient.connect(function () {
attachTestGlobalClientAndResume(gClient,
"test-stack",
function (aResponse... | run_test | identifier_name |
test_breakpoint-07.js | /* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
/**
* Check that setting a breakpoint in a line without code in the second child | var gDebuggee;
var gClient;
var gThreadClient;
function run_test()
{
initTestDebuggerServer();
gDebuggee = addTestGlobal("test-stack");
gClient = new DebuggerClient(DebuggerServer.connectPipe());
gClient.connect(function () {
attachTestGlobalClientAndResume(gClient,
"tes... | * script will skip forward.
*/
| random_line_split |
DraftOffsetKey.js | /**
* Copyright (c) 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @provides... | decoratorKey: parseInt(decoratorKey, 10),
leafKey: parseInt(leafKey, 10),
};
},
};
module.exports = DraftOffsetKey; | blockKey, | random_line_split |
Register_sale.graphql.ts | /* tslint:disable */
import { ReaderFragment } from "relay-runtime";
import { FragmentRefs } from "relay-runtime";
export type Register_sale = {
readonly slug: string;
readonly internalID: string;
readonly status: string | null;
readonly requireIdentityVerification: boolean | null;
readonly " $refT... | },
{
"kind": "ScalarField",
"alias": null,
"name": "status",
"args": null,
"storageKey": null
},
{
"kind": "ScalarField",
"alias": null,
"name": "requireIdentityVerification",
"args": null,
"storageKey": null
}
]
};
(node as any).hash = '... | "name": "internalID",
"args": null,
"storageKey": null | random_line_split |
buildUaBlockRegex.test.ts | import { expect } from '@hapi/code'
import * as Lab from '@hapi/lab'
import { buildUaBlockRegex } from '../../src/modules'
export const lab = Lab.script()
const describe = lab.describe
const it = lab.it | before(() => {
result = buildUaBlockRegex(['A', 'B', 'C'])
})
it('expect a RegEx to be returned', () => {
expect(result).to.exist()
expect(result).to.equal(new RegExp(`^.*(a|b|c).*$`))
})
})
describe('when passing in an empty Array', () => {
let result: RegExp
before(() =... | const before = lab.before
describe('buildUaBlockRegex', () => {
describe('when passing in a valid Array', () => {
let result: RegExp | random_line_split |
thread.rs | use alloc::boxed::Box;
use core::mem;
use system::syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, sys_waitpid, CLONE_VM, CLONE_FS, CLONE_FILES,
TimeSpec};
use time::Duration;
/// An owned permission to join on a thread (block on its termination).
///
/// A `JoinHandle` *detaches* the child th... |
}
/// Sleep for a duration
pub fn sleep(duration: Duration) {
let req = TimeSpec {
tv_sec: duration.as_secs() as i64,
tv_nsec: duration.subsec_nanos() as i32,
};
let mut rem = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
let _ = sys_nanosleep(&req, &mut rem);
}
/// Sleep... | {
let mut status = 0;
match sys_waitpid(self.pid, &mut status, 0) {
Ok(_) => unsafe { *Box::from_raw(self.result_ptr) },
Err(_) => None
}
} | identifier_body |
thread.rs | use alloc::boxed::Box;
use core::mem;
use system::syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, sys_waitpid, CLONE_VM, CLONE_FS, CLONE_FILES,
TimeSpec};
use time::Duration;
/// An owned permission to join on a thread (block on its termination).
///
/// A `JoinHandle` *detaches* the child th... | <F, T>(f: F) -> JoinHandle<T>
where F: FnOnce() -> T,
F: Send + 'static,
T: Send + 'static
{
let result_ptr: *mut Option<T> = Box::into_raw(box None);
//This must only be used by the child
let boxed_f = Box::new(f);
match unsafe { sys_clone(CLONE_VM | CLONE_FS | CLONE_FILES).unw... | spawn | identifier_name |
thread.rs | use alloc::boxed::Box;
use core::mem;
use system::syscall::{sys_clone, sys_exit, sys_yield, sys_nanosleep, sys_waitpid, CLONE_VM, CLONE_FS, CLONE_FILES,
TimeSpec};
use time::Duration;
/// An owned permission to join on a thread (block on its termination).
///
/// A `JoinHandle` *detaches* the child th... | let _ = sys_nanosleep(&req, &mut rem);
}
/// Sleep for a number of milliseconds
pub fn sleep_ms(ms: u32) {
let secs = ms as u64 / 1000;
let nanos = (ms % 1000) * 1000000;
sleep(Duration::new(secs, nanos))
}
/// Spawns a new thread, returning a `JoinHandle` for it.
///
/// The join handle will implicit... | let mut rem = TimeSpec {
tv_sec: 0,
tv_nsec: 0,
};
| random_line_split |
App.js | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import update from 'immutability-helper';
class ListItemBullet extends Component {
render() {
let cssClasses = `listbullet`;
const bulletStyle = {
border: `5px solid ${this.props.color}`,
backgroundColor:... | <div className="App-routemap-div">
<h2>{this.props.title}</h2>
<ul className={cssClasses} style={ulStyle}>
<div style={ulBeforeStyle}></div>
{ renderList(this.props.datalist) }
</ul>
</div>
);
}
}
class App extends Component {
constructor() {
super();
th... |
return ( | random_line_split |
App.js | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import update from 'immutability-helper';
class ListItemBullet extends Component {
render() {
let cssClasses = `listbullet`;
const bulletStyle = {
border: `5px solid ${this.props.color}`,
backgroundColor:... | () {
super();
this.state = {
list_unix: [
{
name: "Git 使用與教學",
url: "https://se101.mtsa.me/Slide/Git/#/"
}
],
'list_system': [
"作業系統概述",
"分散式系統架構",
"Scaling Up"
],
'list_data': [
"大數據分析簡介",
"TensorFlow 簡介",... | constructor | identifier_name |
create_health_report.py | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for adding and editing sheriff rotations."""
from __future__ import print_function
from __future__ import division
from __futur... | table_layout = self.request.get('tableLayout')
override = int(self.request.get('override'))
user = users.get_current_user()
if not name or not master_bot or not tests or not table_layout or not user:
self.response.out.write(json.dumps({
'error': 'Please fill out the form entirely.'
... | name = self.request.get('tableName')
master_bot = self.request.get('tableBots').splitlines()
tests = self.request.get('tableTests').splitlines() | random_line_split |
create_health_report.py | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for adding and editing sheriff rotations."""
from __future__ import print_function
from __future__ import division
from __futur... | (request_handler.RequestHandler):
def get(self):
"""Renders the UI with the form fields."""
self.RenderStaticHtml('create_health_report.html')
def post(self):
"""POSTS the data to the datastore."""
user = users.get_current_user()
if not user:
self.response.out.write(json.dumps({'error':... | CreateHealthReportHandler | identifier_name |
create_health_report.py | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for adding and editing sheriff rotations."""
from __future__ import print_function
from __future__ import division
from __futur... | def get(self):
"""Renders the UI with the form fields."""
self.RenderStaticHtml('create_health_report.html')
def post(self):
"""POSTS the data to the datastore."""
user = users.get_current_user()
if not user:
self.response.out.write(json.dumps({'error': 'User not logged in.'}))
retur... | identifier_body | |
create_health_report.py | # Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provides the web interface for adding and editing sheriff rotations."""
from __future__ import print_function
from __future__ import division
from __futur... |
try:
created_table = table_config.CreateTableConfig(
name=name, bots=master_bot, tests=tests, layout=table_layout,
username=user.email(), override=override)
except table_config.BadRequestError as error:
self.response.out.write(json.dumps({
'error': error.message,
... | self.response.out.write(json.dumps({
'error': 'Please fill out the form entirely.'
}))
return | conditional_block |
Session.ts | import {SessionDao} from "../database/daos/SessionDao"
import {getClient} from "../database/Connection"
import {ISessionRow} from "../models/Session"
import {IUserRow} from "../models/User"
import {Option, some, none} from "../Option"
import * as _ from "lodash"
import * as Promise from "bluebird"
import * as crypto fr... | return session;
}
async function refresh(session: ISessionRow) {
const update = {
valid_until: moment().add(2, "weeks").toISOString()
}
await dao.update(update, "user_id", session.user_id);
return <ISessionRow> _.assign(_.clone(session), update);
}
function isValid(session: ISess... | token: token.toString("hex")
}
await dao.insert(session);
| random_line_split |
Session.ts |
import {SessionDao} from "../database/daos/SessionDao"
import {getClient} from "../database/Connection"
import {ISessionRow} from "../models/Session"
import {IUserRow} from "../models/User"
import {Option, some, none} from "../Option"
import * as _ from "lodash"
import * as Promise from "bluebird"
import * as crypto f... |
}
export async function deleteIfExists(userId: number) {
return dao.delete(userId);
} | {
return none<ISessionRow>();
} | conditional_block |
Session.ts |
import {SessionDao} from "../database/daos/SessionDao"
import {getClient} from "../database/Connection"
import {ISessionRow} from "../models/Session"
import {IUserRow} from "../models/User"
import {Option, some, none} from "../Option"
import * as _ from "lodash"
import * as Promise from "bluebird"
import * as crypto f... | (session: ISessionRow) {
return moment(session.valid_until).isAfter(moment());
}
export async function getOrCreate(user: IUserRow) : Promise<ISessionRow> {
const session = await dao.getById(user.id);
if (session == null) {
return create(user);
}
if (isValid(session)) {
ret... | isValid | identifier_name |
Session.ts |
import {SessionDao} from "../database/daos/SessionDao"
import {getClient} from "../database/Connection"
import {ISessionRow} from "../models/Session"
import {IUserRow} from "../models/User"
import {Option, some, none} from "../Option"
import * as _ from "lodash"
import * as Promise from "bluebird"
import * as crypto f... | {
return dao.delete(userId);
} | identifier_body | |
sequence.rs | use io::fai::FaiRecord;
use sequence::*;
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct FaiSequence {
record: FaiRecord,
filename: PathBuf,
}
impl FaiSequence {
pub fn new<P: AsRe... |
fn length(&self) -> usize {
self.record.length()
}
fn vec(&self) -> Vec<DnaNucleotide> {
self.subsequence(0, self.length()).vec()
}
fn subsequence(&self, offset: usize, length: usize) -> DnaSequence {
let n_lines = offset / self.record.linebases();
let n_bases = of... | }
}
impl Sequence<DnaNucleotide> for FaiSequence {
type SubsequenceType = DnaSequence; | random_line_split |
sequence.rs |
use io::fai::FaiRecord;
use sequence::*;
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct FaiSequence {
record: FaiRecord,
filename: PathBuf,
}
impl FaiSequence {
pub fn new<P: AsR... |
fn vec(&self) -> Vec<DnaNucleotide> {
self.subsequence(0, self.length()).vec()
}
fn subsequence(&self, offset: usize, length: usize) -> DnaSequence {
let n_lines = offset / self.record.linebases();
let n_bases = offset - (n_lines * self.record.linebases());
let file_offset... | {
self.record.length()
} | identifier_body |
sequence.rs |
use io::fai::FaiRecord;
use sequence::*;
use std::fmt;
use std::fs::File;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::path::Path;
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct | {
record: FaiRecord,
filename: PathBuf,
}
impl FaiSequence {
pub fn new<P: AsRef<Path>>(record: FaiRecord, filename: &P) -> FaiSequence {
FaiSequence {
record: record,
filename: filename.as_ref().to_path_buf(),
}
}
}
impl Sequence<DnaNucleotide> for FaiSequence... | FaiSequence | identifier_name |
Battery20Rounded.js | import React from 'react'; |
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M7 17v3.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V17H7z" /><path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V3c0-.55-.45-1-1-1h-2c-.55 0-1 .45-1 1v1H8.33C7.6 4 7 4.6 7 5.33V17h10V5.33z" /></g></Rea... | import createSvgIcon from './utils/createSvgIcon'; | random_line_split |
MapScreen.js | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
// import {Map, InfoWindow, Marker, Polygon, GoogleApiWrapper} from 'google-maps-react';
import history from '../history';
import { poiClusters } from '../Config/sampleMapClusters';
import appConfig from '../Config/params';
import MapComponent... | {
return POIClustersData[i];
}
else
{
return tmpFlag;
}
}
/**
* Check if point(latlong object) is inside polygon
* Returns boolean true or false
*/
pointInPoly(point, polygon) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Resea... | }
}
if(tmpFlag) | random_line_split |
MapScreen.js | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
// import {Map, InfoWindow, Marker, Polygon, GoogleApiWrapper} from 'google-maps-react';
import history from '../history';
import { poiClusters } from '../Config/sampleMapClusters';
import appConfig from '../Config/params';
import MapComponent... |
if(tmpFlag)
{
return POIClustersData[i];
}
else
{
return tmpFlag;
}
}
/**
* Check if point(latlong object) is inside polygon
* Returns boolean true or false
*/
pointInPoly(point, polygon) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Ho... | {
tmpFlag = this.pointInPoly(point, POIClustersData[i].polygonOverlay.coordinates);
if(tmpFlag)
{
break;
}
} | conditional_block |
MapScreen.js | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
// import {Map, InfoWindow, Marker, Polygon, GoogleApiWrapper} from 'google-maps-react';
import history from '../history';
import { poiClusters } from '../Config/sampleMapClusters';
import appConfig from '../Config/params';
import MapComponent... |
componentWillMount() {
fetch(appConfig.app.API_BASE_URL+'clusters')
.then(response => response.json(true))
.then((responseData) => {
// console.log(JSON.parse(responseData.body));
// venue.showInMap = "Yes"
let apiResponseData = JSON.parse(responseData.body);
let all... | {
super(props);
// const window_google_instance = this.props.google;
this.state = { width: '0', height: '0' };
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
this.mapMarkers = this.parseMarkers();
this.state.mapDataLoaded = false;
this.state.mapMarkersData = [];
... | identifier_body |
MapScreen.js | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
// import {Map, InfoWindow, Marker, Polygon, GoogleApiWrapper} from 'google-maps-react';
import history from '../history';
import { poiClusters } from '../Config/sampleMapClusters';
import appConfig from '../Config/params';
import MapComponent... | (inputCoordinates)
{
let tmpData = [];
for (let j = 0; j < inputCoordinates.length; j++) {
tmpData.push({
lat: inputCoordinates[j].latitude,
lng: inputCoordinates[j].longitude
});
}
return tmpData;
}
val2key(val,array){
for (var key in array) {
let thi... | transformClusterCoordinates | identifier_name |
index.d.ts | // Type definitions for bell 9.3
// Project: https://github.com/hapijs/bell
// Definitions by: Simon Schick <https://github.com/SimonSchick>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.8
import { Server, Request, Plugin, AuthCredentials } from 'hapi';
declare module 'ha... | 'arcgisonline' |
'auth0' |
'azuread' |
'bitbucket' |
'digitalocean' |
'discord' |
'dropbox' |
'dropboxV2' |
'facebook' |
'fitbit' |
'foursquare' |
'github' |
'gitlab' |
'google' |
'googleplus' |
'instagram' |
'linkedin' |
'live' |
'medium' |
'meetup' |
'mixer' |
'nest' |
'o... | export type Provider = | random_line_split |
blocked.js | var blockedModule = {
find: function (UserBlocked, user, blocked) {
return UserBlocked.findOne({
or: [{
user: user.id,
blocked: blocked.id
}, {
blocked: user.id,
user: blocked.id
}]
});
},
isUserBlocked: function (UserBlocked, user, blocked) {
return b... |
return UserBlocked.create({
user: user.id,
blocked: blocked.id
}).then(function (created) {
return created;
});
});
},
remove: function (UserBlocked, user, blocked) {
return UserBlocked.destroy({
user: user.id,
blocked: blocked.id
});
}
};
module... | {
return found;
} | conditional_block |
blocked.js | var blockedModule = {
find: function (UserBlocked, user, blocked) {
return UserBlocked.findOne({
or: [{
user: user.id, | blocked: user.id,
user: blocked.id
}]
});
},
isUserBlocked: function (UserBlocked, user, blocked) {
return blockedModule.find(UserBlocked, user, blocked).then(function (found) {
return found;
});
},
create: function (UserBlocked, user, blocked) {
return blockedModule.... | blocked: blocked.id
}, { | random_line_split |
HypothermicPresence.tsx | import React from "react";
import Analyzer, { Options } from "parser/core/Analyzer";
import SPELLS from "common/SPELLS";
import Statistic from "parser/ui/Statistic";
import { STATISTIC_ORDER } from "parser/ui/StatisticBox";
import BoringSpellValue from "parser/ui/BoringSpellValue";
import RunicPowerTracker from "../... |
}
statistic() {
return (
<Statistic
position={STATISTIC_ORDER.OPTIONAL(50)}
size="flexible"
>
<BoringSpellValue
spell={SPELLS.HYPOTHERMIC_PRESENCE_TALENT}
value={`${this.runicPowerTracker.totalHypothermicPresenceReduction}`}
label="Runic Power save... | {
return;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.