file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
types.rs | //! Exports Rust counterparts for all the common GLSL types, along with a few marker traits
use rasen::prelude::{Dim, TypeName};
use std::ops::{Add, Div, Index, Mul, Rem, Sub};
use crate::{
context::{Container, Context},
value::{IntoValue, Value},
};
pub trait AsTypeName {
const TYPE_NAME: &'static Type... | &TypeName::Sampler(<<V as Vector>::Scalar as AsTypeName>::TYPE_NAME, Dim::Dim2D);
} | where
<V as Vector>::Scalar: AsTypeName,
{
const TYPE_NAME: &'static TypeName = | random_line_split |
test_util.rs | extern crate mazth;
#[allow(unused_imports)]
use std::ops::Div;
#[allow(unused_imports)]
use std::cmp::Ordering;
use self::mazth::i_comparable::IComparableError;
use self::mazth::mat::{Mat3x1, Mat4};
use implement::math::util;
#[test]
fn | (){
//look_at
{
let eye : Mat3x1<f32> = Mat3x1 { _val: [5.0,5.0,5.0] };
let center : Mat3x1<f32> = Mat3x1 { _val: [0.0,0.0,0.0] };
let up : Mat3x1<f32> = Mat3x1 { _val: [0.0,1.0,0.0] };
let lookat = util::look_at( eye, center, up );
assert!( lookat.is_equal( &Mat4{ _val... | test_math_util | identifier_name |
test_util.rs | extern crate mazth;
#[allow(unused_imports)]
use std::ops::Div;
#[allow(unused_imports)]
use std::cmp::Ordering;
use self::mazth::i_comparable::IComparableError;
use self::mazth::mat::{Mat3x1, Mat4};
use implement::math::util;
#[test]
fn test_math_util() | {
//look_at
{
let eye : Mat3x1<f32> = Mat3x1 { _val: [5.0,5.0,5.0] };
let center : Mat3x1<f32> = Mat3x1 { _val: [0.0,0.0,0.0] };
let up : Mat3x1<f32> = Mat3x1 { _val: [0.0,1.0,0.0] };
let lookat = util::look_at( eye, center, up );
assert!( lookat.is_equal( &Mat4{ _val: ... | identifier_body | |
test_util.rs | extern crate mazth;
#[allow(unused_imports)]
use std::ops::Div;
#[allow(unused_imports)]
use std::cmp::Ordering;
use self::mazth::i_comparable::IComparableError;
use self::mazth::mat::{Mat3x1, Mat4};
use implement::math::util;
#[test]
fn test_math_util(){
//look_at
{
let eye : Mat3x1<f32> = Mat3x1 {... | 0.0, 0.0, 0.0, 1.0 ], _is_row_major: true }, 0.0001f32 ).expect("look_at result unexpected") );
}
//perspective transform
{
let fov = 90.0;
let aspect = 1.0;
let near = 0.1;
let far = 100.0;
let persp = util::perspecti... | let lookat = util::look_at( eye, center, up );
assert!( lookat.is_equal( &Mat4{ _val: [ 0.70711, 0.0, -0.70711, 0.0,
-0.40825, 0.81650, -0.40825, 0.0,
0.57735, 0.57735, 0.57735, -8.66025, | random_line_split |
arduino.js | var five = require('johnny-five');
var plane = require('./plane');
var config = require('../config');
| var board, paintMotor;
module.exports = {
init: function() {
if (config.arduino) {
board = new five.Board();
board.on('ready', this.onBoardReady);
}
},
onBoardReady: function() {
console.log('OK')
plane.init();
paintMotor = new five.Servo({
pin: 9,
range: [80,170]
... | var state = 'waiting'; | random_line_split |
arduino.js | var five = require('johnny-five');
var plane = require('./plane');
var config = require('../config');
var state = 'waiting';
var board, paintMotor;
module.exports = {
init: function() {
if (config.arduino) |
},
onBoardReady: function() {
console.log('OK')
plane.init();
paintMotor = new five.Servo({
pin: 9,
range: [80,170]
});
this.repl.inject({
paint: paintMotor
});
state = 'ready';
},
applyRotation: function(gamma, beta) {
if (state === 'ready') {
plane.ap... | {
board = new five.Board();
board.on('ready', this.onBoardReady);
} | conditional_block |
cache.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | (): CacheResult<T> {
if (this.result) {
return this.result;
}
const cts = new CancellationTokenSource();
const promise = this.task(cts.token);
this.result = {
promise,
dispose: () => {
this.result = null;
cts.cancel();
cts.dispose();
}
};
return this.result;
}
}
| get | identifier_name |
cache.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
}
| {
if (this.result) {
return this.result;
}
const cts = new CancellationTokenSource();
const promise = this.task(cts.token);
this.result = {
promise,
dispose: () => {
this.result = null;
cts.cancel();
cts.dispose();
}
};
return this.result;
} | identifier_body |
cache.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... | } | return this.result;
} | random_line_split |
cache.ts | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*---------------------------------------------------------------... |
const cts = new CancellationTokenSource();
const promise = this.task(cts.token);
this.result = {
promise,
dispose: () => {
this.result = null;
cts.cancel();
cts.dispose();
}
};
return this.result;
}
}
| {
return this.result;
} | conditional_block |
manager.py | """
The events manager contains the class that manages custom and abstract callbacks into the system callbacks.
Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals
being created by other apps in a single place so it could be used over all apps.
For exa... |
else:
self.signals[signal_code] = instance
def listen(self, signal, target, conditions=None, **kwargs):
"""
Register a listing client to the signal given (signal instance or string).
:param signal: Signal instance or string: "namespace:code"
:param target: Target method to call.
:param conditions: Re... | self.callbacks[code] = instance | conditional_block |
manager.py | """
The events manager contains the class that manages custom and abstract callbacks into the system callbacks.
Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals
being created by other apps in a single place so it could be used over all apps.
For exa... | try:
signal = self.get_signal(sig_name)
signal.set_self(func, slf)
except Exception as e:
logging.warning(str(e), exc_info=sys.exc_info())
self.reserved = dict()
self.reserved_self = dict()
def init_app(self, app):
"""
Initiate app, load all signal/callbacks files. (just import, they s... |
for sig_name, recs in self.reserved_self.items():
for func, slf in recs: | random_line_split |
manager.py | """
The events manager contains the class that manages custom and abstract callbacks into the system callbacks.
Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals
being created by other apps in a single place so it could be used over all apps.
For exa... | (cls):
SignalManager.register_signal(cls)
return cls
| public_callback | identifier_name |
manager.py | """
The events manager contains the class that manages custom and abstract callbacks into the system callbacks.
Once a signals is registered here it could be used by string reference. This makes it easy to have dynamically signals
being created by other apps in a single place so it could be used over all apps.
For exa... |
def create_app_manager(self, app):
"""
This method will create the manager instance for the app context.
:param app: App instance.
:type app: pyplanet.apps.config.AppConfig
:return: SignalManager instance for the app.
:rtype: pyplanet.core.events.manager.AppSignalManager
"""
return AppSignalManager(... | """
Finish startup the core, this will copy reservations. (PRIVATE).
"""
self.finish_reservations() | identifier_body |
register.js | /**
* Copyright (c) 2011 Bruno Jouhier <bruno.jouhier@sage.com>
*
* 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
* restriction, including without limitation the rights to use,
... | * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
*... | random_line_split | |
amp-embedly-card-impl.js | import {removeElement} from '#core/dom';
import {Layout_Enum, applyFillContent} from '#core/dom/layout';
import {Services} from '#service';
import {userAssert} from '#utils/log';
import {TAG as KEY_TAG} from './amp-embedly-key';
import {getIframe} from '../../../src/3p-frame';
import {listenFor} from '../../../src/... |
}
/** @override */
layoutCallback() {
// Add optional paid api key attribute if provided
// to remove embedly branding.
if (this.apiKey_) {
this.element.setAttribute(API_KEY_ATTR_NAME, this.apiKey_);
}
const iframe = getIframe(this.win, this.element, 'embedly');
iframe.title = thi... | {
this.apiKey_ = ampEmbedlyKeyElement.getAttribute('value');
} | conditional_block |
amp-embedly-card-impl.js | import {removeElement} from '#core/dom';
import {Layout_Enum, applyFillContent} from '#core/dom/layout';
import {Services} from '#service';
import {userAssert} from '#utils/log';
import {TAG as KEY_TAG} from './amp-embedly-key';
import {getIframe} from '../../../src/3p-frame';
import {listenFor} from '../../../src/... |
/** @override */
unlayoutCallback() {
if (this.iframe_) {
removeElement(this.iframe_);
this.iframe_ = null;
}
return true;
}
/** @override */
isLayoutSupported(layout) {
return layout == Layout_Enum.RESPONSIVE;
}
/**
* @param {boolean=} opt_onLayout
* @override
*/... | {
// Add optional paid api key attribute if provided
// to remove embedly branding.
if (this.apiKey_) {
this.element.setAttribute(API_KEY_ATTR_NAME, this.apiKey_);
}
const iframe = getIframe(this.win, this.element, 'embedly');
iframe.title = this.element.title || 'Embedly card';
cons... | identifier_body |
amp-embedly-card-impl.js | import {removeElement} from '#core/dom';
import {Layout_Enum, applyFillContent} from '#core/dom/layout';
import {Services} from '#service';
import {userAssert} from '#utils/log';
import {TAG as KEY_TAG} from './amp-embedly-key';
|
/**
* Component tag identifier.
* @const {string}
*/
export const TAG = 'amp-embedly-card';
/**
* Attribute name used to set api key with name
* expected by embedly.
* @const {string}
*/
const API_KEY_ATTR_NAME = 'data-card-key';
/**
* Implementation of the amp-embedly-card component.
* See {@link ../amp-em... | import {getIframe} from '../../../src/3p-frame';
import {listenFor} from '../../../src/iframe-helper'; | random_line_split |
amp-embedly-card-impl.js | import {removeElement} from '#core/dom';
import {Layout_Enum, applyFillContent} from '#core/dom/layout';
import {Services} from '#service';
import {userAssert} from '#utils/log';
import {TAG as KEY_TAG} from './amp-embedly-key';
import {getIframe} from '../../../src/3p-frame';
import {listenFor} from '../../../src/... | () {
userAssert(
this.element.getAttribute('data-url'),
'The data-url attribute is required for <%s> %s',
TAG,
this.element
);
const ampEmbedlyKeyElement = document.querySelector(KEY_TAG);
if (ampEmbedlyKeyElement) {
this.apiKey_ = ampEmbedlyKeyElement.getAttribute('value'... | buildCallback | identifier_name |
test_unquote.py | # coding: utf-8
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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 o... | (u'\'1 \\\'2\\\' 3\'', u'1 \\\'2\\\' 3'),
(u'"', u'"'),
(u'\'', u'\''),
# Not entirely sure these are good but they match the current
# behaviour
(u'"1""2"', u'1""2'),
(u'\'1\'\'2\'', u'1\'\'2'),
(u'"1" 2 "3"', u'1" 2 "3'),
... | (u'\'1\\\'', u'\'1\\\''),
(u'"1 \\"2\\" 3"', u'1 \\"2\\" 3'), | random_line_split |
test_unquote.py | # coding: utf-8
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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 o... | :
UNQUOTE_DATA = (
(u'1', u'1'),
(u'\'1\'', u'1'),
(u'"1"', u'1'),
(u'"1 \'2\'"', u'1 \'2\''),
(u'\'1 "2"\'', u'1 "2"'),
(u'\'1 \'2\'\'', u'1 \'2\''),
(u'"1\\"', u'"1\\"'),
(u'\'1\\\'', u'\'1\\\''),
(u'"1 \\"... | TestUnquote | identifier_name |
test_unquote.py | # coding: utf-8
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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 o... |
def test_unquote(self):
for datapoint in self.UNQUOTE_DATA:
yield self.check_unquote, datapoint[0], datapoint[1]
| tools.eq_(unquote(quoted), expected) | identifier_body |
test_unquote.py | # coding: utf-8
# (c) 2015, Toshio Kuratomi <tkuratomi@ansible.com>
#
# This file is part of Ansible
#
# Ansible 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 o... | yield self.check_unquote, datapoint[0], datapoint[1] | conditional_block | |
cloud_formation.py | #
# 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 may not... | (
self, *, stack_name: str, params: Optional[dict] = None, aws_conn_id: str = 'aws_default', **kwargs
):
super().__init__(**kwargs)
self.params = params or {}
self.stack_name = stack_name
self.aws_conn_id = aws_conn_id
def execute(self, context):
self.log.info('P... | __init__ | identifier_name |
cloud_formation.py | #
# 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 may not... | cloudformation_hook = AWSCloudFormationHook(aws_conn_id=self.aws_conn_id)
cloudformation_hook.delete_stack(self.stack_name, self.params) | random_line_split | |
cloud_formation.py | #
# 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 may not... |
def execute(self, context):
self.log.info('Parameters: %s', self.params)
cloudformation_hook = AWSCloudFormationHook(aws_conn_id=self.aws_conn_id)
cloudformation_hook.create_stack(self.stack_name, self.params)
class CloudFormationDeleteStackOperator(BaseOperator):
"""
An operato... | super().__init__(**kwargs)
self.stack_name = stack_name
self.params = params
self.aws_conn_id = aws_conn_id | identifier_body |
filters.js | angular.module('Directory.csvImports.filters', ['Directory.csvImports.models'])
.filter('type', ['Schema', function(Schema) {
return function (inputs, cond) {
if (typeof cond == 'undefined' || cond == null || cond == '' || cond == '*') {
return inputs;
}
var things = [];
angular.forEach(inputs, ... |
});
return things;
}
}])
.filter('isExtraField', ['Schema', function(Schema) {
return function isExtraField (headers, mapping) {
if (mapping) {
var things = [];
angular.forEach(mapping, function (mapping, index) {
var match = false;
angular.forEach(Schema.columns, function ... | {
things.push(column);
} | conditional_block |
filters.js | angular.module('Directory.csvImports.filters', ['Directory.csvImports.models'])
.filter('type', ['Schema', function(Schema) {
return function (inputs, cond) {
if (typeof cond == 'undefined' || cond == null || cond == '' || cond == '*') {
return inputs;
}
var things = [];
angular.forEach(inputs, ... | }); | return getIntVal(a.state) - getIntVal(b.state);
})
} | random_line_split |
filters.js | angular.module('Directory.csvImports.filters', ['Directory.csvImports.models'])
.filter('type', ['Schema', function(Schema) {
return function (inputs, cond) {
if (typeof cond == 'undefined' || cond == null || cond == '' || cond == '*') {
return inputs;
}
var things = [];
angular.forEach(inputs, ... |
return function sortByImportState (imports) {
if (imports)
return imports.sort(function (a, b) {
return getIntVal(a.state) - getIntVal(b.state);
})
}
}); | {
switch(state) {
case 'error': return 0;
case 'new': return 1;
case 'analyzed': return 2;
case 'analyzing': return 3;
case 'importing': return 4;
case 'queued_analyze': return 5;
case 'queud_import': return 6;
case 'imported': return 7;
case 'cancelled': return... | identifier_body |
filters.js | angular.module('Directory.csvImports.filters', ['Directory.csvImports.models'])
.filter('type', ['Schema', function(Schema) {
return function (inputs, cond) {
if (typeof cond == 'undefined' || cond == null || cond == '' || cond == '*') {
return inputs;
}
var things = [];
angular.forEach(inputs, ... | (state) {
switch(state) {
case 'error': return 0;
case 'new': return 1;
case 'analyzed': return 2;
case 'analyzing': return 3;
case 'importing': return 4;
case 'queued_analyze': return 5;
case 'queud_import': return 6;
case 'imported': return 7;
case 'cancelled'... | getIntVal | identifier_name |
impala_test_suite.py | # Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
@classmethod
def __create_exec_option_dimension(cls):
cluster_sizes = ALL_CLUSTER_SIZES
disable_codegen_options = ALL_DISABLE_CODEGEN_OPTIONS
batch_sizes = ALL_BATCH_SIZES
exec_single_node_option = [0]
if cls.exploration_strategy() == 'core':
disable_codegen_options = [False]
clust... | if pytest.config.option.table_formats:
table_formats = list()
for tf in pytest.config.option.table_formats.split(','):
dataset = get_dataset_from_workload(cls.get_workload())
table_formats.append(TableFormatInfo.create_from_string(dataset, tf))
tf_dimensions = TestDimension('table_form... | identifier_body |
impala_test_suite.py | # Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | return client.close_query(query)
@execute_wrapper
def execute_query_async(self, query, query_options=None):
self.client.set_configuration(query_options)
return self.client.execute_async(query)
@execute_wrapper
def close_query(self, query):
return self.client.close_query(query)
@execute_wrap... | def close_query_using_client(self, client, query): | random_line_split |
impala_test_suite.py | # Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... | (cls, host_port=IMPALAD):
client = create_connection(host_port=host_port,
use_kerberos=pytest.config.option.use_kerberos)
client.connect()
return client
@classmethod
def create_impala_service(cls, host_port=IMPALAD, webserver_port=25000):
host, port = host_port.split(':')
return Impalad... | create_impala_client | identifier_name |
impala_test_suite.py | # Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
else:
host, port = pytest.config.option.namenode_http_address.split(":")
hdfs_client = get_hdfs_client(host, port)
return hdfs_client
@classmethod
def all_db_names(self):
results = self.client.execute("show databases").data
# Extract first column - database name
return [row.split(... | hdfs_client = get_hdfs_client_from_conf(HDFS_CONF) | conditional_block |
server.rs | use std::collections::HashMap;
use std::cmp::max;
use iron::{Iron, Chain};
use router::Router;
use persistent::State;
use chrono::{Duration, NaiveDate, NaiveDateTime};
use serde_json::builder::ObjectBuilder;
use serde_json::Value;
use serde;
use SERVER_ADDRESS;
use errors::*;
use load::{SummarizedWeek, Kind, TestRun,... | ,
Err(err) => {
// TODO: Print to stderr
println!("An error occurred: {:?}", err);
Response::with((status::InternalServerError, err.to_string()))
}
};
resp.set_mut(Header(AccessControlAllowOrigin::Any));
Ok(resp)
}
... | {
let mut resp = Response::with((status::Ok, serde_json::to_string(&json).unwrap()));
resp.set_mut(Header(ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![]))));
resp
} | conditional_block |
server.rs | use std::collections::HashMap;
use std::cmp::max;
use iron::{Iron, Chain};
use router::Router;
use persistent::State;
use chrono::{Duration, NaiveDate, NaiveDateTime};
use serde_json::builder::ObjectBuilder;
use serde_json::Value;
use serde;
use SERVER_ADDRESS;
use errors::*;
use load::{SummarizedWeek, Kind, TestRun,... | {
Crate,
Phase,
}
impl serde::Deserialize for GroupBy {
fn deserialize<D>(deserializer: &mut D) -> ::std::result::Result<GroupBy, D::Error>
where D: serde::de::Deserializer
{
struct GroupByVisitor;
impl serde::de::Visitor for GroupByVisitor {
type Value = GroupBy;
... | GroupBy | identifier_name |
server.rs | use std::collections::HashMap;
use std::cmp::max;
use iron::{Iron, Chain};
use router::Router;
use persistent::State;
use chrono::{Duration, NaiveDate, NaiveDateTime};
use serde_json::builder::ObjectBuilder;
use serde_json::Value;
use serde;
use SERVER_ADDRESS;
use errors::*;
use load::{SummarizedWeek, Kind, TestRun,... | for krate in benchmark.by_crate.values() {
if krate.contains_key("total") {
sum += krate["total"];
count += 1;
}
}
if rustc.by_crate["total"].contains_key("total") {
sum += 2.0 * rustc.by_crate["... | let mut sum = 0.0;
let mut count = 0; | random_line_split |
server.rs | use std::collections::HashMap;
use std::cmp::max;
use iron::{Iron, Chain};
use router::Router;
use persistent::State;
use chrono::{Duration, NaiveDate, NaiveDateTime};
use serde_json::builder::ObjectBuilder;
use serde_json::Value;
use serde;
use SERVER_ADDRESS;
use errors::*;
use load::{SummarizedWeek, Kind, TestRun,... | {
let mut router = Router::new();
router.get("/summary", Summary::handler);
router.get("/info", Info::handler);
router.post("/data", Data::handler);
router.post("/get_tabular", Tabular::handler);
router.post("/get", Days::handler);
router.post("/stats", Stats::handler);
let mut chain =... | identifier_body | |
tests.rs | // Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::time::Duration;
use crate::{Process, ProcessResultMetadata};
use bazel_protos::gen::build::bazel::... | restored_action_metadata,
ExecutedActionMetadata {
worker_start_timestamp: Some(Timestamp {
seconds: 0,
nanos: 0,
}),
worker_completed_timestamp: Some(Timestamp {
seconds: 20,
nanos: 30,
}),
..ExecutedActionMetadata::default()
}
);
// The re... | random_line_split | |
tests.rs | // Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::time::Duration;
use crate::{Process, ProcessResultMetadata};
use bazel_protos::gen::build::bazel::... |
#[test]
fn process_result_metadata_to_and_from_executed_action_metadata() {
let action_metadata = ExecutedActionMetadata {
worker_start_timestamp: Some(Timestamp {
seconds: 100,
nanos: 20,
}),
worker_completed_timestamp: Some(Timestamp {
seconds: 120,
nanos: 50,
}),
..Exe... | {
// TODO: Tests like these would be cleaner with the builder pattern for the rust-side Process API.
let process_generator = |description: String, timeout: Option<Duration>| {
let mut p = Process::new(vec![]);
p.description = description;
p.timeout = timeout;
p
};
fn hash<Hashable: Hash>(hasha... | identifier_body |
tests.rs | // Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::time::Duration;
use crate::{Process, ProcessResultMetadata};
use bazel_protos::gen::build::bazel::... | () {
let metadata = ProcessResultMetadata::new(Some(concrete_time::Duration::new(5, 150)));
let time_saved = metadata.time_saved_from_cache(Duration::new(1, 100));
assert_eq!(time_saved, Some(Duration::new(4, 50)));
// If the cache lookup took more time than the process, we return 0.
let metadata = ProcessRe... | process_result_metadata_time_saved_from_cache | identifier_name |
node.py | import threading
from queue import Queue, Empty
from time import sleep
from libAnt.drivers.driver import Driver
from libAnt.message import *
class Network:
def __init__(self, key: bytes = b'\x00' * 8, name: str = None):
|
def __str__(self):
return self.name
class Pump(threading.Thread):
def __init__(self, driver: Driver, initMessages, out: Queue, onSucces, onFailure):
super().__init__()
self._stopper = threading.Event()
self._driver = driver
self._out = out
self._initMessages =... | self.key = key
self.name = name
self.number = 0 | identifier_body |
node.py | import threading
from queue import Queue, Empty
from time import sleep
from libAnt.drivers.driver import Driver |
class Network:
def __init__(self, key: bytes = b'\x00' * 8, name: str = None):
self.key = key
self.name = name
self.number = 0
def __str__(self):
return self.name
class Pump(threading.Thread):
def __init__(self, driver: Driver, initMessages, out: Queue, onSucces, onFailur... | from libAnt.message import *
| random_line_split |
node.py | import threading
from queue import Queue, Empty
from time import sleep
from libAnt.drivers.driver import Driver
from libAnt.message import *
class Network:
def __init__(self, key: bytes = b'\x00' * 8, name: str = None):
self.key = key
self.name = name
self.number = 0
def __str__(self... |
elif msg.type == MESSAGE_CHANNEL_BROADCAST_DATA:
bmsg = BroadcastMessage(msg.type, msg.content).build(msg.content)
self._onSuccess(bmsg)
except Empty:
pass
except ... | for w in self._waiters:
if w.type == msg.content[1]: # ACK
self._waiters.remove(w)
# TODO: Call waiter callback from tuple (waiter, callback)
break | conditional_block |
node.py | import threading
from queue import Queue, Empty
from time import sleep
from libAnt.drivers.driver import Driver
from libAnt.message import *
class Network:
def __init__(self, key: bytes = b'\x00' * 8, name: str = None):
self.key = key
self.name = name
self.number = 0
def __str__(self... | (self):
pass
| getCapabilities | identifier_name |
mod.rs | use std::sync::atomic::AtomicBool;
use std::ptr;
use libc;
use {CreationError, Event};
use BuilderAttribs;
pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor};
use winapi;
mod event;
mod gl;
mod init;
mod monitor;
///
pub struct HeadlessContext(Window);
impl HeadlessContext {
/// ... | {
/// Main handle for the window.
window: winapi::HWND,
/// This represents a "draw context" for the surface of the window.
hdc: winapi::HDC,
/// OpenGL context.
context: winapi::HGLRC,
/// Binded to `opengl32.dll`.
///
/// `wglGetProcAddress` returns null for GL 1.1 functions be... | Window | identifier_name |
mod.rs | use std::sync::atomic::AtomicBool;
use std::ptr;
use libc;
use {CreationError, Event};
use BuilderAttribs;
pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor};
use winapi;
mod event;
mod gl;
mod init;
mod monitor;
///
pub struct HeadlessContext(Window);
| impl HeadlessContext {
/// See the docs in the crate root file.
pub fn new(builder: BuilderAttribs) -> Result<HeadlessContext, CreationError> {
let BuilderAttribs { dimensions, gl_version, gl_debug, .. } = builder;
init::new_window(dimensions, "".to_string(), None, gl_version, gl_debug, false, t... | random_line_split | |
mod.rs | use std::sync::atomic::AtomicBool;
use std::ptr;
use libc;
use {CreationError, Event};
use BuilderAttribs;
pub use self::monitor::{MonitorID, get_available_monitors, get_primary_monitor};
use winapi;
mod event;
mod gl;
mod init;
mod monitor;
///
pub struct HeadlessContext(Window);
impl HeadlessContext {
/// ... |
/// See the docs in the crate root file.
pub fn get_outer_size(&self) -> Option<(uint, uint)> {
use std::mem;
let mut rect: winapi::RECT = unsafe { mem::uninitialized() };
if unsafe { winapi::GetWindowRect(self.window, &mut rect) } == 0 {
return None
}
Som... | {
use std::mem;
let mut rect: winapi::RECT = unsafe { mem::uninitialized() };
if unsafe { winapi::GetClientRect(self.window, &mut rect) } == 0 {
return None
}
Some((
(rect.right - rect.left) as uint,
(rect.bottom - rect.top) as uint
)... | identifier_body |
detailRowCompCache.d.ts | // Type definitions for @ag-grid-community/core v25.1.0
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
import { ICellRendererComp } from "../cellRenderers/iCellRenderer";
import { RowNode } from "../../entities/rowNode";
import { BeanStub } from "../../context/beanStub... | extends BeanStub {
private cacheItems;
private maxCacheSize;
private active;
private postConstruct;
addOrDestroy(rowNode: RowNode, pinned: string | null, comp: ICellRendererComp): void;
private getCacheItem;
private stampCacheItem;
private destroyFullWidthRow;
private purgeCache;
... | DetailRowCompCache | identifier_name |
detailRowCompCache.d.ts | // Type definitions for @ag-grid-community/core v25.1.0
// Project: http://www.ag-grid.com/
// Definitions by: Niall Crosby <https://github.com/ag-grid/>
import { ICellRendererComp } from "../cellRenderers/iCellRenderer";
import { RowNode } from "../../entities/rowNode";
import { BeanStub } from "../../context/beanStub... | private cacheItems;
private maxCacheSize;
private active;
private postConstruct;
addOrDestroy(rowNode: RowNode, pinned: string | null, comp: ICellRendererComp): void;
private getCacheItem;
private stampCacheItem;
private destroyFullWidthRow;
private purgeCache;
get(rowNode: RowNo... | * still be applied after the detail grid is shown for the second time.
*/
export declare class DetailRowCompCache extends BeanStub { | random_line_split |
skills_scene.rs | use std::path::Path;
use uorustlibs::skills::Skills;
use cgmath::Point2;
use ggez::event::{KeyCode, KeyMods};
use ggez::graphics::{self, Text};
use ggez::{Context, GameResult};
use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName};
pub struct SkillsScene {
pages: Vec<Text>,
exiting: bool,
}
impl<'a> Sk... |
}
| {
match keycode {
KeyCode::Escape => self.exiting = true,
_ => (),
}
} | identifier_body |
skills_scene.rs | use std::path::Path;
use uorustlibs::skills::Skills;
use cgmath::Point2;
use ggez::event::{KeyCode, KeyMods};
use ggez::graphics::{self, Text};
use ggez::{Context, GameResult};
use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName};
pub struct SkillsScene {
pages: Vec<Text>,
exiting: bool,
}
impl<'a> Sk... | ;
format!("{} {}", glyph, skill.name)
})
.collect();
Text::new(skills.join("\n"))
})
.collect();
items
}
Err(error) => {
... | { "-" } | conditional_block |
skills_scene.rs | use std::path::Path;
use uorustlibs::skills::Skills;
use cgmath::Point2;
use ggez::event::{KeyCode, KeyMods};
use ggez::graphics::{self, Text};
use ggez::{Context, GameResult};
use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName};
pub struct SkillsScene {
pages: Vec<Text>,
exiting: bool,
}
impl<'a> Sk... | fn update(
&mut self,
_ctx: &mut Context,
_engine_data: &mut (),
) -> GameResult<Option<SceneChangeEvent<SceneName>>> {
if self.exiting {
Ok(Some(SceneChangeEvent::PopScene))
} else {
Ok(None)
}
}
fn key_down_event(
&mut se... | Ok(())
}
| random_line_split |
skills_scene.rs | use std::path::Path;
use uorustlibs::skills::Skills;
use cgmath::Point2;
use ggez::event::{KeyCode, KeyMods};
use ggez::graphics::{self, Text};
use ggez::{Context, GameResult};
use scene::{BoxedScene, Scene, SceneChangeEvent, SceneName};
pub struct | {
pages: Vec<Text>,
exiting: bool,
}
impl<'a> SkillsScene {
pub fn new() -> BoxedScene<'a, SceneName, ()> {
let skills = Skills::new(
&Path::new("./assets/skills.idx"),
&Path::new("./assets/skills.mul"),
);
let text = match skills {
Ok(skills) =>... | SkillsScene | identifier_name |
fakeipmitool.py | import os
import time
import yaml
import random
import argparse
from rackattack.physical import pikapatch
from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool
intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)}
rangesProbabilities = intervalRanges.keys()
rangesProbabi... |
else:
raise NotImplementedError
def sol(subaction):
if subaction != "activate":
return
possibleOutputLines = ("Yo yo i'm a cool server",
"This server has got swag.",
"Wow this totally looks like a serial log of a linux server",
... | print "Chassis Power Control: Down/Off" | conditional_block |
fakeipmitool.py | import os
import time
import yaml
import random
import argparse
from rackattack.physical import pikapatch
from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool
intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)}
rangesProbabilities = intervalRanges.keys()
rangesProbabi... |
def main(args):
useFakeRackConf()
useFakeIPMITool()
if args.I != "lanplus":
assert args.I is None
action = dict(power=power, sol=sol).get(args.action)
action(args.subaction)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-I", default=None, typ... | if subaction != "activate":
return
possibleOutputLines = ("Yo yo i'm a cool server",
"This server has got swag.",
"Wow this totally looks like a serial log of a linux server",
"asdasd")
while True:
withinBound = ran... | identifier_body |
fakeipmitool.py | import os
import time
import yaml
import random
import argparse
from rackattack.physical import pikapatch
from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool
| intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)}
rangesProbabilities = intervalRanges.keys()
rangesProbabilities.sort()
def informFakeConsumersManagerOfReboot(hostname):
rebootsPipe = os.environ["FAKE_REBOOTS_PIPE_PATH"]
fd = os.open(rebootsPipe, os.O_WRONLY)
os.write(fd, "%(hostname)s,"... | random_line_split | |
fakeipmitool.py | import os
import time
import yaml
import random
import argparse
from rackattack.physical import pikapatch
from rackattack.physical.tests.integration.main import useFakeRackConf, useFakeIPMITool
intervalRanges = {0: (0.01, 0.05), 0.85: (0.3, 0.6), 0.95: (2, 4)}
rangesProbabilities = intervalRanges.keys()
rangesProbabi... | (args):
useFakeRackConf()
useFakeIPMITool()
if args.I != "lanplus":
assert args.I is None
action = dict(power=power, sol=sol).get(args.action)
action(args.subaction)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-I", default=None, type=str)
... | main | identifier_name |
lagos.py | #! /usr/bin/python3
# -*- coding:utf-8 -*-
# lagos
# by antoine@2ohm.fr
"""
Play a little with imap.
"""
import imaplib
import smtplib
from lib.remail import remail
from lib.redoc import redoc
import yaml
import sys
import os
import logging
# Config the log machine
logging.basicConfig(
format='\033[90m[%(lev... |
# Define aliases
pool = config.get('pool', '/tmp/pool/')
# Init the connexion with the IMAP server
logging.info('Connect to the IMAP server')
M = imaplib.IMAP4_SSL(config.get('imap_server', ''))
M.login(config.get('imap_user', ''),
config.get('imap_password', ''))
M.select()
# Fetch all mails
typ, data = M... | """Send a mail.
"""
S = smtplib.SMTP(config.get('smtp_server', ''))
S.login(config.get('smtp_user', ''),
config.get('smtp_password', ''))
S.sendmail(fromaddr, toaddr, mss)
S.quit() | identifier_body |
lagos.py | #! /usr/bin/python3
# -*- coding:utf-8 -*-
# lagos
# by antoine@2ohm.fr
"""
Play a little with imap.
"""
import imaplib
import smtplib
from lib.remail import remail
from lib.redoc import redoc
import yaml
import sys
import os
import logging
# Config the log machine
logging.basicConfig(
format='\033[90m[%(lev... |
d.meta_write()
#logging.info('Send a message back')
#sendMail(config.get('imap_user', ''), sender, 'Hello back.', config)
M.close()
M.logout()
| newMeta = allMeta.get(filename, allMeta)
d.meta_add(newMeta) | conditional_block |
lagos.py | #! /usr/bin/python3
# -*- coding:utf-8 -*-
# lagos
# by antoine@2ohm.fr
"""
Play a little with imap.
"""
import imaplib
import smtplib
from lib.remail import remail
from lib.redoc import redoc
import yaml
import sys
import os
import logging
# Config the log machine
logging.basicConfig(
format='\033[90m[%(lev... | (fromaddr, toaddr, mss, config):
"""Send a mail.
"""
S = smtplib.SMTP(config.get('smtp_server', ''))
S.login(config.get('smtp_user', ''),
config.get('smtp_password', ''))
S.sendmail(fromaddr, toaddr, mss)
S.quit()
# Define aliases
pool = config.get('pool', '/tmp/pool/')
# Init t... | sendMail | identifier_name |
lagos.py | #! /usr/bin/python3
# -*- coding:utf-8 -*-
# lagos
# by antoine@2ohm.fr
"""
Play a little with imap.
"""
import imaplib
import smtplib
from lib.remail import remail
from lib.redoc import redoc
import yaml
import sys
import os
import logging
# Config the log machine
logging.basicConfig(
format='\033[90m[%(lev... |
print('from: %s' % sender)
print('about: %s' % subject)
print('%s' % content)
print(filenames)
for filename in filenames:
# Create a redoc
path = os.path.join(pool, filename)
d = redoc(path)
# Look for additional metadata
allMeta = yaml.load(content)
... | random_line_split | |
subscribe.component.ts | import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {Person} from './person'
import {RepPwdValidator} from './repPwdValidator.directive'
import {SubscribeService} from './subscribe.service';
@Component({
selector: 'subscription',
templateUrl: 'app/subscribe/sub... | else this.passwordFieldType = 'password';
}
onBlurEmail(){
console.log('ONBLUREMAIL');
}
register(){
this.subscribeService.post(this.person).then(
rc => {
this.returnedCode = rc;
console.log('returnedCode: '+rc);
if(rc=='registration_completed') {
this.router.navigate(['... |
hideShowPassword(){
if (this.passwordFieldType == 'password') this.passwordFieldType = 'text';
| random_line_split |
subscribe.component.ts | import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {Person} from './person'
import {RepPwdValidator} from './repPwdValidator.directive'
import {SubscribeService} from './subscribe.service';
@Component({
selector: 'subscription',
templateUrl: 'app/subscribe/sub... |
if(rc=='wrong_captcha') {
this.reloadCaptcha();
}
}
);
}
reloadCaptcha(){
/*this.router.navigate(['/authenticate', 'registration_completed']); */
if(this.captchaUrl.includes('captchaTempArg1')) this.captchaUrl = 'api/showCaptcha?captchaTempArg2=1';
else this.captchaUrl = 'api/sho... | {
this.router.navigate(['/authenticate', rc]);
} | conditional_block |
subscribe.component.ts | import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {Person} from './person'
import {RepPwdValidator} from './repPwdValidator.directive'
import {SubscribeService} from './subscribe.service';
@Component({
selector: 'subscription',
templateUrl: 'app/subscribe/sub... |
}
| { } | identifier_body |
subscribe.component.ts | import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {Person} from './person'
import {RepPwdValidator} from './repPwdValidator.directive'
import {SubscribeService} from './subscribe.service';
@Component({
selector: 'subscription',
templateUrl: 'app/subscribe/sub... | implements OnInit{
constructor(router: Router, private subscribeService: SubscribeService) {
this.router=router;
}
router:Router;
person = new Person('','','','');
active = true;
passwordFieldType = 'password';
returnedCode: String;
captchaUrl = 'api/showCaptcha';
newPerson()... | SubscribeComponent | identifier_name |
student-routing.module.ts | import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {StudentListComponent} from './student-list/student-list.component';
import {StudentDetailComponent} from './student-detail/student-detail.component';
import {StudentComponent} from './student/student.component';
impo... | {
path: 'add', canActivate: [AuthGuardService], component: StudentDetailComponent
},
{
path: 'delete/:studentId', canActivate: [AuthGuardService], component: StudentComponent
},
{
path: 'detail/:studentId', canActivate: [AuthGuardService], component: StudentComponent
},
{
path: 'update/:st... | // {path: ':studentId', component: StudentComponent}
// ]
// }, | random_line_split |
student-routing.module.ts | import {NgModule} from '@angular/core';
import {Routes, RouterModule} from '@angular/router';
import {StudentListComponent} from './student-list/student-list.component';
import {StudentDetailComponent} from './student-detail/student-detail.component';
import {StudentComponent} from './student/student.component';
impo... | {
}
| StudentRoutingModule | identifier_name |
config.js | (function(App) {
'use strict';
var Config = {
title: 'Guimovie',
platform: process.platform,
genres: [
'All',
'Action',
'Adventure',
'Animation',
'Biography',
'Comedy',
'Crime',
'Documentary'... | 'Mystery',
'Romance',
'Sci-Fi',
'Short',
'Sport',
'Thriller',
'War',
'Western'
],
sorters: [
'popularity',
'date',
'year',
'rating',
'alphabet'
... | 'Film-Noir',
'History',
'Horror',
'Music',
'Musical', | random_line_split |
config.js | (function(App) {
'use strict';
var Config = {
title: 'Guimovie',
platform: process.platform,
genres: [
'All',
'Action',
'Adventure',
'Animation',
'Biography',
'Comedy',
'Crime',
'Documentary'... |
return App.Providers.get(provider);
}
};
App.Config = Config;
})(window.App); | {
return _.map(provider, function(t) {
return App.Providers.get(t);
});
} | conditional_block |
advanced.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/empty';
import { GlobalService } from '../../shared/services/global.service';
import { NavigationService, Page } from '../../shared/serv... | (urlPostfix: string): string {
return `${this.urlPrefix}${urlPostfix}`;
}
}
| makeUrl | identifier_name |
advanced.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/empty';
import { GlobalService } from '../../shared/services/global.service';
import { NavigationService, Page } from '../../shared/serv... |
}
@Injectable()
export class AdvancedService {
private urlPrefix = '';
private readonly walletName;
private readonly accountName = 'account 0';
private headers = new HttpHeaders({'Content-Type': 'application/json'});
constructor(private httpClient: HttpClient, private globalService: GlobalService... | {} | identifier_body |
advanced.service.ts | import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/empty';
import { GlobalService } from '../../shared/services/global.service';
import { NavigationService, Page } from '../../shared/serv... | }
return addresses;
}
private makeUrl(urlPostfix: string): string {
return `${this.urlPrefix}${urlPostfix}`;
}
} | private processAddresses(response: any): string[] {
const addresses = new Array<string>();
for (const address of response) {
addresses.push(address); | random_line_split |
cycle_basis.py | #!/usr/bin/env python
"""
cycle_basis.py
functions for calculating the cycle basis of a graph
"""
from numpy import *
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.path import Path
if matplotlib.__version__ >= '1.3.0':
from matplotlib.p... |
def outer_loop(G, cycles):
""" Detects the boundary loop in the set of fundamental cycles
by noting that the boundary is precisely the one loop with
maximum area (since it contains all other loops, they all must
have smaller area)
"""
return max([(c.area(), c) for c in cycles])[1]
def shortes... | """ Returns a matplotlib Path object describing the cycle.
"""
# Set up polygon
verts = zeros((cycle.coords.shape[0] + 1, cycle.coords.shape[1]))
verts[:-1,:] = cycle.coords
verts[-1,:] = cycle.coords[0,:]
codes = Path.LINETO*ones(verts.shape[0])
codes[0] = Path.MOVETO
codes[-1] = Path.... | identifier_body |
cycle_basis.py | #!/usr/bin/env python
"""
cycle_basis.py
functions for calculating the cycle basis of a graph
"""
from numpy import *
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.path import Path
if matplotlib.__version__ >= '1.3.0':
from matplotlib.p... |
if len(cycleset) != n_cycles:
print "WARNING: Found only", len(cycleset), "cycles!!"
t1 = time.time()
print "Detected fundamental cycles in {}s".format(t1 - t0)
#print "Number of detected facets:", len(cycleset)
return list(cycleset)
def find_neighbor_cycles(G, cycles):
""" Returns a... | path, edges, coords = traverse_graph(G, u, v)
cycleset.add(Cycle(G, edges, coords=coords))
path, edges, coords = traverse_graph(G, v, u)
cycleset.add(Cycle(G, edges, coords=coords)) | conditional_block |
cycle_basis.py | #!/usr/bin/env python
"""
cycle_basis.py
functions for calculating the cycle basis of a graph
"""
from numpy import *
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.path import Path
if matplotlib.__version__ >= '1.3.0':
from matplotlib.p... | (self, other):
""" Returns an edge set representing the intersection of
the two cycles.
"""
inters = self.edgeset.intersection(other.edgeset)
return inters
def union(self, other, data=True):
""" Returns the edge set corresponding to the union of two cycles.
... | intersection | identifier_name |
cycle_basis.py | #!/usr/bin/env python
"""
cycle_basis.py
functions for calculating the cycle basis of a graph
"""
from numpy import *
import networkx as nx
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.path import Path
if matplotlib.__version__ >= '1.3.0':
from matplotlib.p... | # Remove pathological protruding loops
if prev in nodes_visited_set:
n_ind = nodes_visited.index(prev)
del nodes_visited[n_ind+1:]
del coords[n_ind+1:]
del edges_visited[n_ind:]
nodes_visited_set.add(prev)
edges_visited.append((nodes_visited... | random_line_split | |
setup.py | from setuptools import setup, find_packages
from codecs import open
from os import path | long_description = f.read()
setup(
name='jestocke-mangopaysdk',
version='3.0.6',
description='A client library written in python to work with mangopay v2 api',
long_description='This SDK is a client library for interacting with the Mangopay API.',
url='https://github.com/Mangopay/mangopay2-pyth... |
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'DESCRIPTION.md'), encoding='utf-8') as f: | random_line_split |
views.py | """
Views to support bulk email functionalities like opt-out.
"""
import logging
from six import text_type
from django.contrib.auth.models import User
from django.http import Http404
from bulk_email.models import Optout
from courseware.courses import get_course_by_id
from edxmako.shortcuts import render_to_respons... | except InvalidKeyError:
raise Http404("course")
unsub_check = request.POST.get('unsubscribe', False)
context = {
'course': course,
'unsubscribe': unsub_check
}
if request.method == 'GET':
return render_to_response('bulk_email/confirm_unsubscribe.html', context)
... | except UsernameDecryptionException as exn:
raise Http404(text_type(exn))
except User.DoesNotExist:
raise Http404("username") | random_line_split |
views.py | """
Views to support bulk email functionalities like opt-out.
"""
import logging
from six import text_type
from django.contrib.auth.models import User
from django.http import Http404
from bulk_email.models import Optout
from courseware.courses import get_course_by_id
from edxmako.shortcuts import render_to_respons... | """
A view that let users opt out of any email updates.
This meant is meant to be the target of an opt-out link or button.
The `token` parameter must decrypt to a valid username.
The `course_id` is the string course key of any course.
Raises a 404 if there are any errors parsing the input.
"""... | identifier_body | |
views.py | """
Views to support bulk email functionalities like opt-out.
"""
import logging
from six import text_type
from django.contrib.auth.models import User
from django.http import Http404
from bulk_email.models import Optout
from courseware.courses import get_course_by_id
from edxmako.shortcuts import render_to_respons... |
return render_to_response('bulk_email/unsubscribe_success.html', context)
| Optout.objects.get_or_create(user=user, course_id=course_key)
log.info(
u"User %s (%s) opted out of receiving emails from course %s",
user.username,
user.email,
course_id,
) | conditional_block |
views.py | """
Views to support bulk email functionalities like opt-out.
"""
import logging
from six import text_type
from django.contrib.auth.models import User
from django.http import Http404
from bulk_email.models import Optout
from courseware.courses import get_course_by_id
from edxmako.shortcuts import render_to_respons... | (request, token, course_id):
"""
A view that let users opt out of any email updates.
This meant is meant to be the target of an opt-out link or button.
The `token` parameter must decrypt to a valid username.
The `course_id` is the string course key of any course.
Raises a 404 if there are any ... | opt_out_email_updates | identifier_name |
and.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/.
//
//! AND implementation.
//!
//! Will be automatically included when including `filter::Filter`, so importing th... | <T, U>(T, U);
impl<T, U> FailableAnd<T, U> {
pub fn new(a: T, b: U) -> FailableAnd<T, U> {
FailableAnd(a, b)
}
}
impl<N, T, U, E> FailableFilter<N> for FailableAnd<T, U>
where T: FailableFilter<N, Error = E>,
U: FailableFilter<N, Error = E>
{
type Error = E;
fn filter(&self, e... | FailableAnd | identifier_name |
and.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/.
//
//! AND implementation.
//!
//! Will be automatically included when including `filter::Filter`, so importing th... |
}
| {
Ok(self.0.filter(e)? && self.1.filter(e)?)
} | identifier_body |
and.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/.
//
//! AND implementation.
//!
//! Will be automatically included when including `filter::Filter`, so importing th... | } | } | random_line_split |
drag-and-drop.js | /**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or a... | {
module.exports = DragAndDrop;
} | conditional_block | |
drag-and-drop.js | /**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or a... | document.addEventListener('dragenter', _ => {
this._dropZone.classList.add('dropping');
this._dragging = true;
});
document.addEventListener('drop', e => {
e.stopPropagation();
e.preventDefault();
this._resetDraggingUI();
// Note, this ignores multiple files in the dro... | e.stopPropagation();
e.preventDefault();
e.dataTransfer.dropEffect = 'copy'; // Explicitly show as copy action.
});
| random_line_split |
drag-and-drop.js | /**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or a... | (fileHandlerCallback) {
this._dropZone = document.querySelector('.drop_zone');
this._fileHandlerCallback = fileHandlerCallback;
this._dragging = false;
this._addListeners();
}
_addListeners() {
// The mouseleave event is more reliable than dragleave when the user drops
// the file outside ... | constructor | identifier_name |
drag-and-drop.js | /**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or a... |
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = DragAndDrop;
}
| {
this._dropZone.classList.remove('dropping');
this._dragging = false;
} | identifier_body |
fullcalendar.js | /**
* ---------------------------------------------------------------------
* GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2015-2020 Teclib' and contributors.
*
* http://glpi-project.org
*
* based on GLPI - Gestionnaire Libre de Parc Informatique
* Copyright (C) 2003-2014 by the INDEPNET Devel... | require('@fullcalendar/core');
require('@fullcalendar/daygrid');
require('@fullcalendar/interaction');
require('@fullcalendar/list');
require('@fullcalendar/timegrid');
require('@fullcalendar/rrule');
require('@fullcalendar/core/main.css');
require('@fullcalendar/daygrid/main.css');
require('@fullcalendar/list/main.cs... | // lib is exported as a module, so it must be imported as a module
import { } from 'rrule'
// Fullcalendar library | random_line_split |
__init__.py | import decimal
try:
import thread
except ImportError:
import dummy_thread as thread
from threading import local
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import util
from django.db.transaction import TransactionManagementError
from django.utils import datet... | newly created ID.
"""
return cursor.fetchone()[0]
def field_cast_sql(self, db_type):
"""
Given a column type (e.g. 'BLOB', 'VARCHAR'), returns the SQL necessary
to cast it before using it in a WHERE statement. Note that the
resulting string should contain a '... | Given a cursor object that has just performed an INSERT...RETURNING
statement into a table that has an auto-incrementing ID, returns the | random_line_split |
__init__.py | import decimal
try:
import thread
except ImportError:
import dummy_thread as thread
from threading import local
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import util
from django.db.transaction import TransactionManagementError
from django.utils import datet... |
class BaseDatabaseIntrospection(object):
"""
This class encapsulates all backend-specific introspection utilities
"""
data_types_reverse = {}
def __init__(self, connection):
self.connection = connection
def get_field_type(self, data_type, description):
"""Hook for a database ... | """
This class encapsulates all backend-specific differences, such as the way
a backend performs ordering or calculates the ID of a recently-inserted
row.
"""
compiler_module = "django.db.models.sql.compiler"
def __init__(self):
self._cache = None
def autoinc_sql(self, table, colum... | identifier_body |
__init__.py | import decimal
try:
import thread
except ImportError:
import dummy_thread as thread
from threading import local
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import util
from django.db.transaction import TransactionManagementError
from django.utils import datet... | (self, value):
"""
Transform a datetime value to an object compatible with what is expected
by the backend driver for datetime columns.
"""
if value is None:
return None
return unicode(value)
def value_to_db_time(self, value):
"""
Transfor... | value_to_db_datetime | identifier_name |
__init__.py | import decimal
try:
import thread
except ImportError:
import dummy_thread as thread
from threading import local
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS
from django.db.backends import util
from django.db.transaction import TransactionManagementError
from django.utils import datet... |
return getattr(self._cache, compiler_name)
def quote_name(self, name):
"""
Returns a quoted version of the given table, index or column name. Does
not quote the given name if it's already been quoted.
"""
raise NotImplementedError()
def random_function_sql(self... | self._cache = import_module(self.compiler_module) | conditional_block |
utils.test.ts | import { validateNameVersion } from './utils'
describe('Validate name and version', () => {
test('Standard naming', () => {
const axios = { name: 'axios', version: '^0.21.1' }
expect(validateNameVersion(axios)).toEqual(axios)
const pkg = { name: 'pkg', version: '4.3.7' }
expect(validateNameVersion(p... | name: 'hard-source-webpack-plugin',
version: 'git+https://github.com/botpress/hard-source-webpack-plugin.git'
}
expect(validateNameVersion(pkg)).toEqual(pkg)
})
}) | random_line_split | |
testrunner.py | #!/usr/bin/env python
from __future__ import print_function
import argparse
import os
from falafel import findout_terminal_width
from falafel import test_list
from falafel.runners import FalafelTestRunner
from falafel.loaders import FalafelTestLoader
parser = argparse.ArgumentParser(description='custom test runner ... |
width = findout_terminal_width()
print(" info ".center(width, '='))
print("suite: %s" % pkg)
print("tests: %s" % allowed_tests)
print("interactive tests: %s" % args.interactive)
print('=' * width)
if args.interactive:
os.environ['INTERACTIVE_TESTS'] = '1'
loader = FalafelTestLoader(allowed_tests=allowed_tests)
... | pkg = args.suite
allowed_tests = args.test | random_line_split |
testrunner.py | #!/usr/bin/env python
from __future__ import print_function
import argparse
import os
from falafel import findout_terminal_width
from falafel import test_list
from falafel.runners import FalafelTestRunner
from falafel.loaders import FalafelTestLoader
parser = argparse.ArgumentParser(description='custom test runner ... |
try:
from tabulate import tabulate
except ImportError:
for data in tdata:
print(" %-30s\tin %-30s\tskipped: %s" % data)
else:
headers = ['class.method', 'module']
if with_skipped:
headers.append('skipped')
print('\n%s' % tabulate(tdata, heade... | print("The following tests will be run:", end='') | conditional_block |
thread-local-in-ctfe.rs | // Copyright 2017 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 ... | () -> u32 {
A
//~^ ERROR thread-local statics cannot be accessed at compile-time
}
fn main() {}
| f | identifier_name |
thread-local-in-ctfe.rs | // Copyright 2017 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 ... |
#[thread_local]
static A: u32 = 1;
static B: u32 = A;
//~^ ERROR thread-local statics cannot be accessed at compile-time
static C: &u32 = &A;
//~^ ERROR thread-local statics cannot be accessed at compile-time
const D: u32 = A;
//~^ ERROR thread-local statics cannot be accessed at compile-time
const E: &u32 = &A;
/... | #![feature(const_fn, thread_local)] | random_line_split |
thread-local-in-ctfe.rs | // Copyright 2017 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 ... | {} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.