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 |
|---|---|---|---|---|
select_handler.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/. */
///
/// Implementation of the callbacks that the CSS selector engine uses to query the DOM.
///
use dom::node::Ab... |
// TODO: Use a Bloom filter.
fn named_ancestor_node(&self, node: &AbstractNode, name: &str) -> Option<AbstractNode> {
let mut node = *node;
loop {
let parent = node.parent_node();
match parent {
Some(parent) => {
let mut found = false... | {
node.parent_node()
} | identifier_body |
load_test_file.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from page_objects import *
from selenium import webdriver
import datetime
import time
import Queue
import threading
import traceback
tenders = Queue.Queue()
tenders_ids = []
tenders_threads = 2
bids = Queue.Queue()
bids_failed = {}
runs = Queue.Queue()
class CreateT... | self.find_tender.find_tender(self.tender_id)
if not self.make_bid_page.make_bid():
bids_failed[self.tender_id] = 'failed'
print('Bid failed for tender: {}'.format(self.tender_id))
return
bids_fa... | exited = False
def __init__(self, queue, user, password, tender_id, driver):
threading.Thread.__init__(self)
self.queue = queue
self.driver = driver
self.tender_id = tender_id
self.login_page_provider = LoginPage(user, password, self.driver)
self.find_tender = FindTe... | identifier_body |
load_test_file.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from page_objects import *
from selenium import webdriver
import datetime
import time
import Queue
import threading
import traceback
tenders = Queue.Queue()
tenders_ids = []
tenders_threads = 2
bids = Queue.Queue()
bids_failed = {}
runs = Queue.Queue()
class CreateT... | (self, queue, user, password, tender_id, driver):
threading.Thread.__init__(self)
self.queue = queue
self.driver = driver
self.tender_id = tender_id
self.login_page_provider = LoginPage(user, password, self.driver)
self.find_tender = FindTenderPage(self.driver)
se... | __init__ | identifier_name |
load_test_file.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from page_objects import *
from selenium import webdriver
import datetime
import time
import Queue
import threading
import traceback
tenders = Queue.Queue()
tenders_ids = []
tenders_threads = 2
bids = Queue.Queue()
bids_failed = {}
runs = Queue.Queue()
class CreateT... | Wait for all to complete
tenders.join()
print('Tenders created - ' + ', '.join(tenders_ids))
# Start making tenders bids
print('Start making bids...')
drivers = {}
for tid in tenders_ids:
for provider in provider_users.items():
driver = webdriver.Chrome()
driver.set_window_size(1200, 1000)
... | ers.put(True)
# | conditional_block |
load_test_file.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from page_objects import *
from selenium import webdriver
import datetime
import time
import Queue
import threading
import traceback
tenders = Queue.Queue()
tenders_ids = []
tenders_threads = 2
bids = Queue.Queue()
bids_failed = {}
runs = Queue.Queue()
class CreateT... | def __init__(self, queue, driver):
threading.Thread.__init__(self)
self.queue = queue
self.driver = driver
self.login_page_owner = LoginPage(
owner_users['email'], owner_users['password'], self.driver
)
self.create_tender_page = CreateTenderPage(self.drive... | random_line_split | |
payment_gateway_accounts_info.py | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... |
@property
def payment_gateway_accounts(self):
"""Gets the payment_gateway_accounts of this PaymentGatewayAccountsInfo. # noqa: E501
# noqa: E501
:return: The payment_gateway_accounts of this PaymentGatewayAccountsInfo. # noqa: E501
:rtype: list[PaymentGatewayAccount]
... | """PaymentGatewayAccountsInfo - a model defined in Swagger""" # noqa: E501
self._payment_gateway_accounts = None
self.discriminator = None
if payment_gateway_accounts is not None:
self.payment_gateway_accounts = payment_gateway_accounts | identifier_body |
payment_gateway_accounts_info.py | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... | if payment_gateway_accounts is not None:
self.payment_gateway_accounts = payment_gateway_accounts
@property
def payment_gateway_accounts(self):
"""Gets the payment_gateway_accounts of this PaymentGatewayAccountsInfo. # noqa: E501
# noqa: E501
:return: The paymen... | self.discriminator = None
| random_line_split |
payment_gateway_accounts_info.py | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... | (self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(oth... | to_str | identifier_name |
payment_gateway_accounts_info.py | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.gi... |
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| return False | conditional_block |
profile.js | import Controller from '@ember/controller';
import {set as emberSet } from '@ember/object';
import user from '../models/user';
import app_state from '../utils/app_state';
import i18n from '../utils/i18n';
import modal from '../utils/modal';
import persistence from '../utils/persistence';
import profiles from '../utils/... | // navigate to the results page (should work even if offline and haven't been able to push yet)
app_state.controller.transitionToRoute('user.log', json.user_name, 'profile-' + json.guid);
// stashes.log({
// profile: json
// });
// stashes.push_log();
// TO... | if(persistence.get('online')) {
stashes.push_log();
} | random_line_split |
profile.js | import Controller from '@ember/controller';
import {set as emberSet } from '@ember/object';
import user from '../models/user';
import app_state from '../utils/app_state';
import i18n from '../utils/i18n';
import modal from '../utils/modal';
import persistence from '../utils/persistence';
import profiles from '../utils/... | else {
emberSet(a, 'selected', false);
}
});
this.set('answer_ts', (new Date()).getTime());
this.send('highlight_blank');
},
submit: function() {
stashes.track_daily_event('profile');
var _this = this;
var nonce = _this.get('user.external_nonce') || app_sta... | {
emberSet(a, 'selected', true);
} | conditional_block |
json.rs | //! Experimental loader which takes a program specification in Json form.
use crate::architecture::*;
use crate::loader::*;
use crate::memory::backing::*;
use crate::memory::MemoryPermissions;
use serde_json::Value;
use std::fs::File;
use std::io::Read;
use std::path::Path;
/// Experimental loader which takes a progr... |
}
| {
Vec::new()
} | identifier_body |
json.rs | //! Experimental loader which takes a program specification in Json form.
use crate::architecture::*;
use crate::loader::*;
use crate::memory::backing::*;
use crate::memory::MemoryPermissions;
use serde_json::Value;
use std::fs::File;
use std::io::Read;
use std::path::Path;
/// Experimental loader which takes a progr... | (&self) -> Result<Memory> {
Ok(self.memory.clone())
}
fn function_entries(&self) -> Result<Vec<FunctionEntry>> {
Ok(self.function_entries.clone())
}
fn program_entry(&self) -> u64 {
self.entry
}
fn architecture(&self) -> &dyn Architecture {
self.architecture.as... | memory | identifier_name |
json.rs | //! Experimental loader which takes a program specification in Json form.
use crate::architecture::*;
use crate::loader::*;
use crate::memory::backing::*;
use crate::memory::MemoryPermissions;
use serde_json::Value;
use std::fs::File;
use std::io::Read;
use std::path::Path;
/// Experimental loader which takes a progr... | function_entries.push(FunctionEntry::new(address, Some(name)));
}
} else {
bail!("functions missing");
}
let mut memory = Memory::new(architecture.endian());
if let Value::Array(ref segments) = root["segments"] {
for segment in segment... | random_line_split | |
scrollbar_wdg.py | ###########################################################
#
# Copyright (c) 2014, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... |
spt.scrollbar.drag_motion = function(evt, bvr, mouse_411) {
var src_el = spt.behavior.get_bvr_src( bvr );
var dy = mouse_411.curr_y - spt.scrollbar.mouse_start_y;
var pos_y = spt.scrollbar.el_start_y + dy;
if (pos_y < 0) {
return;
}
var content = spt.scrollbar.content;
var content... | return r'''
spt.scrollbar = {};
spt.scrollbar.mouse_start_y = null;
spt.scrollbar.el_start_y = null;
spt.scrollbar.top = null;
spt.scrollbar.content = null;
spt.scrollbar.drag_setup = function(evt, bvr, mouse_411) {
spt.scrollbar.mouse_start_y = mouse_411.curr_y;
var src_el = spt.behavior.get_bvr_src( bvr );... | identifier_body |
scrollbar_wdg.py | ###########################################################
#
# Copyright (c) 2014, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | (my):
return r'''
spt.scrollbar = {};
spt.scrollbar.mouse_start_y = null;
spt.scrollbar.el_start_y = null;
spt.scrollbar.top = null;
spt.scrollbar.content = null;
spt.scrollbar.drag_setup = function(evt, bvr, mouse_411) {
spt.scrollbar.mouse_start_y = mouse_411.curr_y;
var src_el = spt.behavior.get_... | get_onload_js | identifier_name |
scrollbar_wdg.py | ###########################################################
#
# Copyright (c) 2014, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... | bar.add_style("height: 30px")
bar.add_style("border: solid 1px black")
bar.add_color("background", "background3")
#bar.add_border()
bar.add_style("border-radius: 5")
bar.add_style("position: absolute")
bar.add_style("top: 0px")
top.add_behavior( {
... | bar.add_class("spt_scrollbar")
bar.add_class("hand")
top.add(bar)
bar.add_style("width: %s" % width) | random_line_split |
scrollbar_wdg.py | ###########################################################
#
# Copyright (c) 2014, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... |
width = 8
top.add_style("width: %s" % width)
top.add_style("position: absolute")
top.add_style("top: 0px")
top.add_style("right: 0px")
top.add_color("background", "background")
top.add_style("margin: 3px 5px")
top.add_style("opacity: 0.0")
to... | content_class = "spt_content" | conditional_block |
test.rs | use common;
use token;
use sourcefile;
use assembler::definition as definition_assembler;
#[test]
fn empty() {
assert("test_code/roo/definition/Empty.roo", "test_code/java/definition/Empty.java");
}
#[test]
fn record() {
assert("test_code/roo/definition/Record.roo", "test_code/java/definition/Record.java");
}... | }
}
fn assert_output(output: String, file: &str) {
let code = common::read_file(file);
assert!(output == code, "expecting compiled code to be \n'{}'\n, got \n'{}'\n", code, output);
} | random_line_split | |
test.rs | use common;
use token;
use sourcefile;
use assembler::definition as definition_assembler;
#[test]
fn empty() {
assert("test_code/roo/definition/Empty.roo", "test_code/java/definition/Empty.java");
}
#[test]
fn record() {
assert("test_code/roo/definition/Record.roo", "test_code/java/definition/Record.java");
}... | (roo_file: &str, java_file: &str) {
let tokens = token::tokenize_string(common::read_file(roo_file), roo_file.to_string());
let sourecfile_result = sourcefile::get_sourcefile(&tokens, 0);
match sourecfile_result {
Err(e) => panic!("expecting definition result to be valid, got {}", e.error_message()... | assert | identifier_name |
test.rs | use common;
use token;
use sourcefile;
use assembler::definition as definition_assembler;
#[test]
fn empty() {
assert("test_code/roo/definition/Empty.roo", "test_code/java/definition/Empty.java");
}
#[test]
fn record() {
assert("test_code/roo/definition/Record.roo", "test_code/java/definition/Record.java");
}... |
fn assert_output(output: String, file: &str) {
let code = common::read_file(file);
assert!(output == code, "expecting compiled code to be \n'{}'\n, got \n'{}'\n", code, output);
}
| {
let tokens = token::tokenize_string(common::read_file(roo_file), roo_file.to_string());
let sourecfile_result = sourcefile::get_sourcefile(&tokens, 0);
match sourecfile_result {
Err(e) => panic!("expecting definition result to be valid, got {}", e.error_message()),
Ok(sourcefile) => {
... | identifier_body |
request.rs | std::{fmt, io, ops};
use futures::{Async, Future, Poll};
use futures::sync::{mpsc, oneshot, BiLock, BiLockGuard};
use ::bits::{AdditionalBuilder, ComposeMode, ComposeResult, DName,
Message, MessageBuf, MessageBuilder, Question};
use super::conf::ResolvConf;
use super::error::Error;
//============ The Pa... | lBuilder);
impl TransportMessage {
/// Sets the message ID to the given value.
pub fn set_id(&mut self, id: u16) {
self.0.header_mut().set_id(id)
}
/// Checks whether `answer` is an answer to this message.
pub fn is_answer(&self, answer: &Message) -> bool {
answer.is_answer(&self.0... | essage(Additiona | identifier_name |
request.rs | .
use std::{fmt, io, ops};
use futures::{Async, Future, Poll};
use futures::sync::{mpsc, oneshot, BiLock, BiLockGuard};
use ::bits::{AdditionalBuilder, ComposeMode, ComposeResult, DName,
Message, MessageBuf, MessageBuilder, Question};
use super::conf::ResolvConf;
use super::error::Error;
//============ ... | /// the other one is kept by the query request. This way, we don’t need to
/// pass the message back when the transport is done which makes a lot easier
/// to treat all these cases where values along the way are dropped. In order
/// to allow the message being taken out of the lock, the lock’s content is
/// an option... | /// Transport messages are always kept wrapped into a pair of bi-locks. One
/// of those locks goes into the transport request for use by the transport, | random_line_split |
request.rs | use std::{fmt, io, ops};
use futures::{Async, Future, Poll};
use futures::sync::{mpsc, oneshot, BiLock, BiLockGuard};
use ::bits::{AdditionalBuilder, ComposeMode, ComposeResult, DName,
Message, MessageBuf, MessageBuilder, Question};
use super::conf::ResolvConf;
use super::error::Error;
//============ The... | Returns a bytes slice for sending over datagram transports.
pub fn dgram_bytes(&mut self) -> &[u8] {
&self.0.preview()[2..]
}
}
//------------ TransportMessageGuard -----------------------------------------
/// A RAII guard for a locked transport message.
///
/// This implements both `Deref` and `Der... | self.0.preview()
}
/// | identifier_body |
excessPropertyCheckWithUnions.ts | // @strict: true
type ADT = {
tag: "A",
a1: string
} | {
tag: "D",
d20: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20
} | {
tag: "T",
}
let wrong: ADT = { tag: "T", a1: "extra" }
wrong = { tag: "A", d20: 12 }
wrong = { tag: "D" }
type Ambiguous = {
tag... | c: "c", // ok -- kind: "A", an: { a: string } | { c: string }
}
} | random_line_split | |
builder.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will ... | @param resolver: A schema object name resolver.
@type resolver: L{resolver.Resolver}
"""
self.resolver = resolver
def build(self, name):
""" build a an object for the specified typename as defined in the schema """
if isinstance(name, str):
type =... | """ | random_line_split |
builder.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will ... |
def skip_child(self, child, ancestry):
""" get whether or not to skip the specified child """
if child.any(): return True
for x in ancestry:
if x.choice():
return True
return False
def ordering(self, type):
""" get the or... | """ add required attributes """
for attr, ancestry in type.attributes():
name = '_%s' % attr.name
value = attr.get_default()
setattr(data, name, value) | identifier_body |
builder.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will ... |
setattr(data, type.name, value)
if value is not None:
data = value
if not isinstance(data, list):
self.add_attributes(data, resolved)
for child, ancestry in resolved.children():
if self.skip_child(child, ancestry):
continue... | value = Factory.object(resolved.name)
md = value.__metadata__
md.sxtype = resolved
md.ordering = self.ordering(resolved) | conditional_block |
builder.py | # This program is free software; you can redistribute it and/or modify
# it under the terms of the (LGPL) GNU Lesser General Public License as
# published by the Free Software Foundation; either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will ... | (self, resolver):
"""
@param resolver: A schema object name resolver.
@type resolver: L{resolver.Resolver}
"""
self.resolver = resolver
def build(self, name):
""" build a an object for the specified typename as defined in the schema """
if isinstance(... | __init__ | identifier_name |
Form.tsx | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your... | (option: any) {
return option === this.state.selectedValue
}
render() {
return (
<form>
{this.props.options.map((option: any) => {
return (
<StyledRadioEntry key={option}>
<StyledRadio
type="radio"
value={option}
... | isSelectedValue | identifier_name |
Form.tsx | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j 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... |
render() {
return (
<form>
{this.props.options.map((option: any) => {
return (
<StyledRadioEntry key={option}>
<StyledRadio
type="radio"
value={option}
id={option}
checked={this.isSelectedValue(opti... | {
return option === this.state.selectedValue
} | identifier_body |
Form.tsx | /*
* Copyright (c) "Neo4j"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* Neo4j 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... | font-size: 14px;
padding: 6px 12px;
width: 100%;
&[type='checkbox'] {
display: inline-block;
margin-right: 5px;
vertical-align: middle;
width: auto;
}
`
export const StyledForm = styled.form`
width: 100%;
`
export const StyledFormElement = styled.div`
margin: 0 0 10px 0;
`
export const... | display: block;
height: 34px; | random_line_split |
day_10.rs | #![allow(transmute_ptr_to_ref)]
use std::mem;
use std::boxed::Box;
use std::option::Option;
use std::ops::Deref;
use std::ops::DerefMut;
use std::marker::Copy;
use std::clone::Clone;
struct Bucket {
key: Option<i32>,
value: Option<i32>,
next: Option<Link>
}
impl Bucket {
fn new(key: i32, value: i32)... | key: None,
value: None,
next: None
}
}
}
struct Link {
ptr: *mut Bucket
}
impl Link {
fn new(bucket: Bucket) -> Link {
Link {
ptr: Box::into_raw(Box::new(bucket))
}
}
}
impl Deref for Link {
type Target = Bucket;
fn der... | Bucket { | random_line_split |
day_10.rs | #![allow(transmute_ptr_to_ref)]
use std::mem;
use std::boxed::Box;
use std::option::Option;
use std::ops::Deref;
use std::ops::DerefMut;
use std::marker::Copy;
use std::clone::Clone;
struct Bucket {
key: Option<i32>,
value: Option<i32>,
next: Option<Link>
}
impl Bucket {
fn new(key: i32, value: i32)... | (&mut self) -> &mut Bucket {
unsafe { mem::transmute(self.ptr) }
}
}
impl Copy for Link { }
impl Clone for Link {
fn clone(&self) -> Link {
Link {
ptr: self.ptr
}
}
}
const CAPACITY: usize = 16;
#[derive(Default)]
pub struct Map {
size: usize,
table: Vec<Link... | deref_mut | identifier_name |
day_10.rs | #![allow(transmute_ptr_to_ref)]
use std::mem;
use std::boxed::Box;
use std::option::Option;
use std::ops::Deref;
use std::ops::DerefMut;
use std::marker::Copy;
use std::clone::Clone;
struct Bucket {
key: Option<i32>,
value: Option<i32>,
next: Option<Link>
}
impl Bucket {
fn new(key: i32, value: i32)... |
}
pub fn contains(&self, key: i32) -> bool {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).key == Some(key)
}
fn iterate(&self, key: i32, index: usize) -> Link {
let mut link = self.table[index];
while (*link).ke... | {
self.size += 1;
let mut new_bucket = Bucket::new(key, value);
let link = self.table[index];
new_bucket.next = Some(link);
self.table[index] = Link::new(new_bucket);
} | conditional_block |
day_10.rs | #![allow(transmute_ptr_to_ref)]
use std::mem;
use std::boxed::Box;
use std::option::Option;
use std::ops::Deref;
use std::ops::DerefMut;
use std::marker::Copy;
use std::clone::Clone;
struct Bucket {
key: Option<i32>,
value: Option<i32>,
next: Option<Link>
}
impl Bucket {
fn new(key: i32, value: i32)... |
fn iterate(&self, key: i32, index: usize) -> Link {
let mut link = self.table[index];
while (*link).key != Some(key) && (*link).next.is_some() {
link = (*link).next.unwrap();
}
link
}
pub fn get(&self, key: i32) -> Option<i32> {
let index = self.table.c... | {
let index = self.table.capacity() & key as usize;
let link = self.iterate(key, index);
(*link).key == Some(key)
} | identifier_body |
day_4.rs | use std::borrow::Cow;
use std::str::Chars;
use std::iter::Peekable;
pub fn evaluate<'s>(src: Cow<'s, str>) -> f64 {
let mut chars = (*src).chars().peekable();
parse_expression(chars.by_ref())
}
fn parse_expression(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_term(chars.by_ref());
loop ... | }
fn parse_term(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_arg(chars.by_ref());
loop {
match chars.peek().cloned() {
Some('×') => {
chars.next();
result *= parse_arg(chars.by_ref());
},
Some('÷') => {
... | }
result | random_line_split |
day_4.rs | use std::borrow::Cow;
use std::str::Chars;
use std::iter::Peekable;
pub fn evaluate<'s>(src: Cow<'s, str>) -> f64 {
let mut chars = (*src).chars().peekable();
parse_expression(chars.by_ref())
}
fn parse_expression(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_term(chars.by_ref());
loop ... | assert_eq!(evaluate(Cow::Borrowed("(4+10)÷2-3×((4+6)-2)")), -17.0);
}
}
| identifier_body | |
day_4.rs | use std::borrow::Cow;
use std::str::Chars;
use std::iter::Peekable;
pub fn evaluate<'s>(src: Cow<'s, str>) -> f64 {
let mut chars = (*src).chars().peekable();
parse_expression(chars.by_ref())
}
fn parse_expression(chars: &mut Peekable<Chars>) -> f64 {
let mut result = parse_term(chars.by_ref());
loop ... | {
assert_eq!(evaluate(Cow::Borrowed("4-1")), 3.0);
}
#[test]
fn evaluate_mul() {
assert_eq!(evaluate(Cow::Borrowed("5×6")), 30.0);
}
#[test]
fn evaluate_div() {
assert_eq!(evaluate(Cow::Borrowed("40÷10")), 4.0);
}
#[test]
fn evaluate_multiple_operations() ... | aluate_sub() | identifier_name |
metadata.py | # -*- coding: utf-8 -*-
"""
This script contains the definition of the Metadata class.
It can also be invoked in order to create a Metadata object
and save it to a file in the data directory.
"""
import cPickle
import config
class Metadata(object):
"""
Class for storing metadata about a neural network and i... |
elif task == 'srl_classify':
self.pred_dist_table = 'pred_dist_table'
self.target_dist_table = 'srl_classify_target_dist_table'
self.transitions = None
self.type_features = 'srl_classify_type_features'
self.caps_features = 'srl_classify_c... | self.pred_dist_table = 'srl_boundary_pred_dist_table'
self.target_dist_table = 'srl_boundary_target_dist_table'
self.transitions = 'srl_boundary_srl_transitions'
self.type_features = 'srl_boundary_type_features'
self.caps_features = 'srl_boundary_caps_features'
... | conditional_block |
metadata.py | # -*- coding: utf-8 -*-
"""
This script contains the definition of the Metadata class.
It can also be invoked in order to create a Metadata object
and save it to a file in the data directory.
"""
import cPickle
import config
class Metadata(object):
"""
Class for storing metadata about a neural network and i... |
def save_to_file(self):
"""
Save the contents of the metadata to a file. The filename is determined according
to the task.
"""
filename = self.paths[self.metadata]
with open(filename, 'wb') as f:
cPickle.dump(self.__dict__, f, 2)
@classmeth... | """Shows the task at hand and which attributes are used."""
lines = []
lines.append("Metadata for task %s" % self.task)
for k in self.__dict__:
if isinstance(k, str) and k.startswith('use_'):
lines.append('%s: %s' % (k, self.__dict__[k]))
return '\n'.... | identifier_body |
metadata.py | # -*- coding: utf-8 -*-
"""
This script contains the definition of the Metadata class.
It can also be invoked in order to create a Metadata object
and save it to a file in the data directory.
"""
import cPickle
import config
class Metadata(object):
"""
Class for storing metadata about a neural network and i... | (self):
"""
Save the contents of the metadata to a file. The filename is determined according
to the task.
"""
filename = self.paths[self.metadata]
with open(filename, 'wb') as f:
cPickle.dump(self.__dict__, f, 2)
@classmethod
def load_from_file(... | save_to_file | identifier_name |
metadata.py | # -*- coding: utf-8 -*-
"""
This script contains the definition of the Metadata class.
It can also be invoked in order to create a Metadata object
and save it to a file in the data directory.
"""
import cPickle
import config
class Metadata(object):
"""
Class for storing metadata about a neural network and i... | elif task == 'srl':
# one step srl
self.pred_dist_table = 'srl_1step_pred_dist_table'
self.target_dist_table = 'srl_1step_target_dist_table'
self.transitions = 'srl_1step_srl_transitions'
self.type_features = 'srl_1step_type_features'
self.... | random_line_split | |
dannybot.js | /*eslint-env browser */
// main dannybot script
const mail = require('./mail');
const storage = require('electron-json-storage');
const fs = require('fs');
const q = require('q');
var readFile = q.nbind(fs.readFile);
/* Function to run when DOM loaded */
function ready() {
init_tab_handler();
show_counts();... | {
var url = await storage.get('checklist_url');
if (!url) {
var url_json = await readFile('/home/danny/Private/lifehacking/checklist-url.js');
url = JSON.parse(url_json).api;
storage.set('checklist_url', url);
}
console.log(JSON.stringify(checklist));
var response = await win... | identifier_body | |
dannybot.js | /*eslint-env browser */
// main dannybot script
const mail = require('./mail');
const storage = require('electron-json-storage');
const fs = require('fs');
const q = require('q');
var readFile = q.nbind(fs.readFile);
/* Function to run when DOM loaded */
function ready() {
init_tab_handler();
show_counts();... |
console.log(JSON.stringify(checklist));
var response = await window.fetch(url, { method: 'PUT', headers: { 'Content-Type': 'application/json'}, body: JSON.stringify(checklist)});
console.log(response.status);
}
| {
var url_json = await readFile('/home/danny/Private/lifehacking/checklist-url.js');
url = JSON.parse(url_json).api;
storage.set('checklist_url', url);
} | conditional_block |
dannybot.js | /*eslint-env browser */
// main dannybot script
const mail = require('./mail');
const storage = require('electron-json-storage');
const fs = require('fs');
const q = require('q');
var readFile = q.nbind(fs.readFile);
/* Function to run when DOM loaded */
function ready() {
init_tab_handler();
show_counts();... | switch_active_tab(active, this);
};
}
}
function find_active_tab(tb) {
for(var i = 0; i < tb.length; ++i) {
if (tb[i].classList.contains('active')) {
return tb[i];
}
}
}
function tab_div(tab) {
var div_id = tab.dataset.tab;
return document.getElement... | var active = find_active_tab(tab_buttons); | random_line_split |
dannybot.js | /*eslint-env browser */
// main dannybot script
const mail = require('./mail');
const storage = require('electron-json-storage');
const fs = require('fs');
const q = require('q');
var readFile = q.nbind(fs.readFile);
/* Function to run when DOM loaded */
function ready() {
init_tab_handler();
show_counts();... | (hn) {
hn.classList.add('checklist-container');
var cl = await read_checklist();
var a_checklist = cl.evening;
Object.keys(a_checklist).forEach(function (k) {
var item = a_checklist[k];
var div = document.createElement('div');
div.classList.add('checklist-item');
var chec... | construct_checklist | identifier_name |
mock.py | mocking of apitools clients.
This module allows you to mock out the constructor of a particular apitools
client, for a specific API and version. Then, when the client is created, it
will be run against an expected session that you define. This way code that is
not aware of the testing framework can construct new clie... | (self, key, mocked_client, real_method):
self.__key = key
self.__mocked_client = mocked_client
self.__real_method = real_method
def Expect(self, request, response=None, exception=None, **unused_kwargs):
"""Add an expectation on the mocked method.
Exactly one of response and... | __init__ | identifier_name |
mock.py | easy mocking of apitools clients.
This module allows you to mock out the constructor of a particular apitools
client, for a specific API and version. Then, when the client is created, it
will be run against an expected session that you define. This way code that is
not aware of the testing framework can construct new... | self.__real_service_classes = {}
self.__real_client = real_client
self._request_responses = []
self.__real_include_fields = None
def __enter__(self):
return self.Mock()
def Mock(self):
"""Stub out the client class with mocked services."""
client = self.... | """Mock an apitools client."""
def __init__(self, client_class, real_client=None):
"""Mock an apitools API, given its class.
Args:
client_class: The class for the API. eg, if you
from apis.sqladmin import v1beta3
then you can pass v1beta3.SqladminV1beta3 to ... | identifier_body |
mock.py | mocking of apitools clients.
This module allows you to mock out the constructor of a particular apitools
client, for a specific API and version. Then, when the client is created, it
will be run against an expected session that you define. This way code that is
not aware of the testing framework can construct new clie... | request: The request that should be expected
response: The response that should be returned or None if
exception is provided.
exception: An exception that should be thrown, or None.
"""
# TODO(jasmuth): the unused_kwargs provides a placeholder for
# f... |
Exactly one of response and exception should be specified.
Args: | random_line_split |
mock.py | mocking of apitools clients.
This module allows you to mock out the constructor of a particular apitools
client, for a specific API and version. Then, when the client is created, it
will be run against an expected session that you define. This way code that is
not aware of the testing framework can construct new clie... |
if exception and not isinstance(exception, exceptions.Error):
raise exceptions.ConfigurationValueError(
'Exceptions must be instances of Error')
self.__response = response
self.__exception = exception
@property
def key(self):
return self.__key
... | raise exceptions.ConfigurationValueError(
'Responses should not be an instance of Error') | conditional_block |
sys_test_params.py | '''-------------------------------------------------------------------------
Copyright IBM Corp. 2015, 2015 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/... | PASSWORD = 'passw0rd' | random_line_split | |
auto-doc_it.py | # -*- coding: utf-8 -*-
# scrapy_web
# Copyright (C) 2016-2017 Matteo.Redaelli@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | picture_url = entry.xpath('.//img[@class="tires_item_image "]/@src').extract_first()
## estract eu labels
eu_fuel = entry.xpath('.//div[@class="eu_re"]//li[2]/img/@src').extract_first()
eu_wet = entry.xpath('.//div[@class="eu_re"]//li[4]/img/@src').extract_first()
... | for entry in response.xpath('//li[@class="ovVisLi"]'):
url = entry.xpath('.//div[@class="image"]/a/@href').extract_first()
manufacturer_number = entry.xpath('.//div[@class="description"]//span[@style="font-size: 12px;"]/text()').extract_first().replace("MPN: ","")
##brand
... | identifier_body |
auto-doc_it.py | # -*- coding: utf-8 -*-
# scrapy_web
# Copyright (C) 2016-2017 Matteo.Redaelli@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | (self, width="195", height="65", diameter="15", *args, **kwargs):
super(AutoDocIt, self).__init__(*args, **kwargs)
self.allowed_domains = ["auto-doc.it"]
#self.start_urls = ['http://www.auto-doc.it/pneumatici?Width=%s&CrossSections=%s&Size=%s&Season=&page=1' % (width, height, diameter)]
... | __init__ | identifier_name |
auto-doc_it.py | # -*- coding: utf-8 -*-
# scrapy_web
# Copyright (C) 2016-2017 Matteo.Redaelli@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... |
ean = entry.xpath('.//span[@class="article_number"]/text()').extract_first().replace("EAN: ","")
product = entry.xpath('.//div[@class="name"]/a/text()').extract_first()
size = entry.xpath('.//div[@class="nr"]/text()').extract_first()
description... | m=re.match(".+/(.+)-.+-.+$", url)
if m:
brand = m.group(1).replace("-", " ") | conditional_block |
auto-doc_it.py | # -*- coding: utf-8 -*-
# scrapy_web
# Copyright (C) 2016-2017 Matteo.Redaelli@gmail.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# ... | # scrapy crawl auto-doc.it -t jsonlines -o data/a.json
import scrapy
import re
class AutoDocIt(scrapy.Spider):
name = "auto-doc.it"
def __init__(self, width="195", height="65", diameter="15", *args, **kwargs):
super(AutoDocIt, self).__init__(*args, **kwargs)
self.allowed_domains = ["aut... | # along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# usage: | random_line_split |
swipe.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.2-master-71674b0
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.swipe
* @description Swipe module!
*/
/**
* @ngdoc directive
* @module material.components.swi... |
})(window, window.angular); | {
var directiveName = 'md' + name;
var eventName = '$md.' + name.toLowerCase();
DirectiveFactory.$inject = ["$parse"];
return DirectiveFactory;
/* ngInject */
function DirectiveFactory($parse) {
return { restrict: 'A', link: postLink };
function postLink(scope, element, attr) {
var f... | identifier_body |
swipe.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.2-master-71674b0
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.swipe
* @description Swipe module!
*/
/**
* @ngdoc directive
* @module material.components.swi... | });
}
}
}
})(window, window.angular); | scope.$apply(function() { fn(scope, { $event: ev }); }); | random_line_split |
swipe.js | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.2-master-71674b0
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.swipe
* @description Swipe module!
*/
/**
* @ngdoc directive
* @module material.components.swi... | ($parse) {
return { restrict: 'A', link: postLink };
function postLink(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.on(eventName, function(ev) {
scope.$apply(function() { fn(scope, { $event: ev }); });
});
}
}
}
})(window, window.angula... | DirectiveFactory | identifier_name |
resolve-type-param-in-item-in-trait.rs | // Issue #14603: Check for references to type parameters from the
// outer scope (in this case, the trait) used on items in an inner
// scope (in this case, the enum).
trait TraitA<A> {
fn outer(&self) {
enum Foo<B> {
Variance(A)
//~^ ERROR can't use generic parameters from oute... |
}
trait TraitD<A> {
fn outer(&self) {
fn foo<B>(a: A) { }
//~^ ERROR can't use generic parameters from outer function
}
}
fn main() { }
| {
struct Foo<B> { a: A }
//~^ ERROR can't use generic parameters from outer function
} | identifier_body |
resolve-type-param-in-item-in-trait.rs | // Issue #14603: Check for references to type parameters from the
// outer scope (in this case, the trait) used on items in an inner
// scope (in this case, the enum).
trait TraitA<A> {
fn outer(&self) {
enum Foo<B> {
Variance(A)
//~^ ERROR can't use generic parameters from oute... | () { }
| main | identifier_name |
resolve-type-param-in-item-in-trait.rs | // Issue #14603: Check for references to type parameters from the
// outer scope (in this case, the trait) used on items in an inner | trait TraitA<A> {
fn outer(&self) {
enum Foo<B> {
Variance(A)
//~^ ERROR can't use generic parameters from outer function
}
}
}
trait TraitB<A> {
fn outer(&self) {
struct Foo<B>(A);
//~^ ERROR can't use generic parameters from outer functi... | // scope (in this case, the enum).
| random_line_split |
util.py | import functools
from time import strftime
import tensorflow as tf
# lazy_property: no need for if $ not None logic
def | (function):
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def decorator(self):
if not hasattr(self, attribute):
setattr(self, attribute, function(self))
return getattr(self, attribute)
return decorator
def timestamp() -> str:
return... | lazy_property | identifier_name |
util.py | import functools
from time import strftime
import tensorflow as tf
# lazy_property: no need for if $ not None logic
def lazy_property(function):
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def decorator(self):
if not hasattr(self, attribute):
set... |
return decorator
@doublewrap
def define_scope(function, scope=None, *args, **kwargs):
"""
A decorator for functions that define TensorFlow operations. The wrapped
function will only be executed once. Subsequent calls to it will directly
return the result so that operations are added to the graph... | return lambda wrapee: function(wrapee, *args, **kwargs) | conditional_block |
util.py | import functools
from time import strftime
import tensorflow as tf
# lazy_property: no need for if $ not None logic
def lazy_property(function):
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def decorator(self):
if not hasattr(self, attribute):
set... | @functools.wraps(function)
def decorator(self):
if not hasattr(self, attribute):
with tf.variable_scope(name, *args, **kwargs):
setattr(self, attribute, function(self))
return getattr(self, attribute)
return decorator
def unzip(iterable):
return zip(*iterab... | name = scope or function.__name__
@property | random_line_split |
util.py | import functools
from time import strftime
import tensorflow as tf
# lazy_property: no need for if $ not None logic
def lazy_property(function):
attribute = '_cache_' + function.__name__
@property
@functools.wraps(function)
def decorator(self):
if not hasattr(self, attribute):
set... |
return decorator
@doublewrap
def define_scope(function, scope=None, *args, **kwargs):
"""
A decorator for functions that define TensorFlow operations. The wrapped
function will only be executed once. Subsequent calls to it will directly
return the result so that operations are added to the graph... | if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
return function(args[0])
else:
return lambda wrapee: function(wrapee, *args, **kwargs) | identifier_body |
client_only.rs | extern crate jsonrpc_core;
extern crate jsonrpc_core_client;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::IoHandler;
use jsonrpc_core::futures::{self, TryFutureExt};
use jsonrpc_core_client::transports::local;
#[rpc(client)]
pub trait Rpc {
/// Returns a protocol version
#[rpc(name = "protocolVersion... | {
let fut = {
let handler = IoHandler::new();
let (client, _rpc_client) = local::connect::<gen_client::Client, _, _>(handler);
client
.add(5, 6)
.map_ok(|res| println!("5 + 6 = {}", res))
};
let _ = futures::executor::block_on(fut);
} | identifier_body | |
client_only.rs | extern crate jsonrpc_core;
extern crate jsonrpc_core_client;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::IoHandler;
use jsonrpc_core::futures::{self, TryFutureExt};
use jsonrpc_core_client::transports::local;
#[rpc(client)]
pub trait Rpc {
/// Returns a protocol version | /// Adds two numbers and returns a result
#[rpc(name = "add", alias("callAsyncMetaAlias"))]
fn add(&self, a: u64, b: u64) -> Result<u64>;
}
fn main() {
let fut = {
let handler = IoHandler::new();
let (client, _rpc_client) = local::connect::<gen_client::Client, _, _>(handler);
client
.add(5, 6)
.map_ok(... | #[rpc(name = "protocolVersion")]
fn protocol_version(&self) -> Result<String>;
| random_line_split |
client_only.rs | extern crate jsonrpc_core;
extern crate jsonrpc_core_client;
#[macro_use]
extern crate jsonrpc_derive;
use jsonrpc_core::IoHandler;
use jsonrpc_core::futures::{self, TryFutureExt};
use jsonrpc_core_client::transports::local;
#[rpc(client)]
pub trait Rpc {
/// Returns a protocol version
#[rpc(name = "protocolVersion... | () {
let fut = {
let handler = IoHandler::new();
let (client, _rpc_client) = local::connect::<gen_client::Client, _, _>(handler);
client
.add(5, 6)
.map_ok(|res| println!("5 + 6 = {}", res))
};
let _ = futures::executor::block_on(fut);
}
| main | identifier_name |
contract.rs | // PactHash
// Written in 2015 by
// Andrew Poelstra <apoelstra@wpsoftware.net> | // To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You should have received a copy of the CC0 Public Domain Dedication
// along with this sof... | // | random_line_split |
contract.rs | // PactHash
// Written in 2015 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You s... | (data: &str) -> Result<Nonce, Error> {
let bytes = try!(data.from_hex().map_err(Error::Hex));
if bytes.len() != NONCE_LEN {
return Err(Error::BadLength(bytes.len()));
}
unsafe {
use std::{mem, ptr};
let mut ret: [u8; NONCE_LEN] = mem::uninitialized();
... | from_hex | identifier_name |
contract.rs | // PactHash
// Written in 2015 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You s... |
/// Decode an ASCII string as a contract
pub fn from_ascii_str(s: &str, nonce: Nonce) -> Result<Contract, Error> {
let bytes = s.as_bytes();
if bytes.len() != DATA_LEN {
Err(Error::BadLength(bytes.len()))
} else {
Ok(Contract {
ty: Type::Text,
... | {
let addr: Address = try!(FromBase58::from_base58check(s).map_err(Error::Base58));
if addr.network != expected_network {
return Err(Error::WrongNetwork(addr.network, expected_network));
}
Ok(Contract {
ty: match addr.ty {
address::Type::PubkeyHash... | identifier_body |
contract.rs | // PactHash
// Written in 2015 by
// Andrew Poelstra <apoelstra@wpsoftware.net>
//
// To the extent possible under law, the author(s) have dedicated all
// copyright and related and neighboring rights to this software to
// the public domain worldwide. This software is distributed without
// any warranty.
//
// You s... |
}
}
impl fmt::LowerHex for Contract {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// TODO no need to allocate here, I'm just being lazy
for ch in &self.serialize()[..] {
try!(write!(f, "{:02x}", *ch));
}
Ok(())
}
}
| {
Ok(Contract {
ty: Type::Text,
nonce: nonce,
data: bytes.to_owned()
})
} | conditional_block |
clone.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | Some(i) => i,
None => cx.span_bug(trait_span,
format!("unnamed field in normal struct in `deriving({})`",
name))
};
cx.field_imm(field.span, ident, subcall(field))
}).collect::... | let fields = all_fields.iter().map(|field| {
let ident = match field.name { | random_line_split |
clone.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | format!("static method in `deriving({})`",
name))
}
if all_fields.len() >= 1 && all_fields.get(0).name.is_none() {
// enum-like
let subcalls = all_fields.iter().map(subcall)... | {
let clone_ident = substr.method_ident;
let ctor_ident;
let all_fields;
let subcall = |field: &FieldInfo|
cx.expr_method_call(field.span, field.self_, clone_ident, Vec::new());
match *substr.fields {
Struct(ref af) => {
ctor_ident = substr.type_ident;
all_fi... | identifier_body |
clone.rs | // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (cx: &mut ExtCtxt,
span: Span,
mitem: @MetaItem,
item: @Item,
push: |@Item|) {
let inline = cx.meta_word(span, InternedString::new("inline"));
let attrs = vec!(cx.attribute(span, inline));
let... | expand_deriving_clone | identifier_name |
0005_auto_20141127_1436.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('computing', '0004_auto_20141127_1425'),
]
operations = [ | fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.CharField(max_length=200)),
('from_ip', models.CharField(max_length=15)),
('to_ip', models.CharField(max_length=15)),
... | migrations.CreateModel(
name='Subnet', | random_line_split |
0005_auto_20141127_1436.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
| migrations.AddField(
model_name='computer',
name='subnet',
field=models.ForeignKey(blank=True, to='computing.Subnet', null=True),
preserve_default=True,
),
]
| dependencies = [
('computing', '0004_auto_20141127_1425'),
]
operations = [
migrations.CreateModel(
name='Subnet',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('name', models.... | identifier_body |
0005_auto_20141127_1436.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class | (migrations.Migration):
dependencies = [
('computing', '0004_auto_20141127_1425'),
]
operations = [
migrations.CreateModel(
name='Subnet',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
... | Migration | identifier_name |
test_helpers.rs | //! A testing module for Runner/Process traits.
//!
//! When implementing different pieces of this crate, it was expedient
//! to have some testing structs in place. This might also be useful for
//! other developers who would want to ensure proper functionality.
use std::thread;
use std::sync::mpsc;
use chan;
use std:... |
impl TestProcess {
/// Create a new TestProcess.
pub fn new(runner: TestRunner) -> TestProcess {
let (sn, rc) = mpsc::channel();
let (send_runner, recv_runner) = mpsc::channel::<TestRunner>();
// Marid sender/receiver
let (signals, sig_recv) = chan::async();
thread::spaw... | random_line_split | |
test_helpers.rs | //! A testing module for Runner/Process traits.
//!
//! When implementing different pieces of this crate, it was expedient
//! to have some testing structs in place. This might also be useful for
//! other developers who would want to ensure proper functionality.
use std::thread;
use std::sync::mpsc;
use chan;
use std:... |
}
impl TestRunner {
/// Create a new TestRunner.
pub fn new(data: usize, sender: Sender<bool>) -> TestRunner {
TestRunner {
data: data,
sender: sender,
}
}
}
impl Runner for TestRunner {
fn setup(&mut self) -> Result<(), MaridError> {
self.data = 27;
... | {
"a testing error"
} | identifier_body |
test_helpers.rs | //! A testing module for Runner/Process traits.
//!
//! When implementing different pieces of this crate, it was expedient
//! to have some testing structs in place. This might also be useful for
//! other developers who would want to ensure proper functionality.
use std::thread;
use std::sync::mpsc;
use chan;
use std:... | (runner: TestRunner) -> TestProcess {
let (sn, rc) = mpsc::channel();
let (send_runner, recv_runner) = mpsc::channel::<TestRunner>();
// Marid sender/receiver
let (signals, sig_recv) = chan::async();
thread::spawn(move || {
let mut runner = Box::new(recv_runner.recv()... | new | identifier_name |
views.py | #-*- encoding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, RequestContext, render
from membro_profile.forms import MembroForm, MembroProfileForm, EditProfileForm
from django.contrib.aut... | else:
return HttpResponse('Inscrição não encontrado')
@login_required
def edit_profile(request):
membro = request.user
form = EditProfileForm(
request.POST or None,
initial={
'first_name': membro.first_name,
'last_name': membro.last_name,
'cpf': ... | eturn render_to_response('profile/profile.html', {'m':membro}, context)
| conditional_block |
views.py | #-*- encoding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, RequestContext, render
from membro_profile.forms import MembroForm, MembroProfileForm, EditProfileForm
from django.contrib.aut... | uest):
context = RequestContext(request)
print (str(request.user) == 'AnonymousUser')
if str(request.user) == 'AnonymousUser':
return render_to_response('profile/login.html', context)
else:
queryset = Submissao.objects.filter(autor_id=request.user.membroprofile.id or None)
if reque... | x(req | identifier_name |
views.py | #-*- encoding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, RequestContext, render
from membro_profile.forms import MembroForm, MembroProfileForm, EditProfileForm
from django.contrib.aut... |
@login_required
def user_logout(request):
# Since we know the user is logged in, we can now just log them out.
logout(request)
# Take the user back to the homepage.
return HttpResponseRedirect('/')
@login_required
def profile(request):
context = RequestContext(request)
print (context)
us... | context = RequestContext(request)
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
membro = authenticate(username=username,password=password)
if membro:
if membro.is_active:
login(request, membro)
... | identifier_body |
views.py | #-*- encoding: utf-8 -*-
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response, RequestContext, render
from membro_profile.forms import MembroForm, MembroProfileForm, EditProfileForm
from django.contrib.aut... |
if request.user.is_authenticated():
membro = MembroProfile.objects.filter(user__username=request.user).latest('user').user
context["membro"] = membro
context['lista_resumos'] = queryset
return render_to_response('profile/index.html', context)
else:
return render_to_res... | return render_to_response('profile/login.html', context)
else:
queryset = Submissao.objects.filter(autor_id=request.user.membroprofile.id or None) | random_line_split |
cityhash.rs | : &[u8]
if len <= 24 {
return if len <= 12 {
if len <= 4 {
hash32Len0to4(s, len)
} else {
hash32_len_5_to_12(s, len)
}
} else {
hash32_len_13_to_24(s, len)
}
}
// len > 32
let mut h = len as u32;
let mut g = (len as u32).wrapping_mul(C1);
let... | (mut h: u32) -> u32 {
h ^= h >> 16;
h = h.wrapping_mul(0x85ebca6b);
h ^= h >> 13;
h = h.wrapping_mul(0xc2b2ae35);
h ^= h >> 16;
return h;
}
// Mur is a helper from Murmur3 for combining two 32-bit values.
fn mur(mut a: u32, mut h: u32) -> u32 {
a = a.wrapping_mul(C1);
a = rotate32(a, 17... | fmix | identifier_name |
cityhash.rs | return if len <= 12 {
if len <= 4 {
hash32Len0to4(s, len)
} else {
hash32_len_5_to_12(s, len)
}
} else {
hash32_len_13_to_24(s, len)
}
}
// len > 32
let mut h = len as u32;
let mut g = (len as u32).wrapping_mul(C1);
let mut f = g;
let mut a0... |
pub fn cityhash32(mut s: &[u8], len: usize) -> u32 { // mut s: &[u8]
if len <= 24 { | random_line_split | |
cityhash.rs | &[u8]
if len <= 24 {
return if len <= 12 {
if len <= 4 {
hash32Len0to4(s, len)
} else {
hash32_len_5_to_12(s, len)
}
} else {
hash32_len_13_to_24(s, len)
}
}
// len > 32
let mut h = len as u32;
let mut g = (len as u32).wrapping_mul(C1);
let ... |
// rotate32 is a bitwise rotate
fn rotate32(val: u32, shift: u32) -> u32 {
if shift == 0 {
return val;
}
return val >> shift | val << (32 - shift)
}
// Some primes between 2^63 and 2^64 for various uses.
pub const K0: u64 = 0xc3a5c85c97cb3127;
pub const K1: u64 = 0xb492b66fbe98f273;
pub const K2:... | {
(p[0] as u32) | (p[1] as u32) << 8 | (p[2] as u32) << 16 | (p[3] as u32) << 24
} | identifier_body |
cityhash.rs | : &[u8]
if len <= 24 {
return if len <= 12 | else {
hash32_len_13_to_24(s, len)
}
}
// len > 32
let mut h = len as u32;
let mut g = (len as u32).wrapping_mul(C1);
let mut f = g;
let mut a0 = rotate32(fetch32(&s[len-4..]).wrapping_mul(C1), 17).wrapping_mul(C2);
let mut a1 = rotate32(fetch32(&s[len-8..]).wrapping_mul(C1), 17).wrapping_m... | {
if len <= 4 {
hash32Len0to4(s, len)
} else {
hash32_len_5_to_12(s, len)
}
} | conditional_block |
ec_public_key.rs | // Copyright 2017 Brian Smith <brian@briansmith.org>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed exc... | }
// The length of the longest supported EC public key (P-384).
const MAX_LEN: usize = 1 + (2 * 48);
impl ECPublicKey {
// DNSSEC encodes uncompressed EC public keys without the standard 0x04
// prefix that indicates they are uncompressed, but crypto libraries
// require that prefix.
pub fn from_unpre... | random_line_split | |
ec_public_key.rs | // Copyright 2017 Brian Smith <brian@briansmith.org>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed exc... | {
buf: [u8; MAX_LEN],
len: usize,
}
// The length of the longest supported EC public key (P-384).
const MAX_LEN: usize = 1 + (2 * 48);
impl ECPublicKey {
// DNSSEC encodes uncompressed EC public keys without the standard 0x04
// prefix that indicates they are uncompressed, but crypto libraries
//... | ECPublicKey | identifier_name |
ec_public_key.rs | // Copyright 2017 Brian Smith <brian@briansmith.org>
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed exc... |
pub fn prefixed_bytes(&self) -> &[u8] {
&self.buf[..self.len]
}
#[cfg(feature = "ring")]
pub fn unprefixed_bytes(&self) -> &[u8] {
&self.buf[1..self.len]
}
}
| {
let field_len = match algorithm {
Algorithm::ECDSAP256SHA256 => 32,
Algorithm::ECDSAP384SHA384 => 48,
_ => return Err("only ECDSAP256SHA256 and ECDSAP384SHA384 are supported by Ec".into()),
};
let len = 1 + (2 * field_len);
if len - 1 != without_pref... | identifier_body |
rapi.py | IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THE... |
# Access forbidden
raise http.HttpForbidden()
def HandleRequest(self, req):
"""Handles a request.
"""
ctx = self._GetRequestContext(req)
# Deserialize request parameters
if req.request_body:
# RFC2616, 7.2.1: Any HTTP/1.1 message containing an entity-body SHOULD
# include ... | return True | conditional_block |
rapi.py | . IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY TH... | @param reqauth: Whether to require authentication
"""
# pylint: disable=W0233
# it seems pylint doesn't see the second parent class there
http.server.HttpServerHandler.__init__(self)
http.auth.HttpServerRequestAuthentication.__init__(self)
self._client_cls = _client_cls
self._resmap = c... | @type reqauth: bool | random_line_split |
rapi.py | IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THE... | (self, req):
"""Handles a request.
"""
ctx = self._GetRequestContext(req)
# Deserialize request parameters
if req.request_body:
# RFC2616, 7.2.1: Any HTTP/1.1 message containing an entity-body SHOULD
# include a Content-Type header field defining the media type of that
# body. [.... | HandleRequest | identifier_name |
rapi.py | IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THE... | else:
ctx.body_data = None
try:
result = ctx.handler_fn()
except rpcerr.TimeoutError:
raise http.HttpGatewayTimeout()
except rpcerr.ProtocolError as err:
raise http.HttpBadGateway(str(err))
req.resp_headers[http.HTTP_CONTENT_TYPE] = http.HTTP_APP_JSON
return serializer... | """Handles a request.
"""
ctx = self._GetRequestContext(req)
# Deserialize request parameters
if req.request_body:
# RFC2616, 7.2.1: Any HTTP/1.1 message containing an entity-body SHOULD
# include a Content-Type header field defining the media type of that
# body. [...] If the media ... | identifier_body |
tridentnet_r152v1bc4_c5_2x.py | _bn_shared = True
branch_conv_shared = True
branch_deform = False
assert num_branch == len(branch_ids)
assert num_branch == len(valid_ranges)
class KvstoreParam:
kvstore = "local"
batch_image = General.batch_image
gpus = [0, 1, 2, 3, 4, 5, 6, 7]
... | data_name.append("valid_ranges") | conditional_block | |
tridentnet_r152v1bc4_c5_2x.py | 3
train_scaleaware = True
test_scaleaware = True
branch_ids = range(num_branch)
branch_dilates = [1, 2, 3]
valid_ranges = [(0, 90), (30, 160), (90, -1)]
valid_ranges_on_origin = True
branch_bn_shared = True
branch_conv_shared = True
branch_deform =... | :
conv_channel = 512
mean = (0, 0, 0, 0)
std = (1, 1, 1, 1)
class proposal:
pre_nms_top_n = 12000 if is_train else 6000
post_nms_top_n = 500 if is_train else 300
nms_thr = 0.7
min_bbox_side = 0
class subsample_proposal... | head | identifier_name |
tridentnet_r152v1bc4_c5_2x.py | 3
train_scaleaware = True
test_scaleaware = True
branch_ids = range(num_branch)
branch_dilates = [1, 2, 3]
valid_ranges = [(0, 90), (30, 160), (90, -1)]
valid_ranges_on_origin = True
branch_bn_shared = True
branch_conv_shared = True
branch_deform ... | aspects = (0.5, 1.0, 2.0)
class assign:
allowed_border = 0
pos_thr = 0.7
neg_thr = 0.3
min_pos_thr = 0.0
class sample:
image_anchor = 256
pos_fraction = 0.5
class trident:
invalid_anchor_threshd = ... | short = 800 // 16
long = 1200 // 16
stride = 16
scales = (2, 4, 8, 16, 32) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.