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 |
|---|---|---|---|---|
__openerp__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the G... | Ecrypted passwords
==================
Interaction with LDAP authentication:
-------------------------------------
This module is currently not compatible with the ``user_ldap`` module and
will disable LDAP authentication completely if installed at the same time.
""",
'depends': ['base'],
'data': [],
'auto_... | random_line_split | |
main.rs | Cursive;
use cursive::direction::*;
use cursive::event::*;
use cursive::theme::*;
use cursive::view::*;
use cursive::views::*;
mod litrpc;
fn | () {
let matches = clap_app!(lit_af_rs =>
(version: "0.1.0")
(author: "Trey Del Bonis <j.delbonis.3@gmail.com>")
(about: "CLI client for Lit")
(@arg a: +takes_value "Address to connect to. Default: localhost")
(@arg p: +takes_value "Port to connect to lit to. Default: idk ... | main | identifier_name |
main.rs | ::Cursive;
use cursive::direction::*;
use cursive::event::*;
use cursive::theme::*;
use cursive::view::*;
use cursive::views::*;
mod litrpc;
fn main() {
let matches = clap_app!(lit_af_rs =>
(version: "0.1.0")
(author: "Trey Del Bonis <j.delbonis.3@gmail.com>")
(about: "CLI client for Lit"... | let dt: DateTime<Utc> = DateTime::from_utc(ndt, chrono::Utc);
let mut data = LinearLayout::new(Orientation::Vertical);
data.add_child(TextView::new(format!("Channel # {}", chan.CIdx)));
data.add_child(TextView::new(format!("Outpoint: {}", chan.OutPoint)));
data.add_child(TextView::new(format!("Peer... | random_line_split | |
main.rs | Cursive;
use cursive::direction::*;
use cursive::event::*;
use cursive::theme::*;
use cursive::view::*;
use cursive::views::*;
mod litrpc;
fn main() {
let matches = clap_app!(lit_af_rs =>
(version: "0.1.0")
(author: "Trey Del Bonis <j.delbonis.3@gmail.com>")
(about: "CLI client for Lit")
... |
c.call_on_id("chans", |cpan: &mut Panel<LinearLayout>| {
let mut c_view = LinearLayout::new(Orientation::Vertical);
c_view.add_child(TextView::new("Channels"));
chans.into_iter()
.map(generate_view_for_chan)
.for_each(|e| c_view.add_child(e))... | {
use std::mem;
let clp: *mut litrpc::LitRpcClient = unsafe { mem::transmute(cl) };
move |c: &mut Cursive| {
let clrc: &mut litrpc::LitRpcClient = unsafe { mem::transmute(clp) };
// Channels.
let chans: Vec<litrpc::ChanInfo> = match clrc.call_chan_list(0) {
Ok(clr) =... | identifier_body |
main.rs | Cursive;
use cursive::direction::*;
use cursive::event::*;
use cursive::theme::*;
use cursive::view::*;
use cursive::views::*;
mod litrpc;
fn main() {
let matches = clap_app!(lit_af_rs =>
(version: "0.1.0")
(author: "Trey Del Bonis <j.delbonis.3@gmail.com>")
(about: "CLI client for Lit")
... | ,
Err(err) => panic!("{:?}", err)
};
c.call_on_id("bals", |balpan: &mut Panel<LinearLayout>| {
let mut bal_view = LinearLayout::new(Orientation::Vertical);
bal_view.add_child(TextView::new("Balances"));
bal_view.add_child(DummyView);
bals.int... | {
let mut addrs: Vec<(u32, String)> = ar.CoinTypes.into_iter()
.zip(ar.WitAddresses.into_iter())
.collect();
addrs.sort_by(|a, b| match cmp::Ord::cmp(&a.0, &b.0) {
cmp::Ordering::Equal => cmp::Ord::cmp(&a.1, &b.1),
... | conditional_block |
subsampling_step.py | # Copyright 2017 reinforce.io. 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... |
def tf_step(
self,
time,
variables,
arguments,
**kwargs
):
"""
Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
argument... | """
Creates a new subsampling-step meta optimizer instance.
Args:
optimizer: The optimizer which is modified by this meta optimizer.
fraction: The fraction of instances of the batch to subsample.
"""
assert isinstance(fraction, float) and fraction > 0.0
s... | identifier_body |
subsampling_step.py | # Copyright 2017 reinforce.io. 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... |
else:
raise TensorForceError("Invalid argument type.")
except StopIteration:
raise TensorForceError("Invalid argument type.")
batch_size = tf.shape(input=some_argument)[0]
num_samples = tf.cast(
x=(self.fraction * tf.cast(x=batch_size... | some_argument = next(arguments_iter) | conditional_block |
subsampling_step.py | # Copyright 2017 reinforce.io. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing pe... | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# | random_line_split |
subsampling_step.py | # Copyright 2017 reinforce.io. 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... | (MetaOptimizer):
"""
The subsampling-step meta optimizer randomly samples a subset of batch instances to calculate
the optimization step of another optimizer.
"""
def __init__(self, optimizer, fraction=0.1, scope='subsampling-step', summary_labels=()):
"""
Creates a new subsamplin... | SubsamplingStep | identifier_name |
output-plugin-descriptor-form-directive.js | goog.module('grrUi.forms.outputPluginDescriptorFormDirective');
goog.module.declareLegacyNamespace();
const apiService = goog.requireType('grrUi.core.apiService');
const reflectionService = goog.requireType('grrUi.core.reflectionService');
/**
* Controller for OutputPluginDescriptorFormDirective.
* @unrestricted
... | if (item['plugin_type'] === 'LEGACY') {
this.outputPluginsDescriptors[item['name']] = item;
}
}.bind(this));
this.allowedPluginsNames =
Object
.keys(
/** @type {!Object} */ (this.outputPluginsDescriptors))
.sort();
if ... | {
/** @private {!angular.Scope} */
this.scope_ = $scope;
/** @private {!apiService.ApiService} */
this.grrApiService_ = grrApiService;
/** @private {!reflectionService.ReflectionService} */
this.grrReflectionService_ = grrReflectionService;
/** @type {Object} */
this.outputPluginsDesc... | identifier_body |
output-plugin-descriptor-form-directive.js | goog.module('grrUi.forms.outputPluginDescriptorFormDirective');
goog.module.declareLegacyNamespace();
const apiService = goog.requireType('grrUi.core.apiService');
const reflectionService = goog.requireType('grrUi.core.reflectionService');
/**
* Controller for OutputPluginDescriptorFormDirective.
* @unrestricted
... | ($scope, grrApiService, grrReflectionService) {
/** @private {!angular.Scope} */
this.scope_ = $scope;
/** @private {!apiService.ApiService} */
this.grrApiService_ = grrApiService;
/** @private {!reflectionService.ReflectionService} */
this.grrReflectionService_ = grrReflectionService;
/*... | constructor | identifier_name |
output-plugin-descriptor-form-directive.js | goog.module('grrUi.forms.outputPluginDescriptorFormDirective');
goog.module.declareLegacyNamespace();
const apiService = goog.requireType('grrUi.core.apiService');
const reflectionService = goog.requireType('grrUi.core.reflectionService');
/**
* Controller for OutputPluginDescriptorFormDirective.
* @unrestricted
... | * @export
*/
exports.OutputPluginDescriptorFormDirective.semantic_type =
'OutputPluginDescriptor'; | random_line_split | |
output-plugin-descriptor-form-directive.js | goog.module('grrUi.forms.outputPluginDescriptorFormDirective');
goog.module.declareLegacyNamespace();
const apiService = goog.requireType('grrUi.core.apiService');
const reflectionService = goog.requireType('grrUi.core.reflectionService');
/**
* Controller for OutputPluginDescriptorFormDirective.
* @unrestricted
... |
}.bind(this));
this.allowedPluginsNames =
Object
.keys(
/** @type {!Object} */ (this.outputPluginsDescriptors))
.sort();
if (angular.isUndefined(
this.scope_.$eval('value.value.plugin_name.value'))) {
this.scope_['value']... | {
this.outputPluginsDescriptors[item['name']] = item;
} | conditional_block |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use consensus_types::block::Block;
use diem_crypto::HashValue;
use diem_types::transaction::Transaction;
mod execution_correctness;
mod execution_correctness_manager;
mod local;
mod process;
mod remote_service;... | (block: &Block) -> (HashValue, Vec<Transaction>) {
let id = block.id();
let mut transactions = vec![Transaction::BlockMetadata(block.into())];
transactions.extend(
block
.payload()
.unwrap_or(&vec![])
.iter()
.map(|txn| Transaction::UserTransaction(txn... | id_and_transactions_from_block | identifier_name |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use consensus_types::block::Block;
use diem_crypto::HashValue;
use diem_types::transaction::Transaction;
mod execution_correctness;
mod execution_correctness_manager;
mod local;
mod process;
mod remote_service;... | {
let id = block.id();
let mut transactions = vec![Transaction::BlockMetadata(block.into())];
transactions.extend(
block
.payload()
.unwrap_or(&vec![])
.iter()
.map(|txn| Transaction::UserTransaction(txn.clone())),
);
(id, transactions)
} | identifier_body | |
lib.rs | // Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use consensus_types::block::Block;
use diem_crypto::HashValue;
use diem_types::transaction::Transaction;
| mod remote_service;
mod serializer;
mod thread;
pub use crate::{
execution_correctness::ExecutionCorrectness,
execution_correctness_manager::ExecutionCorrectnessManager, process::Process,
};
#[cfg(test)]
mod tests;
fn id_and_transactions_from_block(block: &Block) -> (HashValue, Vec<Transaction>) {
let id... | mod execution_correctness;
mod execution_correctness_manager;
mod local;
mod process; | random_line_split |
ApplicationsAdminWidget.js | import React from 'react'
import { Provider } from 'react-redux'
import { Route, Switch } from 'react-router-dom';
import RegisterComponent from '../../RegisterComponent'
import createStore from './redux/create'
import AppList from './components/AppList' |
const ApplicationsAdminWidget = (props) => {
const store = createStore(props)
return (
<Provider store={store} >
<Switch>
<Route exact path="/admin/applications/:id/users" component={AppUsers} />
<Route path="/admin/applications/:id/edit" component={AppEdit} />
<Route path="/adm... | import AppUsers from './components/AppUsers'
import AppEdit from './components/AppEdit'
import AppDiff from './components/AppDiff' | random_line_split |
closures.rs | // build-fail
// compile-flags:-Zpolymorphize=on
#![feature(generic_const_exprs, rustc_attrs)]
//~^ WARN the feature `generic_const_exprs` is incomplete
// This test checks that the polymorphization analysis correctly detects unused const
// parameters in closures.
// Function doesn't have any generic parameters to b... |
// Function has an unused generic parameter in closure, but not in parent.
#[rustc_polymorphize_error]
pub fn used_parent<const T: usize>() -> usize {
let x: usize = T;
let add_one = |x: usize| x + 1;
//~^ ERROR item has unused generic parameters
x + add_one(3)
}
// Function uses generic parameter in... | {
//~^ ERROR item has unused generic parameters
let add_one = |x: usize| x + 1;
//~^ ERROR item has unused generic parameters
add_one(3)
} | identifier_body |
closures.rs | // build-fail
// compile-flags:-Zpolymorphize=on
#![feature(generic_const_exprs, rustc_attrs)]
//~^ WARN the feature `generic_const_exprs` is incomplete
// This test checks that the polymorphization analysis correctly detects unused const
// parameters in closures.
// Function doesn't have any generic parameters to b... | //~^ ERROR item has unused generic parameters
add_one(3)
}
// Function has an unused generic parameter in closure, but not in parent.
#[rustc_polymorphize_error]
pub fn used_parent<const T: usize>() -> usize {
let x: usize = T;
let add_one = |x: usize| x + 1;
//~^ ERROR item has unused generic para... | // Function has an unused generic parameter in parent and closure.
#[rustc_polymorphize_error]
pub fn unused<const T: usize>() -> usize {
//~^ ERROR item has unused generic parameters
let add_one = |x: usize| x + 1; | random_line_split |
closures.rs | // build-fail
// compile-flags:-Zpolymorphize=on
#![feature(generic_const_exprs, rustc_attrs)]
//~^ WARN the feature `generic_const_exprs` is incomplete
// This test checks that the polymorphization analysis correctly detects unused const
// parameters in closures.
// Function doesn't have any generic parameters to b... | <const T: usize>() -> usize {
//~^ ERROR item has unused generic parameters
let add_one = |x: usize| x + 1;
//~^ ERROR item has unused generic parameters
add_one(3)
}
// Function has an unused generic parameter in closure, but not in parent.
#[rustc_polymorphize_error]
pub fn used_parent<const T: usize... | unused | identifier_name |
kill-setuid.rs | extern crate libc;
extern crate seccomp_sys;
fn main() | assert!(seccomp_sys::seccomp_load(context) == 0);
assert!(libc::setuid(1000) == 0); /* process would be killed here */
}
}
| {
unsafe {
let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW);
let comparator = seccomp_sys::scmp_arg_cmp {
arg: 0,
op: seccomp_sys::scmp_compare::SCMP_CMP_EQ,
datum_a: 1000,
datum_b: 0,
}; /* arg[0] equals 1000 */
le... | identifier_body |
kill-setuid.rs | extern crate libc;
extern crate seccomp_sys;
fn | () {
unsafe {
let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW);
let comparator = seccomp_sys::scmp_arg_cmp {
arg: 0,
op: seccomp_sys::scmp_compare::SCMP_CMP_EQ,
datum_a: 1000,
datum_b: 0,
}; /* arg[0] equals 1000 */
... | main | identifier_name |
kill-setuid.rs | extern crate libc;
extern crate seccomp_sys;
fn main() {
unsafe { | let comparator = seccomp_sys::scmp_arg_cmp {
arg: 0,
op: seccomp_sys::scmp_compare::SCMP_CMP_EQ,
datum_a: 1000,
datum_b: 0,
}; /* arg[0] equals 1000 */
let syscall_number = 105; /* setuid on x86_64 */
assert!(
seccomp_sys::secc... | let context = seccomp_sys::seccomp_init(seccomp_sys::SCMP_ACT_ALLOW); | random_line_split |
Plugin.py | #!/usr/bin/env python
#
# Plugin.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi... | (self, name):
return super(Plugin, self).__getitem__(name)
def __delitem__(self, name):
return super(Plugin, self).__delitem__(name)
__getattr__ = __getitem__
__setattr__ = __setitem__
| __getitem__ | identifier_name |
Plugin.py | #!/usr/bin/env python
#
# Plugin.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi... | return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))
def __setitem__(self, key, value):
return super(Plugin, self).__setitem__(key, value)
def __getitem__(self, name):
return super(Plugin, self).__getitem__(name)
def __delitem__(self, name):
return super(Plugin... | self.__dict__[key] = val
def __repr__(self): | random_line_split |
Plugin.py | #!/usr/bin/env python
#
# Plugin.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi... |
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))
def __setitem__(self, key, value):
return super(Plugin, self).__setitem__(key, value)
def __getitem__(self, name):
return super(Plugin, self).__getitem__(name)
def __delitem__(self, name):
... | self.__dict__[key] = val | conditional_block |
Plugin.py | #!/usr/bin/env python
#
# Plugin.py
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; wi... |
def __getstate__(self):
return list(self.__dict__.items())
def __setstate__(self, items):
for key, val in items:
self.__dict__[key] = val
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, dict.__repr__(self))
def __setitem__(self, key, value):
... | if init is None:
init = dict()
dict.__init__(self, init) | identifier_body |
datatype-date-format_fr.js | /*
YUI 3.5.0 (build 5089)
Copyright 2012 Yahoo! Inc. All rights reserved.
Licensed under the BSD License. | YUI.add("lang/datatype-date-format_fr",function(a){a.Intl.add("datatype-date-format","fr",{"a":["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],"A":["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"],"b":["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],"B":["jan... | http://yuilibrary.com/license/
*/ | random_line_split |
compute_rigid_transform.py | #!/usr/bin/env python
# encoding: utf-8
"""
Author: Isabel Restrepo
August 12, 2012
Compute rigid transformation between two point clounds using feature correspondances
"""
import os
import sys
import glob
import time
from optparse import OptionParser
from xml.etree.ElementTree import ElementTree
from vpcl_adaptor imp... | parser.add_option("-d", "--descriptor", action="store", type="string", dest="descriptor_type", help="name of the descriptor i.e FPFH");
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", default=False, help="verbose - if false std is redirected to a logfile");
(opts, args) = parser.parse_args()
p... | random_line_split | |
compute_rigid_transform.py | #!/usr/bin/env python
# encoding: utf-8
"""
Author: Isabel Restrepo
August 12, 2012
Compute rigid transformation between two point clounds using feature correspondances
"""
import os
import sys
import glob
import time
from optparse import OptionParser
from xml.etree.ElementTree import ElementTree
from vpcl_adaptor imp... |
src_fname = src_scene_root + "/" + opts.basename_in + "_" + str(percentile) + ".ply"
src_features_dir = src_scene_root + "/" + descriptor_type + "_" + str(radius);
src_features_fname = src_features_dir + "/descriptors_" + str(percentile) + ".pcd";
tgt_fname = tgt_scene_root + "/" + opts.basename_in + "_" + str(per... | vpcl_batch.set_stdout("./logs/log_" + descriptor_type + 'percetile' + str(percentile) +'.log') | conditional_block |
eventhubs.js | var uuid = require('uuid');
var supportedEnvironments = require('../../utils/supportedEnvironments');
var testMatrix = [];
var instanceId;
var bindingId;
var resourceGroupName, namespaceName, azureeventhubs;
var environment = process.env['ENVIRONMENT'];
var location = supportedEnvironments[environment]['location'];... |
testMatrix.push(azureeventhubs);
module.exports = testMatrix; | {
azureeventhubs.e2e = true;
} | conditional_block |
eventhubs.js | var uuid = require('uuid');
var supportedEnvironments = require('../../utils/supportedEnvironments');
var testMatrix = [];
var instanceId;
var bindingId;
var resourceGroupName, namespaceName, azureeventhubs;
var environment = process.env['ENVIRONMENT'];
var location = supportedEnvironments[environment]['location'];... | 'eventHubName': 'testeh',
'location': location,
'tags': {
'foo': 'bar'
}
},
bindingParameters: {},
credentials: {
'namespace_name': namespaceName,
'event_hub_name': 'testeh',
'shared_access_key_name': '<string>',
'shared_access_key_value': '<string>',
},
e2e: false
};
// ... | provisioningParameters: {
'resourceGroup': resourceGroupName,
'namespaceName': namespaceName, | random_line_split |
consumers.py | from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer
from django.conf import settings
from django.utils import timezone
from .models import Route
class BusConsumer(JsonWebsocketConsumer):
groups = ["bus"]
def connect(self):
self.user = self.scope["user... | (self, user=None):
all_routes = Route.objects.all()
data = {}
route_list = []
for route in all_routes:
serialized = {
"id": route.id,
"bus_number": route.bus_number,
"space": route.space,
"route_name": route.rout... | _serialize | identifier_name |
consumers.py | from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer
from django.conf import settings
from django.utils import timezone
from .models import Route
class BusConsumer(JsonWebsocketConsumer):
groups = ["bus"]
def connect(self):
self.user = self.scope["user... | }
route_list.append(serialized)
if user and user in route.user_set.all():
data["userRouteId"] = route.id
data["allRoutes"] = route_list
return data
def within_time_range(self, time):
now_hour = timezone.localtime().hour
within_mor... | "space": route.space,
"route_name": route.route_name,
"status": route.status, | random_line_split |
consumers.py | from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer
from django.conf import settings
from django.utils import timezone
from .models import Route
class BusConsumer(JsonWebsocketConsumer):
groups = ["bus"]
def connect(self):
|
def receive_json(self, content): # pylint: disable=arguments-differ
if not self.connected:
return
if content.get("type") == "keepalive":
self.send_json({"type": "keepalive-response"})
return
if self.user is not None and self.user.is_authenticated and ... | self.user = self.scope["user"]
headers = dict(self.scope["headers"])
remote_addr = headers[b"x-real-ip"].decode() if b"x-real-ip" in headers else self.scope["client"][0]
if (not self.user.is_authenticated or self.user.is_restricted) and remote_addr not in settings.INTERNAL_IPS:
self.... | identifier_body |
consumers.py | from asgiref.sync import async_to_sync
from channels.generic.websocket import JsonWebsocketConsumer
from django.conf import settings
from django.utils import timezone
from .models import Route
class BusConsumer(JsonWebsocketConsumer):
groups = ["bus"]
def connect(self):
self.user = self.scope["user... |
else:
self.send_json({"error": "User does not have permissions."})
def bus_update(self, event):
if not self.connected:
return
self.send_json(event["data"])
def _serialize(self, user=None):
all_routes = Route.objects.all()
data = {}
rout... | try:
if self.within_time_range(content["time"]):
route = Route.objects.get(id=content["id"])
route.status = content["status"]
if content["time"] == "afternoon" and route.status == "a":
route.space = content["space"]
... | conditional_block |
lib.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | }
fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
}
fn add(rt: &Runtime) -> Result<()> {
let scmd = rt.cli().subcommand_matches("add").unwrap(); // safed by main()
let mut ids = rt
.ids::<crate::ui::PathProvider>()
.context("No StoreId supplied")?
.ok_or_... |
fn description() -> &'static str {
"Add annotations to entries" | random_line_split |
lib.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... |
Ok(())
}
fn remove(rt: &Runtime) -> Result<()> {
let scmd = rt.cli().subcommand_matches("remove").unwrap(); // safed by main()
let annotation_name = scmd.value_of("annotation_name").unwrap(); // safed by clap
let delete = scmd.is_present("delete-annotation");
rt.ids::<crate::... | {
debug!("No entries to annotate");
} | conditional_block |
lib.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... |
fn build_cli<'a>(app: App<'a, 'a>) -> App<'a, 'a> {
ui::build_ui(app)
}
fn name() -> &'static str {
env!("CARGO_PKG_NAME")
}
fn description() -> &'static str {
"Add annotations to entries"
}
fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
}... | {
match rt.cli().subcommand_name().ok_or_else(|| anyhow!("No command called"))? {
"add" => add(&rt),
"remove" => remove(&rt),
"list" => list(&rt),
other => {
debug!("Unknown command");
if rt.handle_unknown_subcommand("imag-a... | identifier_body |
lib.rs | //
// imag - the personal information management suite for the commandline
// Copyright (C) 2015-2020 Matthias Beyer <mail@beyermatthias.de> and contributors
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the F... | () -> &'static str {
"Add annotations to entries"
}
fn version() -> &'static str {
env!("CARGO_PKG_VERSION")
}
}
fn add(rt: &Runtime) -> Result<()> {
let scmd = rt.cli().subcommand_matches("add").unwrap(); // safed by main()
let mut ids = rt
.ids::<crate::ui::PathProvider>(... | description | identifier_name |
__main__.py | # Run all test suites
import unittest, os
from database_api_test_archive import *
from database_api_test_course import *
from database_api_test_exam import *
from database_api_test_teacher import *
from database_api_test_user import *
from rest_api_test_user import *
# List of test suites
db_suites = [u... | unittest.TextTestRunner(verbosity=2).run(suite) | conditional_block | |
__main__.py | # Run all test suites
| from database_api_test_archive import *
from database_api_test_course import *
from database_api_test_exam import *
from database_api_test_teacher import *
from database_api_test_user import *
from rest_api_test_user import *
# List of test suites
db_suites = [unittest.TestLoader().loadTestsFromTestCase(Arc... |
import unittest, os
| random_line_split |
connection_service.get_iam_policy.js | // Copyright 2022 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | () {
// Construct request
const request = {
resource,
};
// Run request
const response = await connectionClient.getIamPolicy(request);
console.log(response);
}
callGetIamPolicy();
// [END bigqueryconnection_v1_generated_ConnectionService_GetIamPolicy_async]
}
process.on('unhandled... | callGetIamPolicy | identifier_name |
connection_service.get_iam_policy.js | // Copyright 2022 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | const connectionClient = new ConnectionServiceClient();
async function callGetIamPolicy() {
// Construct request
const request = {
resource,
};
// Run request
const response = await connectionClient.getIamPolicy(request);
console.log(response);
}
callGetIamPolicy();
// [END bi... | {
// [START bigqueryconnection_v1_generated_ConnectionService_GetIamPolicy_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* REQUIRED: The resource for which the policy is being requested.
* See the operation documentation for the appropriate value for this ... | identifier_body |
connection_service.get_iam_policy.js | // Copyright 2022 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2)); | }
callGetIamPolicy();
// [END bigqueryconnection_v1_generated_ConnectionService_GetIamPolicy_async]
} | random_line_split |
lib.rs | // The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.
use Direction::*;
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Direction {
North,
East,
South,
West,
}
pub struct Robot {
x: isize,
y: isize,
... |
pub fn instructions(self, instructions: &str) -> Self {
instructions.chars().fold(self, |accu, c| {
match c {
'A' => accu.advance(),
'L' => accu.turn_left(),
'R' => accu.turn_right(),
_ => unreachable!(),
}
})
... | {
let (new_x, new_y) = match self.direction {
North => (self.x, self.y + 1),
East => (self.x + 1, self.y),
South => (self.x, self.y - 1),
West => (self.x - 1, self.y),
};
Robot::new(new_x, new_y, self.direction)
} | identifier_body |
lib.rs | // The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.
use Direction::*;
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Direction {
North,
East,
South,
West,
}
pub struct Robot {
x: isize,
y: isize,
... | 'A' => accu.advance(),
'L' => accu.turn_left(),
'R' => accu.turn_right(),
_ => unreachable!(),
}
})
}
pub fn position(&self) -> (isize, isize) {
(self.x, self.y)
}
pub fn direction(&self) -> &Direction {
... | }
pub fn instructions(self, instructions: &str) -> Self {
instructions.chars().fold(self, |accu, c| {
match c { | random_line_split |
lib.rs | // The code below is a stub. Just enough to satisfy the compiler.
// In order to pass the tests you can add-to or change any of this code.
use Direction::*;
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub enum Direction {
North,
East,
South,
West,
}
pub struct | {
x: isize,
y: isize,
direction: Direction,
}
impl Robot {
pub fn new(x: isize, y: isize, d: Direction) -> Self {
Robot {
x: x,
y: y,
direction: d,
}
}
pub fn turn_right(self) -> Self {
let new_direction = match self.direction {
... | Robot | identifier_name |
test_recursivity-nope.py |
def find_words(letters):
| if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for f in removed(letters, w)
w = a + b + c + d + e + f
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for g in removed(letters, w)
w = a + b + c + d + e + g
if w in WORDS: results.... | """ find_words from scrabble transformation to
recursive """
results = set()
for a in letters:
if a in WORDS: results.add(a)
if a not in PREFIXES: continue
for b in removed(letters, a):
w = a + b
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for c in removed(letters, w):
w = a +... | identifier_body |
test_recursivity-nope.py |
def find_words(letters):
""" find_words from scrabble transformation to
recursive """
results = set()
for a in letters:
if a in WORDS: results.add(a)
if a not in PREFIXES: continue
for b in removed(letters, a):
w = a + b
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for c in remov... | w = a + b + c
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for d in removed(letters, w)
w = a + b + c + d
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for e in removed(letters, w)
w = a + b + c + d + e
if w in WORDS: results.add(w)
if w n... | conditional_block | |
test_recursivity-nope.py | def find_words(letters):
""" find_words from scrabble transformation to | if a in WORDS: results.add(a)
if a not in PREFIXES: continue
for b in removed(letters, a):
w = a + b
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for c in removed(letters, w):
w = a + b + c
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for d in removed(le... | recursive """
results = set()
for a in letters: | random_line_split |
test_recursivity-nope.py |
def | (letters):
""" find_words from scrabble transformation to
recursive """
results = set()
for a in letters:
if a in WORDS: results.add(a)
if a not in PREFIXES: continue
for b in removed(letters, a):
w = a + b
if w in WORDS: results.add(w)
if w not in PREFIXES: continue
for c in removed(letters, w):... | find_words | identifier_name |
base.py | # Copyright 2014 Dietrich Epp.
# This file is part of SGLib. SGLib is licensed under the terms of the
# 2-clause BSD license. For more information, see LICENSE.txt.
BASE_CONFIG = {
'Config.PlatformToolset': 'v120',
'Config.CharacterSet': 'Unicode',
'ClCompile.WarningLevel': 'Level3',
'ClCompile.SDLCh... | 'Config.UseDebugLibraries': True,
'VC.LinkIncremental': True,
'ClCompile.Optimization': 'Disabled',
'ClCompile.PreprocessorDefinitions': ['WIN32', '_DEBUG', '_WINDOWS'],
}
RELEASE_CONFIG = {
'Config.WholeProgramOptimization': True,
'Config.UseDebugLibraries': False,
'VC.LinkIncremental': Fa... | }
DEBUG_CONFIG = { | random_line_split |
get_ng_build.py | import io
import os
import requests
import shutil
import sys
import zipfile
from waxe_image import __version__
API_RELEASES_URL = 'https://api.github.com/repos/waxe/waxe-image/releases'
NG_BUILD_FOLDER = 'website'
def | (argv=sys.argv):
if len(argv) > 2:
print('Too many arguments')
sys.exit(1)
global NG_BUILD_FOLDER
if len(argv) == 2:
NG_BUILD_FOLDER = argv[1]
if os.path.isdir(NG_BUILD_FOLDER):
shutil.rmtree(NG_BUILD_FOLDER)
if os.path.exists(NG_BUILD_FOLDER):
print('There is... | main | identifier_name |
get_ng_build.py | import io
import os
import requests
import shutil
import sys
import zipfile
from waxe_image import __version__
API_RELEASES_URL = 'https://api.github.com/repos/waxe/waxe-image/releases'
NG_BUILD_FOLDER = 'website'
def main(argv=sys.argv):
if len(argv) > 2:
print('Too many arguments')
sys.exit(1... | ng_asset = asset
break
assert(ng_asset)
url = ng_asset['browser_download_url']
r = requests.get(url, stream=True)
if r.status_code != 200:
raise ValueError('Bad status code %s' % r.status_code)
z = zipfile.ZipFile(io.StringIO(r.content))
z.extractall(NG_BUILD_F... | if 'waxe-image-ng.zip' in asset['browser_download_url']: | random_line_split |
get_ng_build.py | import io
import os
import requests
import shutil
import sys
import zipfile
from waxe_image import __version__
API_RELEASES_URL = 'https://api.github.com/repos/waxe/waxe-image/releases'
NG_BUILD_FOLDER = 'website'
def main(argv=sys.argv):
if len(argv) > 2:
print('Too many arguments')
sys.exit(1... |
r = requests.get(API_RELEASES_URL)
if r.status_code != 200:
raise ValueError('Bad status code %s' % r.status_code)
releases = r.json()
release = None
for rel in releases:
if rel['tag_name'] == __version__:
release = rel
break
if not release:
ra... | print('There is an issue with the folder %s' % NG_BUILD_FOLDER)
sys.exit(1) | conditional_block |
get_ng_build.py | import io
import os
import requests
import shutil
import sys
import zipfile
from waxe_image import __version__
API_RELEASES_URL = 'https://api.github.com/repos/waxe/waxe-image/releases'
NG_BUILD_FOLDER = 'website'
def main(argv=sys.argv):
| release = rel
break
if not release:
raise Exception('No release found for the current version %s' %
__version__)
ng_asset = None
for asset in release['assets']:
if 'waxe-image-ng.zip' in asset['browser_download_url']:
ng_asset = a... | if len(argv) > 2:
print('Too many arguments')
sys.exit(1)
global NG_BUILD_FOLDER
if len(argv) == 2:
NG_BUILD_FOLDER = argv[1]
if os.path.isdir(NG_BUILD_FOLDER):
shutil.rmtree(NG_BUILD_FOLDER)
if os.path.exists(NG_BUILD_FOLDER):
print('There is an issue with the fo... | identifier_body |
test_init.py | # 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 agreed to in writing, software
# distributed under the Li... | ():
config_settings = {}
config = pretend.stub(
add_request_method=pretend.call_recorder(lambda f, name, reify: None),
get_settings=lambda: config_settings,
)
i18n.includeme(config)
assert config.add_request_method.calls == [
pretend.call(i18n._locale, name="locale", reify=... | test_includeme | identifier_name |
test_init.py | # 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 agreed to in writing, software
# distributed under the Li... | config_settings = {}
config = pretend.stub(
add_request_method=pretend.call_recorder(lambda f, name, reify: None),
get_settings=lambda: config_settings,
)
i18n.includeme(config)
assert config.add_request_method.calls == [
pretend.call(i18n._locale, name="locale", reify=True),
... | identifier_body | |
test_init.py | # 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 agreed to in writing, software
# distributed under the Li... | import pretend
from warehouse import i18n
def test_sets_locale(monkeypatch):
locale_obj = pretend.stub()
locale_cls = pretend.stub(
parse=pretend.call_recorder(lambda l: locale_obj),
)
monkeypatch.setattr(i18n, "Locale", locale_cls)
request = pretend.stub(locale_name=pretend.stub())
... | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
| random_line_split |
electrode_ocv_gen.py | import pickle
from matplotlib import pyplot as plt
plt.style.use('classic')
import matplotlib as mpl
fs = 12.
fw = 'bold'
mpl.rc('lines', linewidth=2., color='k')
mpl.rc('font', size=fs, weight=fw, family='Arial')
mpl.rc('legend', fontsize='small')
import numpy
def grad( x, u ) :
return numpy.gradient(u) / nu... |
#scale_x1 = 1.9
#shift_x1 = -.03
## LFP Prada - (cell 2)
#scale_x = 1.25
#shift_x = 1.05-scale_x
# Graphite - scale NMC cyl cells (cell 4)
scale_x2 = 1/.8 #1./0.83 #
shift_x2 = -.06 #-.035
#scale_x2 = 1/.74
#shift_x2 = -.04
figres = 300
figname = base_dir+'ocv-plots_'+date+'.pdf'
sty = [ '-', '--' ]
fsz = (190./... | #scale_x = 1.8#1.5 # 1.55
#shift_x = -.01#-.06 #-.12
scale_x = 1.42 # 1.55
shift_x = -.03 #-.12 | random_line_split |
electrode_ocv_gen.py | import pickle
from matplotlib import pyplot as plt
plt.style.use('classic')
import matplotlib as mpl
fs = 12.
fw = 'bold'
mpl.rc('lines', linewidth=2., color='k')
mpl.rc('font', size=fs, weight=fw, family='Arial')
mpl.rc('legend', fontsize='small')
import numpy
def grad( x, u ) :
|
date = '20160519'
base = '/home/mk-sim-linux/Battery_TempGrad/Python/batt_simulation/battsimpy/'
base_dir = '/home/mk-sim-linux/Battery_TempGrad/JournalPaper2/Paper2/ocv_unif35/'
fig_dir = '/home/mk-sim-linux/Battery_TempGrad/JournalPaper3/modeling_paper_p3/figs/'
#base_dir = '/home/m_klein/tgs_data/ocv_unif35/'
... | return numpy.gradient(u) / numpy.gradient(x) | identifier_body |
electrode_ocv_gen.py | import pickle
from matplotlib import pyplot as plt
plt.style.use('classic')
import matplotlib as mpl
fs = 12.
fw = 'bold'
mpl.rc('lines', linewidth=2., color='k')
mpl.rc('font', size=fs, weight=fw, family='Arial')
mpl.rc('legend', fontsize='small')
import numpy
def | ( x, u ) :
return numpy.gradient(u) / numpy.gradient(x)
date = '20160519'
base = '/home/mk-sim-linux/Battery_TempGrad/Python/batt_simulation/battsimpy/'
base_dir = '/home/mk-sim-linux/Battery_TempGrad/JournalPaper2/Paper2/ocv_unif35/'
fig_dir = '/home/mk-sim-linux/Battery_TempGrad/JournalPaper3/modeling_paper_p... | grad | identifier_name |
electrode_ocv_gen.py | import pickle
from matplotlib import pyplot as plt
plt.style.use('classic')
import matplotlib as mpl
fs = 12.
fw = 'bold'
mpl.rc('lines', linewidth=2., color='k')
mpl.rc('font', size=fs, weight=fw, family='Arial')
mpl.rc('legend', fontsize='small')
import numpy
def grad( x, u ) :
return numpy.gradient(u) / nu... |
Ua = numpy.interp( x_cell, xin2*scale_x2+shift_x2, Uin2 )
# Plot the estimated full cell ocv curve for the aligned anode and cathode equilibrium curves
#a1.plot( x_cell, Uc-U_cell, ':k', label='U$_{anode}$ fit' )
#a1t.set_ylim([0.,2.])
a1.plot( x_cell, Uc-Ua, ':k', label='U$_{cell}$ fit' )
# Calculate the align... | Uc = numpy.interp( x_cell, xin*scale_x+shift_x, Uin ) | conditional_block |
beamProfiler.py | from PyQt4 import QtCore
import acq4.Manager
import acq4.util.imageAnalysis as imageAnalysis
run = True
man = acq4.Manager.getManager()
cam = man.getDevice('Camera')
frames = []
def | (frame):
global frames
frames.append(frame)
cam.sigNewFrame.connect(collect)
def measure():
if len(frames) == 0:
QtCore.QTimer.singleShot(100, measure)
return
global run
if run:
global frames
frame = frames[-1]
frames = []
img = frame.data()
... | collect | identifier_name |
beamProfiler.py | from PyQt4 import QtCore
import acq4.Manager
import acq4.util.imageAnalysis as imageAnalysis
run = True
man = acq4.Manager.getManager()
cam = man.getDevice('Camera')
frames = []
def collect(frame):
global frames
frames.append(frame)
cam.sigNewFrame.connect(collect)
def measure():
if len(frames)... |
global run
if run:
global frames
frame = frames[-1]
frames = []
img = frame.data()
w,h = img.shape
img = img[2*w/5:3*w/5, 2*h/5:3*h/5]
w,h = img.shape
fit = imageAnalysis.fitGaussian2D(img, [100, w/2., h/2., w/4., 0])
# convert si... | QtCore.QTimer.singleShot(100, measure)
return | conditional_block |
beamProfiler.py | from PyQt4 import QtCore
import acq4.Manager
import acq4.util.imageAnalysis as imageAnalysis
run = True
man = acq4.Manager.getManager()
cam = man.getDevice('Camera')
frames = []
def collect(frame):
|
cam.sigNewFrame.connect(collect)
def measure():
if len(frames) == 0:
QtCore.QTimer.singleShot(100, measure)
return
global run
if run:
global frames
frame = frames[-1]
frames = []
img = frame.data()
w,h = img.shape
img = img[2*w/5:3*w... | global frames
frames.append(frame) | identifier_body |
beamProfiler.py | from PyQt4 import QtCore
import acq4.Manager
import acq4.util.imageAnalysis as imageAnalysis
| man = acq4.Manager.getManager()
cam = man.getDevice('Camera')
frames = []
def collect(frame):
global frames
frames.append(frame)
cam.sigNewFrame.connect(collect)
def measure():
if len(frames) == 0:
QtCore.QTimer.singleShot(100, measure)
return
global run
if run:
g... | run = True | random_line_split |
models.py | from BTrees.OOBTree import OOBTree
from arche.interfaces import IObjectWillBeRemovedEvent
from arche.interfaces import IRoot
from arche.interfaces import IUser
from pyramid.traversal import find_root
from zope.component import adapter
from zope.interface import implementer
from arche_pas_social.interfaces import ISoci... | (object):
name = "None"
title = ""
def __init__(self, context):
self.context = context
def login(self, identifier):
mapper = IProviderMapper(self.context)
userid = mapper.get_userid(self.name, identifier)
if userid:
return userid
def get_identifier(self... | SocialAuth | identifier_name |
models.py | from BTrees.OOBTree import OOBTree
from arche.interfaces import IObjectWillBeRemovedEvent
from arche.interfaces import IRoot
from arche.interfaces import IUser
from pyramid.traversal import find_root
from zope.component import adapter
from zope.interface import implementer
from arche_pas_social.interfaces import ISoci... | del self.service_identifier_to_userid[name_id]
del self.userid_to_services[userid]
@implementer(ISocialAuth)
@adapter(IRoot)
class SocialAuth(object):
name = "None"
title = ""
def __init__(self, context):
self.context = context
def login(self, identifier):
mapper ... | def remove_userid(self, userid):
for name_id in self.userid_to_services.get(userid, ()): | random_line_split |
models.py | from BTrees.OOBTree import OOBTree
from arche.interfaces import IObjectWillBeRemovedEvent
from arche.interfaces import IRoot
from arche.interfaces import IUser
from pyramid.traversal import find_root
from zope.component import adapter
from zope.interface import implementer
from arche_pas_social.interfaces import ISoci... |
del self.userid_to_services[userid]
@implementer(ISocialAuth)
@adapter(IRoot)
class SocialAuth(object):
name = "None"
title = ""
def __init__(self, context):
self.context = context
def login(self, identifier):
mapper = IProviderMapper(self.context)
userid = mapper.ge... | del self.service_identifier_to_userid[name_id] | conditional_block |
models.py | from BTrees.OOBTree import OOBTree
from arche.interfaces import IObjectWillBeRemovedEvent
from arche.interfaces import IRoot
from arche.interfaces import IUser
from pyramid.traversal import find_root
from zope.component import adapter
from zope.interface import implementer
from arche_pas_social.interfaces import ISoci... |
def get_identifier(self, data): #pragma : no coverage
raise NotImplementedError()
def get_data(self, request): #pragma : no coverage
raise NotImplementedError()
def get_appstruct(self, data): #pragma : no coverage
raise NotImplementedError()
def remove_user_when_deleted... | mapper = IProviderMapper(self.context)
userid = mapper.get_userid(self.name, identifier)
if userid:
return userid | identifier_body |
mod.rs | )]
pub enum Event<'a> {
Begin(&'a Info),
Data(SimpleContent<'a>),
End(&'a Info),
Resync,
}
pub trait EventsHandler {
fn event(&mut self, e : Event);
}
#[cfg(feature="nightly")]
impl<F:FnMut(Event)->()> EventsHandler for F {
fn event(&mut self, e : Event) {
self.call_mut((e,))
}
}
... |
}
}
fn try_parse_element_data<'a, E : EventsHandler+?Sized>(&mut self, buf:&'a [u8], len:usize, typ : super::Type, cb: &mut E) -> ResultOfTryParseSomething<'a> {
use self::ResultOfTryParseSomething::{NoMoreData,KeepGoing,Error};
use self::Event::{Data};
use self::SimpleCont... | {
let (_, trail) = buf.split_at(1);
KeepGoing(trail)
} | conditional_block |
mod.rs | Clone)]
pub enum Event<'a> {
Begin(&'a Info),
Data(SimpleContent<'a>),
End(&'a Info),
Resync,
}
pub trait EventsHandler {
fn event(&mut self, e : Event);
}
#[cfg(feature="nightly")]
impl<F:FnMut(Event)->()> EventsHandler for F {
fn event(&mut self, e : Event) {
self.call_mut((e,))
... | }
impl ParserState {
fn try_resync<'a>(&mut self, buf:&'a [u8]) -> ResultOfTryParseSomething<'a> {
use self::ResultOfTryParseSomething::*;
if buf.len() < 4 {
return NoMoreData;
}
let (fourbytes, _) = buf.split_at(4);
let id : u32 = (fourbytes[0] as u32)*0x100000... | random_line_split | |
mod.rs | )]
pub enum Event<'a> {
Begin(&'a Info),
Data(SimpleContent<'a>),
End(&'a Info),
Resync,
}
pub trait EventsHandler {
fn event(&mut self, e : Event);
}
#[cfg(feature="nightly")]
impl<F:FnMut(Event)->()> EventsHandler for F {
fn event(&mut self, e : Event) {
self.call_mut((e,))
}
}
... | () -> ParserState {
self::Parser::new()
}
//////////////////////////////
impl fmt::Debug for Info {
fn fmt(&self, f:&mut fmt::Formatter) -> fmt::Result
{
let cl = super::database::id_to_class(self.id);
let typ = super::database::class_to_type(cl);
let cldesc = match cl {
... | new | identifier_name |
mod.rs | B | 0x1C53BB6B | 0x1941A469 | 0x1043A770 | 0x1254C367
=> {
self.mode = ParserMode::Header;
KeepGoing(buf)
}
_ => {
let (_, trail) = buf.split_at(1);
KeepGoing(trail)
}
}
}
fn try_parse... | {
use self::ResultOfTryParseSomething::*;
use self::ParserMode::*;
//cb.log(format!("feed_bytes {} len={}", bytes[0], self.accumulator.len()).as_str() );
self.accumulator.extend_from_slice(bytes);
let tmpvector = self.accumulator.to_vec();
{
... | identifier_body | |
b5a87848-de56-451e-84a6-edd26ad4958f-en_US.ts | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1">
<context>
<name>WakeOnLan</name>
<message>
<location filename="../plugininfo.h" line="29"/>
<source>WakeOnLan</source>
<extracomment>The name of the plugin WakeOnLan (b5a87848-de56-451e-84a6-edd26ad4958f)</extracomme... | <location filename="../plugininfo.h" line="35"/>
<source>Wake On Lan</source>
<extracomment>The name of the DeviceClass (3c8f2447-dcd0-4882-8c09-99e579e4d24c)</extracomment>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../pluginin... | <source>guh</source>
<extracomment>The name of the vendor (2062d64d-3232-433c-88bc-0d33c0ba2ba6)</extracomment>
<translation type="unfinished"></translation>
</message>
<message> | random_line_split |
lib.rs | //! This crate defines a macro for creating iterators which implement
//! recurrence relations.
/*
This is an implementation detail, but it *also* needs to be visible at the
*expansion* site of the `recurrence` macro (*i.e.* in another crate). Thus,
we need to publically export this macro. That said, we don't want i... | &self.slice[real_index.0]
}
}
impl Iterator for Recurrence {
type Item = $sty;
#[inline]
fn next(&mut self) -> Option<$sty> {
if self.pos < MEM_SIZE {
let nex... | let offset = Wrapping(self.offset);
let window = Wrapping(MEM_SIZE);
let real_index = index - offset + window; | random_line_split |
models.py | import os
import mimetypes
from django.conf import settings as django_settings
from django.db import models
from django.template.defaultfilters import slugify
from django.core.files.images import get_image_dimensions
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models impor... | (self):
try:
return self._dimensions_cache
except AttributeError:
if self.is_image():
self._dimensions_cache = get_image_dimensions(self.upload.path)
else:
self._dimensions_cache = (None, None)
return self._dimensions_cache
... | _get_dimensions | identifier_name |
models.py | import os
import mimetypes
from django.conf import settings as django_settings
from django.db import models
from django.template.defaultfilters import slugify
from django.core.files.images import get_image_dimensions
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models impor... |
for link in links:
ref = self.slug
opts = ':'.join(['%s=%s' % (k,v) for k,v in link[1].items()])
if opts:
ref += ':' + opts
yield {'desc': link[0],
'ref': ref}
def mime_image(self):
if not settings.ADMINFILES_STDICO... | links = settings.ADMINFILES_INSERT_LINKS[key]
break | conditional_block |
models.py | import os
import mimetypes
from django.conf import settings as django_settings
from django.db import models
from django.template.defaultfilters import slugify
from django.core.files.images import get_image_dimensions
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models impor... | for link in links:
ref = self.slug
opts = ':'.join(['%s=%s' % (k,v) for k,v in link[1].items()])
if opts:
ref += ':' + opts
yield {'desc': link[0],
'ref': ref}
def mime_image(self):
if not settings.ADMINFILES_STDICON... | if key in settings.ADMINFILES_INSERT_LINKS:
links = settings.ADMINFILES_INSERT_LINKS[key]
break | random_line_split |
models.py | import os
import mimetypes
from django.conf import settings as django_settings
from django.db import models
from django.template.defaultfilters import slugify
from django.core.files.images import get_image_dimensions
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models impor... |
def _get_dimensions(self):
try:
return self._dimensions_cache
except AttributeError:
if self.is_image():
self._dimensions_cache = get_image_dimensions(self.upload.path)
else:
self._dimensions_cache = (None, None)
return se... | return self.content_type == 'image' | identifier_body |
cron-send-create-app.py | - %(message)s',
)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ocutil = OCUtil()
commandDelay = 5 # seconds
# use parsed arg instead
#testLoopCountMax = 180 # * commandDelay = 15min
testCurlCountMax = 18 # * commandDelay = 1min30s
testNoPodCountMax = 18 # * commandDelay = 1min30s
def runOCcmd(cmd, bas... | ():
""" parse the args from the cli """
logger.debug("parse_args()")
parser = argparse.ArgumentParser(description='OpenShift app create end-to-end test')
parser.add_argument('-v', '--verbose', action='store_true', default=None, help='Verbose?')
parser.add_argument('--source', default="openshift/hel... | parse_args | identifier_name |
cron-send-create-app.py | - %(message)s',
)
logger = logging.getLogger()
logger.setLevel(logging.INFO)
ocutil = OCUtil()
commandDelay = 5 # seconds
# use parsed arg instead
#testLoopCountMax = 180 # * commandDelay = 15min
testCurlCountMax = 18 # * commandDelay = 1min30s
testNoPodCountMax = 18 # * commandDelay = 1min30s
def runOCcmd(cmd, bas... |
def setup(config):
""" global setup for tests """
logger.info('setup()')
logger.debug(config)
project = None
try:
project = runOCcmd_yaml("get project {}".format(config.namespace))
logger.debug(project)
except Exception:
pass # don't want exception if project not foun... | """ get Pod from all possible pods """
pods = ocutil.get_pods()
result = None
for pod in pods['items']:
if pod and pod['metadata']['name'] and pod['metadata']['name'].startswith(name):
# if we have a pod already, and this one is a build or deploy pod, don't worry about it
# ... | identifier_body |
cron-send-create-app.py | _code})
ms.add_metric({'openshift.master.app.build.create.time': run_time})
else:
ms.add_metric({'openshift.master.app.create': create_app})
ms.add_metric({'openshift.master.app.create.code': http_code})
ms.add_metric({'openshift.master.app.create.time': run_time})
ms.send_metri... | logger.info('Deploy State: Success')
logger.info('Service HTTP response code: %s', test_response['http_code']) | conditional_block | |
cron-send-create-app.py | commands through ocutil """
logger.info(base_cmd + " " + cmd)
ocy_time = time.time()
ocy_result = ocutil.run_user_cmd_yaml(cmd, base_cmd=base_cmd, )
logger.info("oc command took %s seconds", str(time.time() - ocy_time))
return ocy_result
def parse_args():
""" parse the args from the cli """
... |
# finish time tracking
run_time = str(time.time() - start_time) | random_line_split | |
oc_version.py | # pylint: skip-file
# pylint: disable=too-many-instance-attributes
class OCVersion(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
config,
debug):
''' Constructor for OCVer... | def filter_versions(stdout):
''' filter the oc version output '''
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if not line:
continue
... | return False
@staticmethod | random_line_split |
oc_version.py | # pylint: skip-file
# pylint: disable=too-many-instance-attributes
class OCVersion(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def | (self,
config,
debug):
''' Constructor for OCVersion '''
super(OCVersion, self).__init__(None, config)
self.debug = debug
@staticmethod
def openshift_installed():
''' check if openshift is installed '''
import yum
yum_base = yu... | __init__ | identifier_name |
oc_version.py | # pylint: skip-file
# pylint: disable=too-many-instance-attributes
class OCVersion(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
config,
debug):
''' Constructor for OCVer... |
# horrible hack to get openshift version in Openshift 3.2
# By default "oc version in 3.2 does not return an "openshift" version
if "openshift" not in version_dict:
version_dict["openshift"] = version_dict["oc"]
return version_dict
@staticmethod
def add_custom_v... | for term in version_search:
if not line:
continue
if line.startswith(term):
version_dict[term] = line.split()[-1] | conditional_block |
oc_version.py | # pylint: skip-file
# pylint: disable=too-many-instance-attributes
class OCVersion(OpenShiftCLI):
''' Class to wrap the oc command line tools '''
# pylint allows 5
# pylint: disable=too-many-arguments
def __init__(self,
config,
debug):
''' Constructor for OCVer... |
@staticmethod
def add_custom_versions(versions):
''' create custom versions strings '''
versions_dict = {}
for tech, version in versions.items():
# clean up "-" from version
if "-" in version:
version = version.split("-")[0]
if ve... | ''' filter the oc version output '''
version_dict = {}
version_search = ['oc', 'openshift', 'kubernetes']
for line in stdout.strip().split('\n'):
for term in version_search:
if not line:
continue
if line.startswith(term):
... | identifier_body |
mrsltoxrsl.py | ib
except:
raise Exception('arclib not found - no problem unless using ARC')
def format_xrsl(xrsl):
"""An indenter for xrsl files.
Rules:
0) remove original indentation (strip lines, remove \\n)
1) indent every line by 2 spaces for every open bracket '('
2) insert \\n before... |
outfiles.append([f,target])
# job output, maybe transfer automatically to MiG server
destination = destination + '/'.join(['job_output', j_name,''])
stdout = '.'.join([j_name,'stdout'])
stderr = '.'.join([j_name,'stderr'])
# do not merge stdout and stderr
a... | target = ''.join([destination,target])
# means: automatic upload to jobdir on MiG server. | conditional_block |
mrsltoxrsl.py | ['RESOURCE']:
l = targetstring.rsplit(':',1)
if len(l) == 2:
tmp_str += '(&(cluster=%s)(queue=%s))' % (l[1],l[0])
logger.debug("added to targets: %s" % tmp_str)
else:
logger.debug("ignoring malformed target %s" ... | flip_for_input | identifier_name | |
mrsltoxrsl.py | ib
except:
raise Exception('arclib not found - no problem unless using ARC')
def format_xrsl(xrsl):
"""An indenter for xrsl files.
Rules:
0) remove original indentation (strip lines, remove \\n)
1) indent every line by 2 spaces for every open bracket '('
2) insert \\n before... | # ['daughter:benedict.grid.aau.dk','other:fyrgrid.grid.aau.dk']
# Each entry leads to a cluster/queue combination, and all
# entries will be disjoint for the resulting xrsl.
# Why we do it first: the arclib Xrsl API does not allow to
# construct relations with inner AND and OR, ... | """Translate an (already checked) mRSL dictionary into xRSL,
suitable for submitting to an ARC resource.
Returns arclib.Xrsl object.
Throws exception if errors in the xRSL generation occur."""
logger.debug('to translate:\n%s\n using session ID %s' \
% (mrsl_dic... | identifier_body |
mrsltoxrsl.py | clib
except:
raise Exception('arclib not found - no problem unless using ARC')
def format_xrsl(xrsl):
"""An indenter for xrsl files.
Rules:
0) remove original indentation (strip lines, remove \\n)
1) indent every line by 2 spaces for every open bracket '('
2) insert \\n befo... | raw = ''.join(map(string.strip, ('%s' % xrsl).split('\n')))
def indent(acc, n, s):
if not s:
return acc
if s[0] == '(':
start = '\n' + ' '*n
return(indent(acc + start + '(', n+2, s[1:]))
elif s[0] == ')':
return(indent(acc + ')', n-2, ... | # raw string, without old indentation and newlines | random_line_split |
views.py | from django import forms
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.db.models import ObjectDoesNotExist
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.template import RequestContext
from django.utils.translation import uge... |
else:
form = OrderItemForm()
return render_to_response('product/product_detail.html', {
'object': product,
'form': form,
}, context_instance=RequestContext(request))
| form = OrderItemForm(request.POST)
if form.is_valid():
order = shop.order_from_request(request, create=True)
try:
order.modify_item(product, form.cleaned_data.get('quantity'))
messages.success(request, _('The cart has been updated.'))
except V... | conditional_block |
views.py | from django import forms
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.db.models import ObjectDoesNotExist
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.template import RequestContext
from django.utils.translation import uge... | (request, object_id):
product = get_object_or_404(Product.objects.filter(is_active=True), pk=object_id)
if request.method == 'POST':
form = OrderItemForm(request.POST)
if form.is_valid():
order = shop.order_from_request(request, create=True)
try:
order.m... | product_detail | identifier_name |
views.py | from django import forms
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.db.models import ObjectDoesNotExist
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.template import RequestContext
from django.utils.translation import uge... | }, context_instance=RequestContext(request)) |
return render_to_response('product/product_detail.html', {
'object': product,
'form': form, | random_line_split |
views.py | from django import forms
from django.contrib import messages
from django.core.exceptions import ValidationError
from django.db.models import ObjectDoesNotExist
from django.shortcuts import get_object_or_404, redirect, render_to_response
from django.template import RequestContext
from django.utils.translation import uge... |
def product_detail(request, object_id):
product = get_object_or_404(Product.objects.filter(is_active=True), pk=object_id)
if request.method == 'POST':
form = OrderItemForm(request.POST)
if form.is_valid():
order = shop.order_from_request(request, create=True)
try:
... | quantity = forms.IntegerField(label=_('quantity'), initial=1,
min_value=1, max_value=100) | identifier_body |
main.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/.
*/
//! A Takuzu (a.k.a. Binairo) solver.
//!
//! # Usage
//!
//! ```shell
//! takuzu [FILE]...
//! takuzu {--help | ... | match $result {
Ok(ok) => print_solutions(&ok.0, &ok.1, None),
Err(err) => eprintln!("error: {}", causes_fold(&err)),
}
};
($result:expr, $filename:expr) => {
match $result {
Ok(ok) => print_solutions(&ok.0, &ok.1, Some($filename)),
Err(err... | random_line_split | |
main.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/.
*/
//! A Takuzu (a.k.a. Binairo) solver.
//!
//! # Usage
//!
//! ```shell
//! takuzu [FILE]...
//! takuzu {--help | ... |
/// Prints a grid's solution(s) to `stdout`.
///
/// If there is more than one solution, the grids are separated an empty line.
/// If `stdout` is a terminal, prints the grids with colors and preceded by
/// a numbered label. Optionnally, prints the filename before the solutions.
fn print_solutions(grid: &Grid, solut... | {
let grid = match filename {
"-" => stdin().source()?,
_ => ::std::fs::File::open(filename)?.source()?,
};
let solutions = grid.solve()?;
Ok((grid, solutions))
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.