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 |
|---|---|---|---|---|
windows.py | (self):
return self.right - self.left
width = property(getWidth, None, None, "")
def getSize(self):
return self.width, self.height
size = property(getSize, None, None, "")
def ContainsPoint(self, pt):
"""determines if this RECT contains the given POINT pt
returns ... | getWidth | identifier_name | |
regress-352742-01.js | /* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
var gTestfile = 'regress-35... |
exitFunc ('test');
}
| {
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
print('If the test harness fails, this test fails.');
expect = 4;
z = {valueOf: Function};
actual = 2;
try {
[11].filter(z);
}
catch(e)
{
actual = 3;
print(e);
}
actual = 4;
reportCompare(expect, actual, s... | identifier_body |
regress-352742-01.js | /* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
var gTestfile = 'regress-35... | var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
print('If the test harness fails, t... | var actual = ''; | random_line_split |
regress-352742-01.js | /* -*- Mode: javascript; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* 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/. */
var gTestfile = 'regress-35... | ()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
print('If the test harness fails, this test fails.');
expect = 4;
z = {valueOf: Function};
actual = 2;
try {
[11].filter(z);
}
catch(e)
{
actual = 3;
print(e);
}
actual = 4;
reportCompare(expect, actual... | test | identifier_name |
other-layers.js | import React, { Component } from 'react'
import {
Circle,
FeatureGroup,
LayerGroup, | TileLayer,
} from '../../src'
export default class OtherLayersExample extends Component {
render () {
const center = [51.505, -0.09]
const rectangle = [
[51.49, -0.08],
[51.5, -0.06],
]
return (
<Map center={center} zoom={13}>
<TileLayer
attribution='© <a h... | Map,
Popup,
Rectangle, | random_line_split |
other-layers.js | import React, { Component } from 'react'
import {
Circle,
FeatureGroup,
LayerGroup,
Map,
Popup,
Rectangle,
TileLayer,
} from '../../src'
export default class OtherLayersExample extends Component {
| () {
const center = [51.505, -0.09]
const rectangle = [
[51.49, -0.08],
[51.5, -0.06],
]
return (
<Map center={center} zoom={13}>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org... | render | identifier_name |
ordered-bubble.js | import F2 from '@antv/f2';
const Shape = F2.Shape;
Shape.registerShape('point', 'with-text', {
draw: function draw(cfg, container) {
const size = cfg.size;
const x = cfg.x;
const y = cfg.y;
const circle = container.addShape('Circle', {
className: 'point',
attrs: {
x,
y,
... | tickInerval: 1
}
});
chart.axis(false);
chart.tooltip(false);
chart.legend(false);
chart.point()
.position('x*y')
.color('volumes', '#BAE7FF-#1890FF-#0050B3')
.size('volumes', [ 10, 50 ])
.shape('with-text');
chart.render(); | },
x: {
max: 12, | random_line_split |
from_bytes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::cmp;
use encoding::label::encoding_from_whatwg_label;
use encoding::all::UTF_8;
use encoding::{EncodingR... | (css: &[u8], protocol_encoding_label: Option<&str>,
environment_encoding: Option<EncodingRef>)
-> (String, EncodingRef) {
// https://drafts.csswg.org/css-syntax/#the-input-byte-stream
match protocol_encoding_label {
None => (),
Some(labe... | decode_stylesheet_bytes | identifier_name |
from_bytes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::cmp;
use encoding::label::encoding_from_whatwg_label;
use encoding::all::UTF_8;
use encoding::{EncodingR... | Some(fallback) => return decode_replace(css, fallback)
}
return decode_replace(css, UTF_8 as EncodingRef)
}
#[inline]
fn decode_replace(input: &[u8], fallback_encoding: EncodingRef)-> (String, EncodingRef) {
let (result, used_encoding) = decode(input, DecoderTrap::Replace, fallback_encoding);
... | match environment_encoding {
None => (), | random_line_split |
from_bytes.rs | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use std::cmp;
use encoding::label::encoding_from_whatwg_label;
use encoding::all::UTF_8;
use encoding::{EncodingR... | Some(fallback) => match fallback.name() {
"utf-16be" | "utf-16le"
=> return decode_replace(css, UTF_8 as EncodingRef),
_ => return decode_replace(css, fallback),
}
}
}
}
... | {
// https://drafts.csswg.org/css-syntax/#the-input-byte-stream
match protocol_encoding_label {
None => (),
Some(label) => match encoding_from_whatwg_label(label) {
None => (),
Some(fallback) => return decode_replace(css, fallback)
}
}
if css.starts_with("... | identifier_body |
ImportComponent.tsx |
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import SettingController, { DBEnum } from "../SettingController";
import FileUtil from "../../../../Base/Util/FileUtil";
import StdUtil from "../../../../Base/Util/StdUtil";
import UserSettingsController from "../../UserSettingsController";
/**
... |
message: string;
}
/**
* ステータス
*/
export interface ImportStat {
message: Array<ImportResult>,
}
export default class ImportComponent extends React.Component<ImportProp, ImportStat> {
/**
* コンストラクタ
* @param props
* @param context
*/
constructor(props?: ImportProp, context?: an... | ed: boolean; | identifier_name |
ImportComponent.tsx |
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import SettingController, { DBEnum } from "../SettingController";
import FileUtil from "../../../../Base/Util/FileUtil";
import StdUtil from "../../../../Base/Util/StdUtil";
import UserSettingsController from "../../UserSettingsController";
/**
... | /**
*
*/
public OnClick(event) {
this.setState({
message: new Array<ImportResult>(),
});
FileUtil.SelectImportFile((file) => {
FileUtil.Import(file,
(data) => {
this.props.owner.Import(data,
... | );
}
| random_line_split |
edges.rs | //! Edges representation in GIR.
use prelude::{EdgeWeight, Idx};
/// Single edge representation.
///
/// `Idx` indicates unique id of the endpoint node of the edge, assigned based on the
/// GIR creation order.
/// Last byte denotes last character in the kmer.
pub type Edge = (Idx, EdgeWeight, u8);
/// Stores informa... | }
}
impl Default for Edges {
fn default() -> Edges {
Edges {
outgoing: Box::new([]),
idx: 0,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_edge() {
let mut e: Edges = Edges::empty(0);
assert_eq!(e.idx, 0);
assert_e... | random_line_split | |
edges.rs | //! Edges representation in GIR.
use prelude::{EdgeWeight, Idx};
/// Single edge representation.
///
/// `Idx` indicates unique id of the endpoint node of the edge, assigned based on the
/// GIR creation order.
/// Last byte denotes last character in the kmer.
pub type Edge = (Idx, EdgeWeight, u8);
/// Stores informa... |
/// Adds edge with the given endpoint.
pub fn add_edge(&mut self, to: Idx, last_char: u8) {
let mut out_ = Vec::new();
out_.extend_from_slice(&self.outgoing);
out_.push((to, 1, last_char));
self.outgoing = out_.into_boxed_slice();
}
/// Removes edges with weight below ... | {
Edges {
outgoing: Box::new([]),
idx: idx_,
}
} | identifier_body |
edges.rs | //! Edges representation in GIR.
use prelude::{EdgeWeight, Idx};
/// Single edge representation.
///
/// `Idx` indicates unique id of the endpoint node of the edge, assigned based on the
/// GIR creation order.
/// Last byte denotes last character in the kmer.
pub type Edge = (Idx, EdgeWeight, u8);
/// Stores informa... | () {
let mut e: Edges = Edges::empty(0);
assert_eq!(e.idx, 0);
assert_eq!(e.outgoing.len(), 0);
e.add_edge(0, b'a');
assert_eq!(e.outgoing.len(), 1);
}
#[test]
fn removes_weak_edges() {
let mut e: Edges = Edges::empty(1);
assert_eq!(e.idx, 1);
... | adds_edge | identifier_name |
ProcessMonitor.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#*/1 * * * * python /xxx/monitor.py >> /xxx/logs/monitor.log 2>&1 &
import sys
import subprocess
import os.path as op
import socket
def this_abs_path(script_name):
return op.abspath(op.join(op.dirname(__file__), script_name))
def monitor_process(key_word, cmd):
... |
if __name__ == '__main__':
main() | yuanzhaopin() | identifier_body |
ProcessMonitor.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#*/1 * * * * python /xxx/monitor.py >> /xxx/logs/monitor.log 2>&1 &
import sys
import subprocess
import os.path as op
import socket
def this_abs_path(script_name):
return op.abspath(op.join(op.dirname(__file__), script_name))
def monitor_process(key_word, cmd):
... | ():
cmd = '%s start' % this_abs_path('gun.sh')
#monitor_process('\[yuanzhaopin\]', cmd)
monitor_port('tcp', 8635, cmd)
def main():
yuanzhaopin()
if __name__ == '__main__':
main() | yuanzhaopin | identifier_name |
ProcessMonitor.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#*/1 * * * * python /xxx/monitor.py >> /xxx/logs/monitor.log 2>&1 &
import sys
import subprocess
import os.path as op
import socket
def this_abs_path(script_name):
return op.abspath(op.join(op.dirname(__file__), script_name))
def monitor_process(key_word, cmd):
... |
sys.stderr.write('process[%s] is lost, run [%s]\n' % (key_word, cmd))
subprocess.call(cmd, shell=True)
def monitor_port(protocol, port, cmd):
address = ('127.0.0.1', port)
socket_type = socket.SOCK_STREAM if protocol == 'tcp' else socket.SOCK_DGRAM
client = socket.socket(socket.AF_INET, socket_typ... | return | conditional_block |
ProcessMonitor.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#*/1 * * * * python /xxx/monitor.py >> /xxx/logs/monitor.log 2>&1 &
import sys
import subprocess
import os.path as op
import socket
def this_abs_path(script_name):
return op.abspath(op.join(op.dirname(__file__), script_name))
def monitor_process(key_word, cmd):
... | yuanzhaopin()
if __name__ == '__main__':
main() | #monitor_process('\[yuanzhaopin\]', cmd)
monitor_port('tcp', 8635, cmd)
def main(): | random_line_split |
lib.rs | _session::lint::{LintArray, LintPass};
pub fn provide(providers: &mut Providers) {
levels::provide(providers);
*providers = Providers { lint_mod, ..*providers };
}
fn | (tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
}
macro_rules! pre_expansion_lint_passes {
($macro:path, $args:tt) => {
$macro!($args, [KeywordIdents: KeywordIdents,]);
};
}
macro_rules! early_lint_passes {
($mac... | lint_mod | identifier_name |
lib.rs | _session::lint::{LintArray, LintPass};
pub fn provide(providers: &mut Providers) {
levels::provide(providers);
*providers = Providers { lint_mod, ..*providers };
}
fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
}... | }
if no_interleave_lints {
pre_expansion_lint_passes!(register_passes, register_pre_expansion_pass);
early_lint_passes!(register_passes, register_early_pass);
late_lint_passes!(register_passes, register_late_pass);
late_lint_mod_passes!(register_passes, register_late_mod_pass);
... | {
macro_rules! add_lint_group {
($name:expr, $($lint:ident),*) => (
store.register_group(false, $name, None, vec![$(LintId::of($lint)),*]);
)
}
macro_rules! register_pass {
($method:ident, $ty:ident, $constructor:expr) => {
store.register_lints(&$ty::get_lint... | identifier_body |
lib.rs | ::lint::{LintArray, LintPass};
pub fn provide(providers: &mut Providers) {
levels::provide(providers);
*providers = Providers { lint_mod, ..*providers };
}
fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
}
macro_... |
lint_store
}
/// Tell the `LintStore` about all the built-in lints (the ones
/// defined in this crate and the ones defined in
/// `rustc_session::lint::builtin`).
fn register_builtins(store: &mut LintStore, no_interleave_lints: bool) {
macro_rules! add_lint_group {
($name:expr, $($lint:ident),*) => ... | {
register_internals(&mut lint_store);
} | conditional_block |
lib.rs | _session::lint::{LintArray, LintPass};
pub fn provide(providers: &mut Providers) {
levels::provide(providers);
*providers = Providers { lint_mod, ..*providers };
}
fn lint_mod(tcx: TyCtxt<'_>, module_def_id: LocalDefId) {
late::late_lint_mod(tcx, module_def_id, BuiltinCombinedModuleLateLintPass::new());
}... | store.register_renamed("bare_trait_object", "bare_trait_objects");
store.register_renamed("unstable_name_collision", "unstable_name_collisions");
store.register_renamed("unused_doc_comment", "unused_doc_comments");
store.register_renamed("async_idents", "keyword_idents");
store.register_renamed("exc... | // Register renamed and removed lints.
store.register_renamed("single_use_lifetime", "single_use_lifetimes");
store.register_renamed("elided_lifetime_in_path", "elided_lifetimes_in_paths"); | random_line_split |
rm.rs | #![crate_name = "rm"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#![feature(macro_rules)]
extern crate getopts;
extern crate libc;... | (msg: &str) -> bool {
print(msg);
read_prompt()
}
fn read_prompt() -> bool {
stdio::flush();
match BufferedReader::new(stdin()).read_line() {
Ok(line) => {
match line.as_slice().char_at(0) {
'y' | 'Y' => true,
'n' | 'N' => false,
_ => ... | prompt | identifier_name |
rm.rs | #![crate_name = "rm"]
/*
* This file is part of the uutils coreutils package.
*
* (c) Arcterus <arcterus@mail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
#![feature(macro_rules)]
extern crate getopts;
extern crate libc;... | } | random_line_split | |
describe-endpoint.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iot::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | println!();
}
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
show_address(&client, &endpoint_type).await
}
| {
tracing_subscriber::fmt::init();
let Opt {
region,
endpoint_type,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
println!();
if ver... | identifier_body |
describe-endpoint.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iot::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... |
let shared_config = aws_config::from_env().region(region_provider).load().await;
let client = Client::new(&shared_config);
show_address(&client, &endpoint_type).await
}
| {
println!("IoT client version: {}", PKG_VERSION);
println!(
"Region: {}",
region_provider.region().await.unwrap().as_ref()
);
println!("Endpoint type: {}", &endpoint_type);
println!();
} | conditional_block |
describe-endpoint.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iot::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | // - iot:Jobs - Returns an AWS IoT device management Jobs API endpoint.
/// * `[-r REGION]` - The Region in which the client is created.
/// If not supplied, uses the value of the **AWS_REGION** environment variable.
/// If the environment variable is not set, defaults to **us-west-2**.
/// * `[-v]` - Whether to... | /// * `-e ENDPOINT-TYPE - The type of endpoint.
/// Must be one of:
/// - iot:Data - Returns a VeriSign signed data endpoint.
/// - iot:Data-ATS - Returns an ATS signed data endpoint.
/// - iot:CredentialProvider - Returns an AWS IoT credentials provider API endpoint. | random_line_split |
describe-endpoint.rs | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_iot::{Client, Error, Region, PKG_VERSION};
use structopt::StructOpt;
#[derive(Debug, StructOpt)]
struct Opt {
/// The AWS Region.
... | () -> Result<(), Error> {
tracing_subscriber::fmt::init();
let Opt {
region,
endpoint_type,
verbose,
} = Opt::from_args();
let region_provider = RegionProviderChain::first_try(region.map(Region::new))
.or_default_provider()
.or_else(Region::new("us-west-2"));
... | main | identifier_name |
multiwindow.rs | mod support;
use glutin::event::{Event, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::window::WindowBuilder;
use glutin::ContextBuilder;
use support::{ContextCurrentWrapper, ContextTracker, ContextWrapper};
fn main() | match event {
Event::LoopDestroyed => return,
Event::WindowEvent { event, window_id } => match event {
WindowEvent::Resized(physical_size) => {
let windowed_context = ct.get_current(windows[&window_id].0).unwrap();
let windowed_cont... | {
let el = EventLoop::new();
let mut ct = ContextTracker::default();
let mut windows = std::collections::HashMap::new();
for index in 0..3 {
let title = format!("Charming Window #{}", index + 1);
let wb = WindowBuilder::new().with_title(title);
let windowed_context = ContextBuil... | identifier_body |
multiwindow.rs | mod support;
use glutin::event::{Event, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::window::WindowBuilder;
use glutin::ContextBuilder;
use support::{ContextCurrentWrapper, ContextTracker, ContextWrapper};
fn main() {
let el = EventLoop::new();
let mut ct = ContextTracker::defau... | windows.insert(window_id, (context_id, gl, index));
}
el.run(move |event, _, control_flow| {
println!("{:?}", event);
match event {
Event::LoopDestroyed => return,
Event::WindowEvent { event, window_id } => match event {
WindowEvent::Resized(physi... | let context_id = ct.insert(ContextCurrentWrapper::PossiblyCurrent(
ContextWrapper::Windowed(windowed_context),
)); | random_line_split |
multiwindow.rs | mod support;
use glutin::event::{Event, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::window::WindowBuilder;
use glutin::ContextBuilder;
use support::{ContextCurrentWrapper, ContextTracker, ContextWrapper};
fn | () {
let el = EventLoop::new();
let mut ct = ContextTracker::default();
let mut windows = std::collections::HashMap::new();
for index in 0..3 {
let title = format!("Charming Window #{}", index + 1);
let wb = WindowBuilder::new().with_title(title);
let windowed_context = ContextB... | main | identifier_name |
multiwindow.rs | mod support;
use glutin::event::{Event, WindowEvent};
use glutin::event_loop::{ControlFlow, EventLoop};
use glutin::window::WindowBuilder;
use glutin::ContextBuilder;
use support::{ContextCurrentWrapper, ContextTracker, ContextWrapper};
fn main() {
let el = EventLoop::new();
let mut ct = ContextTracker::defau... | else {
*control_flow = ControlFlow::Wait
}
});
}
| {
*control_flow = ControlFlow::Exit
} | conditional_block |
performanceTests.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restric... | }
let average = timer.stop() / iterations;
expect(average).toBeLessThan(Helpers.getExpectedTime(plugin.name, expectedTime));
return average;
}
});
}
| visual.update({ dataViews: [Helpers.getDataViewByVisual(plugin.name)], viewport: { width: 100, height: 100 } });
}
| conditional_block |
performanceTests.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restric... | }
else if (visual.update) {
visual.update({ dataViews: [Helpers.getDataViewByVisual(plugin.name)], viewport: { width: 100, height: 100 } });
}
}
let average = timer.stop() / iterations;
expect(average).toBeLessThan(... | let timer = new Timer();
visual = powerbi.extensibility.createVisualAdapter(plugin);
visual.init({
element: element,
host: hostServices,
style: VisualStyles.create(),
viewport: {
height: element.hei... | identifier_body |
performanceTests.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restric... | lugin: VisualPlugin, iterations: number = DEFAULT_ITERATIONS_COUNT, expectedTime: number = DEFAULT_MAX_TIME_FOR_RENDER): number {
let timer = new Timer();
visual = powerbi.extensibility.createVisualAdapter(plugin);
visual.init({
element: element,
hos... | nPerformanceTest(p | identifier_name |
performanceTests.ts | /*
* Power BI Visualizations
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restric... | // Exclude map, filled map, and heat map because they require more advanced mocking in order to run in test mode
describe("Performance measuring", () => {
let visual: powerbi.IVisual, element: JQuery;
let hostServices = mocks.createVisualHostServices();
let measurePlugin = powerbi.vis... | const ESTIMATE_FOR_MEASURE_PLUGIN_NAME = "scatterChart";
const DEFAULT_HEIGHT = "770";
const DEFAULT_WIDTH = "770";
const EXCLUDED_VISUALS: string[] = [MEASURE_PLUGIN_NAME, "sunburstCustom", "sunburst", "basicShape", "bingNews", "bingSocialNews", "bingSocialTweets", "partitionMap", "categoricalFilter", ... | random_line_split |
member.rs | use clap::ArgMatches;
use rand::{thread_rng, Rng};
use std::fmt;
pub fn build(matches: &ArgMatches) -> Vec<NewMember> |
fn extract_names<'a>(matches: &'a ArgMatches) -> Vec<&'a str> {
matches
.value_of("members")
.expect("members")
.split(",")
.collect()
}
#[derive(Debug, Serialize)]
pub struct NewMember {
name: String,
position: i32,
}
impl NewMember {
pub fn new(name: &str, position:... | {
let mut names = extract_names(matches);
let mut rng = thread_rng();
rng.shuffle(&mut names);
names
.into_iter()
.enumerate()
.map(|(index, name)| {
let position = index as i32 + 1;
NewMember::new(name, position)
})
.collect()
} | identifier_body |
member.rs | use clap::ArgMatches;
use rand::{thread_rng, Rng};
use std::fmt;
pub fn build(matches: &ArgMatches) -> Vec<NewMember> {
let mut names = extract_names(matches);
let mut rng = thread_rng();
rng.shuffle(&mut names);
names
.into_iter()
.enumerate()
.map(|(index, name)| {
... | (name: &str, position: i32) -> NewMember {
NewMember {
name: name.into(),
position: position,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct Member {
pub id: i32,
pub name: String,
pub position: i32,
pub active: bool,
pub driver: bool,
}... | new | identifier_name |
member.rs | use clap::ArgMatches;
use rand::{thread_rng, Rng};
use std::fmt;
pub fn build(matches: &ArgMatches) -> Vec<NewMember> {
let mut names = extract_names(matches);
let mut rng = thread_rng();
rng.shuffle(&mut names);
names
.into_iter()
.enumerate()
.map(|(index, name)| {
... | .value_of("members")
.expect("members")
.split(",")
.collect()
}
#[derive(Debug, Serialize)]
pub struct NewMember {
name: String,
position: i32,
}
impl NewMember {
pub fn new(name: &str, position: i32) -> NewMember {
NewMember {
name: name.into(),
... | matches | random_line_split |
15. Guess 4 turns.py | from random import randint
board = []
for x in range(5):
|
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print s... | board.append(["O"] * 5) | conditional_block |
15. Guess 4 turns.py | from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
|
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
print "Turn", turn + 1
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
... | return randint(0, len(board[0]) - 1) | identifier_body |
15. Guess 4 turns.py | from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def random_col(board):
return randint(0,... | print "Turn", turn + 1
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))
if guess_row == ship_row and guess_col == ship_col:
print "Congratulations! You sunk my battleship!"
else:
if (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col ... |
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4): | random_line_split |
15. Guess 4 turns.py | from random import randint
board = []
for x in range(5):
board.append(["O"] * 5)
def print_board(board):
for row in board:
print " ".join(row)
print "Let's play Battleship!"
print_board(board)
def random_row(board):
return randint(0, len(board) - 1)
def | (board):
return randint(0, len(board[0]) - 1)
ship_row = random_row(board)
ship_col = random_col(board)
print ship_row
print ship_col
# Everything from here on should go in your for loop!
# Be sure to indent four spaces!
for turn in range(4):
print "Turn", turn + 1
guess_row = int(raw_input("Guess Row:"))... | random_col | identifier_name |
scan-negative-lookahead.rs | #![feature(phase)]
#[phase(plugin)] extern crate scan;
extern crate scan_util;
const TEST_PAIRS: &'static [(&'static str, Result<&'static str, ()>)] = &[
("words 'a b c'", Ok("[a, b, c]")),
("words 'a b c", Err(())),
// for sinistersnare:
("def add x y: x y + end", Ok("def add [x, y]: [x, y, +] end")),
];
#[test... | (s: &str) -> Result<String, scan_util::ScanError> {
scan! {
s,
"words '" [(?!"'") ws:&str]* "'" => format!("{}", ws),
#[tokenizer="IdentsAndInts"]
"def" name:&str [(?!":") args:&str]* ":" [(?!"end") body_toks:&str]* "end" => {
format!("def {} {}: {} end", name, args, body_toks)
},
}
}
| do_scan | identifier_name |
scan-negative-lookahead.rs | #![feature(phase)]
#[phase(plugin)] extern crate scan;
extern crate scan_util;
const TEST_PAIRS: &'static [(&'static str, Result<&'static str, ()>)] = &[
("words 'a b c'", Ok("[a, b, c]")),
("words 'a b c", Err(())),
// for sinistersnare:
("def add x y: x y + end", Ok("def add [x, y]: [x, y, +] end")),
];
#[test... |
fn do_scan(s: &str) -> Result<String, scan_util::ScanError> {
scan! {
s,
"words '" [(?!"'") ws:&str]* "'" => format!("{}", ws),
#[tokenizer="IdentsAndInts"]
"def" name:&str [(?!":") args:&str]* ":" [(?!"end") body_toks:&str]* "end" => {
format!("def {} {}: {} end", name, args, body_toks)
},
}
}
| {
for &(inp, exp) in TEST_PAIRS.iter() {
let got = do_scan(inp);
match exp {
Ok(exp_str) => assert_eq!(got, Ok(exp_str.into_string())),
Err(()) => assert!(got.is_err()),
}
}
} | identifier_body |
scan-negative-lookahead.rs | #![feature(phase)]
#[phase(plugin)] extern crate scan;
extern crate scan_util;
const TEST_PAIRS: &'static [(&'static str, Result<&'static str, ()>)] = &[
("words 'a b c'", Ok("[a, b, c]")),
("words 'a b c", Err(())),
// for sinistersnare:
("def add x y: x y + end", Ok("def add [x, y]: [x, y, +] end")),
];
#[test... | Ok(exp_str) => assert_eq!(got, Ok(exp_str.into_string())),
Err(()) => assert!(got.is_err()),
}
}
}
fn do_scan(s: &str) -> Result<String, scan_util::ScanError> {
scan! {
s,
"words '" [(?!"'") ws:&str]* "'" => format!("{}", ws),
#[tokenizer="IdentsAndInts"]
"def" name:&str [(?!":") args:&str]* ":" [(?... | fn test_scan() {
for &(inp, exp) in TEST_PAIRS.iter() {
let got = do_scan(inp);
match exp { | random_line_split |
release.rs | use { Button, Event, Input };
/// The release of a button
pub trait ReleaseEvent: Sized {
/// Creates a release event.
fn from_button(button: Button, old_event: &Self) -> Option<Self>;
/// Calls closure if this is a release event.
fn release<U, F>(&self, f: F) -> Option<U>
where F: FnMut(Button... |
}
impl<I: ReleaseEvent> ReleaseEvent for Event<I> {
fn from_button(button: Button, old_event: &Self) -> Option<Self> {
if let &Event::Input(ref old_input) = old_event {
<I as ReleaseEvent>::from_button(button, old_input)
.map(|x| Event::Input(x))
} else {
No... | {
match *self {
Input::Release(button) => Some(f(button)),
_ => None
}
} | identifier_body |
release.rs | use { Button, Event, Input };
/// The release of a button
pub trait ReleaseEvent: Sized {
/// Creates a release event.
fn from_button(button: Button, old_event: &Self) -> Option<Self>;
/// Calls closure if this is a release event.
fn release<U, F>(&self, f: F) -> Option<U>
where F: FnMut(Button... | (button: Button, _old_event: &Self) -> Option<Self> {
Some(Input::Release(button))
}
fn release<U, F>(&self, mut f: F) -> Option<U>
where F: FnMut(Button) -> U
{
match *self {
Input::Release(button) => Some(f(button)),
_ => None
}
}
}
impl<I: Rel... | from_button | identifier_name |
release.rs | use { Button, Event, Input };
/// The release of a button
pub trait ReleaseEvent: Sized {
/// Creates a release event.
fn from_button(button: Button, old_event: &Self) -> Option<Self>;
/// Calls closure if this is a release event.
fn release<U, F>(&self, f: F) -> Option<U>
where F: FnMut(Button... |
fn release<U, F>(&self, mut f: F) -> Option<U>
where F: FnMut(Button) -> U
{
match *self {
Input::Release(button) => Some(f(button)),
_ => None
}
}
}
impl<I: ReleaseEvent> ReleaseEvent for Event<I> {
fn from_button(button: Button, old_event: &Self) -> Op... | random_line_split | |
SubjectPhenotypeHeatmapWindow.js | var ref = this;
this.callParent();
},
exportButtonHandler : function() {
if ( this.heatmap == null ) |
var canvas = this.heatmap.down( '#matrixCanvas' );
if ( canvas == null ) {
return;
}
var imgsrc = canvas.el.dom.toDataURL( 'image/png' );
var strDownloadMime = "image/octet-stream";
document.location.href = imgsrc.replace( "image/png", strDownloadMime );
},
draw : ... | {
return;
} | conditional_block |
SubjectPhenotypeHeatmapWindow.js | var ref = this;
this.callParent();
},
exportButtonHandler : function() {
if ( this.heatmap == null ) {
return;
}
var canvas = this.heatmap.down( '#matrixCanvas' );
if ( canvas == null ) {
return;
}
var imgsrc = canvas.el.dom.toDataURL( 'image/png' )... |
M2V.Util.dataType.renderGenderCell = function(ctx, value, row, column, size) {
var color;
value = value.toUpperCase();
if ( value.toUpperCase() === "MALE" || value.toUpperCase() === "M" || value.toUpperCase() === "Y" ) {
color = colors[4]; // blue
} else if ( value... | }; | random_line_split |
argument-passing.rs | // Copyright 2012-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 | // option. This file may not be copied, modified, or distributed
// except according to those terms.
// pretty-expanded FIXME #23616
struct X {
x: isize
}
fn f1(a: &mut X, b: &mut isize, c: isize) -> isize {
let r = a.x + *b + c;
a.x = 0;
*b = 10;
return r;
}
fn f2<F>(a: isize, f: F) -> isize w... | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your | random_line_split |
argument-passing.rs | // Copyright 2012-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-MI... | {
let mut a = X {x: 1};
let mut b = 2;
let c = 3;
assert_eq!(f1(&mut a, &mut b, c), 6);
assert_eq!(a.x, 0);
assert_eq!(b, 10);
assert_eq!(f2(a.x, |_| a.x = 50), 0);
assert_eq!(a.x, 50);
} | identifier_body | |
argument-passing.rs | // Copyright 2012-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-MI... | (a: &mut X, b: &mut isize, c: isize) -> isize {
let r = a.x + *b + c;
a.x = 0;
*b = 10;
return r;
}
fn f2<F>(a: isize, f: F) -> isize where F: FnOnce(isize) { f(1); return a; }
pub fn main() {
let mut a = X {x: 1};
let mut b = 2;
let c = 3;
assert_eq!(f1(&mut a, &mut b, c), 6);
ass... | f1 | identifier_name |
LiveLocation.js | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/** @interface */
export default class LiveLocation {
update() {
}
/**
* @return {?Workspace.UILocation}
*/
uiLocation() {
}
dispose()... | () {
this._locationPool._delete(this);
this._updateDelegate = null;
}
/**
* @override
* @return {boolean}
*/
isBlackboxed() {
throw 'Not implemented';
}
}
/**
* @unrestricted
*/
export class LiveLocationPool {
constructor() {
this._locations = new Set();
}
/**
* @param {!L... | dispose | identifier_name |
LiveLocation.js | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/** @interface */
export default class LiveLocation {
update() {
}
/**
* @return {?Workspace.UILocation}
*/
uiLocation() {
}
dispose()... | Bindings = Bindings || {};
/** @interface */
Bindings.LiveLocation = LiveLocation;
/** @constructor */
Bindings.LiveLocationWithPool = LiveLocationWithPool;
/** @constructor */
Bindings.LiveLocationPool = LiveLocationPool; | /* Legacy exported object */
self.Bindings = self.Bindings || {};
/* Legacy exported object */ | random_line_split |
oldLibPlagia.py | f): return 'PAB'+str(self.d)
def __repr__(self): return 'PAB'+repr(self.d)
def setAfterTokens(self):
self.N = token.NT_OFFSET
def setCustomNames(self):
self.N = DicIncr.NAME_OFFSET
def initNameToToken():
nameToToken = DicIncr()
nameToToken.setAfterTokens()
# Record ope... | r__(sel | identifier_name | |
oldLibPlagia.py | '*', '**', '/', '//', '%', '<<', '>>', '&', '|', '^', '~', '<', '>', '<=', '>=', '==', '!=',
'(', ')', '[', ']', '{', '}', ',', ':', '.', ';', '@', '=', '+=', '-=', '*=', '/=', '//=', '%=', '&=', '|=', '^=', '>>=', '<<=', '**=',]:
nameToToken[s]
# Record some keywords, so that it gives averag... | def getNameToToken(self):
'''Name to token is not thread-safe : all tokens should be precomputed in a single thread!'''
dic = self.db.execute('SELECT * FROM PickleNameToToken').fetchone()
return pickle.loads(dic[0]) if dic else initNameToToken()
def setNameToToken(self, nameToToken):
... | .sDB = sDB
self.db = sqlite3.connect(self.sDB, timeout)
with self.db as db:
db.execute('CREATE TABLE IF NOT EXISTS PickleNameToToken (data BLOB NOT NULL)') # Stores the nameToToken which is the customized token infos taking into account identifiers. Should be unique and project-wide...
... | identifier_body |
oldLibPlagia.py | , lBufP)
### Score is not permutative
##def scoreSimA(lTokA, lTokB):
## sc11 = scoreBlocksSimA(lTokA, detectBlocks(lTokA))
## sc22 = scoreBlocksSimA(lTokB, detectBlocks(lTokB))
## sc12 = scoreBlocksSimA(lTokA, detectBlocks(lTokB))
## return 2*sc12/(sc11+sc22)
##def scoreBlocksSimA(lTokin,llTokin):
... | lP = [Process(target=workerCompare, args=(sDB, bEnd, q)) for q in lQueues] | random_line_split | |
oldLibPlagia.py | Converts tokens to integers (it's easier to compare, and to customize)
def intifyTokens(lTok):
l = []
for tok in lTok:
# Translates operators to integers (a single token OP is used by Python to reduce the number of tokens)
if tok.type in (token.OP, token.NAME):
l.append(nameToToken[... | PATH='libplagia/libplagia.dll'
| conditional_block | |
CommandArgs.js | class CommandArgs extends Array {
constructor(client, args) |
shift() {
this.rawArgs.shift();
return super.shift();
}
rawSlice(...args) {
return this.rawArgs.slice(...args);
}
static get [Symbol.species]() { return Array; }
static splitInput(client, text) {
const { output, rawOutput } = client.ArgumentLexer.parse(text);
return { words: output... | {
if (Array.isArray(args))
super(...args);
else if (typeof args === 'string') {
const { words, raw } = CommandArgs.splitInput(client, args);
super(...words);
this.rawArgs = raw;
} else super(args);
} | identifier_body |
CommandArgs.js | class CommandArgs extends Array {
constructor(client, args) {
if (Array.isArray(args))
super(...args);
else if (typeof args === 'string') {
const { words, raw } = CommandArgs.splitInput(client, args);
super(...words);
this.rawArgs = raw;
} else super(args);
}
shift() {
thi... | }
};
break;
case ' ':
temp += ' ';
if (!inPhrase && temp != ' ') {
if (!escaped) {
words.push(temp);
temp = '';
}
} els... | random_line_split | |
CommandArgs.js | class CommandArgs extends Array {
constructor(client, args) {
if (Array.isArray(args))
super(...args);
else if (typeof args === 'string') {
const { words, raw } = CommandArgs.splitInput(client, args);
super(...words);
this.rawArgs = raw;
} else super(args);
}
shift() {
thi... | () { return Array; }
static splitInput(client, text) {
const { output, rawOutput } = client.ArgumentLexer.parse(text);
return { words: output, raw: rawOutput };
/*
let words = [];
text = text.replace(/\n/g, '\n ');
let chars = text.split('');
let escaped = false;
let inPhrase = false;... | [Symbol.species] | identifier_name |
rpc.py | quasar.util import toUtf8, notify, getLocalizedString, getLocalizedLabel, system_information
from quasar.overlay import OverlayText
from quasar.dialog_select import DialogSelect
from quasar.dialog_insert import DialogInsert
XBMC_PLAYER = xbmc.Player()
class QuasarRPCServer(BaseHandler):
public_methods_pattern = ... |
def GetCurrentView(self):
skinPath = xbmc.translatePath('special://skin/')
xml = os.path.join(skinPath, 'addon.xml')
f = xbmcvfs.File(xml)
read = f.read()
f.close()
try:
src = re.search('defaultresolution="([^"]+)', read, re.DOTALL).group(1)
exce... | return ADDON.setSetting(*args, **kwargs) | identifier_body |
rpc.py | from quasar.util import toUtf8, notify, getLocalizedString, getLocalizedLabel, system_information
from quasar.overlay import OverlayText
from quasar.dialog_select import DialogSelect
from quasar.dialog_insert import DialogInsert
XBMC_PLAYER = xbmc.Player()
class QuasarRPCServer(BaseHandler):
public_methods_patter... |
return self._failures[addonId]
def AddonCheck(self, addonId):
if addonId in self._failures:
return self._failures[addonId]
return 0
def AddonSettings(self, addonId):
return xbmc.executebuiltin("Addon.OpenSettings(%s)" % addonId)
def GetLanguage(self, *args, **... | try:
time.sleep(10)
notify(getLocalizedString(30111))
urllib2.urlopen("%s/provider/%s/disable" % (QUASARD_HOST, addonId))
except:
notify(getLocalizedString(30112))
return 0 | conditional_block |
rpc.py | from quasar.util import toUtf8, notify, getLocalizedString, getLocalizedLabel, system_information
from quasar.overlay import OverlayText
from quasar.dialog_select import DialogSelect
from quasar.dialog_insert import DialogInsert
XBMC_PLAYER = xbmc.Player()
class QuasarRPCServer(BaseHandler):
public_methods_patter... |
def Dialog(self, title, message):
dialog = xbmcgui.Dialog()
return dialog.ok(getLocalizedLabel(title), getLocalizedLabel(message))
def Dialog_Confirm(self, title, message):
dialog = xbmcgui.Dialog()
return dialog.yesno(getLocalizedLabel(title), getLocalizedLabel(message))
... | def Keyboard(self, default="", heading="", hidden=False):
keyboard = xbmc.Keyboard(default, getLocalizedLabel(heading), hidden)
keyboard.doModal()
if keyboard.isConfirmed():
return keyboard.getText() | random_line_split |
rpc.py | quasar.util import toUtf8, notify, getLocalizedString, getLocalizedLabel, system_information
from quasar.overlay import OverlayText
from quasar.dialog_select import DialogSelect
from quasar.dialog_insert import DialogInsert
XBMC_PLAYER = xbmc.Player()
class QuasarRPCServer(BaseHandler):
public_methods_pattern = ... | (self):
settings = []
settingsFile = os.path.join(ADDON.getAddonInfo("path"), "resources", "settings.xml")
with open(settingsFile, 'r') as settingsStr:
fileContent = settingsStr.read()
keyType = re.findall(r".*id=\"(\w+)\".*type=\"(\w+)\"", fileContent)
for key, _... | GetAllSettings | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from glob import glob
from setuptools import find_packages, setup
from os.path import join, dirname
execfile(join(dirname(__file__), 'openerp', 'release.py')) # Load release variables
lib_name = 'openerp'
def py2exe_datafiles():
|
import docutils
import passlib
import requests
data_mapping = ((docutils, 'docutils'),
(passlib, 'passlib'),
(requests, 'requests'))
for mod, datadir in data_mapping:
basedir = dirname(mod.__file__)
for root, _, filenames in os.walk(basedir):... | data_files = {}
data_files['Microsoft.VC90.CRT'] = glob('C:\Microsoft.VC90.CRT\*.*')
for root, dirnames, filenames in os.walk('openerp'):
for filename in filenames:
if not re.match(r'.*(\.pyc|\.pyo|\~)$', filename):
data_files.setdefault(root, []).append(join(root, filename)... | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from glob import glob
from setuptools import find_packages, setup
from os.path import join, dirname
execfile(join(dirname(__file__), 'openerp', 'release.py')) # Load release variables
lib_name = 'openerp'
def py2exe_datafiles():
data_files = {}... | 'passlib',
'pillow', # windows binary http://www.lfd.uci.edu/~gohlke/pythonlibs/
'psutil', # windows binary code.google.com/p/psutil/downloads/list
'psycogreen',
'psycopg2 >= 2.2',
'python-chart',
'pydot',
'pyparsing',
'pypdf',
'pyserial'... | 'ofxparse', | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from glob import glob
from setuptools import find_packages, setup
from os.path import join, dirname
execfile(join(dirname(__file__), 'openerp', 'release.py')) # Load release variables
lib_name = 'openerp'
def py2exe_datafiles():
data_files = {}... | ():
if os.name == 'nt':
import py2exe
return {
'console': [
{'script': 'odoo.py'},
{'script': 'openerp-gevent'},
{'script': 'openerp-server', 'icon_resources': [
(1, join('setup', 'win32', 'static', 'pixmaps', 'openerp-i... | py2exe_options | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
from glob import glob
from setuptools import find_packages, setup
from os.path import join, dirname
execfile(join(dirname(__file__), 'openerp', 'release.py')) # Load release variables
lib_name = 'openerp'
def py2exe_datafiles():
data_files = {}... |
import babel
data_files['babel/localedata'] = glob(join(dirname(babel.__file__), 'localedata', '*'))
others = ['global.dat', 'numbers.py', 'support.py', 'plural.py']
data_files['babel'] = map(lambda f: join(dirname(babel.__file__), f), others)
others = ['frontend.py', 'mofile.py']
data_files['... | data_files.setdefault(root, []).append(join(root, filename)) | conditional_block |
fiborec.py | from fractions import Fraction as f
import sys
# draw points of squares->tiling a rectangle
# size of squares = fibonacci seq
def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
xs,ys=[],[]
depth=50
clas... | (self):
# North->West->South->East->North
# 0,1 -> -1,0 -> 0,-1 -> 1,0 -> 0,1
tmp=self.direction[0]
self.direction[0]=-1*self.direction[1]
self.direction[1]=tmp
cursor=Cursor()
rabbits=[0,1]
for i in range(depth):
p1 = [cursor.position[0],cursor.position[1]]
cursor.forward(rabbits[-1])
p2 = [cursor.posit... | turnleft | identifier_name |
fiborec.py | from fractions import Fraction as f
import sys
# draw points of squares->tiling a rectangle
# size of squares = fibonacci seq
def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
xs,ys=[],[]
depth=50
clas... |
print len(xs), 'points'
import numpy as np
import matplotlib.pylab as plt
fig,ax = plt.subplots(figsize=(8,8))
ax.set_ylim([-1.2,1.2])
ax.set_xlim([-1.2,1.2])
#ax.scatter(xs,ys)
ax.plot(xs,ys)
plt.show()
| xs[i] = f(xs[i], max )
ys[i] = f(ys[i], max ) | conditional_block |
fiborec.py | from fractions import Fraction as f
import sys
# draw points of squares->tiling a rectangle
# size of squares = fibonacci seq
def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): return sqr(x2-x)+sqr(y2-y)
xs,ys=[],[]
depth=50
clas... | ys += [p1[1]]
xs += [p2[0]]
ys += [p2[1]]
xs += [p3[0]]
ys += [p3[1]]
xs += [p1[0]]
ys += [p1[1]]
rabbits+=[rabbits[-1]+rabbits[-2]]
max=max(xs+ys)
for i in range(0,len(xs)):
xs[i] = f(xs[i], max )
ys[i] = f(ys[i], max )
print len(xs), 'points'
import numpy as np
import matplotlib.pylab as plt
fig,ax = pl... | random_line_split | |
fiborec.py | from fractions import Fraction as f
import sys
# draw points of squares->tiling a rectangle
# size of squares = fibonacci seq
def sqr(x): return x*x
def greenq(x,y,x2,y2): return 2*(x2-x)*(y2-y)
def redq(x,y,x2,y2): return sqr(x2-x)-sqr(y2-y)
def blueq(x,y,x2,y2): |
xs,ys=[],[]
depth=50
class Cursor:
direction=[0,1]
position=[0,0]
def forward(self,n):
self.position[0]=self.position[0]+self.direction[0]*n
self.position[1]=self.position[1]+self.direction[1]*n
def turnleft(self):
# North->West->South->East->North
# 0,1 -> -1,0 -> 0,-1 -> 1,0 -> 0,1
tmp=self.direction... | return sqr(x2-x)+sqr(y2-y) | identifier_body |
html5.js | /*! HTML5 Shiv vpre3.6 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
Uncompressed source: https://github.com/aFarkas/html5shiv */
(function (a, b) {
function h(a, b) {
var c = a.createElement("p"),
d = a.getElementsByTagName("head")[0] || a.documentElement;
return c.innerHTML... | (a) {
var b;
return a.documentShived ? a : (l.shivCSS && !f && (b = !! h(a, "article,aside,details,figcaption,figure,footer,header,hgroup,nav,section{display:block}audio{display:none}canvas,video{display:inline-block;*display:inline;*zoom:1}[hidden]{display:none}audio[controls]{display:inline-block;*dis... | k | identifier_name |
html5.js | /*! HTML5 Shiv vpre3.6 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
Uncompressed source: https://github.com/aFarkas/html5shiv */
(function (a, b) {
function h(a, b) {
var c = a.createElement("p"),
d = a.getElementsByTagName("head")[0] || a.documentElement;
return c.innerHTML... | }()
})();
var l = {
elements: c.elements || "abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",
shivCSS: c.shivCSS !== !1,
shivMethods: c.shivMethods !== !1,
type: "d... | } catch (a) {
return !0
}
var c = b.createDocumentFragment();
return typeof c.cloneNode == "undefined" || typeof c.createDocumentFragment == "undefined" || typeof c.createElement == "undefined" | random_line_split |
html5.js | /*! HTML5 Shiv vpre3.6 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
Uncompressed source: https://github.com/aFarkas/html5shiv */
(function (a, b) {
function h(a, b) |
function i() {
var a = l.elements;
return typeof a == "string" ? a.split(" ") : a
}
function j(a) {
var b = {}, c = a.createElement,
f = a.createDocumentFragment,
g = f();
a.createElement = function (a) {
if (!l.shivMethods) return c(a);... | {
var c = a.createElement("p"),
d = a.getElementsByTagName("head")[0] || a.documentElement;
return c.innerHTML = "x<style>" + b + "</style>", d.insertBefore(c.lastChild, d.firstChild)
} | identifier_body |
ivy-codemirror.js | import { inject as service } from '@ember/service';
import { get } from '@ember/object';
import lint from 'consul-ui/utils/editor/lint';
const MODES = [
{
name: 'JSON',
mime: 'application/json',
mode: 'javascript',
ext: ['json', 'map'],
alias: ['json5'],
},
{
name: 'HCL',
mime: 'text/x... | }
export default {
initialize,
}; | getEditor: function(element) {
return get(this, 'dom').element('textarea + div', element).CodeMirror;
},
}); | random_line_split |
ivy-codemirror.js | import { inject as service } from '@ember/service';
import { get } from '@ember/object';
import lint from 'consul-ui/utils/editor/lint';
const MODES = [
{
name: 'JSON',
mime: 'application/json',
mode: 'javascript',
ext: ['json', 'map'],
alias: ['json5'],
},
{
name: 'HCL',
mime: 'text/x... | });
}
export default {
initialize,
};
| {
const IvyCodeMirrorComponent = application.resolveRegistration('component:ivy-codemirror');
const IvyCodeMirrorService = application.resolveRegistration('service:code-mirror');
// Make sure ivy-codemirror respects/maintains a `name=""` attribute
IvyCodeMirrorComponent.reopen({
attributeBindings: ['name'],... | identifier_body |
ivy-codemirror.js | import { inject as service } from '@ember/service';
import { get } from '@ember/object';
import lint from 'consul-ui/utils/editor/lint';
const MODES = [
{
name: 'JSON',
mime: 'application/json',
mode: 'javascript',
ext: ['json', 'map'],
alias: ['json5'],
},
{
name: 'HCL',
mime: 'text/x... | (application) {
const IvyCodeMirrorComponent = application.resolveRegistration('component:ivy-codemirror');
const IvyCodeMirrorService = application.resolveRegistration('service:code-mirror');
// Make sure ivy-codemirror respects/maintains a `name=""` attribute
IvyCodeMirrorComponent.reopen({
attributeBindi... | initialize | identifier_name |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(unused_must_use)]
mod conversions;
pub use conversions::require_digest;
#[cfg(test)]
mod conversions_tests;
pub mod gen {
// NOTE: Prost automatically relies on the existenc... |
}
}
}
pub mod semver {
tonic::include_proto!("build.bazel.semver");
}
}
}
pub mod buildbarn {
pub mod cas {
tonic::include_proto!("buildbarn.cas");
}
}
pub mod pants {
pub mod cache {
tonic::include_proto!("pants.cache");
}
}
}
mod ... | {
Digest {
hash: String::from(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
),
size_bytes: 0,
}
} | identifier_body |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(unused_must_use)]
mod conversions;
pub use conversions::require_digest;
#[cfg(test)]
mod conversions_tests;
pub mod gen {
// NOTE: Prost automatically relies on the existenc... | () -> Digest {
Digest {
hash: String::from(
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
),
size_bytes: 0,
}
}
}
}
}
pub mod semver {
tonic::include_prot... | empty_digest | identifier_name |
lib.rs | // Copyright 2018 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
#![deny(unused_must_use)]
mod conversions;
pub use conversions::require_digest;
#[cfg(test)]
mod conversions_tests;
pub mod gen {
// NOTE: Prost automatically relies on the existenc... | }
}
}
pub mod buildbarn {
pub mod cas {
tonic::include_proto!("buildbarn.cas");
}
}
pub mod pants {
pub mod cache {
tonic::include_proto!("pants.cache");
}
}
}
mod verification;
pub use crate::verification::verify_directory_canonical;
#[cfg(test)]
mod verification_tests; | }
}
pub mod semver {
tonic::include_proto!("build.bazel.semver"); | random_line_split |
treeview.py | # -*- coding: utf-8 -*-
# Maestro Music Manager - https://github.com/maestromusic/maestro
# Copyright (C) 2009-2015 Martin Altmayer, Michael Helmling
#
# 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 Foun... |
def localActions(self):
return [action for action in self.actions() if action not in self.treeActions.values()]
def contextMenuEvent(self, event):
menu = self.actionConf.createMenu(self)
for action in self.localActions():
menu.addAction(action)
if menu.isEmpty():
... | self.selection = TreeviewSelection(self.level, selectionModel)
for action in self.treeActions.values():
if isinstance(action, actions.TreeAction):
action.initialize(self.selection) | conditional_block |
treeview.py | # -*- coding: utf-8 -*-
# Maestro Music Manager - https://github.com/maestromusic/maestro
# Copyright (C) 2009-2015 Martin Altmayer, Michael Helmling
#
# 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 Foun... |
@classmethod
def addActionDefinition(cls, *args, **kwargs):
if 'actionConf' not in cls.__dict__:
cls.actionConf = actions.TreeActionConfiguration()
cls.actionConf.root.addActionDefinition(*args, **kwargs)
def _handleActionDefAdded(self, actionDef):
self.treeActions[act... | super().__init__(parent)
self.level = level
self.affectGlobalSelection = affectGlobalSelection
self.setHeaderHidden(True)
self.setExpandsOnDoubleClick(False)
self.setAlternatingRowColors(True)
self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
... | identifier_body |
treeview.py | # -*- coding: utf-8 -*-
# Maestro Music Manager - https://github.com/maestromusic/maestro
# Copyright (C) 2009-2015 Martin Altmayer, Michael Helmling
#
# 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 Foun... |
class DraggingTreeView(TreeView):
"""This is the baseclass of tree views that allow to drag and drop wrappers, e.g. playlist and editor.
It handles the following issues:
- Drag&drop actions must be enclosed in one undo-macro.
- Drags between views of the same class default to a move, d... | for itemRange in selection]
| random_line_split |
treeview.py | # -*- coding: utf-8 -*-
# Maestro Music Manager - https://github.com/maestromusic/maestro
# Copyright (C) 2009-2015 Martin Altmayer, Michael Helmling
#
# 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 Foun... | (self, event):
if event.keyboardModifiers() & Qt.ShiftModifier:
event.setDropAction(Qt.MoveAction)
elif event.keyboardModifiers() & Qt.ControlModifier:
event.setDropAction(Qt.CopyAction)
elif isinstance(event.source(), type(self)):
event.setDropAction(Qt.MoveA... | _changeDropAction | identifier_name |
bio_json_xml.js | var fs = require('fs');
/*var mulu = fs.readFileSync('./mulu.html','utf8');
var sutra = mulu.replace(/<sutra>/g,'#<sutra>').split(/#/);
var vol = function(sutra){
for (var i in sutra){
var vol = sutra[i].match(/<vol>(.+)<\/vol>/);
var sutraid = sutra[i].match(/<sutraid n="(.+)"\/>/);
if (vol == null || sutraid ... | var cname = sutra[i].match(/<taisho.+chi="(.+)\/">/g);
var sutraid = sutra[i].match(/<sutraid n="(.+)"\/>/);
if (cname == null || sutraid == null) {
console.log('');
} else {
console.log(sutraid[1],cname.map(function(cname){
var chiname = cname.replace(/<taisho.+chi="(.+)\/>/g,"$1");
return chinam... | }
var cname = function(sutra){
for (var i in sutra){ | random_line_split |
syscache.py | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from builtins import round
import gdb
import re
import zlib
import sys
from datetime import timedelta
if sys.version_info.... |
def init_utsname_cache(self):
d = {}
for field in self.utsname.type.fields():
val = self.utsname[field.name].string()
d[field.name] = val
self.utsname_cache = d
return self.utsname_cache
utsname_fields = [ 'sysname', 'nodename', 'release',
... | self.utsname = self.init_uts_ns['name']
return self.utsname | identifier_body |
syscache.py | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from builtins import round
import gdb
import re
import zlib
import sys
from datetime import timedelta
if sys.version_info.... | return self.ikconfig_cache
def __getitem__(self, name):
return self.ikconfig_cache[name]
class CrashKernelCache(CrashCache):
__symvals__ = [ 'avenrun' ]
__symbol_callbacks__ = [
( 'jiffies', 'setup_jiffies' ),
( 'jiffies_64', 'setup_jiffies' ) ]
... | m = re.match("CONFIG_([^=]*)=(.*)", line)
if m:
self.ikconfig_cache[m.group(1)] = m.group(2)
| random_line_split |
syscache.py | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from builtins import round
import gdb
import re
import zlib
import sys
from datetime import timedelta
if sys.version_info.... | (metric):
# The kernel needs to do fixed point trickery to calculate
# a floating point average. We can just return a float.
return round(long(metric) / (1 << 11), 2)
@staticmethod
def format_loadavg(metrics):
out = []
for metric in metrics:
out.append(str(m... | calculate_loadavg | identifier_name |
syscache.py | # -*- coding: utf-8 -*-
# vim:set shiftwidth=4 softtabstop=4 expandtab textwidth=79:
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from builtins import round
import gdb
import re
import zlib
import sys
from datetime import timedelta
if sys.version_info.... |
return self.ikconfig_cache
def __getitem__(self, name):
return self.ikconfig_cache[name]
class CrashKernelCache(CrashCache):
__symvals__ = [ 'avenrun' ]
__symbol_callbacks__ = [
( 'jiffies', 'setup_jiffies' ),
( 'jiffies_64', 'setup_jiffies' ) ]
... | line = re.sub("#.*$", "", line).strip()
if not line:
continue
m = re.match("CONFIG_([^=]*)=(.*)", line)
if m:
self.ikconfig_cache[m.group(1)] = m.group(2) | conditional_block |
rename-path-item.command.ts | /**
* @license
* Copyright 2017 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... | (document: OasDocument): void {
console.info("[RenamePathItemCommand] Executing.");
this._doPathRename(document, this._oldPath, this._newPath, this._alsoRenameSubpaths);
}
/**
* Removes the pathItem.
* @param document
*/
public undo(document: OasDocument): void {
cons... | execute | identifier_name |
rename-path-item.command.ts | /**
* @license
* Copyright 2017 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... | /**
* Does the work of renaming a path from one name to another.
* @param document
* @param from
* @param to
* @param alsoRenameSubpaths
*/
private _doPathRename(document: OasDocument, from: string, to: string, alsoRenameSubpaths: boolean): void {
let pathsToRename: any[] =... | this._doPathRename(document, this._newPath, this._oldPath, this._alsoRenameSubpaths);
}
| random_line_split |
rename-path-item.command.ts | /**
* @license
* Copyright 2017 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... |
pathsToRename.forEach( p2r => {
this._renamePath(document, p2r.from, p2r.to);
});
}
/**
* Does the work of renaming a path.
* @param from
* @param to
*/
private _renamePath(document: OasDocument, from: string, to: string): void {
let fromPathParamNa... | {
document.paths.pathItemNames().forEach( pathName => {
if (pathName.indexOf(from) === 0 && pathName !== from) {
pathsToRename.push({
from: pathName,
to: to + pathName.substring(from.length)
});
... | conditional_block |
rename-path-item.command.ts | /**
* @license
* Copyright 2017 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law o... |
/**
* Adds the new pathItem to the document.
* @param document
*/
public execute(document: OasDocument): void {
console.info("[RenamePathItemCommand] Executing.");
this._doPathRename(document, this._oldPath, this._newPath, this._alsoRenameSubpaths);
}
/**
* Removes... | {
return "RenamePathItemCommand";
} | identifier_body |
call.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... | () {
let s = r#"{
"data" : "0x1111222233334444555566667777888899990000aaaabbbbccccddddeeeeffff",
"destination" : "",
"gasLimit" : "0x1748766aa5",
"value" : "0x00"
}"#;
let call: Call = serde_json::from_str(s).unwrap();
assert_eq!(&call.data[..],
&[0x11, 0x11, 0x22, 0x22, 0x33, 0x33, 0x44, 0x44, ... | call_deserialization_empty_dest | identifier_name |
call.rs | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any la... |
assert_eq!(&call.data[..],
&[0x11, 0x11, 0x22, 0x22, 0x33, 0x33, 0x44, 0x44, 0x55, 0x55, 0x66, 0x66, 0x77, 0x77,
0x88, 0x88, 0x99, 0x99, 0x00, 0x00, 0xaa, 0xaa, 0xbb, 0xbb, 0xcc, 0xcc, 0xdd, 0xdd,
0xee, 0xee, 0xff, 0xff]);
assert_eq!(call.destination, MaybeEmpty::None);
assert_eq!(call.gas_limit, U... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.