file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
Dashboard.tsx | import * as React from 'react';
import { experimentalStyled as styled } from '@material-ui/core/styles';
import CssBaseline from '@material-ui/core/CssBaseline';
import MuiDrawer from '@material-ui/core/Drawer';
import Box from '@material-ui/core/Box';
import MuiAppBar, { AppBarProps as MuiAppBarProps } from '@material... |
const drawerWidth: number = 240;
interface AppBarProps extends MuiAppBarProps {
open?: boolean;
}
const AppBar = styled(MuiAppBar, {
shouldForwardProp: (prop) => prop !== 'open',
})<AppBarProps>(({ theme, open }) => ({
zIndex: theme.zIndex.drawer + 1,
transition: theme.transitions.create(['width', 'margin'],... | {
return (
<Typography variant="body2" color="text.secondary" align="center" {...props}>
{'Copyright © '}
<Link color="inherit" href="https://material-ui.com/">
Your Website
</Link>{' '}
{new Date().getFullYear()}
{'.'}
</Typography>
);
}
| identifier_body |
namespace-internal.ts | import defaultDictionary from './locales/en/messages.json';
import { DictNamespaces } from '../../types-internal/i18n-internal-namespace';
import { isObject, isString } from '../utils';
/**
* Evaluate messages dictionary and return object for namespace chaining
*
* @param dict - Messages dictionary
* @param [keyPa... | }
return;
}
result[key] = section;
});
return result as DictNamespaces<typeof defaultDictionary>;
}
/**
* Type safe access to the internal messages dictionary sections
*
* @example I18n.ui(I18nInternalNS.ui.blockTunes.toggler, 'Click to tune');
*/
export const I18nInternalNS = getNamespa... | random_line_split | |
namespace-internal.ts | import defaultDictionary from './locales/en/messages.json';
import { DictNamespaces } from '../../types-internal/i18n-internal-namespace';
import { isObject, isString } from '../utils';
/**
* Evaluate messages dictionary and return object for namespace chaining
*
* @param dict - Messages dictionary
* @param [keyPa... | */
if (isLastSection) {
result[key] = newPath;
} else {
result[key] = getNamespaces(section, newPath);
}
return;
}
result[key] = section;
});
return result as DictNamespaces<typeof defaultDictionary>;
}
/*
*
* Type safe access to the internal messages dict... | {
const result = {};
Object.entries(dict).forEach(([key, section]) => {
if (isObject(section)) {
const newPath = keyPath ? `${keyPath}.${key}` : key;
/**
* Check current section values, if all of them are strings, so there is the last section
*/
const isLastSection = Object.val... | identifier_body |
namespace-internal.ts | import defaultDictionary from './locales/en/messages.json';
import { DictNamespaces } from '../../types-internal/i18n-internal-namespace';
import { isObject, isString } from '../utils';
/**
* Evaluate messages dictionary and return object for namespace chaining
*
* @param dict - Messages dictionary
* @param [keyPa... | e {
result[key] = getNamespaces(section, newPath);
}
return;
}
result[key] = section;
});
return result as DictNamespaces<typeof defaultDictionary>;
}
/**
* Type safe access to the internal messages dictionary sections
*
* @example I18n.ui(I18nInternalNS.ui.blockTunes.toggler, 'Cl... | result[key] = newPath;
} els | conditional_block |
namespace-internal.ts | import defaultDictionary from './locales/en/messages.json';
import { DictNamespaces } from '../../types-internal/i18n-internal-namespace';
import { isObject, isString } from '../utils';
/**
* Evaluate messages dictionary and return object for namespace chaining
*
* @param dict - Messages dictionary
* @param [keyPa... | (dict: object, keyPath?: string): DictNamespaces<typeof defaultDictionary> {
const result = {};
Object.entries(dict).forEach(([key, section]) => {
if (isObject(section)) {
const newPath = keyPath ? `${keyPath}.${key}` : key;
/**
* Check current section values, if all of them are strings, so... | getNamespaces | identifier_name |
setup.py | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
def readfile(fn):
|
setup(
name="usfm2osis",
packages=find_packages(exclude=["tests*"]),
version="0.6.1",
description="Tools for converting Bibles from USFM to OSIS XML",
author="Christopher C. Little",
author_email="chrisclittle+usfm2osis@gmail.com",
url="https://github.com/chrislit/usfm2osis",
download... | """Read fn and return the contents."""
with open(path.join(here, fn), "r", encoding="utf-8") as f:
return f.read() | identifier_body |
setup.py | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
|
def readfile(fn):
"""Read fn and return the contents."""
with open(path.join(here, fn), "r", encoding="utf-8") as f:
return f.read()
setup(
name="usfm2osis",
packages=find_packages(exclude=["tests*"]),
version="0.6.1",
description="Tools for converting Bibles from USFM to OSIS XML",
... | random_line_split | |
setup.py | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
def | (fn):
"""Read fn and return the contents."""
with open(path.join(here, fn), "r", encoding="utf-8") as f:
return f.read()
setup(
name="usfm2osis",
packages=find_packages(exclude=["tests*"]),
version="0.6.1",
description="Tools for converting Bibles from USFM to OSIS XML",
author="Ch... | readfile | identifier_name |
run.py | import ConfigParser
import sys, traceback
from slackclient import SlackClient | from chatterbot import ChatBot
import os
from os import listdir
from os.path import isfile, join
from chatterbot.trainers import ChatterBotCorpusTrainer
config = ConfigParser.SafeConfigParser({"host": "searchhub.lucidworks.com", "port":80})
config.read('config.cfg')
token = config.get("Slack", "token") # found ... | random_line_split | |
run.py | import ConfigParser
import sys, traceback
from slackclient import SlackClient
from chatterbot import ChatBot
import os
from os import listdir
from os.path import isfile, join
from chatterbot.trainers import ChatterBotCorpusTrainer
config = ConfigParser.SafeConfigParser({"host": "searchhub.lucidworks.com", "port":... |
storage = config.get("Chatterbot", "storage_dir")
if not os.path.exists(storage):
os.makedirs(storage)
bot_name = config.get("Slack", "bot_name")
print "Starting Slack"
sc = SlackClient(token)
print "Starting Chatterbot"
chatbot = ChatBot(bot_name, storage_adapter="chatterbot.adapters.storage.JsonDatabaseAdapte... | channels = channel_str.split(",")
for channel in channels:
#print channel
channel_names.append(channel) | conditional_block |
calculate_distances.py | import math
from numba import njit
from tardis.montecarlo.montecarlo_numba import (
njit_dict_no_parallel,
)
import tardis.montecarlo.montecarlo_numba.numba_config as nc
from tardis.montecarlo.montecarlo_numba.numba_config import (
C_SPEED_OF_LIGHT,
MISS_DISTANCE,
SIGMA_THOMSON,
CLOSE_LINE_THRESH... | (electron_density, tau_event):
"""
Calculate distance to Thomson Scattering
Parameters
----------
electron_density : float
tau_event : float
"""
# add full_relativity here
return tau_event / (electron_density * SIGMA_THOMSON)
| calculate_distance_electron | identifier_name |
calculate_distances.py | import math
from numba import njit
from tardis.montecarlo.montecarlo_numba import (
njit_dict_no_parallel,
)
import tardis.montecarlo.montecarlo_numba.numba_config as nc
from tardis.montecarlo.montecarlo_numba.numba_config import (
C_SPEED_OF_LIGHT,
MISS_DISTANCE,
SIGMA_THOMSON,
CLOSE_LINE_THRESH... | # hit inner boundary
distance = -r * mu - math.sqrt(check)
delta_shell = -1
else:
# miss inner boundary
distance = math.sqrt(
r_outer * r_outer + ((mu * mu - 1.0) * r * r)
) - (r * mu)
delta_shell = 1
return... | if check >= 0.0: | random_line_split |
calculate_distances.py | import math
from numba import njit
from tardis.montecarlo.montecarlo_numba import (
njit_dict_no_parallel,
)
import tardis.montecarlo.montecarlo_numba.numba_config as nc
from tardis.montecarlo.montecarlo_numba.numba_config import (
C_SPEED_OF_LIGHT,
MISS_DISTANCE,
SIGMA_THOMSON,
CLOSE_LINE_THRESH... |
if nc.ENABLE_FULL_RELATIVITY:
return calculate_distance_line_full_relativity(
nu_line, nu, time_explosion, r_packet
)
return distance
@njit(**njit_dict_no_parallel)
def calculate_distance_line_full_relativity(
nu_line, nu, time_explosion, r_packet
):
# distance = - mu * r... | raise MonteCarloException(
"nu difference is less than 0.0"
) | conditional_block |
calculate_distances.py | import math
from numba import njit
from tardis.montecarlo.montecarlo_numba import (
njit_dict_no_parallel,
)
import tardis.montecarlo.montecarlo_numba.numba_config as nc
from tardis.montecarlo.montecarlo_numba.numba_config import (
C_SPEED_OF_LIGHT,
MISS_DISTANCE,
SIGMA_THOMSON,
CLOSE_LINE_THRESH... | """
Calculate distance to Thomson Scattering
Parameters
----------
electron_density : float
tau_event : float
"""
# add full_relativity here
return tau_event / (electron_density * SIGMA_THOMSON) | identifier_body | |
wish.py | #
# My wish for Pynamite
#
from __future__ import with_statement
from pynamite import *
from pynamite.actor import TextBox
def scene1():
# define some actors
x = TextBox("Pynamite")
y = TextBox("Rocks!!!")
# tell the first actor to enter
enter(x)
# wait for a keypress to continue
pause(... |
in_parallel(together)
# wait for intput
pause()
# last actor leaves
fadeout(1.0,y)
pause()
# add that scene to the play
add_scene(scene1)
def scene2():
# define the actor
x = TextBox("Yes, it Rocks!!!")
# set its opacity to 0.0
set_var(x, "opacity", 0.0)
# have it e... | fadeout(4.0,x)
with serial():
linear(y, "opacity", end_val=.5, duration=1.0)
linear(y, "opacity", end_val=.0, duration=1.0)
linear(y, "opacity", end_val=1.0, duration=2.0)
#fadeout(.5,y)
#fadein(.5,y) | identifier_body |
wish.py | #
# My wish for Pynamite
#
from __future__ import with_statement
from pynamite import *
from pynamite.actor import TextBox
def scene1():
# define some actors
x = TextBox("Pynamite")
y = TextBox("Rocks!!!")
# tell the first actor to enter
enter(x)
# wait for a keypress to continue
pause(... | ():
fadeout(4.0,x)
with serial():
linear(y, "opacity", end_val=.5, duration=1.0)
linear(y, "opacity", end_val=.0, duration=1.0)
linear(y, "opacity", end_val=1.0, duration=2.0)
#fadeout(.5,y)
#fadein(.5,y)
in_parallel(together)
# wait f... | together | identifier_name |
wish.py | #
# My wish for Pynamite
#
from __future__ import with_statement
from pynamite import *
from pynamite.actor import TextBox
def scene1():
# define some actors
x = TextBox("Pynamite")
y = TextBox("Rocks!!!")
# tell the first actor to enter
enter(x)
# wait for a keypress to continue
pause(... |
# have the actor leave
leave()
# add this scene
add_scene(scene2)
# run it
run() | smooth(x, "opacity", end_val=.5,duration=.25)
smooth(x, "opacity", end_val=1.0,duration=.5)
# wait for input
pause() | random_line_split |
check.versions.ts | import {VERSION_NPM, VERSION_NODE} from '../config';
function reportError(message: string) {
console.error(require('chalk').white.bgRed.bold(message));
process.exit(1);
}
module.exports = function check(gulp, plugins) {
return function () {
let exec = require('child_process').exec;
let semver = require(... | }
});
exec('node --version',
function (error, stdout, stderr) {
if (error !== null) {
reportError('npm preinstall error: ' + error + stderr);
}
if (!semver.gte(stdout, VERSION_NODE)) {
reportError('NODE is not in required version! Required is ' + VER... | }
if (!semver.gte(stdout, VERSION_NPM)) {
reportError('NPM is not in required version! Required is ' + VERSION_NPM + ' and you\'re using ' + stdout); | random_line_split |
check.versions.ts | import {VERSION_NPM, VERSION_NODE} from '../config';
function reportError(message: string) |
module.exports = function check(gulp, plugins) {
return function () {
let exec = require('child_process').exec;
let semver = require('semver');
exec('npm --version',
function (error, stdout, stderr) {
if (error !== null) {
reportError('npm preinstall error: ' + error + stderr);
... | {
console.error(require('chalk').white.bgRed.bold(message));
process.exit(1);
} | identifier_body |
check.versions.ts | import {VERSION_NPM, VERSION_NODE} from '../config';
function reportError(message: string) {
console.error(require('chalk').white.bgRed.bold(message));
process.exit(1);
}
module.exports = function check(gulp, plugins) {
return function () {
let exec = require('child_process').exec;
let semver = require(... |
});
};
};
| {
reportError('NODE is not in required version! Required is ' + VERSION_NODE + ' and you\'re using ' + stdout);
} | conditional_block |
check.versions.ts | import {VERSION_NPM, VERSION_NODE} from '../config';
function | (message: string) {
console.error(require('chalk').white.bgRed.bold(message));
process.exit(1);
}
module.exports = function check(gulp, plugins) {
return function () {
let exec = require('child_process').exec;
let semver = require('semver');
exec('npm --version',
function (error, stdout, stder... | reportError | identifier_name |
spinner.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
use gobject_ffi;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner>): Widget;
match fn {
... | (&self) {
unsafe {
ffi::gtk_spinner_start(self.to_glib_none().0);
}
}
fn stop(&self) {
unsafe {
ffi::gtk_spinner_stop(self.to_glib_none().0);
}
}
fn get_property_active(&self) -> bool {
let mut value = Value::from(&false);
unsafe ... | start | identifier_name |
spinner.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
use gobject_ffi;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner>): Widget;
match fn {
... |
}
pub trait SpinnerExt {
fn start(&self);
fn stop(&self);
fn get_property_active(&self) -> bool;
fn set_property_active(&self, active: bool);
}
impl<O: IsA<Spinner> + IsA<glib::object::Object>> SpinnerExt for O {
fn start(&self) {
unsafe {
ffi::gtk_spinner_start(self.to_gli... | {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spinner_new()).downcast_unchecked()
}
} | identifier_body |
spinner.rs | // This file was generated by gir (5c017c9) from gir-files (71d73f0)
// DO NOT EDIT
use Widget;
use ffi;
use glib;
use glib::Value;
use glib::object::Downcast;
use glib::object::IsA;
use glib::translate::*;
use gobject_ffi;
glib_wrapper! {
pub struct Spinner(Object<ffi::GtkSpinner>): Widget;
match fn {
... | let mut value = Value::from(&false);
unsafe {
gobject_ffi::g_object_get_property(self.to_glib_none().0, "active".to_glib_none().0, value.to_glib_none_mut().0);
}
value.get().unwrap()
}
fn set_property_active(&self, active: bool) {
unsafe {
gobject... | random_line_split | |
ToolbarTest.ts | import { ApproxStructure, Assertions, FocusTools, GeneralSteps, Keyboard, Keys, Logger, Step } from '@ephox/agar';
import { AlloyComponent, Behaviour, Focusing, GuiFactory, Keying, TestHelpers, Toolbar } from '@ephox/alloy';
import { UnitTest } from '@ephox/bedrock';
import { Arr, Option, Result } from '@ephox/katamari... | }); | success,
failure
); | random_line_split |
session.py | # Copyright (C) 2008, Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... | def shutdown_completed(self):
if env.is_emulator():
self._close_emulator()
elif self._logout_mode != self.MODE_LOGOUT:
bus = dbus.SystemBus()
if have_systemd():
try:
proxy = bus.get_object('org.freedesktop.login1',
... | MODE_LOGOUT = 0
MODE_SHUTDOWN = 1
MODE_REBOOT = 2
def __init__(self):
session.SessionManager.__init__(self)
self._logout_mode = None
def logout(self):
self._logout_mode = self.MODE_LOGOUT
self.initiate_shutdown()
def shutdown(self):
self._logout_mode = self... | identifier_body |
session.py | # Copyright (C) 2008, Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... | (self):
Gtk.main_quit()
if 'SUGAR_EMULATOR_PID' in os.environ:
pid = int(os.environ['SUGAR_EMULATOR_PID'])
os.kill(pid, signal.SIGTERM)
# Need to call this ASAP so the atexit handlers get called before we
# get killed by the X (dis)connection
sys.exit()
... | _close_emulator | identifier_name |
session.py | # Copyright (C) 2008, Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... |
_session_manager = None
def have_systemd():
return os.access("/run/systemd/seats", 0) >= 0
class SessionManager(session.SessionManager):
MODE_LOGOUT = 0
MODE_SHUTDOWN = 1
MODE_REBOOT = 2
def __init__(self):
session.SessionManager.__init__(self)
self._logout_mode = None
de... | import sys
import logging
from sugar3 import session
from sugar3 import env | random_line_split |
session.py | # Copyright (C) 2008, Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in... |
session.SessionManager.shutdown_completed(self)
Gtk.main_quit()
def _close_emulator(self):
Gtk.main_quit()
if 'SUGAR_EMULATOR_PID' in os.environ:
pid = int(os.environ['SUGAR_EMULATOR_PID'])
os.kill(pid, signal.SIGTERM)
# Need to call this ASAP so ... | CONSOLEKIT_DBUS_PATH = '/org/freedesktop/ConsoleKit/Manager'
try:
proxy = bus.get_object('org.freedesktop.ConsoleKit',
CONSOLEKIT_DBUS_PATH)
pm = dbus.Interface(proxy,
'org.freedesk... | conditional_block |
issue-2936.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | {
let x: isize = foo::<isize, cbar>(cbar(5));
assert_eq!(x, 5);
} | identifier_body | |
issue-2936.rs | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or ... | () {
let x: isize = foo::<isize, cbar>(cbar(5));
assert_eq!(x, 5);
}
| main | identifier_name |
issue-2936.rs | // Copyright 2012 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 ... | struct cbar {
x: isize,
}
impl bar<isize> for cbar {
fn get_bar(&self) -> isize {
self.x
}
}
fn cbar(x: isize) -> cbar {
cbar {
x: x
}
}
pub fn main() {
let x: isize = foo::<isize, cbar>(cbar(5));
assert_eq!(x, 5);
} | random_line_split | |
auto-generate-readme.py | from pathlib import Path
class MarkdownParser():
| start = (f'{mark} {name}' in line)
if start:
end = False
if include_header:
content.append(line)
content = '\n'.join(content)
return content
def overview(self):
overview = self.header('Overview'... | def __init__(self, text):
self.text = text
self.lines = text.split('\n')
def title(self):
return self.lines[0].split(' ')[1]
def header(self, name, level, include_header=False):
start = False
end = False
content = []
mark = '#' * level
for line i... | identifier_body |
auto-generate-readme.py | from pathlib import Path
class MarkdownParser():
def __init__(self, text):
self.text = text
self.lines = text.split('\n')
def title(self):
return self.lines[0].split(' ')[1]
def header(self, name, level, include_header=False):
start = False
end = False
co... |
else:
content.append(line)
else:
start = (f'{mark} {name}' in line)
if start:
end = False
if include_header:
content.append(line)
content = '\n'.join(content)
... | start = False | conditional_block |
auto-generate-readme.py | from pathlib import Path
class | ():
def __init__(self, text):
self.text = text
self.lines = text.split('\n')
def title(self):
return self.lines[0].split(' ')[1]
def header(self, name, level, include_header=False):
start = False
end = False
content = []
mark = '#' * level
f... | MarkdownParser | identifier_name |
auto-generate-readme.py | from pathlib import Path
class MarkdownParser():
def __init__(self, text):
self.text = text
self.lines = text.split('\n')
def title(self):
return self.lines[0].split(' ')[1]
def header(self, name, level, include_header=False):
start = False
end = False
co... | text = text.replace('# C++\n', f'# C++{title}\n')
text = text.replace(f'<!-- overview -->', overview)
text = text.replace(f'<!-- features -->', features)
return text
def main():
src_dir = Path(__file__).parent
parsers = []
srcs = list(src_dir.glob('CPP*.md'))
srcs.sort(reverse=True)
... | random_line_split | |
conftest.py | # -*- coding: utf-8 -*-
"""Defines fixtures available to all tests."""
import pytest
from webtest import TestApp
from p101stat.app import create_app
from p101stat.database import db as _db
from p101stat.settings import TestConfig
from .factories import IdolFactory
@pytest.yield_fixture(scope='function')
def app():... |
@pytest.fixture(scope='function')
def testapp(app):
"""A Webtest app."""
return TestApp(app)
@pytest.yield_fixture(scope='function')
def db(app):
"""A database for the tests."""
_db.app = app
with app.app_context():
_db.create_all()
yield _db
# Explicitly close DB connection
... | """An application for the tests."""
_app = create_app(TestConfig)
ctx = _app.test_request_context()
ctx.push()
yield _app
ctx.pop() | identifier_body |
conftest.py | # -*- coding: utf-8 -*-
"""Defines fixtures available to all tests."""
import pytest
from webtest import TestApp
from p101stat.app import create_app
from p101stat.database import db as _db
from p101stat.settings import TestConfig
from .factories import IdolFactory
@pytest.yield_fixture(scope='function')
def app():... |
# Explicitly close DB connection
_db.session.close()
_db.drop_all()
@pytest.fixture
def idol(db):
"""A idol for the tests."""
idol = IdolFactory()
db.session.commit()
return idol | random_line_split | |
conftest.py | # -*- coding: utf-8 -*-
"""Defines fixtures available to all tests."""
import pytest
from webtest import TestApp
from p101stat.app import create_app
from p101stat.database import db as _db
from p101stat.settings import TestConfig
from .factories import IdolFactory
@pytest.yield_fixture(scope='function')
def app():... | (app):
"""A Webtest app."""
return TestApp(app)
@pytest.yield_fixture(scope='function')
def db(app):
"""A database for the tests."""
_db.app = app
with app.app_context():
_db.create_all()
yield _db
# Explicitly close DB connection
_db.session.close()
_db.drop_all()
@pyt... | testapp | identifier_name |
enumvalues_2.js | var searchData=
[
['call_5factive',['CALL_ACTIVE',['../client__channel_8c.html#a6ca2e6dbf0562417ab7c66e8907a56b1a38c567ba414b95843eea67ead22156b9',1,'client_channel.c']]],
['call_5fcancelled',['CALL_CANCELLED',['../client__channel_8c.html#a6ca2e6dbf0562417ab7c66e8907a56b1a64c64130e25c5cd2d884b8c16093a89d',1,'client... | ['census_5ffeature_5fstats',['CENSUS_FEATURE_STATS',['../census_8h.html#abe92e59c22481b0de3742673cbbb1bf8a84c772b868e53ee3487c7bfc8e8b2f1a',1,'census.h']]],
['census_5ffeature_5ftracing',['CENSUS_FEATURE_TRACING',['../census_8h.html#abe92e59c22481b0de3742673cbbb1bf8ab0722326e730113d5be97f643c3e6718',1,'census.h']]]... | ['census_5ffeature_5fnone',['CENSUS_FEATURE_NONE',['../census_8h.html#abe92e59c22481b0de3742673cbbb1bf8aac1986834f37851b8d899c4a08c8e3ab',1,'census.h']]], | random_line_split |
resourceImage.js | import React from 'react'
import { randomColorFor } from '../../utils.js'
import ImageLoadMixin from '../../lib/imageLoadMixin.js'
const ResourceImage = React.createClass({
mixins: [ImageLoadMixin],
propTypes () {
return {
resource: React.PropTypes.object.isRequired | }
},
getInitialState () {
return {
showPlaceholder: true
}
},
componentDidMount () {
// If depiction url loads, hide placeholder
this.loadImage(this.props.resource.depiction, (img) => this.setState({ showPlaceholder: false }))
},
render () {
var style = { position: 'relative... | random_line_split | |
resourceImage.js | import React from 'react'
import { randomColorFor } from '../../utils.js'
import ImageLoadMixin from '../../lib/imageLoadMixin.js'
const ResourceImage = React.createClass({
mixins: [ImageLoadMixin],
propTypes () {
return {
resource: React.PropTypes.object.isRequired
}
},
getInitialState () {
... |
var placeholderImage = this.state.showPlaceholder ? <span style={styleLionColor} className='lg-icon nypl-icon-logo-mark agent-listing-image-placeholder'></span> : null
return <div className={this.props.className} style={style}>{placeholderImage}</div>
}
})
export default ResourceImage
| {
style = { background: 'url(' + this.props.resource.depiction + ')', position: 'relative' }
} | conditional_block |
resourceImage.js | import React from 'react'
import { randomColorFor } from '../../utils.js'
import ImageLoadMixin from '../../lib/imageLoadMixin.js'
const ResourceImage = React.createClass({
mixins: [ImageLoadMixin],
propTypes () {
return {
resource: React.PropTypes.object.isRequired
}
},
getInitialState () | ,
componentDidMount () {
// If depiction url loads, hide placeholder
this.loadImage(this.props.resource.depiction, (img) => this.setState({ showPlaceholder: false }))
},
render () {
var style = { position: 'relative', backgroundSize: 'cover' }
var styleLionColor = { color: randomColorFor(this.pr... | {
return {
showPlaceholder: true
}
} | identifier_body |
resourceImage.js | import React from 'react'
import { randomColorFor } from '../../utils.js'
import ImageLoadMixin from '../../lib/imageLoadMixin.js'
const ResourceImage = React.createClass({
mixins: [ImageLoadMixin],
| () {
return {
resource: React.PropTypes.object.isRequired
}
},
getInitialState () {
return {
showPlaceholder: true
}
},
componentDidMount () {
// If depiction url loads, hide placeholder
this.loadImage(this.props.resource.depiction, (img) => this.setState({ showPlaceholder... | propTypes | identifier_name |
index.ts | import '@pixi/polyfill';
import * as utils from '@pixi/utils';
import { AccessibilityManager } from '@pixi/accessibility';
import { InteractionManager } from '@pixi/interaction';
import { Application } from '@pixi/app';
import { Renderer, BatchRenderer } from '@pixi/core';
import { Extract } from '@pixi/extract';
impo... | NoiseFilter,
};
// Export ES for those importing specifically by name,
export * from '@pixi/accessibility';
export * from '@pixi/app';
export * from '@pixi/constants';
export * from '@pixi/compressed-textures';
export * from '@pixi/core';
export * from '@pixi/display';
export * from '@pixi/extract';
export * from ... | FXAAFilter, | random_line_split |
lib.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Input system for lumol using TOML as a language
#![warn(missing_docs, trivial_casts, unused_import_braces, variant_size_differences)]
#![warn(unused_qualifications, unused_results, rust_2018_idioms)]
// Clippy ... | Ok(())
}
| return Err(Error::from(
format!("can only read version 1 of input, got version {}", version),
));
}
| conditional_block |
lib.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Input system for lumol using TOML as a language
#![warn(missing_docs, trivial_casts, unused_import_braces, variant_size_differences)]
#![warn(unused_qualifications, unused_results, rust_2018_idioms)]
// Clippy ... | let input = config.get("input").ok_or(
Error::from("missing 'input' table")
)?;
let version = input.get("version").ok_or(
Error::from("missing 'version' key in 'input' table")
)?;
let version = version.as_integer().ok_or(
Error::from("'input.version' must be an integer")
... | identifier_body | |
lib.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Input system for lumol using TOML as a language
#![warn(missing_docs, trivial_casts, unused_import_braces, variant_size_differences)]
#![warn(unused_qualifications, unused_results, rust_2018_idioms)]
// Clippy ... | onfig: &Table) -> Result<(), Error> {
let input = config.get("input").ok_or(
Error::from("missing 'input' table")
)?;
let version = input.get("version").ok_or(
Error::from("missing 'version' key in 'input' table")
)?;
let version = version.as_integer().ok_or(
Error::from("'... | lidate(c | identifier_name |
lib.rs | // Lumol, an extensible molecular simulation engine
// Copyright (C) Lumol's contributors — BSD license
//! Input system for lumol using TOML as a language
#![warn(missing_docs, trivial_casts, unused_import_braces, variant_size_differences)]
#![warn(unused_qualifications, unused_results, rust_2018_idioms)]
// Clippy ... | Error::from("missing 'version' key in 'input' table")
)?;
let version = version.as_integer().ok_or(
Error::from("'input.version' must be an integer")
)?;
if version != 1 {
return Err(Error::from(
format!("can only read version 1 of input, got version {}", version),
... | random_line_split | |
ManagedMetadataService.ts | import { injectable } from "inversify";
import { Term, IManagedMetadataService } from "./IManagedMetadataService";
interface TermFromAPI extends Term {
AvailableForTagging: boolean;
}
interface TermPromises {
[termsetId: string]: Promise<TermFromAPI[]>;
}
// this is an implementation of IManagedMetadataServi... | }
resolve(termArray);
},
(sender, args) => { reject(args); }
);
});
});
}
return this.LoadedTerms[termsetId];
}
public async GetTermsAvailabl... | {
this.LoadedTerms[termsetId] = new Promise<TermFromAPI[]>((resolve, reject) => {
ManagedMetadataService.ExecuteInContext((ctx) => {
const taxonomySession = SP.Taxonomy.TaxonomySession.getTaxonomySession(ctx);
const termStore = taxonomySession.getDefau... | conditional_block |
ManagedMetadataService.ts | import { injectable } from "inversify";
import { Term, IManagedMetadataService } from "./IManagedMetadataService";
interface TermFromAPI extends Term {
AvailableForTagging: boolean;
}
interface TermPromises {
[termsetId: string]: Promise<TermFromAPI[]>;
}
// this is an implementation of IManagedMetadataServi... | (termsetId: string): Promise<Term[]> {
const allTerms = await this.GetTerms(termsetId);
return allTerms.filter(term => term.AvailableForTagging);
}
// this function ensures that CSOM taxonomy methods will be executed after required SP scripts have been loaded
private static ExecuteInContext... | GetTermsAvailableForTagging | identifier_name |
ManagedMetadataService.ts | import { injectable } from "inversify";
import { Term, IManagedMetadataService } from "./IManagedMetadataService";
interface TermFromAPI extends Term {
AvailableForTagging: boolean;
}
interface TermPromises {
[termsetId: string]: Promise<TermFromAPI[]>;
}
// this is an implementation of IManagedMetadataServi... | return this.LoadedTerms[termsetId];
}
public async GetTermsAvailableForTagging(termsetId: string): Promise<Term[]> {
const allTerms = await this.GetTerms(termsetId);
return allTerms.filter(term => term.AvailableForTagging);
}
// this function ensures that CSOM taxonomy methods ... | );
});
});
}
| random_line_split |
gdt.rs | //! # Global Descriptor Table (GDT) manager module
//!
//! ## References
//! - [OSDev GDT](http://wiki.osdev.org/Global_Descriptor_Table)
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::PrivilegeLevel;
pub struct Gdt {
table: [u64; 9],
next_free: usize,... |
}
/// Represents a descriptor
pub enum Descriptor {
UserSegment(u64),
SystemSegment(u64, u64),
}
impl Descriptor {
/// Creates a kernel mode segment
pub fn kernel_code_segment() -> Descriptor {
let flags = USER_SEGMENT | PRESENT | EXECUTABLE | LONG_MODE;
Descriptor::UserSegment(flags.... | {
use x86_64::instructions::tables::{DescriptorTablePointer, lgdt};
use core::mem::size_of;
let ptr = DescriptorTablePointer {
base: self.table.as_ptr() as u64,
limit: (self.table.len() * size_of::<u64>() - 1) as u16,
};
unsafe { lgdt(&ptr) };
} | identifier_body |
gdt.rs | //! # Global Descriptor Table (GDT) manager module
//!
//! ## References
//! - [OSDev GDT](http://wiki.osdev.org/Global_Descriptor_Table)
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::PrivilegeLevel;
pub struct Gdt {
table: [u64; 9],
next_free: usize,... | else {
panic!("GDT full");
}
}
/// Loads the GDT table into memory.
pub fn load(&'static self) {
use x86_64::instructions::tables::{DescriptorTablePointer, lgdt};
use core::mem::size_of;
let ptr = DescriptorTablePointer {
base: self.table.as_ptr() a... | {
let index = self.next_free;
self.table[index] = value;
self.next_free += 1;
index
} | conditional_block |
gdt.rs | //! # Global Descriptor Table (GDT) manager module
//!
//! ## References
//! - [OSDev GDT](http://wiki.osdev.org/Global_Descriptor_Table)
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::PrivilegeLevel;
pub struct Gdt {
table: [u64; 9],
next_free: usize,... | let off = offset as u64;
bits.set_bits(16..40, off.get_bits(0..24));
bits.set_bits(56..64, off.get_bits(24..32));
Descriptor::UserSegment(bits)
}
/// Create a new TSS segment
///
/// ## Parameters
///
/// * `tss` - Task state segment
pub fn tss_segment(tss: ... | let mut bits = flags.bits();
// set the offset | random_line_split |
gdt.rs | //! # Global Descriptor Table (GDT) manager module
//!
//! ## References
//! - [OSDev GDT](http://wiki.osdev.org/Global_Descriptor_Table)
use x86_64::structures::tss::TaskStateSegment;
use x86_64::structures::gdt::SegmentSelector;
use x86_64::PrivilegeLevel;
pub struct Gdt {
table: [u64; 9],
next_free: usize,... | {
UserSegment(u64),
SystemSegment(u64, u64),
}
impl Descriptor {
/// Creates a kernel mode segment
pub fn kernel_code_segment() -> Descriptor {
let flags = USER_SEGMENT | PRESENT | EXECUTABLE | LONG_MODE;
Descriptor::UserSegment(flags.bits())
}
pub fn kernel_data_segment() -> ... | Descriptor | identifier_name |
Halos.js | Clazz.declarePackage ("J.shape");
Clazz.load (["J.shape.AtomShape"], "J.shape.Halos", ["JU.BSUtil", "$.C"], function () {
c$ = Clazz.decorateAsClass (function () {
this.colixSelection = 2;
this.bsHighlight = null;
this.colixHighlight = 10;
Clazz.instantialize (this, arguments);
}, J.shape, "Halos", J.shape.AtomShape);
... | this.bsHighlight = value;
return;
}if (propertyName === "deleteModelAtoms") {
JU.BSUtil.deleteBits (this.bsHighlight, bs);
}this.setPropAS (propertyName, value, bs);
}, "~S,~O,JU.BS");
Clazz.overrideMethod (c$, "setModelVisibilityFlags",
function (bs) {
var bsSelected = (this.vwr.getSelectionHaloEnabled (false) ? this... | random_line_split | |
Halos.js | Clazz.declarePackage ("J.shape");
Clazz.load (["J.shape.AtomShape"], "J.shape.Halos", ["JU.BSUtil", "$.C"], function () {
c$ = Clazz.decorateAsClass (function () {
this.colixSelection = 2;
this.bsHighlight = null;
this.colixHighlight = 10;
Clazz.instantialize (this, arguments);
}, J.shape, "Halos", J.shape.AtomShape);
... | this.setPropAS (propertyName, value, bs);
}, "~S,~O,JU.BS");
Clazz.overrideMethod (c$, "setModelVisibilityFlags",
function (bs) {
var bsSelected = (this.vwr.getSelectionHaloEnabled (false) ? this.vwr.bsA () : null);
for (var i = this.ac; --i >= 0; ) {
var isVisible = bsSelected != null && bsSelected.get (i) || (this.m... | {
JU.BSUtil.deleteBits (this.bsHighlight, bs);
} | conditional_block |
linear.rs | //! Applies a linear transformation to the input data `y = a * x + b`
//!
//! The variables are:
//!
//! - `y`: output value
//! - `a`: weight (a trainable weight in a neural network)
//! - `x`: input value
//! - `b`: bias (not implemented yet)
//!
//! ## Input Data
//!
//! The input can either have one or two dimensio... | }
}
impl<B: IBackend + LayerOps<f32>> ComputeOutput<f32, B> for Linear {
fn compute_output(&self,
backend: &B,
weights: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
output_data: &mut [&mut SharedTensor<f32>]) ... | {
let input = input_data[0].read().unwrap();
// reshape top
let output_shape = self.calculate_output_shape(input.desc());
output_data[0].write().unwrap().resize(&output_shape).unwrap();
output_gradient[0].write().unwrap().resize(&output_shape).unwrap();
// reshape weight
... | identifier_body |
linear.rs | //! Applies a linear transformation to the input data `y = a * x + b`
//!
//! The variables are:
//!
//! - `y`: output value
//! - `a`: weight (a trainable weight in a neural network)
//! - `x`: input value
//! - `b`: bias (not implemented yet)
//!
//! ## Input Data
//!
//! The input can either have one or two dimensio... |
if let Some(weight) = weights_gradient.get(0) {
weight.write().unwrap().resize(&weight_shape).unwrap();
}
}
}
impl<B: IBackend + LayerOps<f32>> ComputeOutput<f32, B> for Linear {
fn compute_output(&self,
backend: &B,
weights: &[&SharedTen... | {
weight.write().unwrap().resize(&weight_shape).unwrap();
let filler = FillerType::Glorot {
input_size: Self::calculate_input_size(input.desc()),
output_size: self.output_size,
};
filler.fill(&mut weight.write().unwrap());
} | conditional_block |
linear.rs | //! Applies a linear transformation to the input data `y = a * x + b`
//!
//! The variables are:
//!
//! - `y`: output value
//! - `a`: weight (a trainable weight in a neural network)
//! - `x`: input value
//! - `b`: bias (not implemented yet)
//!
//! ## Input Data
//!
//! The input can either have one or two dimensio... | (&self,
backend: &B,
weights_data: &[&SharedTensor<f32>],
output_data: &[&SharedTensor<f32>],
output_gradients: &[&SharedTensor<f32>],
input_data: &[&SharedTensor<f32>],
... | compute_input_gradient | identifier_name |
linear.rs | //! Applies a linear transformation to the input data `y = a * x + b`
//!
//! The variables are:
//!
//! - `y`: output value
//! - `a`: weight (a trainable weight in a neural network)
//! - `x`: input value
//! - `b`: bias (not implemented yet)
//!
//! ## Input Data
//!
//! The input can either have one or two dimensio... | type Builder = capnp_config::Builder<'a>;
/// Write the LinearConfig into a capnp message.
fn write_capnp(&self, builder: &mut Self::Builder) {
builder.borrow().set_output_size(self.output_size as u64);
}
}
impl<'a> CapnpRead<'a> for LinearConfig {
type Reader = capnp_config::Reader<'a>;
... | pub output_size: usize,
}
impl<'a> CapnpWrite<'a> for LinearConfig { | random_line_split |
filter_test.py | from . import filter
from click import testing as click_testing
from grow.testing import testing |
class FilterTestCase(unittest.TestCase):
def setUp(self):
self.test_pod_dir = testing.create_test_pod_dir()
self.runner = click_testing.CliRunner()
def test_filter(self):
args = [self.test_pod_dir, '-o', 'missing.po']
result = self.runner.invoke(filter.filter, args, catch_exceptions=False)
s... | import unittest | random_line_split |
filter_test.py | from . import filter
from click import testing as click_testing
from grow.testing import testing
import unittest
class FilterTestCase(unittest.TestCase):
def | (self):
self.test_pod_dir = testing.create_test_pod_dir()
self.runner = click_testing.CliRunner()
def test_filter(self):
args = [self.test_pod_dir, '-o', 'missing.po']
result = self.runner.invoke(filter.filter, args, catch_exceptions=False)
self.assertEqual(0, result.exit_code)
args = [self.t... | setUp | identifier_name |
filter_test.py | from . import filter
from click import testing as click_testing
from grow.testing import testing
import unittest
class FilterTestCase(unittest.TestCase):
|
if __name__ == '__main__':
unittest.main()
| def setUp(self):
self.test_pod_dir = testing.create_test_pod_dir()
self.runner = click_testing.CliRunner()
def test_filter(self):
args = [self.test_pod_dir, '-o', 'missing.po']
result = self.runner.invoke(filter.filter, args, catch_exceptions=False)
self.assertEqual(0, result.exit_code)
args ... | identifier_body |
filter_test.py | from . import filter
from click import testing as click_testing
from grow.testing import testing
import unittest
class FilterTestCase(unittest.TestCase):
def setUp(self):
self.test_pod_dir = testing.create_test_pod_dir()
self.runner = click_testing.CliRunner()
def test_filter(self):
args = [self.tes... | unittest.main() | conditional_block | |
setup.py | from setuptools import setup, find_packages
from codecs import open # To use a consistent encoding
from os import path
from setuptools.command.test import test as test_command
import sys
class Tox(test_command):
# user_options = [('tox-args=', 'a', "Arguments to pass to tox")]
def initialize_options(self):
... |
def finalize_options(self):
test_command.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import tox
errcode = tox.cmdline(self.test_args)
sys.exit(errcode)
here = path.abspath(path.dirname(__file__))
print(here)
with open... | test_command.initialize_options(self)
self.tox_args = None | identifier_body |
setup.py | from setuptools import setup, find_packages
from codecs import open # To use a consistent encoding
from os import path
from setuptools.command.test import test as test_command
import sys
class Tox(test_command):
# user_options = [('tox-args=', 'a', "Arguments to pass to tox")]
def | (self):
test_command.initialize_options(self)
self.tox_args = None
def finalize_options(self):
test_command.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import tox
errcode = tox.cmdline(self.test_args)
sy... | initialize_options | identifier_name |
setup.py | from setuptools import setup, find_packages
from codecs import open # To use a consistent encoding
from os import path
from setuptools.command.test import test as test_command
import sys
class Tox(test_command):
# user_options = [('tox-args=', 'a', "Arguments to pass to tox")]
def initialize_options(self):
... | author='130017964, Cheryl, Emil',
license='MIT',
cmdclass={'test': Tox},
) | version='0.1',
packages=find_packages(),
install_requires=['enum', 'sphinx', ],
tests_require=['tox', ], | random_line_split |
mod.rs | use std::vec::*;
/// Trait needs to be implemented when struct is used for an evoltionary algorithm
pub trait Evolvable {
/// Crosses indivduals together
fn cross_over(&self, other: &Self) -> Self;
/// Slightly mutates self
fn mutate(&mut self);
}
pub enum StopRule {
/// Stops evolving when given... | generationNo += 1;
}
} | random_line_split | |
mod.rs | use std::vec::*;
/// Trait needs to be implemented when struct is used for an evoltionary algorithm
pub trait Evolvable {
/// Crosses indivduals together
fn cross_over(&self, other: &Self) -> Self;
/// Slightly mutates self
fn mutate(&mut self);
}
pub enum StopRule {
/// Stops evolving when given... | {
/// Sets the amount of threads that should be used (to calculate fitness)
/// Defaults to the amount of cpu cores detected
pub threads: usize,
//pub hooks: Vec<EvolutionHooks>
}
impl EvolutionOptions {
pub fn defaults() -> Self {
// TODO: Detect cpu core amount
EvolutionOption... | EvolutionOptions | identifier_name |
mod.rs | use std::vec::*;
/// Trait needs to be implemented when struct is used for an evoltionary algorithm
pub trait Evolvable {
/// Crosses indivduals together
fn cross_over(&self, other: &Self) -> Self;
/// Slightly mutates self
fn mutate(&mut self);
}
pub enum StopRule {
/// Stops evolving when given... |
}
pub fn genetic_evolution<T: Evolvable + Clone + Sync + Send, Fnew, Frate>(population: usize, stop_rule: StopRule, new: Fnew, rate: &mut Frate, opt_options: Option<EvolutionOptions>) -> T
where Fnew: Fn() -> T, Frate: FnMut(&T) -> f64
{
// get options of grab defaults
let options = match opt_options {
... | {
// TODO: Detect cpu core amount
EvolutionOptions {
threads: 6
}
} | identifier_body |
mod.rs | use std::vec::*;
/// Trait needs to be implemented when struct is used for an evoltionary algorithm
pub trait Evolvable {
/// Crosses indivduals together
fn cross_over(&self, other: &Self) -> Self;
/// Slightly mutates self
fn mutate(&mut self);
}
pub enum StopRule {
/// Stops evolving when given... | ,
StopRule::HasNotImprovedSince(gen) => { },
StopRule::Never => { }
}
for i in (0..population).rev() {
if i != bests[0].1 && i != bests[1].1 {
generation.remove(i);
}
}
// Create next Generation (2 best will continue to li... | {
if generationNo >= gen {
return (*generation[bests[0].1]).clone();
}
} | conditional_block |
DisplayObject.ts | import EventDispatcher from '../event/EventDispatcher';
/**
* The {{#crossLink "DisplayObject"}}{{/crossLink}} class is the base class for all objects that can be placed on the display list.
*
* @class DisplayObject
* @extends EventDispatcher
* @module StructureJS
* @submodule view
* @requires Extend
* @requir... |
/**
* The create function is intended to provide a consistent place for the creation or initializing the view.
* It will automatically be called the first time that the view is added to a DisplayObjectContainer.
* It is critical that all subclasses call the super for this function in their overridd... | {
super();
} | identifier_body |
DisplayObject.ts | import EventDispatcher from '../event/EventDispatcher';
/**
* The {{#crossLink "DisplayObject"}}{{/crossLink}} class is the base class for all objects that can be placed on the display list.
*
* @class DisplayObject
* @extends EventDispatcher
* @module StructureJS
* @submodule view
* @requires Extend
* @requir... | {
this.unscaledWidth = unscaledWidth;
this.unscaledHeight = unscaledHeight;
return this;
}
protected _readerStart():void
{
this.ctx.save();
}
public renderCanvas():boolean
{
if (this.ctx === null || this.alpha <= 0 || this.visible === false) return ... | random_line_split | |
DisplayObject.ts | import EventDispatcher from '../event/EventDispatcher';
/**
* The {{#crossLink "DisplayObject"}}{{/crossLink}} class is the base class for all objects that can be placed on the display list.
*
* @class DisplayObject
* @extends EventDispatcher
* @module StructureJS
* @submodule view
* @requires Extend
* @requir... | ():any
{
return this;
}
/**
* The setSize method sets the bounds within which the containing DisplayObject would like that component to lay itself out.
*
* @param unscaledWidth {number} The width within which the component should lay itself out.
* @param unscaledHeight {number} ... | layout | identifier_name |
matchers.js | /* global window beforeEach jasmine it xit fit */
if (typeof global === 'undefined') |
const customMatchers = {
toAlmostEqual: (util, customEqualityTesters) => ({
compare: (actual, expected) => {
const cleanActual = actual
.trim()
.replace(/\n/g, '')
.replace(/\s+/g, ' '); // remove extra whitespace
const cleanExpected = expected
.trim()
.repla... | {
global = window; // eslint-disable-line
} | conditional_block |
matchers.js | /* global window beforeEach jasmine it xit fit */
if (typeof global === 'undefined') {
global = window; // eslint-disable-line
}
const customMatchers = {
toAlmostEqual: (util, customEqualityTesters) => ({
compare: (actual, expected) => {
const cleanActual = actual
.trim()
.replace(/\n/g,... | () {
function executeTest(name, fn, entries, override) {
entries.forEach((entry) => {
const itName = `${name} ${entry.name}`;
const itFn = () => fn(...entry.params);
(override || entry.proxy)(itName, itFn);
});
}
global.entry = (name, ...params) => {
const result = {
name,
... | addDataTableSupport | identifier_name |
matchers.js | /* global window beforeEach jasmine it xit fit */
if (typeof global === 'undefined') {
global = window; // eslint-disable-line
}
const customMatchers = {
toAlmostEqual: (util, customEqualityTesters) => ({
compare: (actual, expected) => {
const cleanActual = actual
.trim()
.replace(/\n/g,... |
global.entry = (name, ...params) => {
const result = {
name,
params,
proxy: it,
};
return result;
};
global.fentry = (name, ...params) => {
const result = {
name,
params,
proxy: fit,
};
return result;
};
global.xentry = (name, ...params) => {
... | {
entries.forEach((entry) => {
const itName = `${name} ${entry.name}`;
const itFn = () => fn(...entry.params);
(override || entry.proxy)(itName, itFn);
});
} | identifier_body |
matchers.js | /* global window beforeEach jasmine it xit fit */
if (typeof global === 'undefined') {
global = window; // eslint-disable-line
}
const customMatchers = {
toAlmostEqual: (util, customEqualityTesters) => ({
compare: (actual, expected) => {
const cleanActual = actual
.trim()
.replace(/\n/g,... | const result = {
name,
params,
proxy: fit,
};
return result;
};
global.xentry = (name, ...params) => {
const result = {
name,
params,
proxy: xit,
};
return result;
};
global.describeTable = (name, fn, ...entries) => {
executeTest(name, fn, entr... | global.fentry = (name, ...params) => { | random_line_split |
lib.rs | // bench command:
//
// ```
// $ rustup run nightly cargo bench
// ```
#![feature(test)]
extern crate rand;
extern crate test;
extern crate quicksort;
extern crate rust_quicksort;
#[cfg(test)]
mod benches {
use rand::{Rng, SeedableRng, StdRng};
use test;
use quicksort;
use rust_quicksort;
static ... | fn bench_quicksort(b: &mut test::Bencher) {
let mut rng: StdRng = SeedableRng::from_seed(&SEED as &[_]);
let mut v: Vec<isize> = rng.gen_iter::<isize>().take(LENGTH).collect();
b.iter(|| quicksort::quicksort(&mut v))
}
#[bench]
fn bench_sort(b: &mut test::Bencher) {
let mu... | b.iter(|| rust_quicksort::quicksort(&mut v))
}
#[bench] | random_line_split |
lib.rs | // bench command:
//
// ```
// $ rustup run nightly cargo bench
// ```
#![feature(test)]
extern crate rand;
extern crate test;
extern crate quicksort;
extern crate rust_quicksort;
#[cfg(test)]
mod benches {
use rand::{Rng, SeedableRng, StdRng};
use test;
use quicksort;
use rust_quicksort;
static ... |
#[bench]
fn bench_sort(b: &mut test::Bencher) {
let mut rng: StdRng = SeedableRng::from_seed(&SEED as &[_]);
let mut v: Vec<isize> = rng.gen_iter::<isize>().take(LENGTH).collect();
b.iter(|| v.sort())
}
} | {
let mut rng: StdRng = SeedableRng::from_seed(&SEED as &[_]);
let mut v: Vec<isize> = rng.gen_iter::<isize>().take(LENGTH).collect();
b.iter(|| quicksort::quicksort(&mut v))
} | identifier_body |
lib.rs | // bench command:
//
// ```
// $ rustup run nightly cargo bench
// ```
#![feature(test)]
extern crate rand;
extern crate test;
extern crate quicksort;
extern crate rust_quicksort;
#[cfg(test)]
mod benches {
use rand::{Rng, SeedableRng, StdRng};
use test;
use quicksort;
use rust_quicksort;
static ... | (b: &mut test::Bencher) {
let mut rng: StdRng = SeedableRng::from_seed(&SEED as &[_]);
let mut v: Vec<isize> = rng.gen_iter::<isize>().take(LENGTH).collect();
b.iter(|| rust_quicksort::quicksort(&mut v))
}
#[bench]
fn bench_quicksort(b: &mut test::Bencher) {
let mut rng: StdRn... | bench_rust_quicksort | identifier_name |
hooking.py | #
# Copyright 2011-2017 Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | with open(os.environ['_hook_domxml']) as f:
return minidom.parseString(f.read())
def write_domxml(domxml):
with open(os.environ['_hook_domxml'], 'w') as f:
f.write(domxml.toxml(encoding='utf-8'))
def read_json():
with open(os.environ['_hook_json']) as f:
return json.loads(f.read(... | random_line_split | |
hooking.py | #
# Copyright 2011-2017 Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... |
def log(message):
sys.stderr.write(message + '\n')
def exit_hook(message, return_code=2):
"""
Exit the hook with a given message, which will be printed to the standard
error stream. A newline will be printed at the end.
The default return code is 2 for signaling that an error occurred.
"""
... | with open(os.environ['_hook_json'], 'w') as f:
f.write(json.dumps(data)) | identifier_body |
hooking.py | #
# Copyright 2011-2017 Red Hat, Inc.
#
# 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 2 of the License, or
# (at your option) any later version.
#
# This program is distributed ... | (domxml):
with open(os.environ['_hook_domxml'], 'w') as f:
f.write(domxml.toxml(encoding='utf-8'))
def read_json():
with open(os.environ['_hook_json']) as f:
return json.loads(f.read())
def write_json(data):
with open(os.environ['_hook_json'], 'w') as f:
f.write(json.dumps(data))... | write_domxml | identifier_name |
index.js | KISSY.add("brix/gallery/switchable/index", function(S,Brick,KSSwitchable) {
/**
* kissy switchable 组件的封装。
* @extends Brix.Brick
* @class Brix.Gallery.Switchable
* <a target="_blank" href="http://docs.kissyui.com/docs/html/api/component/switchable/">其他配置、方法、事件请参考KISSY API</a>
* @param {Obje... | if(self.switchable&&self.switchable.destroy){
self.switchable.destroy();
}
}
});
/**
* Switchable 实例对象类型Tabs|Slide|Carousel|Accordion。
* @cfg switchType
*/
/**
* @property {Object} switchable KISSY switchable实例化后的对象
*/
... | random_line_split | |
index.js | KISSY.add("brix/gallery/switchable/index", function(S,Brick,KSSwitchable) {
/**
* kissy switchable 组件的封装。
* @extends Brix.Brick
* @class Brix.Gallery.Switchable
* <a target="_blank" href="http://docs.kissyui.com/docs/html/api/component/switchable/">其他配置、方法、事件请参考KISSY API</a>
* @param {Obje... | self.config;
},
destructor:function(){
var self = this;
if(self.switchable&&self.switchable.destroy){
self.switchable.destroy();
}
}
});
/**
* Switchable 实例对象类型Tabs|Slide|Carousel|Accordion。
* @cfg switchType
*/
... | chable(self.get('el'),config);
}
config = null;
delete | conditional_block |
index.d.ts | /*
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by ap... | * 'b': 2
* };
*
* var keys = commonKeys( obj, obj2 );
* // returns [ 'a', 'b' ]
*
* @example
* var obj1 = {
* 'a': 1,
* 'b': 2,
* 'c': 3
* };
*
* var obj2 = {
* 'a': 1,
* 'b': 2
* };
*
* var obj3 = {
* 'a': 1,
* };
*
* var keys = commonKeys( obj1, obj2, obj3 );
* // returns [ 'a' ]
*/
declar... | * var obj2 = {
* 'a': 1, | random_line_split |
a_sort.py | import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
return str_to_int(args[1])
def find(ints, offset):
min = float('inf')
min_index = -1
for k, v in enumerate(ints[offset:]):
if v < min:
min = v
min_index = k + offset
retu... |
def solve(args, verbose=False, debug=False):
ints = proc_input(args)
if debug:
from copy import deepcopy
d = deepcopy(ints)
results = []
for i in xrange(len(ints)):
min_index = find(ints, i)
if min_index != i:
results.append((min_index, i))
swap(ints, min_index, i)
if debug:
d.sort()
assert(int... | t = l[a]
l[a] = l[b]
l[b] = t | identifier_body |
a_sort.py | import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
return str_to_int(args[1])
def find(ints, offset):
min = float('inf')
min_index = -1
for k, v in enumerate(ints[offset:]):
if v < min:
min = v
min_index = k + offset
retu... |
else:
solve(list(fileinput.input()), verbose=True)
| test() | conditional_block |
a_sort.py | import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def | (args):
return str_to_int(args[1])
def find(ints, offset):
min = float('inf')
min_index = -1
for k, v in enumerate(ints[offset:]):
if v < min:
min = v
min_index = k + offset
return(min_index)
def swap(l, a, b):
t = l[a]
l[a] = l[b]
l[b] = t
def solve(args, verbose=False, debug=False):
ints = proc_in... | proc_input | identifier_name |
a_sort.py | import fileinput
def str_to_int(s):
return([ int(x) for x in s.split() ])
# args = [ 'line 1', 'line 2', ... ]
def proc_input(args):
return str_to_int(args[1])
def find(ints, offset):
min = float('inf')
min_index = -1
for k, v in enumerate(ints[offset:]):
if v < min:
min = v
min_index = k + offset
retu... | l[b] = t
def solve(args, verbose=False, debug=False):
ints = proc_input(args)
if debug:
from copy import deepcopy
d = deepcopy(ints)
results = []
for i in xrange(len(ints)):
min_index = find(ints, i)
if min_index != i:
results.append((min_index, i))
swap(ints, min_index, i)
if debug:
d.sort()
a... | random_line_split | |
flex.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Computed types for CSS values related to flexbox.
use values::generics::flex::FlexBasis as GenericFlexBasis;
... | () -> Self {
GenericFlexBasis::Width(Width::auto())
}
}
| auto | identifier_name |
flex.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
/// The `width` value type.
#[cfg(feature = "servo")]
pub type Width = ::values::computed::NonNegativeLengthOrPercentageOrAuto;
/// The `width` value type.
#[cfg(feature = "gecko")]
pub type Width = ::values::computed::MozLength;
/// A computed value for the `flex-basis` property.
pub type FlexBasis = GenericFlexBas... |
//! Computed types for CSS values related to flexbox.
use values::generics::flex::FlexBasis as GenericFlexBasis; | random_line_split |
flex.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! Computed types for CSS values related to flexbox.
use values::generics::flex::FlexBasis as GenericFlexBasis;
... |
}
| {
GenericFlexBasis::Width(Width::auto())
} | identifier_body |
AppBase.tsx | import Login from "./components/login/login";
import axios from "axios";
import {Modal, Spin} from "antd";
import EnvUtils from "./utils/env-utils";
import {useEffect, useState} from "react";
import {resourceKey} from "./utils/constants";
import {Route, Switch} from "react-router-dom";
import IndexLayout from "./layout... | </Switch>
);
}
export default AppBase; | <Route path="*/login" component={Login}/>
<Route exact path="*" component={IndexLayout}/>
<Route component={IndexLayout}/> | random_line_split |
AppBase.tsx | import Login from "./components/login/login";
import axios from "axios";
import {Modal, Spin} from "antd";
import EnvUtils from "./utils/env-utils";
import {useEffect, useState} from "react";
import {resourceKey} from "./utils/constants";
import {Route, Switch} from "react-router-dom";
import IndexLayout from "./layout... | adResourceFromServer();
}
} else {
handleRes(JSON.parse(resourceData));
}
}
const loadResourceFromServer = () => {
const resourceApi = '/api/public/blogResource';
axios.get(resourceApi).then(({data}: { data: Record<string, any> }) => {
handleR... | s(JSON.parse(jsonStr));
} else {
lo | conditional_block |
new-array.directive.js | import angular from 'angular';
/**
* Directive that handles the model arrays
*/
export default function(sel, sfPath, schemaForm) {
return {
scope: true,
controller: ['$scope', function SFArrayController($scope) {
this.key = ($scope.form && $scope.form.key) ? $scope.form.key.splice(0, -2) : [];
}]... | };
// We need the form definition to make a decision on how we should listen.
var once = scope.$watch('form', function(form) {
if (!form) {
return;
}
// Always start with one empty form unless configured otherwise.
// Special case: don't do it if form has a ... | }
return model; | random_line_split |
new-array.directive.js | import angular from 'angular';
/**
* Directive that handles the model arrays
*/
export default function(sel, sfPath, schemaForm) {
return {
scope: true,
controller: ['$scope', function SFArrayController($scope) {
this.key = ($scope.form && $scope.form.key) ? $scope.form.key.splice(0, -2) : [];
}]... |
if (subForm) {
var copy = angular.copy(subForm);
copy.arrayIndex = index;
schemaForm.traverseForm(copy, setIndex(index));
formDefCache[index] = copy;
}
}
return formDefCache[index];
};
}
};
}
| {
subForm = {
type: 'section',
items: form.items.map(function(item) {
item.ngModelOptions = form.ngModelOptions;
if (angular.isUndefined(item.readonly)) {
item.readonly = form.readonly;
}
return ite... | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.