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
hashlist.tsx
import React, { CSSProperties } from 'react'; import TextField from './string'; import commonView from '../HOC/commonView'; import ObjectView from './object'; import IconButton from '../Components/IconButton'; import { WidgetProps } from 'jsoninput/typings/types'; import { AddStatementButton } from '../Script/Views/But...
() { removeKey(editKey); } function onKeyChange(value: string) { try { alterKey(editKey, value); } catch { // duplicate key } } return ( <div {...flex}> <div style={{ position: 'relative', flex: 1 }}> <TextField...
remove
identifier_name
hashlist.tsx
import React, { CSSProperties } from 'react'; import TextField from './string'; import commonView from '../HOC/commonView'; import ObjectView from './object'; import IconButton from '../Components/IconButton'; import { WidgetProps } from 'jsoninput/typings/types'; import { AddStatementButton } from '../Script/Views/But...
blurOnly onChange={onKeyChange} view={{ label: keyLabel, style: halfWidth, readOnly, }} /> <div style={halfWidth}>{children}</div> ...
value={editKey}
random_line_split
errors.rs
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use { proc_macro2::{Span, TokenStream}, quote::ToTokens, std::cell::RefCell, }; /// A type for collecting procedural macro errors. #[derive(Default)...
/// Error on literals, expecting attribute syntax. pub fn expect_nested_meta<'a>(&self, nm: &'a syn::NestedMeta) -> Option<&'a syn::Meta> { match nm { syn::NestedMeta::Lit(l) => { self.err(l, "Unexpected literal"); None } syn::NestedM...
{ self.err_span(second, &["Duplicate ", attr_kind, " attribute"].concat()); self.err_span(first, &["First ", attr_kind, " attribute here"].concat()); }
identifier_body
errors.rs
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use { proc_macro2::{Span, TokenStream}, quote::ToTokens, std::cell::RefCell, }; /// A type for collecting procedural macro errors. #[derive(Default)...
(&self, span: Span, msg: &str) { self.push(syn::Error::new(span, msg)); } /// Push a `syn::Error` onto the list of errors to issue. pub fn push(&self, err: syn::Error) { self.errors.borrow_mut().push(err); } } impl ToTokens for Errors { /// Convert the errors into tokens that, when...
err_span
identifier_name
errors.rs
// Copyright (c) 2020 Google LLC All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. use { proc_macro2::{Span, TokenStream}, quote::ToTokens, std::cell::RefCell, }; /// A type for collecting procedural macro errors. #[derive(Default)...
/// Push a `syn::Error` onto the list of errors to issue. pub fn push(&self, err: syn::Error) { self.errors.borrow_mut().push(err); } } impl ToTokens for Errors { /// Convert the errors into tokens that, when emit, will cause /// the user of the macro to receive compiler errors. fn to_t...
pub fn err_span(&self, span: Span, msg: &str) { self.push(syn::Error::new(span, msg)); }
random_line_split
20171030225732-create-favorite.js
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Favorites', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, userId: { type: Sequelize.STRING
recipeId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Recipes', key: 'id' } }, userId: { type: Sequelize.INTEGER, onDelete: 'CASCADE', references: { model: 'Users', key: 'id' ...
}, recipeId: { type: Sequelize.STRING },
random_line_split
dead_code.rs
use ast::cfg::{Block, BlockEnd, BlockId, BlockLink, Function, Instruction, Program}; use plank_syntax::position::Spanned; use std::collections::{HashSet, VecDeque}; use CompileCtx; fn function_block_chain(f: &Function) -> VecDeque<BlockId> { let mut blocks = VecDeque::new(); let mut current = if let Some(block...
.span(span) .build(); } fn can_be_dead(block: &Block) -> bool { for op in &block.ops { match **op { Instruction::Drop(_) => {} _ => return true, } } false } fn analyze_function(f: &mut Function, ctx: &mut CompileCtx) { let mut blocks = function_b...
} ctx.reporter .warning("dead code detected", span)
random_line_split
dead_code.rs
use ast::cfg::{Block, BlockEnd, BlockId, BlockLink, Function, Instruction, Program}; use plank_syntax::position::Spanned; use std::collections::{HashSet, VecDeque}; use CompileCtx; fn function_block_chain(f: &Function) -> VecDeque<BlockId> { let mut blocks = VecDeque::new(); let mut current = if let Some(block...
fn can_be_dead(block: &Block) -> bool { for op in &block.ops { match **op { Instruction::Drop(_) => {} _ => return true, } } false } fn analyze_function(f: &mut Function, ctx: &mut CompileCtx) { let mut blocks = function_block_chain(f); debug_assert_eq!(blo...
{ let mut span = Spanned::span(&block.ops[0]); for i in &block.ops { match **i { Instruction::StartStatement => { span = Spanned::span(i); break; } _ => { span = span.merge(Spanned::span(i)); } } ...
identifier_body
dead_code.rs
use ast::cfg::{Block, BlockEnd, BlockId, BlockLink, Function, Instruction, Program}; use plank_syntax::position::Spanned; use std::collections::{HashSet, VecDeque}; use CompileCtx; fn function_block_chain(f: &Function) -> VecDeque<BlockId> { let mut blocks = VecDeque::new(); let mut current = if let Some(block...
(block: &Block, ctx: &mut CompileCtx) { let mut span = Spanned::span(&block.ops[0]); for i in &block.ops { match **i { Instruction::StartStatement => { span = Spanned::span(i); break; } _ => { span = span.merge(Spanned::...
report_unreachable
identifier_name
dead_code.rs
use ast::cfg::{Block, BlockEnd, BlockId, BlockLink, Function, Instruction, Program}; use plank_syntax::position::Spanned; use std::collections::{HashSet, VecDeque}; use CompileCtx; fn function_block_chain(f: &Function) -> VecDeque<BlockId> { let mut blocks = VecDeque::new(); let mut current = if let Some(block...
} if strong_reachable.is_none() { strong_reachable = Some(reachable.clone()); } follow_strong = true; while let Some(block) = blocks.pop_front() { if !reachable.contains(&block) && can_be_dead(&f.blocks[&block]) { report_unreachable(&f.blo...
{ reachable.insert(block); let block = &f.blocks[&block]; match block.end { BlockEnd::Branch(_, a, b) => { queue.push_back(a); queue.push_back(b); } BlockEnd::Jump(...
conditional_block
seamcarver.js
 function SeamCarver(ctx) {
this._removedSeams = [] } SeamCarver.prototype.energy = function (x, y) { return this._energyInternal(x, y); } SeamCarver.prototype.imageData = function (ctx) { var w = this._w; var h = this._h; var id = ctx.createImageData(w, h); for (var i = 0; i < h; i++) { for (var j = 0; j < w...
var w = ctx.canvas.width; var h = ctx.canvas.height; var imgd = ctx.getImageData(0, 0, w, h); var pix = imgd.data; var img = []; for (var i = 0; i < h; i++) { img.push(new Uint32Array(w)); for (var j = 0; j < w; j++) { img[i][j] = (pix[4 * i * w + 4 * j] << 16) +...
identifier_body
seamcarver.js
 function SeamCarver(ctx) { var w = ctx.canvas.width; var h = ctx.canvas.height; var imgd = ctx.getImageData(0, 0, w, h); var pix = imgd.data; var img = []; for (var i = 0; i < h; i++) { img.push(new Uint32Array(w)); for (var j = 0; j < w; j++) { img[i][j] = (pi...
else { distTo[i][j] = dright + energy; edgeTo[i][j] = j + 1; } } } var min = Number.MAX_VALUE; var minIndex = -1; for (var i = 0; i < w; i++) { if (distTo[h - 1][i] < min) { min = distTo[h - 1][i]; minIndex...
var prevRow = distTo[i - 1]; for (var j = 1; j < w - 1; j++) { var energy = this._energyInternal(j, i); var dleft = prevRow[j - 1]; var dcenter = prevRow[j]; var dright = prevRow[j + 1]; if (dleft < dcenter && dleft < dright) { ...
conditional_block
seamcarver.js
 function SeamCarver(ctx) { var w = ctx.canvas.width; var h = ctx.canvas.height; var imgd = ctx.getImageData(0, 0, w, h); var pix = imgd.data; var img = []; for (var i = 0; i < h; i++) { img.push(new Uint32Array(w)); for (var j = 0; j < w; j++) { img[i][j] = (pi...
return Math.sqrt(dx + dy); }
var y2b = y2 & 0xFF; var dx = (x1r - x2r) * (x1r - x2r) + (x1g - x2g) * (x1g - x2g) + (x1b - x2b) * (x1b - x2b); var dy = (y1r - y2r) * (y1r - y2r) + (y1g - y2g) * (y1g - y2g) + (y1b - y2b) * (y1b - y2b);
random_line_split
seamcarver.js
 function Se
tx) { var w = ctx.canvas.width; var h = ctx.canvas.height; var imgd = ctx.getImageData(0, 0, w, h); var pix = imgd.data; var img = []; for (var i = 0; i < h; i++) { img.push(new Uint32Array(w)); for (var j = 0; j < w; j++) { img[i][j] = (pix[4 * i * w + 4 * j] <<...
amCarver(c
identifier_name
introduction.js
var Quest = require('../quest'), Messages = require('../../../../../../network/messages'), Packets = require('../../../../../../network/packets'), Utils = require('../../../../../../util/utils'); module.exports = Introduction = Quest.extend({ init: function(player, data) { var self = this; ...
self.updatePointers(); }); self.onNPCTalk(function(npc) { var conversation = self.getConversation(npc.id); if (!conversation) return; self.lastNPC = npc; npc.talk(conversation); self.player.send(new Messages.N...
random_line_split
wire.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer ...
(self): pass class QOTD(protocol.Protocol): """Return a quote of the day (RFC 865)""" def connectionMade(self): self.transport.write(self.getQuote()) self.transport.loseConnection() def getQuote(self): """Return a quote. May be overrriden in subclasses.""" return...
stopProducing
identifier_name
wire.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer ...
del name, __all3__
if name not in __all3__: __all__.remove(name) del globals()[name]
conditional_block
wire.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer ...
class Daytime(protocol.Protocol): """Send back the daytime in ASCII form (RFC 867)""" def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readab...
"""Return active users. Override in subclasses.""" return "root\r\n"
identifier_body
wire.py
# Copyright (c) Twisted Matrix Laboratories. # See LICENSE for details. """Implement standard (and unused) TCP protocols. These protocols are either provided by inetd, or are not provided at all. """ from __future__ import absolute_import, division import time import struct from zope.interface import implementer ...
def connectionMade(self): self.transport.write(time.asctime(time.gmtime(time.time())) + '\r\n') self.transport.loseConnection() class Time(protocol.Protocol): """Send back the time in machine readable form (RFC 868)""" def connectionMade(self): # is this correct only for 32-bit m...
random_line_split
hex.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
#[test] pub fn test_from_hex_invalid_char() { assert!("66y6".from_hex().is_err()); } #[test] pub fn test_from_hex_ignores_whitespace() { assert_eq!("666f 6f6\r\n26172 ".from_hex().unwrap(), b"foobar"); } #[test] pub fn test_to_hex_all_bytes() { ...
random_line_split
hex.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(&self) -> &str { match *self { InvalidHexCharacter(..) => "invalid character", InvalidHexLength => "invalid length", } } } impl FromHex for str { /// Convert any hexadecimal encoded string (literal, `@`, `&`, or `~`) /// to the byte values it encodes. /// /...
description
identifier_name
hex.rs
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
let sb = s.as_bytes().to_hex(); b.iter(|| { sb.from_hex().unwrap(); }); b.bytes = sb.len() as u64; } }
identifier_body
tax.js
/** * Shopware 5 * Copyright (c) shopware AG * * According to our dual licensing model, this program can be used either * under the terms of the GNU Affero General Public License, version 3, * or under a proprietary license. * * The texts of the GNU Affero General Public License with an additional * permission...
* GNU Affero General Public License for more details. * * "Shopware" is a registered trademark of shopware AG. * The licensing of the program under the AGPLv3 does not imply a * trademark license. Therefore any rights, title and interest in * our trademarks remain entirely with us. * * @category Shopware * @...
random_line_split
lib.register_restriction.rs
// This file was generated by `cargo dev update_lints`. // Use that command to update this file and do not edit by hand. // Manual edits will be overwritten. store.register_group(true, "clippy::restriction", Some("clippy_restriction"), vec![ LintId::of(arithmetic::FLOAT_ARITHMETIC), LintId::of(arithmetic::INTE...
LintId::of(methods::CLONE_ON_REF_PTR), LintId::of(methods::EXPECT_USED), LintId::of(methods::FILETYPE_IS_FILE), LintId::of(methods::GET_UNWRAP), LintId::of(methods::UNWRAP_USED), LintId::of(misc::FLOAT_CMP_CONST), LintId::of(misc_early::SEPARATED_LITERAL_SUFFIX), LintId::of(misc_early::U...
LintId::of(mem_forget::MEM_FORGET),
random_line_split
window_events.ts
/** * @fileoverview Event handler that flushes pending events for the window. * * @license * Copyright 2020 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://...
} }
{ window.removeEventListener('beforeunload', flushEventsDelegate); window.removeEventListener('unload', flushEventsDelegate); }
conditional_block
window_events.ts
/** * @fileoverview Event handler that flushes pending events for the window. * * @license * Copyright 2020 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://...
implements BatchEventFlushingStrategy { startBatching(flushEventsDelegate: () => void): void { if (window) { window.addEventListener('beforeunload', flushEventsDelegate); window.addEventListener('unload', flushEventsDelegate); } } stopBatching(flushEventsDelegate: () => void): void { if ...
WindowsEventsFlushingStrategy
identifier_name
window_events.ts
/** * @fileoverview Event handler that flushes pending events for the window. * * @license * Copyright 2020 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://...
* 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. */ import {BatchEventFlushingStrategy} from './batch_event_flushing_strategy'; /** * Event handler that flushes pending events for the ...
* Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
cEngine.__pluginTemplate__.js
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports...
return __name__; } }); })(cEngine); },{}]},{},[1])
console.log('destroy'); } };
random_line_split
cEngine.__pluginTemplate__.js
(function e(t,n,r){function s(o,u)
var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; /*global cEngine */ /*eslint no-console:0*/ (function (cEngine) { cEngine.extend('__name__', { create: function create(config) { config = config || {}; var ...
{if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}
identifier_body
cEngine.__pluginTemplate__.js
(function e(t,n,r){function
(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="funct...
s
identifier_name
DocCode.tsx
/* MIT License Copyright (c) 2021 Looker Data Sciences, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modi...
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ...
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
random_line_split
process_json.py
# directory = 'Congressional_Bill_Corpus.v1.00/raw/' directory = '' text_file = directory + 'billtext_org.json' labels_file = directory + 'train.json' output_dir = '/Users/katya/datasets/congress_bills_2/' import sys #pcogennen noah's congress_bills_2 into useable format #to dict: def
(line, char_counter, maximum): quote_counter = 0 while quote_counter < maximum: if line[char_counter:char_counter+1] == '\"': quote_counter += 1 char_counter += 1 # print 'to',line[char_counter:char_counter+10] return char_counter def parse_inside...
skip_ahead_n_quotes
identifier_name
process_json.py
# directory = 'Congressional_Bill_Corpus.v1.00/raw/' directory = '' text_file = directory + 'billtext_org.json' labels_file = directory + 'train.json' output_dir = '/Users/katya/datasets/congress_bills_2/' import sys #pcogennen noah's congress_bills_2 into useable format #to dict: def skip_ahead_n_quotes(line, char...
d = {} for line in open(text_file): if "\"\"" in line: d[name] = '' else: # d = json.load(json_data) # print d char_counter = 0 # print "success" name, char_counter = parse_inside_char(line, char_counter, '\t') # print 'parse' if '\"body\"' in li...
list_of_words = [] word = '' for char in line: if char == ' ': list_of_words.append(word) word = '' else: word += char list_of_words.append(word.strip()) return tuple(list_of_words)
identifier_body
process_json.py
# directory = 'Congressional_Bill_Corpus.v1.00/raw/' directory = '' text_file = directory + 'billtext_org.json' labels_file = directory + 'train.json' output_dir = '/Users/katya/datasets/congress_bills_2/' import sys #pcogennen noah's congress_bills_2 into useable format #to dict: def skip_ahead_n_quotes(line, char...
sys.stdout.flush() print 'done'
labels_out.write(label + '\n')
conditional_block
process_json.py
# directory = 'Congressional_Bill_Corpus.v1.00/raw/' directory = '' text_file = directory + 'billtext_org.json' labels_file = directory + 'train.json' output_dir = '/Users/katya/datasets/congress_bills_2/' import sys #pcogennen noah's congress_bills_2 into useable format #to dict: def skip_ahead_n_quotes(line, char...
except KeyError: print example_name else: labels_out.write(label + '\n') sys.stdout.flush() print 'done'
line = line.replace('\t', ' ') example_name, label = tokenize(line) try: data_out.write(d[example_name] + '\n')
random_line_split
video.py
# -*- coding: utf-8 -*- # Copyright(C) 2010 Roger Philibert # # 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, version 3 of the License. # # This program is distributed in the hope that it will...
raise Exception() except Exception: raise SelectElementException('Could not retrieve video duration') video_file_urls = re.findall(r'"(http://media[^ ,]+\.flv)"', data) if len(video_file_urls) == 0: raise SelectElementException('Video URL not found') ...
try: if m: minutes, seconds = (int(v) for v in to_unicode(m.group(1).strip()).split(':')) video.duration = datetime.timedelta(minutes=minutes, seconds=seconds) else:
random_line_split
video.py
# -*- coding: utf-8 -*- # Copyright(C) 2010 Roger Philibert # # 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, version 3 of the License. # # This program is distributed in the hope that it will...
if len(video_file_urls) == 0: raise SelectElementException('Video URL not found') elif len(video_file_urls) > 1: raise SelectElementException('Many video file URL found') else: video.url = video_file_urls[0] return video
def get_video(self, video=None): _id = to_unicode(self.group_dict['id']) if video is None: video = YoujizzVideo(_id) title_el = select(self.document.getroot(), 'title', 1) video.title = to_unicode(title_el.text.strip()) # youjizz HTML is crap, we must parse it with r...
identifier_body
video.py
# -*- coding: utf-8 -*- # Copyright(C) 2010 Roger Philibert # # 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, version 3 of the License. # # This program is distributed in the hope that it will...
title_el = select(self.document.getroot(), 'title', 1) video.title = to_unicode(title_el.text.strip()) # youjizz HTML is crap, we must parse it with regexps data = lxml.html.tostring(self.document.getroot()) m = re.search(r'<strong>.*?Runtime.*?</strong> (.+?)<br.*>', data) ...
video = YoujizzVideo(_id)
conditional_block
video.py
# -*- coding: utf-8 -*- # Copyright(C) 2010 Roger Philibert # # 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, version 3 of the License. # # This program is distributed in the hope that it will...
(self, video=None): _id = to_unicode(self.group_dict['id']) if video is None: video = YoujizzVideo(_id) title_el = select(self.document.getroot(), 'title', 1) video.title = to_unicode(title_el.text.strip()) # youjizz HTML is crap, we must parse it with regexps ...
get_video
identifier_name
NetworkTest.py
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä ...
# # # You should have received a copy of the GNU General Public License # # along with this program; if not, write to the Free Software # # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, # # MA 02110-1301, USA. ...
# but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. #
random_line_split
NetworkTest.py
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä ...
class NetworkTest(unittest.TestCase): def testHandshake(self): s = TestServer() c = TestConnection() c.connect("localhost") c.sendPacket("moikka") Network.communicate(100) client = s.clients.values()[0] assert client.packet == "moikka" assert client.id == 1 def tearDown(self): ...
f createConnection(self, sock): return TestConnection(sock)
identifier_body
NetworkTest.py
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä ...
ittest.main()
conditional_block
NetworkTest.py
##################################################################### # -*- coding: iso-8859-1 -*- # # # # Frets on Fire # # Copyright (C) 2006 Sami Kyöstilä ...
elf): Network.shutdown() if __name__ == "__main__": unittest.main()
arDown(s
identifier_name
cholesky.rs
#[macro_use] extern crate linxal; extern crate ndarray; extern crate num_traits; extern crate rand; use ndarray::{Array, ArrayBase, Data, Ix2}; use rand::thread_rng; use linxal::types::{LinxalScalar, LinxalMatrix, Symmetric, c32, c64}; use linxal::types::error::{ CholeskyError}; use linxal::generate::{RandomSemiPosit...
} fn cholesky_identity_generic<T: LinxalScalar>() { for n in 1..11 { let m: Array<T, Ix2> = Array::eye(n); let l = m.cholesky(Symmetric::Upper).ok().unwrap(); assert_eq_within_tol!(l, m, 1e-5.into()); } } fn cholesky_generate_generic<T: LinxalScalar>(uplo: Symmetric) { let mut r...
{ // Check the dimension assert_eq!(mat.dim(), chol.dim()); // The matrix must be triangular assert!(chol.is_triangular(uplo, None)); // The fatorization must match the original matrix. match uplo { Symmetric::Lower => { let u = chol.conj_t(); assert_eq_within_t...
identifier_body
cholesky.rs
#[macro_use] extern crate linxal; extern crate ndarray; extern crate num_traits; extern crate rand; use ndarray::{Array, ArrayBase, Data, Ix2}; use rand::thread_rng; use linxal::types::{LinxalScalar, LinxalMatrix, Symmetric, c32, c64}; use linxal::types::error::{ CholeskyError}; use linxal::generate::{RandomSemiPosit...
assert_eq_within_tol!(l, m, 1e-5.into()); } } fn cholesky_generate_generic<T: LinxalScalar>(uplo: Symmetric) { let mut rng = thread_rng(); for n in 1..11 { let m: Array<T, Ix2> = RandomSemiPositive::new(n, &mut rng).generate().unwrap(); let res = m.cholesky(uplo); let chol ...
let l = m.cholesky(Symmetric::Upper).ok().unwrap();
random_line_split
cholesky.rs
#[macro_use] extern crate linxal; extern crate ndarray; extern crate num_traits; extern crate rand; use ndarray::{Array, ArrayBase, Data, Ix2}; use rand::thread_rng; use linxal::types::{LinxalScalar, LinxalMatrix, Symmetric, c32, c64}; use linxal::types::error::{ CholeskyError}; use linxal::generate::{RandomSemiPosit...
<T: LinxalScalar>() { for n in 1..11 { let m: Array<T, Ix2> = Array::eye(n); let l = m.cholesky(Symmetric::Upper).ok().unwrap(); assert_eq_within_tol!(l, m, 1e-5.into()); } } fn cholesky_generate_generic<T: LinxalScalar>(uplo: Symmetric) { let mut rng = thread_rng(); for n in 1...
cholesky_identity_generic
identifier_name
cholesky.rs
#[macro_use] extern crate linxal; extern crate ndarray; extern crate num_traits; extern crate rand; use ndarray::{Array, ArrayBase, Data, Ix2}; use rand::thread_rng; use linxal::types::{LinxalScalar, LinxalMatrix, Symmetric, c32, c64}; use linxal::types::error::{ CholeskyError}; use linxal::generate::{RandomSemiPosit...
} } fn cholesky_identity_generic<T: LinxalScalar>() { for n in 1..11 { let m: Array<T, Ix2> = Array::eye(n); let l = m.cholesky(Symmetric::Upper).ok().unwrap(); assert_eq_within_tol!(l, m, 1e-5.into()); } } fn cholesky_generate_generic<T: LinxalScalar>(uplo: Symmetric) { let...
{ let l = chol.conj_t(); println!("{:?} {:?} {:?} {:?}", chol, l, l.dot(chol), mat); assert_eq_within_tol!(l.dot(chol), mat, 1e-4.into()); }
conditional_block
contents.js
standaloneAddContents({ code: "castor_2015", title: "Concours Castor 2015", folder: "2015/", tasks: [ { code: "2015-JP-04-crane-operating", title: "Piloter la grue" }, { code: "2015-CZ-02-relationships", title: "Relations d'âges" }, { code: "2015-FR-02-spreading-secret", tit...
title: "Marquage d'oiseaux" }, { code: "2015-FR-13-open-lock", title: "Code du cadenas" }, { code: "2015-FR-07-placing-arrows", title: "Robot qui tourne" }, { code: "2015-FR-01-copy-pattern", title: "Reproduire un dessin" }, { code: "2015-SI-05-horse-races", ti...
title: "Signaux colorés" }, { code: "2015-FR-03-mark-and-shuffle",
random_line_split
utils.rs
#![allow(dead_code)] use std::{cmp, io}; use bytes::{BufMut, BytesMut}; pub const SIZE: usize = 31; #[derive(Serialize, Deserialize)] pub struct Message { pub message: &'static str, } pub struct Writer<'a>(pub &'a mut BytesMut); impl<'a> io::Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Res...
} b'\'' => { let _ = writer.0.put_slice(b"&#x27;"); } b'/' => { let _ = writer.0.put_slice(b"&#x2f;"); } _ => panic!("incorrect indexing"), } } } if last_po...
{ let bytes = s.as_bytes(); let mut last_pos = 0; for (idx, b) in s.as_bytes().iter().enumerate() { if escapable(*b) { let _ = writer.0.put_slice(&bytes[last_pos..idx]); last_pos = idx + 1; match *b { b'<' => { let _ = writer.0...
identifier_body
utils.rs
#![allow(dead_code)] use std::{cmp, io}; use bytes::{BufMut, BytesMut}; pub const SIZE: usize = 31; #[derive(Serialize, Deserialize)] pub struct Message {
} pub struct Writer<'a>(pub &'a mut BytesMut); impl<'a> io::Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.put_slice(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } pub fn get_query_param(query: &str) -> u16 { ...
pub message: &'static str,
random_line_split
utils.rs
#![allow(dead_code)] use std::{cmp, io}; use bytes::{BufMut, BytesMut}; pub const SIZE: usize = 31; #[derive(Serialize, Deserialize)] pub struct Message { pub message: &'static str, } pub struct Writer<'a>(pub &'a mut BytesMut); impl<'a> io::Write for Writer<'a> { fn write(&mut self, buf: &[u8]) -> io::Res...
b'&' => { let _ = writer.0.put_slice(b"&amp;"); } b'"' => { let _ = writer.0.put_slice(b"&quot;"); } b'\'' => { let _ = writer.0.put_slice(b"&#x27;"); } ...
{ let _ = writer.0.put_slice(b"&gt;"); }
conditional_block
utils.rs
#![allow(dead_code)] use std::{cmp, io}; use bytes::{BufMut, BytesMut}; pub const SIZE: usize = 31; #[derive(Serialize, Deserialize)] pub struct Message { pub message: &'static str, } pub struct Writer<'a>(pub &'a mut BytesMut); impl<'a> io::Write for Writer<'a> { fn
(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.put_slice(buf); Ok(buf.len()) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } pub fn get_query_param(query: &str) -> u16 { let q = if let Some(pos) = query.find("q") { query.split_at(pos + 2).1.parse::<u16>().ok(...
write
identifier_name
is_eq.rs
// Compares two token tree lists. Expands to the token tree list inside the first block if the // lists are equivalent, and the second if they are not. Expensive - generates a new macro for // every invocation! This macro is only valid in item position, due to its use of macro_rules. macro_rules! is_eq { ( ...
() { eq_test_1(); eq_test_2(); }
main
identifier_name
is_eq.rs
// Compares two token tree lists. Expands to the token tree list inside the first block if the // lists are equivalent, and the second if they are not. Expensive - generates a new macro for // every invocation! This macro is only valid in item position, due to its use of macro_rules. macro_rules! is_eq { ( ...
{ eq_test_1(); eq_test_2(); }
identifier_body
is_eq.rs
// Compares two token tree lists. Expands to the token tree list inside the first block if the // lists are equivalent, and the second if they are not. Expensive - generates a new macro for // every invocation! This macro is only valid in item position, due to its use of macro_rules. macro_rules! is_eq { ( ...
is_eq_test!($($thingA)*, $($thingB)*); ); } is_eq! { if (a bunch of tokens!) == (another bunch of tokens!) { fn eq_test_1() { println!("They're equal!"); } } else { fn eq_test_1() { println!("As expected, they're not equal."); } } } is_eq! { if (a pile of equivalent tokens...
}
random_line_split
exhaustive_ascii_chars.rs
use malachite_base::chars::exhaustive::exhaustive_ascii_chars; #[test] fn
() { assert_eq!( exhaustive_ascii_chars().collect::<String>(), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !\"#$%&\'()*+,-./:;<=>?@[\\\ ]^_`{|}~\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\ \u{12}\u{13}\u{14}\u{15}\u{16}\u{17...
test_exhaustive_ascii_chars
identifier_name
exhaustive_ascii_chars.rs
use malachite_base::chars::exhaustive::exhaustive_ascii_chars; #[test] fn test_exhaustive_ascii_chars() { assert_eq!( exhaustive_ascii_chars().collect::<String>(), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !\"#$%&\'()*+,-./:;<=>?@[\\\ ]^_`{|}~\u{0}\u{1}\u{2}\u{3}\u{4}\...
assert_eq!(exhaustive_ascii_chars().count(), 1 << 7); }
random_line_split
exhaustive_ascii_chars.rs
use malachite_base::chars::exhaustive::exhaustive_ascii_chars; #[test] fn test_exhaustive_ascii_chars()
{ assert_eq!( exhaustive_ascii_chars().collect::<String>(), "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 !\"#$%&\'()*+,-./:;<=>?@[\\\ ]^_`{|}~\u{0}\u{1}\u{2}\u{3}\u{4}\u{5}\u{6}\u{7}\u{8}\t\n\u{b}\u{c}\r\u{e}\u{f}\u{10}\u{11}\ \u{12}\u{13}\u{14}\u{15}\u{16}\u{17}\u...
identifier_body
p037.py
#! /usr/bin/python3 # The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. # Find the sum of the only eleven primes that are...
if len(truncatables) > 11 + 3: break print(sum(prime for prime in truncatables if prime > 9))
truncatables.append(prime)
conditional_block
p037.py
#! /usr/bin/python3 # The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3. # Find the sum of the only eleven primes that are...
print(sum(prime for prime in truncatables if prime > 9))
random_line_split
cornetto-add-counts.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ add word counts to Cornetto lexical units database file The word count file should have three columns, delimited by white space, containing (1) the count, (2) the lemma, (3) the main POS tag. The tagset is assumed to be the Spoken Dutch Corpus tagset, and the characte...
elif tag in ("ADJ", "BW"): cat = "adj" else: # LET LID TSW VG VZ cat = "other" # Cornetto word forms are stored in unicode form = form.decode("iso-8859-1") count = int(count) if form not in counts: cou...
cat = "verb"
conditional_block
cornetto-add-counts.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ add word counts to Cornetto lexical units database file The word count file should have three columns, delimited by white space, containing (1) the count, (2) the lemma, (3) the main POS tag. The tagset is assumed to be the Spoken Dutch Corpus tagset, and the characte...
(counts, totals, cdb_lu_file): parser = iterparse(cdb_lu_file) for event, elem in parser: if elem.tag == "form": # following the ElementTree conventions, # word form will be ascii or unicode form = elem.get("form-spelling") # lower case because Corne...
add_count_attrib
identifier_name
cornetto-add-counts.py
#!/usr/bin/env python # -*- coding: utf-8 -*-
containing (1) the count, (2) the lemma, (3) the main POS tag. The tagset is assumed to be the Spoken Dutch Corpus tagset, and the character encoding must be ISO-8859-1. The counts appear as the value of the feature "count" on <form> elements. The updated lexical units xml database is written to standard output. Sinc...
""" add word counts to Cornetto lexical units database file The word count file should have three columns, delimited by white space,
random_line_split
cornetto-add-counts.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ add word counts to Cornetto lexical units database file The word count file should have three columns, delimited by white space, containing (1) the count, (2) the lemma, (3) the main POS tag. The tagset is assumed to be the Spoken Dutch Corpus tagset, and the characte...
else: # LET LID TSW VG VZ cat = "other" # Cornetto word forms are stored in unicode form = form.decode("iso-8859-1") count = int(count) if form not in counts: counts[form] = dict(noun=0, verb=0, adj=0, other=0) ...
if not hasattr(file, "read"): file = open(file) counts = {} totals = dict(noun=0, verb=0, adj=0, other=0) for l in file: try: count, form, tag = l.strip().split() except ValueError: stderr.write("Warning; ill-formed line: %s\n" % repr(l)) ...
identifier_body
tests.rs
#[test] fn get_index() { let _ = pretty_env_logger::try_init(); let res = warp::test::request() .reply(&crate::index()); assert_eq!(res.status(), 200); assert_eq!(res.headers()["content-type"], "text/html; charset=utf-8"); } #[test] fn get_badge() { let _ = pretty_env_logger::try_init(); ...
.expect("filter no query"); assert_eq!(style, None); }
random_line_split
tests.rs
#[test] fn get_index() { let _ = pretty_env_logger::try_init(); let res = warp::test::request() .reply(&crate::index()); assert_eq!(res.status(), 200); assert_eq!(res.headers()["content-type"], "text/html; charset=utf-8"); } #[test] fn get_badge() { let _ = pretty_env_logger::try_init(); ...
() { let _ = pretty_env_logger::try_init(); let style = warp::test::request() .path("/warp?style=flat-square") .filter(&crate::style()) .expect("filter flat-square"); assert_eq!(style, Some(crate::Style::FlatSquare)); let style = warp::test::request() .path("/warp?styl...
badge_style
identifier_name
tests.rs
#[test] fn get_index() { let _ = pretty_env_logger::try_init(); let res = warp::test::request() .reply(&crate::index()); assert_eq!(res.status(), 200); assert_eq!(res.headers()["content-type"], "text/html; charset=utf-8"); } #[test] fn get_badge()
#[test] fn get_badge_404() { let _ = pretty_env_logger::try_init(); let res = warp::test::request() .path("/this-crate-should-never-exist-amirite") .reply(&crate::badge()); assert_eq!(res.status(), 404); } #[test] fn badge_style() { let _ = pretty_env_logger::try_init(); let st...
{ let _ = pretty_env_logger::try_init(); let res = warp::test::request() .path("/warp") .reply(&crate::badge()); assert_eq!(res.status(), 302); assert_eq!(res.headers()["expires"], "Sun, 01 Jan 1990 00:00:00 GMT"); assert_eq!(res.headers()["pragma"], "no-cache"); assert_eq!( ...
identifier_body
instr_cmpss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn cmpss_1() { run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM0...
fn cmpss_2() { run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM7)), operand2: Some(IndirectDisplaced(ECX, 712415121, Some(OperandSize::Dword), None)), operand3: Some(Literal8(19)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None...
} #[test]
random_line_split
instr_cmpss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn
() { run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM0)), operand2: Some(Direct(XMM4)), operand3: Some(Literal8(94)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 15, 194, 196, 94], OperandSize::Dword) } #[test] fn...
cmpss_1
identifier_name
instr_cmpss.rs
use ::{BroadcastMode, Instruction, MaskReg, MergeMode, Mnemonic, OperandSize, Reg, RoundingMode}; use ::RegType::*; use ::instruction_def::*; use ::Operand::*; use ::Reg::*; use ::RegScale::*; use ::test::run_test; #[test] fn cmpss_1() { run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM0...
{ run_test(&Instruction { mnemonic: Mnemonic::CMPSS, operand1: Some(Direct(XMM7)), operand2: Some(IndirectDisplaced(RAX, 1640090676, Some(OperandSize::Dword), None)), operand3: Some(Literal8(26)), operand4: None, lock: false, rounding_mode: None, merge_mode: None, sae: false, mask: None, broadcast: None }, &[243, 1...
identifier_body
sinf64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::sinf64; use core::num::Float; use core::f64; use core::f64::consts::PI; // pub fn sinf64(x: f64) -> f64; #[test] fn sinf64_test1() { let x: f64 = f64::nan(); let result: f6...
() { let x: f64 = 90.0 * PI / 180.0; let result: f64 = unsafe { sinf64(x) }; assert_eq!(result, 1.0); } }
sinf64_test6
identifier_name
sinf64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::sinf64; use core::num::Float; use core::f64; use core::f64::consts::PI; // pub fn sinf64(x: f64) -> f64; #[test] fn sinf64_test1() { let x: f64 = f64::nan(); let result: f6...
#[test] fn sinf64_test5() { let x: f64 = 45.0 * PI / 180.0; let result: f64 = unsafe { sinf64(x) }; assert_eq!(result, 0.7071067811865475); } #[test] fn sinf64_test6() { let x: f64 = 90.0 * PI / 180.0; let result: f64 = unsafe { sinf64(x) }; assert_eq!(result, 1.0); } }
{ let x: f64 = 0.0 * PI / 180.0; let result: f64 = unsafe { sinf64(x) }; assert_eq!(result, 0.0); }
identifier_body
sinf64.rs
#![feature(core, core_intrinsics, core_float)] extern crate core; #[cfg(test)] mod tests { use core::intrinsics::sinf64; use core::num::Float; use core::f64; use core::f64::consts::PI; // pub fn sinf64(x: f64) -> f64; #[test] fn sinf64_test1() { let x: f64 = f64::nan(); let result: f6...
} }
assert_eq!(result, 1.0);
random_line_split
Utils.ts
import fs = require('fs'); import path = require('path'); import structure = require('./project/Structure'); export function camelCaseTagName(tagName:string):string { if (tagName.indexOf('-') < 0) { return camelCase(tagName); } return tagName.replace(/\-(\w)/g, function (match, letter) { return letter.to...
return props; } /** * Split attributes definition string by object for jasper client library usage * @param attrs string that represents attributes * @returns {name: '', type: ''} collection of attributes */ export function getJasperAttributes(attrs) { if (typeof (attrs) === 'string') {...
{ return props.split(' ').map(function (item) { var i = item.trim(); return i ? i : null; }).filter(function (i) { return i; }); }
conditional_block
Utils.ts
import fs = require('fs'); import path = require('path'); import structure = require('./project/Structure'); export function camelCaseTagName(tagName:string):string { if (tagName.indexOf('-') < 0) { return camelCase(tagName); } return tagName.replace(/\-(\w)/g, function (match, letter) { return letter.to...
(arr:any) { if (Array.isArray) { return Array.isArray(arr); } else { return arr instanceof Array; } } export function escapeContent(content) { var quotRegexp = /\'/g; var breaklineRegexp = /(?:\r\n|\r|\n)/g; var first = content.replace(/\\/g, '\\\\').replace(quotRegexp, '\\\'').replace(breaklineReg...
isArray
identifier_name
Utils.ts
import fs = require('fs'); import path = require('path'); import structure = require('./project/Structure'); export function camelCaseTagName(tagName:string):string { if (tagName.indexOf('-') < 0) { return camelCase(tagName); } return tagName.replace(/\-(\w)/g, function (match, letter) { return letter.to...
}); } /** * C:\folder\file.exe --> folder */ export function getParentFolderName(filepath:string):string { var path = this.convertPathClient(getPath(filepath)); return path.match(/([^\/]*)\/*$/)[1]; } /** * C:\folder\file.exe --> C:\folder\ */ export function getPath(filepath:string):string { return pat...
random_line_split
Utils.ts
import fs = require('fs'); import path = require('path'); import structure = require('./project/Structure'); export function camelCaseTagName(tagName:string):string { if (tagName.indexOf('-') < 0) { return camelCase(tagName); } return tagName.replace(/\-(\w)/g, function (match, letter) { return letter.to...
/** * Split attributes definition string by object for jasper client library usage * @param attrs string that represents attributes * @returns {name: '', type: ''} collection of attributes */ export function getJasperAttributes(attrs) { if (typeof (attrs) === 'string') { var resultAtt...
{ if (typeof (props) === 'string') { return props.split(' ').map(function (item) { var i = item.trim(); return i ? i : null; }).filter(function (i) { return i; }); } return props; }
identifier_body
setup.py
#!/usr/bin/env python import os from setuptools import setup from distutils.cmd import Command import django_auth_iam def read(*rnames):
setup( name='django-auth-iam', version=django_auth_iam.__version__, description='Django authentication backend using Amazon IAM', long_description=read('README.rst'), url='https://github.com/viewworld/django-auth-iam/', author='Michael Budde', author_email='mb@viewworld.dk', license='G...
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
identifier_body
setup.py
#!/usr/bin/env python
from setuptools import setup from distutils.cmd import Command import django_auth_iam def read(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup( name='django-auth-iam', version=django_auth_iam.__version__, description='Django authentication backend using Amazon IA...
import os
random_line_split
setup.py
#!/usr/bin/env python import os from setuptools import setup from distutils.cmd import Command import django_auth_iam def
(*rnames): return open(os.path.join(os.path.dirname(__file__), *rnames)).read() setup( name='django-auth-iam', version=django_auth_iam.__version__, description='Django authentication backend using Amazon IAM', long_description=read('README.rst'), url='https://github.com/viewworld/django-auth-ia...
read
identifier_name
index.js
var ConfigManager = require('./components/config_manager'); var RenderEngine = require('./components/render_engine'); var OrientationManager = require('./components/orientation_manager'); var Network = require('./components/network'); var LocalStream = require('./components/local_stream'); var DepthRender = require('./...
new DepthRender(ls, REDUCE, re, om.obtain(ls), 0); new ForwardStream(ls, n, SKIP); var l = new Logger(n, re, cm); n.on('found', function(node){ node.render = new DepthRender(new RemoteStream(node), REDUCE, re, om.obtain(node), RenderEngine.SENSOR_DISTANCE); }); n.on('lost', function(node){ node.render.stop(); ...
random_line_split
scrollgroup.directive.ts
import { Directive, ElementRef, HostListener, Input, OnDestroy } from '@angular/core'; import * as $ from 'jquery'; const GROUPS = new Map<string, JQuery[]>();
@Directive({ selector: '[appScrollGroup]', }) export class ScrollGroupDirective implements OnDestroy { @Input() scrollGroup: string; private readonly element: JQuery; constructor(elementRef: ElementRef) { this.element = $(elementRef.nativeElement); GROUPS.set(this.scrollGroup, GROUPS.get(this.scrollGr...
random_line_split
scrollgroup.directive.ts
import { Directive, ElementRef, HostListener, Input, OnDestroy } from '@angular/core'; import * as $ from 'jquery'; const GROUPS = new Map<string, JQuery[]>(); @Directive({ selector: '[appScrollGroup]', }) export class ScrollGroupDirective implements OnDestroy { @Input() scrollGroup: string; private readonly e...
}
{ const scrollTop = this.element.scrollTop(); GROUPS.get(this.scrollGroup).forEach(e => { if (this.element !== e) { e.scrollTop(scrollTop); } }); }
identifier_body
scrollgroup.directive.ts
import { Directive, ElementRef, HostListener, Input, OnDestroy } from '@angular/core'; import * as $ from 'jquery'; const GROUPS = new Map<string, JQuery[]>(); @Directive({ selector: '[appScrollGroup]', }) export class ScrollGroupDirective implements OnDestroy { @Input() scrollGroup: string; private readonly e...
}); } }
{ e.scrollTop(scrollTop); }
conditional_block
scrollgroup.directive.ts
import { Directive, ElementRef, HostListener, Input, OnDestroy } from '@angular/core'; import * as $ from 'jquery'; const GROUPS = new Map<string, JQuery[]>(); @Directive({ selector: '[appScrollGroup]', }) export class ScrollGroupDirective implements OnDestroy { @Input() scrollGroup: string; private readonly e...
() { GROUPS.get(this.scrollGroup).splice(GROUPS.get(this.scrollGroup).indexOf(this.element), 1); } @HostListener('scroll', ['$event']) onScrollEvent(event: MouseEvent) { const scrollTop = this.element.scrollTop(); GROUPS.get(this.scrollGroup).forEach(e => { if (this.element !== e) { e.s...
ngOnDestroy
identifier_name
npo.py
import logging import json import os import re #from pprint import pprint #from itertools import count from urlparse import urljoin from lxml import html from thready import threaded import requests from scrapekit.util import collapse_whitespace from connectedafrica.scrapers.util import MultiCSV from connectedafrica....
elif 'Contact' in addr_type: data['contact_name'] = collapse_whitespace(addr.find('./p').text) for li in addr.findall('.//li'): contact = collapse_whitespace(li.xpath('string()')) contact_type = { 'phone': 'phone', ...
data['postal_address'] = addrs
conditional_block
npo.py
import logging import json import os import re #from pprint import pprint
from urlparse import urljoin from lxml import html from thready import threaded import requests from scrapekit.util import collapse_whitespace from connectedafrica.scrapers.util import MultiCSV from connectedafrica.scrapers.util import make_path log = logging.getLogger('npo') URL_PATTERN = "http://www.npo.gov.za/Pu...
#from itertools import count
random_line_split
npo.py
import logging import json import os import re #from pprint import pprint #from itertools import count from urlparse import urljoin from lxml import html from thready import threaded import requests from scrapekit.util import collapse_whitespace from connectedafrica.scrapers.util import MultiCSV from connectedafrica....
def make_urls(): for i in xrange(1, 16000000): yield i def scrape_npo(csv, i): url = URL_PATTERN % i cache_path = make_cache(i) if not os.path.exists(cache_path): res = requests.get(url) page = { 'url': url, 'http_status': res.status_code, ...
return make_path('.cache/npo/%s/%s/%s/%s/%s.json' % ( i % 10, i % 100, i % 1000, i % 10000, i))
identifier_body
npo.py
import logging import json import os import re #from pprint import pprint #from itertools import count from urlparse import urljoin from lxml import html from thready import threaded import requests from scrapekit.util import collapse_whitespace from connectedafrica.scrapers.util import MultiCSV from connectedafrica....
(i): return make_path('.cache/npo/%s/%s/%s/%s/%s.json' % ( i % 10, i % 100, i % 1000, i % 10000, i)) def make_urls(): for i in xrange(1, 16000000): yield i def scrape_npo(csv, i): url = URL_PATTERN % i cache_path = make_cache(i) if not os.path.exists(cache_path): res = re...
make_cache
identifier_name
autocast_variable.py
return (g._auto_cast_variable_read_dtype is not None and self.true_dtype != g._auto_cast_variable_read_dtype) # pylint:enable=protected-access @property def dtype(self): """The dtype this variable will be casted to when read.""" if self._should_cast(): return ops.get_default_graph()....
# private attributes is hacky and difficult to maintain. @property def _handle_name(self): return self._variable._handle_name # pylint: disable=protected-access
random_line_split
autocast_variable.py
.dtype) def _should_act_as_resource_variable(self): """Pass resource_variable_ops.is_resource_variable check.""" pass def __repr__(self): if context.executing_eagerly() and not self._in_graph_mode: repr_str = ("<AutoCastVariable '{v.name}' shape={v.shape} " 'dtype={v.dtype.name...
return self.read_value() > o
identifier_body
autocast_variable.py
return _maybe_wrap(var) def scatter_update(self, sparse_delta, use_locking=False, name=None): var = self._variable.scatter_update(sparse_delta, use_locking, name) return _maybe_wrap(var) def batch_scatter_update(self, sparse_delta, use_locking=False, name=None): var = self._variable.batch_scatter_...
return create_autocast_variable(variable)
conditional_block
autocast_variable.py
'of type {!r}'.format(dtype.name, self.dtype.name)) val = ops.convert_to_tensor( self._variable, self._variable.dtype, name, as_ref=False) return math_ops.cast(val, self.dtype) def _should_act_as_resource_variable(self): """Pass resource_variable_ops.is_resource_variable check.""" p...
__lt__
identifier_name
mrp_create_prod.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Pexego All Rights Reserved # $Jesús Ventosinos Mayor <jesus@pexego.es>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affer...
if prod_created: raise exceptions.except_orm(_('Product error'), _('The mounted product alredery exists')) self.env['product.product'].create_mounted_product( self.mount_product, self.mounted_product) if self.mounted_product not in ...
self.mounted_product.default_code)])
random_line_split
mrp_create_prod.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Pexego All Rights Reserved # $Jesús Ventosinos Mayor <jesus@pexego.es>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affer...
return True
elf.mount_product.can_mount_ids = [(4, self.mounted_product.id)]
conditional_block
mrp_create_prod.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Pexego All Rights Reserved # $Jesús Ventosinos Mayor <jesus@pexego.es>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affer...
self): if not self.mount_product.default_code or not \ self.mounted_product.default_code: raise exceptions.except_orm(_('Code error'), _('One of the products not have ref.')) prod_created = self.env['product.product'].search( ...
reate_product(
identifier_name
mrp_create_prod.py
# -*- coding: utf-8 -*- ############################################################################## # # Copyright (C) 2014 Pexego All Rights Reserved # $Jesús Ventosinos Mayor <jesus@pexego.es>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affer...
self.env['product.product'].create_mounted_product( self.mount_product, self.mounted_product) if self.mounted_product not in self.mount_product: self.mount_product.can_mount_ids = [(4, self.mounted_product.id)] return True
name = "mrp.mounted.product.create.wizard" mount_product = fields.Many2one('product.product', 'Mount product', required=True) mounted_product = fields.Many2one('product.product', 'mounted product', required=True) @api.multi def ...
identifier_body
focusevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::FocusEventBinding; use dom::bindings::codegen::Bindings::FocusEventBinding::...
else { EventBubbles::DoesNotBubble }; let cancelable = if init.parent.parent.cancelable { EventCancelable::Cancelable } else { EventCancelable::NotCancelable }; let event = FocusEvent::new(global.as_window(), type_, ...
{ EventBubbles::Bubbles }
conditional_block
focusevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::FocusEventBinding; use dom::bindings::codegen::Bindings::FocusEventBinding::...
() -> FocusEvent { FocusEvent { uievent: UIEvent::new_inherited(), related_target: Default::default(), } } pub fn new(window: &Window, type_: DOMString, can_bubble: EventBubbles, cancelable: EventCancelable, vie...
new_inherited
identifier_name
focusevent.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::FocusEventBinding;
use dom::bindings::error::Fallible; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, MutNullableHeap, Root, RootedReference}; use dom::bindings::reflector::reflect_dom_object; use dom::event::{EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; u...
use dom::bindings::codegen::Bindings::FocusEventBinding::FocusEventMethods; use dom::bindings::codegen::Bindings::UIEventBinding::UIEventMethods;
random_line_split