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 |
|---|---|---|---|---|
EnvyBarChart.js | import {Chart} from 'react-google-charts';
import React, {Component, PropTypes} from 'react';
import DataFormatter from '../../utils/DataFormatter';
class | extends Component {
constructor(props) {
super(props);
this.state={
options:{
hAxis: {title: 'Event Type'},
vAxis: {title: 'Envy Events'},
legend: 'none',
},
};
}
generateGraph(events) {
var formatter = new DataFormatter();
var result = formatter.generateEnvyGraph(events);
return resu... | EnvyBarChart | identifier_name |
EnvyBarChart.js | import {Chart} from 'react-google-charts';
import React, {Component, PropTypes} from 'react';
import DataFormatter from '../../utils/DataFormatter';
class EnvyBarChart extends Component {
constructor(props) {
super(props); | this.state={
options:{
hAxis: {title: 'Event Type'},
vAxis: {title: 'Envy Events'},
legend: 'none',
},
};
}
generateGraph(events) {
var formatter = new DataFormatter();
var result = formatter.generateEnvyGraph(events);
return result;
}
render() {
var data = this.generateGraph(this.pr... | random_line_split | |
EnvyBarChart.js | import {Chart} from 'react-google-charts';
import React, {Component, PropTypes} from 'react';
import DataFormatter from '../../utils/DataFormatter';
class EnvyBarChart extends Component {
constructor(props) {
super(props);
this.state={
options:{
hAxis: {title: 'Event Type'},
vAxis: {title: 'Envy Events... |
};
EnvyBarChart.propTypes = {
events: PropTypes.array.isRequired
}
export default EnvyBarChart; | {
var data = this.generateGraph(this.props.events);
return (
<Chart
chartType="ColumnChart"
data={data}
options={this.state.options}
graph_id="EnvyBarChart"
width='40vw'
height='50vh'
/>
);
} | identifier_body |
types.ts | // import { AppSignalsType } from './lib/App'
// import { BlockSignalsType } from './lib/Block'
// import { DataSignalsType, DataServicesType } from './lib/Data'
// import { DragDropSignalsType } from './lib/DragDrop'
// import { FactorySignalsType } from './lib/Factory'
// import { FileStorageSignalsType } from './lib... | } | random_line_split | |
diagnostic.rs | , msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
}
pub fn fileline_help(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help);
}
pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
self.handler.emit(Some((&self.cm, sp)... | (&self, f: &mut fmt::Formatter) -> fmt::Result {
use std::fmt::Display;
match *self {
Bug => "error: internal compiler error".fmt(f),
Fatal | Error => "error".fmt(f),
Warning => "warning".fmt(f),
Note => "note".fmt(f),
Help => "help".fmt(f),
... | fmt | identifier_name |
diagnostic.rs | msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
}
pub fn fileline_help(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help);
}
pub fn span_bug(&self, sp: Span, msg: &str) -> ! |
pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! {
self.span_bug(sp, &format!("unimplemented {}", msg)[]);
}
pub fn handler<'a>(&'a self) -> &'a Handler {
&self.handler
}
}
/// A handler deals with errors; certain errors
/// (fatal, bug, unimpl) may cause immediate exit,
/// others ... | {
self.handler.emit(Some((&self.cm, sp)), msg, Bug);
panic!(ExplicitBug);
} | identifier_body |
diagnostic.rs | , msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Note);
}
pub fn fileline_help(&self, sp: Span, msg: &str) {
self.handler.custom_emit(&self.cm, FileLine(sp), msg, Help);
}
pub fn span_bug(&self, sp: Span, msg: &str) -> ! {
self.handler.emit(Some((&self.cm, sp)... | // to a `LineBufferedWriter`, which means that emitting the reset
// after the newline ends up buffering the reset until we print
// another line or exit. Buffering the reset is a problem if we're
// sharing the terminal with any other programs (e.g. other rustc
... | try!(t.attr(color));
// If `msg` ends in a newline, we need to reset the color before
// the newline. We're making the assumption that we end up writing | random_line_split |
any.rs | use AsLua;
use AsMutLua;
use Push;
use PushGuard;
use LuaRead;
/// Represents any value that can be stored by Lua
#[derive(Clone, Debug, PartialEq)]
pub enum AnyLuaValue {
LuaString(String),
LuaNumber(f64),
LuaBoolean(bool),
LuaArray(Vec<(AnyLuaValue, AnyLuaValue)>),
/// The "Other" element is (h... |
let _lua = match LuaRead::lua_read_at_position(&lua, index) {
Ok(v) => return Ok(AnyLuaValue::LuaString(v)),
Err(lua) => lua
};
/*let _lua = match LuaRead::lua_read_at_position(&lua, index) {
Ok(v) => return Ok(AnyLuaValue::LuaArray(v)),
Err(lua)... | random_line_split | |
any.rs | use AsLua;
use AsMutLua;
use Push;
use PushGuard;
use LuaRead;
/// Represents any value that can be stored by Lua
#[derive(Clone, Debug, PartialEq)]
pub enum AnyLuaValue {
LuaString(String),
LuaNumber(f64),
LuaBoolean(bool),
LuaArray(Vec<(AnyLuaValue, AnyLuaValue)>),
/// The "Other" element is (h... | (lua: L, index: i32) -> Result<AnyLuaValue, L> {
let lua = match LuaRead::lua_read_at_position(&lua, index) {
Ok(v) => return Ok(AnyLuaValue::LuaNumber(v)),
Err(lua) => lua
};
let lua = match LuaRead::lua_read_at_position(&lua, index) {
Ok(v) => return Ok(Any... | lua_read_at_position | identifier_name |
modelsMapper.js | "use strict"
var expect = require('chai').expect;
var mapper = require('../assets/js/lib/template/mapper');
//=====================================================
//============================= We will test the stores
//=====================================================
var mokeModel = {
attributes: {
... | required: true,
maxLength: 40,
minLength: 4,
},
lastName: 'String',
email: {
type: 'email',
required: true,
unique: true
},
age: {
type: 'integer',
min: 18
},
city:"string"
}
}
describe("models mapper", function() { // log... | random_line_split | |
state.js | var accumulate = require("./accumulate")
/* A StateSignal is a signal that does not represent a stateful
primitive source of information but instead is some form
of custom accumulation of state by some logic.
Think of it as a little state machine that is allowed to
transitition state in r... | (tuples) {
tuples = tuples || []
return {
initial: function initial(initialState) {
return accumulate(tuples, initialState)
},
listen: function listen(source, lambda) {
return StateSignal(tuples.concat([[source, lambda]]))
}
}
}
| StateSignal | identifier_name |
state.js | var accumulate = require("./accumulate")
/* A StateSignal is a signal that does not represent a stateful
primitive source of information but instead is some form
of custom accumulation of state by some logic.
Think of it as a little state machine that is allowed to
transitition state in r... | {
tuples = tuples || []
return {
initial: function initial(initialState) {
return accumulate(tuples, initialState)
},
listen: function listen(source, lambda) {
return StateSignal(tuples.concat([[source, lambda]]))
}
}
} | identifier_body | |
state.js | var accumulate = require("./accumulate") | primitive source of information but instead is some form
of custom accumulation of state by some logic.
Think of it as a little state machine that is allowed to
transitition state in reaction to other signals
```js
var transform = require("signaal/transform")
var extend = requi... |
/* A StateSignal is a signal that does not represent a stateful | random_line_split |
mail.py | # Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | (message, subject, to, to_name, sender, sender_name):
"""Mailjet implementation of sending email."""
api_key = app.config.get('MJ_APIKEY_PUBLIC')
api_secret = app.config.get('MJ_APIKEY_PRIVATE')
if not api_key or not api_secret:
app.logger.error('Missing MJ_APIKEY_PUBLIC/MJ_APIKEY_PRIVATE!')
... | _send_mailjet | identifier_name |
mail.py | # Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... | from scoreboard import main
app = main.get_app()
class MailFailure(Exception):
"""Inability to send mail."""
pass
def send(message, subject, to, to_name=None, sender=None, sender_name=None):
"""Send an email."""
sender = sender or app.config.get('MAIL_FROM')
sender_name = sender_name or app.con... | import mailjet_rest
| random_line_split |
mail.py | # Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
def _send_smtp(message, subject, to, to_name, sender, sender_name):
"""SMTP implementation of sending email."""
host = app.config.get('MAIL_HOST')
if not host:
raise MailFailure('SMTP Server Not Configured')
try:
server = smtplib.SMTP(host)
except (smtplib.SMTPConnectError, sock... | app.logger.error('Invalid MAIL_PROVIDER configured!')
raise MailFailure('Invalid MAIL_PROVIDER configured!') | conditional_block |
mail.py | # Copyright 2018 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ag... |
def _send_smtp(message, subject, to, to_name, sender, sender_name):
"""SMTP implementation of sending email."""
host = app.config.get('MAIL_HOST')
if not host:
raise MailFailure('SMTP Server Not Configured')
try:
server = smtplib.SMTP(host)
except (smtplib.SMTPConnectError, sock... | """Send an email."""
sender = sender or app.config.get('MAIL_FROM')
sender_name = sender_name or app.config.get('MAIL_FROM_NAME') or ''
mail_provider = app.config.get('MAIL_PROVIDER')
if mail_provider is None:
app.logger.error('No MAIL_PROVIDER configured!')
raise MailFailure('No MAIL_PR... | identifier_body |
EnrollOnPremController.js | /*!
* Copyright (c) 2015-2016, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by ... |
function getClassName(provider) {
return isRSA(provider) ? 'enroll-rsa' : 'enroll-onprem';
}
return FormController.extend({
className: function () {
return getClassName(this.options.provider);
},
Model: function () {
var provider = this.options.provider;
return {
props... | {
return provider === 'RSA';
} | identifier_body |
EnrollOnPremController.js | /*!
* Copyright (c) 2015-2016, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by ... | (provider) {
return isRSA(provider) ? 'enroll-rsa' : 'enroll-onprem';
}
return FormController.extend({
className: function () {
return getClassName(this.options.provider);
},
Model: function () {
var provider = this.options.provider;
return {
props: {
credentialI... | getClassName | identifier_name |
EnrollOnPremController.js | /*!
* Copyright (c) 2015-2016, Okta, Inc. and/or its affiliates. All rights reserved.
* The Okta software accompanied by this notice is provided pursuant to the Apache License, Version 2.0 (the "License.")
*
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
* Unless required by ... | placeholder: Okta.loc('enroll.onprem.passcode.placeholder', 'login', [vendorName]),
params: {
innerTooltip: Okta.loc('enroll.onprem.passcode.tooltip', 'login', [vendorName])
}
}),
FormType.Toolbar({
noCancelButton: true,
save:... | type: 'password', | random_line_split |
loader.js | EDITOR.loader )
{
/**
* Load core scripts and their dependencies from _source.
* @namespace
* @example
*/
CKEDITOR.loader = (function()
{
// Table of script names and their dependencies.
var scripts =
{
'core/_bootstrap' : [ 'core/config', 'core/ckeditor', 'core/plugins', 'core/scriptloader', 'core... | // We must guarantee the execution order of the scripts, so we
// need to load them one by one. (#4145)
// The following if/else block has been taken from the scriptloader core code.
if ( typeof(script.onreadystatechange) !== "undefined" )
{
/** @ignore */
script.onreadystatechange = funct... | // Append this script to the list of loaded scripts.
CKEDITOR.loader.loadedScripts.push( scriptName );
// Load the next.
CKEDITOR.loader.loadPending();
}
| identifier_body |
loader.js | EDITOR.loader )
{
/**
* Load core scripts and their dependencies from _source.
* @namespace
* @example
*/
CKEDITOR.loader = (function()
{
// Table of script names and their dependencies.
var scripts =
{
'core/_bootstrap' : [ 'core/config', 'core/ckeditor', 'core/plugins', 'core/scriptloader', 'core... |
{
// Append this script to the list of loaded scripts.
CKEDITOR.loader.loadedScripts.push( scriptName );
// Load the next.
CKEDITOR.loader.loadPending();
}
// We must guarantee the execution order of the scripts, so we
// need to load them one by one. (#4145)
// The following ... | ScriptLoaded() | identifier_name |
loader.js | 'core/ckeditor' : [ 'core/ckeditor_basic', 'core/dom', 'core/dtd', 'core/dom/document', 'core/dom/element', 'core/editor', 'core/event', 'core/htmlparser', 'core/htmlparser/element', 'core/htmlparser/fragment', 'core/htmlparser/filter', 'core/htmlparser/basicwriter', 'core/tools' ],
'core/ckeditor_base' : [],
... | // Append this script to the list of loaded scripts.
this.loadedScripts.push( scriptName ); | random_line_split | |
dialogs.module.ts | import { Type } from '@angular/core';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } ... | TdDialogActionsDirective,
TdDialogContentDirective,
} from './dialog.component';
import { TdAlertDialogComponent } from './alert-dialog/alert-dialog.component';
import { TdConfirmDialogComponent } from './confirm-dialog/confirm-dialog.component';
import { TdPromptDialogComponent } from './prompt-dialog/prompt-dialo... |
import {
TdDialogComponent,
TdDialogTitleDirective, | random_line_split |
dialogs.module.ts | import { Type } from '@angular/core';
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input';
import { MatButtonModule } ... | {}
| CovalentDialogsModule | identifier_name |
swell_foop_.py | #!/usr/bin/env python3
"""
Sandbox for "swell-foop" command
"""
import glob
import os
import signal
import sys
import network_mod
import subtask_mod
class | :
"""
Main class
"""
def __init__(self) -> None:
try:
self.config()
sys.exit(self.run())
except (EOFError, KeyboardInterrupt):
sys.exit(114)
except SystemExit as exception:
sys.exit(exception)
@staticmethod
def config() ->... | Main | identifier_name |
swell_foop_.py | #!/usr/bin/env python3
"""
Sandbox for "swell-foop" command
"""
import glob
import os
import signal
import sys
import network_mod
import subtask_mod
class Main:
| if os.name == 'nt':
argv = []
for arg in sys.argv:
files = glob.glob(arg) # Fixes Windows globbing bug
if files:
argv.extend(files)
else:
argv.append(arg)
sys.argv = argv
@staticmeth... | """
Main class
"""
def __init__(self) -> None:
try:
self.config()
sys.exit(self.run())
except (EOFError, KeyboardInterrupt):
sys.exit(114)
except SystemExit as exception:
sys.exit(exception)
@staticmethod
def config() -> None:... | identifier_body |
swell_foop_.py | #!/usr/bin/env python3
"""
Sandbox for "swell-foop" command
"""
import glob
import os
import signal
import sys
import network_mod
import subtask_mod
class Main:
"""
Main class
"""
def __init__(self) -> None:
try:
self.config()
sys.exit(self.run())
except (EOF... |
if __name__ == '__main__':
if '--pydoc' in sys.argv:
help(__name__)
else:
Main() | random_line_split | |
swell_foop_.py | #!/usr/bin/env python3
"""
Sandbox for "swell-foop" command
"""
import glob
import os
import signal
import sys
import network_mod
import subtask_mod
class Main:
"""
Main class
"""
def __init__(self) -> None:
try:
self.config()
sys.exit(self.run())
except (EOF... |
else:
argv.append(arg)
sys.argv = argv
@staticmethod
def run() -> int:
"""
Start program
"""
command = network_mod.Sandbox(
'/usr/games/swell-foop',
args=sys.argv[1:],
errors='stop'
)
... | argv.extend(files) | conditional_block |
test_wms_srs_extent.py | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES ... | r'/service?LAYERs=bar&SERVICE=WMS&FORMAT=image%2Fpng'
'&REQUEST=GetMap&HEIGHT=100&SRS=EPSG%3A25832&styles='
'&VERSION=1.1.1&BBOX=0.0,3500000.0,150.0,3500100.0'
'&WIDTH=75'},
{'body': img.read(), 'headers': {'content-type': 'image/png'}})... |
def test_clipped(self):
with tmp_image((256, 256), format='png', color=(255, 0, 0)) as img:
expected_req = ({'path': | random_line_split |
test_wms_srs_extent.py | you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES O... | ():
module_teardown(test_config)
class TestWMSSRSExtentTest(SystemTest):
config = test_config
def setup(self):
SystemTest.setup(self)
self.common_req = WMS111MapRequest(url='/service?', param=dict(service='WMS',
version... | teardown_module | identifier_name |
test_wms_srs_extent.py | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES ... |
def teardown_module():
module_teardown(test_config)
class TestWMSSRSExtentTest(SystemTest):
config = test_config
def setup(self):
SystemTest.setup(self)
self.common_req = WMS111MapRequest(url='/service?', param=dict(service='WMS',
... | module_setup(test_config, 'wms_srs_extent.yaml') | identifier_body |
check_reqs.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... |
if (!isNodeNewerThanMin()) {
console.log("Node version '" + process.versions.node + "' is not new enough. Please upgrade to " + MIN_NODE_VER + " or newer. Aborting.");
exit(ERROR_VALUE);
}
exit(0);
| {
//Current version is stored as a String in format "X.X.X"
//Must be newer than "0.9.9"
var currentVer = process.versions.node.split(".").map(function (verNumStr) { return parseInt(verNumStr, 10);});
return (currentVer[0] > 0 || currentVer[1] > 9 || currentVer[1] === 9 && currentVer[2] >= 9);
} | identifier_body |
check_reqs.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... |
exit(0);
| {
console.log("Node version '" + process.versions.node + "' is not new enough. Please upgrade to " + MIN_NODE_VER + " or newer. Aborting.");
exit(ERROR_VALUE);
} | conditional_block |
check_reqs.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | () {
//Current version is stored as a String in format "X.X.X"
//Must be newer than "0.9.9"
var currentVer = process.versions.node.split(".").map(function (verNumStr) { return parseInt(verNumStr, 10);});
return (currentVer[0] > 0 || currentVer[1] > 9 || currentVer[1] === 9 && currentVer[2] >= 9);
}
if... | isNodeNewerThanMin | identifier_name |
check_reqs.js | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you... | exit = require('exit'),
signingUtils = require('./lib/signing-utils');
function isNodeNewerThanMin () {
//Current version is stored as a String in format "X.X.X"
//Must be newer than "0.9.9"
var currentVer = process.versions.node.split(".").map(function (verNumStr) { return parseInt(verNumStr, 10);... | var MIN_NODE_VER = "0.9.9",
ERROR_VALUE = 2, | random_line_split |
disk.rs | str.as_ptr(), libc::S_IWUSR | libc::S_IRUSR) } {
0 => Ok(()),
x => Err(x),
}
}
#[cfg(windows)]
fn restrict_permissions_to_owner(_file_path: &Path) -> Result<(), i32> {
Ok(())
}
/// Root keys directory implementation
pub type RootDiskDirectory = DiskDirectory<DiskKeyFileManager>;
/// Disk directory key file man... | fn create(&self, name: &str, key: VaultKey) -> Result<Box<VaultKeyDirectory>, Error> {
let vault_dir = VaultDiskDirectory::create(&self.path, name, key)?;
Ok(Box::new(vault_dir))
}
fn open(&self, name: &str, key: VaultKey) -> Result<Box<VaultKeyDirectory>, Error> {
let vault_dir = VaultDiskDirectory::at(&self... | random_line_split | |
disk.rs | .as_ptr(), libc::S_IWUSR | libc::S_IRUSR) } {
0 => Ok(()),
x => Err(x),
}
}
#[cfg(windows)]
fn restrict_permissions_to_owner(_file_path: &Path) -> Result<(), i32> {
Ok(())
}
/// Root keys directory implementation
pub type RootDiskDirectory = DiskDirectory<DiskKeyFileManager>;
/// Disk directory key file manage... |
})
.collect())
}
fn vault_meta(&self, name: &str) -> Result<String, Error> {
VaultDiskDirectory::meta_at(&self.path, name)
}
}
impl KeyFileManager for DiskKeyFileManager {
fn read<T>(&self, filename: Option<String>, reader: T) -> Result<SafeAccount, Error> where T: io::Read {
let key_file = json::KeyFi... | {
None
} | conditional_block |
disk.rs | .as_ptr(), libc::S_IWUSR | libc::S_IRUSR) } {
0 => Ok(()),
x => Err(x),
}
}
#[cfg(windows)]
fn restrict_permissions_to_owner(_file_path: &Path) -> Result<(), i32> {
Ok(())
}
/// Root keys directory implementation
pub type RootDiskDirectory = DiskDirectory<DiskKeyFileManager>;
/// Disk directory key file manage... |
fn insert(&self, account: SafeAccount) -> Result<SafeAccount, Error> {
// build file path
let filename = account.filename.as_ref().cloned().unwrap_or_else(|| {
let timestamp = time::strftime("%Y-%m-%dT%H-%M-%S", &time::now_utc()).expect("Time-format string is valid.");
format!("UTC--{}Z--{}", timestamp, Uu... | {
// Disk store handles updates correctly iff filename is the same
self.insert(account)
} | identifier_body |
disk.rs | Ok(()),
x => Err(x),
}
}
#[cfg(windows)]
fn restrict_permissions_to_owner(_file_path: &Path) -> Result<(), i32> {
Ok(())
}
/// Root keys directory implementation
pub type RootDiskDirectory = DiskDirectory<DiskKeyFileManager>;
/// Disk directory key file manager
pub trait KeyFileManager: Send + Sync {
/// Read ... | should_create_new_account | identifier_name | |
composite_ticker.ts | import {TickSpec} from "./ticker"
import {ContinuousTicker} from "./continuous_ticker"
import * as p from "core/properties"
import {argmin, sorted_index, is_empty} from "core/util/array"
// This Ticker takes a collection of Tickers and picks the one most appropriate
// for a given range.
export namespace CompositeTic... | else {
const best_index = argmin(errors)
const best_ticker_ndx = ticker_ndxs[best_index]
best_ticker = this.tickers[best_ticker_ndx]
}
return best_ticker
}
get_interval(data_low: number, data_high: number, desired_n_ticks: number): number {
const best_ticker = this.get_best_ticker(d... | {
// this can happen if the data isn't loaded yet, we just default to the first scale
best_ticker = this.tickers[0]
} | conditional_block |
composite_ticker.ts | import {TickSpec} from "./ticker"
import {ContinuousTicker} from "./continuous_ticker"
import * as p from "core/properties"
import {argmin, sorted_index, is_empty} from "core/util/array"
// This Ticker takes a collection of Tickers and picks the one most appropriate
// for a given range.
export namespace CompositeTic... |
get min_intervals(): number[] {
return this.tickers.map((ticker) => ticker.get_min_interval())
}
get max_intervals(): number[] {
return this.tickers.map((ticker) => ticker.get_max_interval())
}
get_min_interval(): number {
return this.min_intervals[0]
}
get_max_interval(): number {
ret... |
// The tickers should be in order of increasing interval size; specifically,
// if S comes before T, then it should be the case that
// S.get_max_interval() < T.get_min_interval().
// FIXME Enforce this automatically. | random_line_split |
composite_ticker.ts | import {TickSpec} from "./ticker"
import {ContinuousTicker} from "./continuous_ticker"
import * as p from "core/properties"
import {argmin, sorted_index, is_empty} from "core/util/array"
// This Ticker takes a collection of Tickers and picks the one most appropriate
// for a given range.
export namespace CompositeTic... |
get max_intervals(): number[] {
return this.tickers.map((ticker) => ticker.get_max_interval())
}
get_min_interval(): number {
return this.min_intervals[0]
}
get_max_interval(): number {
return this.max_intervals[0]
}
get_best_ticker(data_low: number, data_high: number, desired_n_ticks: nu... | {
return this.tickers.map((ticker) => ticker.get_min_interval())
} | identifier_body |
composite_ticker.ts | import {TickSpec} from "./ticker"
import {ContinuousTicker} from "./continuous_ticker"
import * as p from "core/properties"
import {argmin, sorted_index, is_empty} from "core/util/array"
// This Ticker takes a collection of Tickers and picks the one most appropriate
// for a given range.
export namespace CompositeTic... | (attrs?: Partial<CompositeTicker.Attrs>) {
super(attrs)
}
static {
this.define<CompositeTicker.Props>(({Array, Ref}) => ({
tickers: [ Array(Ref(ContinuousTicker)), [] ],
}))
}
// The tickers should be in order of increasing interval size; specifically,
// if S comes before T, then it shoul... | constructor | identifier_name |
predicate.ts | vgField} from './channeldef';
import {DateTime} from './datetime';
import {ExprRef} from './expr';
import {LogicalComposition} from './logical';
import {ParameterName} from './parameter';
import {fieldExpr as timeUnitFieldExpr, normalizeTimeUnit, TimeUnit, TimeUnitParams} from './timeunit';
import {stringify} from './... |
const exprs = [];
if (lower !== null) {
exprs.push(`${fieldExpr} >= ${predicateValueExpr(lower, timeUnit)}`);
}
if (upper !== null) {
exprs.push(`${fieldExpr} <= ${predicateValueExpr(upper, timeUnit)}`);
}
return exprs.length > 0 ? exprs.join(' && ') : 'true';
}
/* istanbul i... | {
return (
'inrange(' +
fieldExpr +
', [' +
predicateValueExpr(lower, timeUnit) +
', ' +
predicateValueExpr(upper, timeUnit) +
'])'
);
} | conditional_block |
predicate.ts | vgField} from './channeldef';
import {DateTime} from './datetime';
import {ExprRef} from './expr';
import {LogicalComposition} from './logical';
import {ParameterName} from './parameter';
import {fieldExpr as timeUnitFieldExpr, normalizeTimeUnit, TimeUnit, TimeUnitParams} from './timeunit';
import {stringify} from './... |
export interface FieldGTEPredicate extends FieldPredicateBase {
/**
* The value that the field should be greater than or equals to.
*/
gte: string | number | DateTime | ExprRef | SignalRef;
}
export function isFieldGTEPredicate(predicate: any): predicate is FieldGTEPredicate {
return predicate && !!predi... | {
return predicate && !!predicate.field && predicate.gt !== undefined;
} | identifier_body |
predicate.ts | , vgField} from './channeldef';
import {DateTime} from './datetime';
import {ExprRef} from './expr';
import {LogicalComposition} from './logical';
import {ParameterName} from './parameter';
import {fieldExpr as timeUnitFieldExpr, normalizeTimeUnit, TimeUnit, TimeUnitParams} from './timeunit';
import {stringify} from '.... | (predicate: FieldPredicate, useInRange = true) {
const {field} = predicate;
const timeUnit = normalizeTimeUnit(predicate.timeUnit)?.unit;
const fieldExpr = timeUnit
? // For timeUnit, cast into integer with time() so we can use ===, inrange, indexOf to compare values directly.
// TODO: We calculate time... | fieldFilterExpression | identifier_name |
predicate.ts | , vgField} from './channeldef';
import {DateTime} from './datetime';
import {ExprRef} from './expr';
import {LogicalComposition} from './logical';
import {ParameterName} from './parameter';
import {fieldExpr as timeUnitFieldExpr, normalizeTimeUnit, TimeUnit, TimeUnitParams} from './timeunit';
import {stringify} from '.... | return `${fieldExpr}===${predicateValueExpr(predicate.equal, timeUnit)}`;
} else if (isFieldLTPredicate(predicate)) {
const upper = predicate.lt;
return `${fieldExpr}<${predicateValueExpr(upper, timeUnit)}`;
} else if (isFieldGTPredicate(predicate)) {
const lower = predicate.gt;
return `${fieldE... |
if (isFieldEqualPredicate(predicate)) { | random_line_split |
main.rs | extern crate clap;
extern crate colored;
extern crate glob;
extern crate libc;
extern crate regex;
//#[macro_use]
extern crate itertools;
mod replacer;
mod operation_mode;
mod interactor;
mod arguments;
mod fs_walker;
use std::io::{BufReader, BufWriter};
use std::io::prelude::*;
use std::fs::{remove_file, rename, F... |
}
pub fn main() {
let args = arguments::parse();
let mode = if args.regex_enabled {
operation_mode::OperationMode::new_regex(&args.search_pattern).expect("Invalid regex")
} else {
operation_mode::OperationMode::new_raw(&args.search_pattern)
};
colored::control::set_override(!args... | {
format!("prep_tmp_file_{}", unsafe { getpid() })
} | identifier_body |
main.rs | extern crate clap;
extern crate colored;
extern crate glob;
extern crate libc;
extern crate regex;
//#[macro_use]
extern crate itertools;
mod replacer;
mod operation_mode;
mod interactor;
mod arguments;
mod fs_walker;
use std::io::{BufReader, BufWriter};
use std::io::prelude::*;
use std::fs::{remove_file, rename, F... | () -> TemporaryPrepFile {
let filename = Self::generate_filename();
let wf = File::create(&filename).expect("Could not create temporary file");
TemporaryPrepFile {
writer: BufWriter::new(wf),
filename: filename,
}
}
fn filename(&self) -> &str {
re... | new | identifier_name |
main.rs | extern crate clap;
extern crate colored;
extern crate glob;
extern crate libc;
extern crate regex;
//#[macro_use]
extern crate itertools;
mod replacer;
mod operation_mode;
mod interactor;
mod arguments;
mod fs_walker;
use std::io::{BufReader, BufWriter};
use std::io::prelude::*;
use std::fs::{remove_file, rename, F... | write!(tmp.writer, "{}{}", line, line_end)
.expect("Failed to write line to temp file.");
curr = next;
next = line_iterator.next();
}
if did_at_least_one_replacement {
let _ = tmp.writer.flush();
... | random_line_split | |
Props.ts | import { BaseFormPropTypes } from '../Form/AbstractFormComponent';
import { TextInputProps } from 'react-native';
import { ReactNode } from 'react';
/**
* @author Sean sean.snow@live.com createAt 2017/11/3
*/
export default interface PropTypes extends BaseFormPropTypes, TextInputProps {
after?: ReactNode;
befor... |
pattern?: RegExp;
required?: boolean;
value?: string;
/**
* 是否启用表单验证,默认为true
*/
validate?: boolean;
/**
* 验证字段的值是否正确
* @param {string} text input 的值
* @returns {boolean} 是否符合预期值
*/
valid?: (text: string) => boolean;
inputStyle?: any;
style?: any;
onChangeText?: (text: strin... |
/**
* input 默认值
*/
defaultValue?: string; | random_line_split |
test_scrooge_gen_integration.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants_test.pant... | return super(ScroogeGenTest, self).run_pants(command, full_config, stdin_data, extra_env,
**kwargs)
@staticmethod
def thrift_test_target(name):
return 'contrib/scrooge/tests/thrift/org/pantsbuild/contrib/scrooge/scrooge_gen:' + name
def test_good(self):... | updated = full_config.get(scope, {})
updated.update(scoped_cfgs)
full_config[scope] = updated | random_line_split |
test_scrooge_gen_integration.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants_test.pant... | (self):
# scrooge_gen should pass with namespace_map specified
cmd = ['gen', self.thrift_test_target('namespace-map-thrift')]
pants_run = self.run_pants(cmd)
self.assert_success(pants_run)
def test_default_java_namespace(self):
# scrooge_gen should pass with default_java_namespace specified
c... | test_namespace_map | identifier_name |
test_scrooge_gen_integration.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants_test.pant... |
return super(ScroogeGenTest, self).run_pants(command, full_config, stdin_data, extra_env,
**kwargs)
@staticmethod
def thrift_test_target(name):
return 'contrib/scrooge/tests/thrift/org/pantsbuild/contrib/scrooge/scrooge_gen:' + name
def test_good(self)... | for scope, scoped_cfgs in config.items():
updated = full_config.get(scope, {})
updated.update(scoped_cfgs)
full_config[scope] = updated | conditional_block |
test_scrooge_gen_integration.py | # coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants_test.pant... | cmd = ['gen', self.thrift_test_target('include-paths-thrift')]
pants_run = self.run_pants(cmd)
self.assert_success(pants_run) | identifier_body | |
Layout.test.tsx | import * as React from 'react' | import Sidebar from '../../containers/Sidebar'
import Layout from '.'
type TestContext = {
sidebar: React.ReactElement<any>
children: React.ReactElement<any>
wrapper: ShallowWrapper<any, {}>
}
describe('Layout', function () {
beforeEach(function (this: TestContext) {
this.children = (
<span classNam... | import {ShallowWrapper, shallow} from 'enzyme' | random_line_split |
titleControl.ts | } from 'vs/workbench/browser/actions';
import { DraggedEditorGroupIdentifier, DraggedEditorIdentifier, fillResourceDataTransfers, LocalSelectionTransfer } from 'vs/workbench/browser/dnd';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { BreadcrumbsConfig } from 'vs/workbench/browser/... | {
return; // only if originating from tabs container
} | conditional_block | |
titleControl.ts | Collector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { prepareActions } from 'vs/workbench/browser/actions';
import { DraggedEditorGroupIdentifier, DraggedEditorIdentifier, fillResourceDataTransfers, LocalSelectionTransfer } from 'vs/workbench/browser/dnd';... | (editorActions: IToolbarActions): { primaryEditorActions: IAction[]; secondaryEditorActions: IAction[]; } {
let primaryEditorActions: IAction[];
let secondaryEditorActions: IAction[];
// Primary actions only for the active group
if (this.accessor.activeGroup === this.group) {
primaryEditorActions = prepareA... | prepareEditorActions | identifier_name |
titleControl.ts | Collector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { prepareActions } from 'vs/workbench/browser/actions';
import { DraggedEditorGroupIdentifier, DraggedEditorIdentifier, fillResourceDataTransfers, LocalSelectionTransfer } from 'vs/workbench/browser/dnd';... |
fillInActionBarActions(titleBarMenu, { arg: this.resourceContext.get(), shouldForwardArgs: true }, { primary, secondary });
}
return { primary, secondary };
}
protected clearEditorActionsToolbar(): void {
this.editorActionsToolbar.setActions([], [])();
this.currentPrimaryEditorActionIds = [];
this.c... | {
const primary: IAction[] = [];
const secondary: IAction[] = [];
// Dispose previous listeners
this.editorToolBarMenuDisposables = dispose(this.editorToolBarMenuDisposables);
// Update the resource context
this.resourceContext.set(toResource(this.group.activeEditor, { supportSideBySide: true }));
// E... | identifier_body |
titleControl.ts | StyleCollector, ITheme, IThemeService, registerThemingParticipant } from 'vs/platform/theme/common/themeService';
import { prepareActions } from 'vs/workbench/browser/actions';
import { DraggedEditorGroupIdentifier, DraggedEditorIdentifier, fillResourceDataTransfers, LocalSelectionTransfer } from 'vs/workbench/browser/... | // Editor actions require the editor control to be there, so we retrieve it via service
const activeControl = this.group.activeControl;
if (activeControl instanceof BaseEditor) {
const codeEditor = getCodeEditor(activeControl.getControl());
const scopedContextKeyService = codeEditor && codeEditor.invokeWith... | // Update the resource context
this.resourceContext.set(toResource(this.group.activeEditor, { supportSideBySide: true }));
| random_line_split |
types.tsx | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDI... | FETCH_REQUEST = '@@metrics/FETCH_REQUEST',
FETCH_SUCCESS = '@@metrics/FETCH_SUCCESS',
FETCH_ERROR = '@@metrics/FETCH_ERROR',
}
export interface IMetricsState {
readonly data: IMetrics;
readonly errors?: AxiosResponse;
readonly loading: boolean;
readonly response?: AxiosResponse;
} | };
}
export enum MetricsActionTypes { | random_line_split |
render_all_data.rs |
/// Used for testing. The message contains a timestamp that would make the
/// same output files look different if they're only generated at different
/// times.
#[cfg(test)]
pub fn save_without_message_as(
&self,
file_name_base: &str,
) -> Result<(), Error> {
self.save... | {
self.save_helper(file_name_base, true)
} | identifier_body | |
render_all_data.rs | generated at different
/// times.
#[cfg(test)]
pub fn save_without_message_as(
&self,
file_name_base: &str,
) -> Result<(), Error> {
self.save_helper(file_name_base, false)
}
fn save_helper(
&self,
file_name_base: &str,
with_message: bool,
) ... | values: self
.get_anagram_mod_numbers()?
.iter()
.map(|num| num.to_c())
.collect(),
c_type: "uint8_t".to_c(),
is_extern: true,
});
group.push(CTree::StdArray {
name: "plain_mod_keys".to_c(),
... | });
group.push(CTree::StdArray {
name: "anagram_mod_numbers".to_c(), | random_line_split |
render_all_data.rs | (&self, file_name_base: &str) -> Result<(), Error> {
self.save_helper(file_name_base, true)
}
/// Used for testing. The message contains a timestamp that would make the
/// same output files look different if they're only generated at different
/// times.
#[cfg(test)]
pub fn save_withou... | save_as | identifier_name | |
render_all_data.rs | at different
/// times.
#[cfg(test)]
pub fn save_without_message_as(
&self,
file_name_base: &str,
) -> Result<(), Error> {
self.save_helper(file_name_base, false)
}
fn save_helper(
&self,
file_name_base: &str,
with_message: bool,
) -> Result<... |
group.push(CTree::LiteralH("#pragma once\n".to_c()));
group.push(CTree::IncludeSelf);
group.push(CTree::IncludeH {
path: "<Arduino.h>".to_c(),
});
group.push(CTree::IncludeH {
path: "<stdint.h>".to_c(),
});
group.push(CTree::IncludeH {
path: "\"config_types.h\"".to_... | {
let msg = autogen_message();
group.push(CTree::LiteralC(msg.clone()));
group.push(CTree::LiteralH(msg));
} | conditional_block |
overlaystep.py | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the ... |
else:
self.wizard.clear_msg('overlay')
# now check import
d = self.wizard.checkImport(self.worker, 'PIL')
d.addCallback(checkImport)
d.addErrback(importError)
self.wizard.waitForTask('overlay')
# first check elements
... | f = ngettext("Worker '%s' is missing GStreamer element '%s'.",
"Worker '%s' is missing GStreamer elements '%s'.",
len(elements))
message = messages.Warning(
T_(f, self.worker, "', '".join(elements)), mid='overlay')
message.add(
... | conditional_block |
overlaystep.py | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the ... | self.text.set_sensitive(sensitive)
def _checkElements(self):
self.model.can_overlay = False
def importError(error):
self.info('could not import PIL')
message = messages.Warning(
T_(N_("Worker '%s' cannot import module '%s'."),
self... | self.show_logo.set_sensitive(sensitive) | random_line_split |
overlaystep.py | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the ... | (unused):
self.wizard.taskFinished()
# taskFinished updates sensitivity
self.model.can_overlay = True
def checkElements(elements):
if elements:
f = ngettext("Worker '%s' is missing GStreamer element '%s'.",
"Worker '%s' is miss... | checkImport | identifier_name |
overlaystep.py | # -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# Flumotion - a streaming media server
# Copyright (C) 2004,2005,2006,2007,2008 Fluendo, S.L. (www.fluendo.com).
# All rights reserved.
# This file may be distributed and/or modified under the terms of
# the GNU General Public License version 2 as published by
# the ... | def checkImport(unused):
self.wizard.taskFinished()
# taskFinished updates sensitivity
self.model.can_overlay = True
def checkElements(elements):
if elements:
f = ngettext("Worker '%s' is missing GStreamer element '%s'.",
... | self.model.can_overlay = False
def importError(error):
self.info('could not import PIL')
message = messages.Warning(
T_(N_("Worker '%s' cannot import module '%s'."),
self.worker, 'PIL'))
message.add(
T_(N_("\nThis module is ... | identifier_body |
exit.js | var Exit = Class.create(Brick, {
initialize: function($super) {
$super();
this.isDraggable = false;
this.isRemoveable = false;
this.isInFront = false;
this.hasShadow = false;
},
drawShape: function(context) {
var checkerBoardSize = 5,
checkerSize = Brick.SIZE / checkerBoa... |
counter++;
}
}
},
createShapes: function(body) {
var shapeDefinition = new b2PolygonDef();
shapeDefinition.vertexCount = 4;
shapeDefinition.restitution = 0;
shapeDefinition.friction = 0.9;
shapeDefinition.vertices[0].Set(0.3, 0.3);
shapeDefinition.vert... | {
context.fillRect(checkerSize * j, checkerSize * i, checkerSize, checkerSize);
} | conditional_block |
exit.js | var Exit = Class.create(Brick, {
initialize: function($super) {
$super();
this.isDraggable = false;
this.isRemoveable = false;
this.isInFront = false;
this.hasShadow = false;
},
drawShape: function(context) {
var checkerBoardSize = 5,
checkerSize = Brick.SIZE / checkerBoa... | createShapes: function(body) {
var shapeDefinition = new b2PolygonDef();
shapeDefinition.vertexCount = 4;
shapeDefinition.restitution = 0;
shapeDefinition.friction = 0.9;
shapeDefinition.vertices[0].Set(0.3, 0.3);
shapeDefinition.vertices[1].Set(-0.3, 0.3);
shapeDefinition.vertices[2].... | random_line_split | |
__init__.py | # $Id$
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtk_kit package driver file.
This performs all initialisation necessary to use VTK from DeVIDE. Makes
sure that all VTK clas... |
# import the main module itself
# the global is so that users can also do:
# from module_kits import vtk_kit
# vtk_kit.vtk.vtkSomeFilter()
global vtk
import vtk
# and do the same for vtkdevide
global vtkdevide
import vtkdevide
# load up some generic functions into this namesp... | preImportVTK(module_manager.setProgress) | conditional_block |
__init__.py | # $Id$
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtk_kit package driver file.
This performs all initialisation necessary to use VTK from DeVIDE. Makes
sure that all VTK clas... | ():
# brought over from ITK Wrapping/CSwig/Python
# Python "help(sys.setdlopenflags)" states:
#
# setdlopenflags(...)
# setdlopenflags(n) -> None
#
# Set the flags that will be used for dlopen() calls. Among other
# things, this will enable a lazy resolving of symbols w... | setDLFlags | identifier_name |
__init__.py | # $Id$
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtk_kit package driver file.
This performs all initialisation necessary to use VTK from DeVIDE. Makes
sure that all VTK clas... |
# set the dynamic loading flags. If we don't do this, we get strange
# errors on 64 bit machines. To see this happen, comment this statement
# and then run the VTK->ITK connection test case.
oldflags = setDLFlags()
percentStep = 100.0 / len(vtkImportList)
currentPercent = 0.0
# do the i... | random_line_split | |
__init__.py | # $Id$
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""vtk_kit package driver file.
This performs all initialisation necessary to use VTK from DeVIDE. Makes
sure that all VTK clas... |
def resetDLFlags(data):
# brought over from ITK Wrapping/CSwig/Python
# Restore the original dlopen flags.
try:
sys.setdlopenflags(data)
except:
pass
def init(module_manager, pre_import=True):
# first do the VTK pre-imports: this is here ONLY to keep the user happy
# it'... | try:
import dl
newflags = dl.RTLD_NOW|dl.RTLD_GLOBAL
except:
newflags = 0x102 # No dl module, so guess (see above).
try:
oldflags = sys.getdlopenflags()
sys.setdlopenflags(newflags)
except:
oldflags = None
return oldflags | identifier_body |
issue-9396.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 ... | () {
let (tx, rx) = channel();
spawn(proc (){
let mut timer = Timer::new().unwrap();
timer.sleep(10);
tx.send(());
});
loop {
match rx.try_recv() {
comm::Data(()) => break,
comm::Empty => {}
comm::Disconnected => unreachable!()
... | main | identifier_name |
issue-9396.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 ... | pub fn main() {
let (tx, rx) = channel();
spawn(proc (){
let mut timer = Timer::new().unwrap();
timer.sleep(10);
tx.send(());
});
loop {
match rx.try_recv() {
comm::Data(()) => break,
comm::Empty => {}
comm::Disconnected => unreachable!... | // except according to those terms.
use std::comm;
use std::io::timer::Timer;
| random_line_split |
issue-9396.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 ... | {
let (tx, rx) = channel();
spawn(proc (){
let mut timer = Timer::new().unwrap();
timer.sleep(10);
tx.send(());
});
loop {
match rx.try_recv() {
comm::Data(()) => break,
comm::Empty => {}
comm::Disconnected => unreachable!()
}
... | identifier_body | |
metadata.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fs::Metadata;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use nix::sys::stat::Mode;
#[cfg(target_os = "linux")]
use std... | fn eden_dev(&self) -> u64 {
// Dummy value
0
}
fn eden_file_size(&self) -> u64 {
self.file_size()
}
fn is_setuid_set(&self) -> bool {
// This doesn't exist for windows
false
}
}
#[cfg(target_os = "linux")]
impl MetadataExt for Metadata {
fn eden_dev... | fn is_setuid_set(&self) -> bool;
}
#[cfg(windows)]
impl MetadataExt for Metadata { | random_line_split |
metadata.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fs::Metadata;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use nix::sys::stat::Mode;
#[cfg(target_os = "linux")]
use std... |
fn is_setuid_set(&self) -> bool {
// This doesn't exist for windows
false
}
}
#[cfg(target_os = "linux")]
impl MetadataExt for Metadata {
fn eden_dev(&self) -> u64 {
self.st_dev()
}
fn eden_file_size(&self) -> u64 {
// Use st_blocks as this represents the actual a... | {
self.file_size()
} | identifier_body |
metadata.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
use std::fs::Metadata;
#[cfg(any(target_os = "macos", target_os = "linux"))]
use nix::sys::stat::Mode;
#[cfg(target_os = "linux")]
use std... | (&self) -> u64 {
// Use st_blocks as this represents the actual amount of
// disk space allocated by the file, not its apparent
// size.
self.st_blocks() * 512
}
fn is_setuid_set(&self) -> bool {
let isuid = Mode::S_ISUID;
self.st_mode() & isuid.bits() != 0
}... | eden_file_size | identifier_name |
linktastic.py | # Linktastic Module
# - A python2/3 compatible module that can create hardlinks/symlinks on windows-based systems
#
# Linktastic is distributed under the MIT License. The follow are the terms and conditions of using Linktastic.
#
# The MIT License (MIT)
# Copyright (c) 2012 Solipsis Development
#
# Permission is here... |
# Create a symlink to src named as dest, but don't fail if you're on nt
def junctionlink(src, dest):
if os.name == 'nt':
_junctionlink_windows(src, dest)
else:
os.symlink(src, dest) | os.symlink(src, dest) | conditional_block |
linktastic.py | # Linktastic Module
# - A python2/3 compatible module that can create hardlinks/symlinks on windows-based systems
#
# Linktastic is distributed under the MIT License. The follow are the terms and conditions of using Linktastic.
#
# The MIT License (MIT)
# Copyright (c) 2012 Solipsis Development
#
# Permission is here... | raise IOError(err.output.decode('utf-8'))
# TODO, find out what kind of messages Windows sends us from mklink
# print(stdout)
# assume if they ret-coded 0 we're good
def _junctionlink_windows(src, dest):
try:
subprocess.check_output(
'cmd /C mklink /D %s %s' % (_escape_para... | try:
subprocess.check_output(
'cmd /C mklink /J %s %s' % (_escape_param(dest), _escape_param(src)),
stderr=subprocess.STDOUT)
except CalledProcessError as err: | random_line_split |
linktastic.py | # Linktastic Module
# - A python2/3 compatible module that can create hardlinks/symlinks on windows-based systems
#
# Linktastic is distributed under the MIT License. The follow are the terms and conditions of using Linktastic.
#
# The MIT License (MIT)
# Copyright (c) 2012 Solipsis Development
#
# Permission is here... |
def _dirlink_windows(src, dest):
try:
subprocess.check_output(
'cmd /C mklink /J %s %s' % (_escape_param(dest), _escape_param(src)),
stderr=subprocess.STDOUT)
except CalledProcessError as err:
raise IOError(err.output.decode('utf-8'))
# TODO, find out what kind of ... | try:
subprocess.check_output(
'cmd /C mklink %s %s' % (_escape_param(dest), _escape_param(src)),
stderr=subprocess.STDOUT)
except CalledProcessError as err:
raise IOError(err.output.decode('utf-8'))
# TODO, find out what kind of messages Windows sends us from mklink
... | identifier_body |
linktastic.py | # Linktastic Module
# - A python2/3 compatible module that can create hardlinks/symlinks on windows-based systems
#
# Linktastic is distributed under the MIT License. The follow are the terms and conditions of using Linktastic.
#
# The MIT License (MIT)
# Copyright (c) 2012 Solipsis Development
#
# Permission is here... | (src, dest):
try:
subprocess.check_output(
'cmd /C mklink /D %s %s' % (_escape_param(dest), _escape_param(src)),
stderr=subprocess.STDOUT)
except CalledProcessError as err:
raise IOError(err.output.decode('utf-8'))
# TODO, find out what kind of messages Windows sends... | _junctionlink_windows | identifier_name |
bootstrap.js | window._ = require('lodash');
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
window.$ = window.jQuery = require('jquery');
/**
* Vue is... | // next();
//});
/**
* Echo exposes an expressive API for subscribing to channels and listening
* for events that are broadcast by Laravel. Echo and event broadcasting
* allows your team to easily build robust real-time web applications.
*/
// import Echo from "laravel-echo"
// window.Echo = new Echo({
// ... | // request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken);
// | random_line_split |
open_url.ts | import {Callback} from "./callback"
import * as p from "core/properties"
import {get_indices} from "core/util/selection"
import {replace_placeholders} from "core/util/templating"
export namespace OpenURL {
export interface Attrs extends Callback.Attrs {
url: string
}
export interface Props extends Callback.... | extends Callback {
properties: OpenURL.Props
constructor(attrs?: Partial<OpenURL.Attrs>) {
super(attrs)
}
static initClass(): void {
this.prototype.type = 'OpenURL'
this.define({
url: [ p.String, 'http://' ],
})
}
execute(_cb_obj: any, cb_data: {[key: string]: any}): any {
fo... | OpenURL | identifier_name |
open_url.ts | import {Callback} from "./callback"
import * as p from "core/properties"
import {get_indices} from "core/util/selection"
import {replace_placeholders} from "core/util/templating"
export namespace OpenURL {
export interface Attrs extends Callback.Attrs {
url: string
}
export interface Props extends Callback.... | OpenURL.initClass() | random_line_split | |
prelude.rs | // Copyright (C) 2017 Pietro Albini
//
// 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 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! Prelude for Fisher.
//!
//! This module re-exports useful... | // the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of | random_line_split |
popper.tsx | import React, { useState } from 'react';
import { usePopper } from 'react-popper';
import { Box } from '@fower/react';
export default () => {
const [referenceElement, setReferenceElement] = useState(null); | const [popperElement, setPopperElement] = useState(null);
const [arrowElement, setArrowElement] = useState(null);
const { styles, attributes } = usePopper(referenceElement, popperElement, {
placement: 'right',
modifiers: [{ name: 'arrow', options: { element: arrowElement } }],
});
return (
<Box p... | random_line_split | |
FlowField.js | from '../../../../src/lib/Perlin';
export default class FlowField {
constructor(w, h, z, resolution, source, cbInit) {
this.ctx;
this.width = w;
this.height = h;
this.field = [];
this.resolution = resolution || 10;
this.rows = Math.round(w / this.resolution);
this.cols = Math.round(h / ... | for (let j = 0; j<this.rows; j++) {
let noiseVal = noise.noise(xOff, yOff, zOff);
let angle = Utils.mapRange(noiseVal, 0, 1, -1, 1);
let vector = new Vector({
x: Math.cos(angle),
y: Math.sin(angle)
});
vectors[z][i][j] = vector;
... | random_line_split | |
FlowField.js | from '../../../../src/lib/Perlin';
export default class FlowField {
| (w, h, z, resolution, source, cbInit) {
this.ctx;
this.width = w;
this.height = h;
this.field = [];
this.resolution = resolution || 10;
this.rows = Math.round(w / this.resolution);
this.cols = Math.round(h / this.resolution);
this.depth = z >= 1 ? z:1;
this.zIndex = 0;
this.mustR... | constructor | identifier_name |
FlowField.js | '../../../../src/lib/Perlin';
export default class FlowField {
constructor(w, h, z, resolution, source, cbInit) {
this.ctx;
this.width = w;
this.height = h;
this.field = [];
this.resolution = resolution || 10;
this.rows = Math.round(w / this.resolution);
this.cols = Math.round(h / this.... |
gridFromSpecial() {
let vectors = this.getSpecialVectors();
this.createGrid(vectors);
}
getSpecialVectors() {
let vectors = [];
for (let z=0; z<this.depth; z++) {
vectors[z] = [];
for (let i = 0; i<this.cols; i++) {
vectors[z][i] = new Array(this.rows);
for (let j = ... | {
source = source || {};
let vectors = this.getVectorsFromPerlinNoise(source.seed, source.res);
this.createGrid(vectors);
} | identifier_body |
FlowField.js | '../../../../src/lib/Perlin';
export default class FlowField {
constructor(w, h, z, resolution, source, cbInit) {
this.ctx;
this.width = w;
this.height = h;
this.field = [];
this.resolution = resolution || 10;
this.rows = Math.round(w / this.resolution);
this.cols = Math.round(h / this.... |
let x = 0;
let y = 0;
this.ctx.clearRect(0, 0, this.width, this.height);
for (let i = 0; i<this.cols; i++) {
y = i * this.resolution;
for (let j = 0; j<this.rows; j++) {
x = j * this.resolution;
let v = this.field[this.zIndex][i][j];
let angle = v.getAngle();
... | {
return;
} | conditional_block |
move-3.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 = @Triple{x: 1, y: 2, z: 3};
for _i in range(0u, 10000u) {
assert_eq!(test(true, x), 2);
}
assert_eq!(test(false, x), 5);
}
| main | identifier_name |
move-3.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 ... | return y.y;
}
pub fn main() {
let x = @Triple{x: 1, y: 2, z: 3};
for _i in range(0u, 10000u) {
assert_eq!(test(true, x), 2);
}
assert_eq!(test(false, x), 5);
} |
fn test(x: bool, foo: @Triple) -> int {
let bar = foo;
let mut y: @Triple;
if x { y = bar; } else { y = @Triple{x: 4, y: 5, z: 6}; } | random_line_split |
move-3.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 ... | else { y = @Triple{x: 4, y: 5, z: 6}; }
return y.y;
}
pub fn main() {
let x = @Triple{x: 1, y: 2, z: 3};
for _i in range(0u, 10000u) {
assert_eq!(test(true, x), 2);
}
assert_eq!(test(false, x), 5);
}
| { y = bar; } | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
/// We have a few jobs that maintain some counters for each Mononoke repository. For example,
/// the latest blobimport... | else {
TransactionResult::Failed
})
}
}
| {
TransactionResult::Succeeded(txn)
} | conditional_block |
lib.rs | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This software may be used and distributed according to the terms of the
* GNU General Public License version 2.
*/
#![deny(warnings)]
/// We have a few jobs that maintain some counters for each Mononoke repository. For example,
/// the latest blobimport... | ctx: CoreContext,
repoid: RepositoryId,
name: &str,
) -> BoxFuture<Option<i64>, Error>;
/// Set the current value of the counter. if `prev_value` is not None, then it sets the value
/// conditionally.
fn set_counter(
&self,
ctx: CoreContext,
repoid: Repos... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.