file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
test_storage.py
from nose.plugins.skip import SkipTest from oyster.conf import settings from oyster.core import Kernel from oyster.storage.gridfs import GridFSStorage from oyster.storage.dummy import DummyStorage def _simple_storage_test(StorageCls): kernel = Kernel(mongo_db='oyster_test') kernel.doc_classes['default'] = {}...
_simple_storage_test(DummyStorage)
identifier_body
index.js
import { Feature } from 'core/feature'; import * as toolkitHelper from 'helpers/toolkit'; export class
extends Feature { constructor() { super(); } shouldInvoke() { return toolkitHelper.getCurrentRouteName().indexOf('budget') !== -1; } invoke() { $('.budget-table-row.is-sub-category').each((index, element) => { const emberId = element.id; const viewData = toolkitHelper.getEmberView(e...
TargetBalanceWarning
identifier_name
index.js
import { Feature } from 'core/feature'; import * as toolkitHelper from 'helpers/toolkit'; export class TargetBalanceWarning extends Feature { constructor() { super(); } shouldInvoke() { return toolkitHelper.getCurrentRouteName().indexOf('budget') !== -1; } invoke() { $('.budget-table-row.is-sub...
currencyElement.addClass('cautious'); } } }); } observe(changedNodes) { if (!this.shouldInvoke()) return; if (changedNodes.has('budget-table-cell-available-div user-data')) { this.invoke(); } } onRouteChanged() { if (!this.shouldInvoke()) return; this.in...
random_line_split
index.js
import { Feature } from 'core/feature'; import * as toolkitHelper from 'helpers/toolkit'; export class TargetBalanceWarning extends Feature { constructor() { super(); } shouldInvoke() { return toolkitHelper.getCurrentRouteName().indexOf('budget') !== -1; } invoke() { $('.budget-table-row.is-sub...
}
{ if (!this.shouldInvoke()) return; this.invoke(); }
identifier_body
comments.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
curr_line.push(rdr.curr.unwrap()); if rdr.curr_is('/') && rdr.nextch_is('*') { rdr.bump(); rdr.bump(); curr_line.push('*'); level += 1; } else { if rdr.curr_is('*') && rdr....
curr_line, col); curr_line = String::new(); rdr.bump(); } else {
random_line_split
comments.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
while i < j && lines[i].trim().is_empty() { i += 1; } // like the first, a last line of all stars should be omitted if j > i && lines[j - 1] .chars() .skip(1) .all(|c| c == '*') { j -= 1; ...
{ i += 1; }
conditional_block
comments.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
fn read_shebang_comment(rdr: &mut StringReader, code_to_the_left: bool, comments: &mut Vec<Comment>) { debug!(">>> shebang comment"); let p = rdr.last_pos; debug!("<<< shebang comment"); comments.push(Comment { style: if code_to_the_left { Trailing } else { Isolated },...
{ while is_whitespace(rdr.curr) && !rdr.is_eof() { if rdr.col == CharPos(0) && rdr.curr_is('\n') { push_blank_line_comment(rdr, &mut *comments); } rdr.bump(); } }
identifier_body
comments.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let comment = "/**\n let a: *i32;\n *a = 5;\n*/"; let stripped = strip_doc_comment_decoration(comment); assert_eq!(stripped, " let a: *i32;\n *a = 5;"); } #[test] fn test_block_doc_comment_4() { let comment = "/*******************\n test\n *********************/"; l...
test_block_doc_comment_3
identifier_name
_cpserver.py
"""Manage HTTP servers with CherryPy.""" import warnings import cherrypy from cherrypy.lib import attributes from cherrypy._cpcompat import basestring # We import * because we want to export check_port # et al as attributes of this module. from cherrypy.process.servers import * class Server(ServerAdapter): """...
"""The filename of the SSL certificate to use.""" ssl_certificate_chain = None """When using PyOpenSSL, the certificate chain to pass to Context.load_verify_locations.""" ssl_private_key = None """The filename of the private key to use with SSL.""" ssl_module = 'pyopenssl' ...
random_line_split
_cpserver.py
"""Manage HTTP servers with CherryPy.""" import warnings import cherrypy from cherrypy.lib import attributes from cherrypy._cpcompat import basestring # We import * because we want to export check_port # et al as attributes of this module. from cherrypy.process.servers import * class Server(ServerAdapter): """...
elif isinstance(value, basestring): self.socket_file = value self.socket_host = None self.socket_port = None else: try: self.socket_host, self.socket_port = value self.socket_file = None except ValueError: ...
self.socket_file = None self.socket_host = None self.socket_port = None
conditional_block
_cpserver.py
"""Manage HTTP servers with CherryPy.""" import warnings import cherrypy from cherrypy.lib import attributes from cherrypy._cpcompat import basestring # We import * because we want to export check_port # et al as attributes of this module. from cherrypy.process.servers import * class Server(ServerAdapter): """...
(self): if self.socket_file: return self.socket_file if self.socket_host is None and self.socket_port is None: return None return (self.socket_host, self.socket_port) def _set_bind_addr(self, value): if value is None: self.socket_file = None ...
_get_bind_addr
identifier_name
_cpserver.py
"""Manage HTTP servers with CherryPy.""" import warnings import cherrypy from cherrypy.lib import attributes from cherrypy._cpcompat import basestring # We import * because we want to export check_port # et al as attributes of this module. from cherrypy.process.servers import * class Server(ServerAdapter): """...
def _set_bind_addr(self, value): if value is None: self.socket_file = None self.socket_host = None self.socket_port = None elif isinstance(value, basestring): self.socket_file = value self.socket_host = None self.socket_port = ...
if self.socket_file: return self.socket_file if self.socket_host is None and self.socket_port is None: return None return (self.socket_host, self.socket_port)
identifier_body
q_sigma.rs
use crate::{ domains::Transition, fa::StateActionUpdate, policies::EnumerablePolicy, utils::argmaxima, Enumerable, Function, Handler, Parameterised, }; use rand::thread_rng; use std::{collections::VecDeque, ops::Index}; struct BackupEntry<S> { pub s: S, pub a: usize, pub q:...
pub fn push(&mut self, entry: BackupEntry<S>) { self.entries.push_back(entry); } pub fn clear(&mut self) { self.entries.clear(); } pub fn propagate(&self, gamma: f64) -> (f64, f64) { let mut g = self.entries[0].q; let mut z = 1.0; let mut isr = 1.0; for k in 0..self.n_ste...
pub fn len(&self) -> usize { self.entries.len() } pub fn pop(&mut self) -> Option<BackupEntry<S>> { self.entries.pop_front() }
random_line_split
q_sigma.rs
use crate::{ domains::Transition, fa::StateActionUpdate, policies::EnumerablePolicy, utils::argmaxima, Enumerable, Function, Handler, Parameterised, }; use rand::thread_rng; use std::{collections::VecDeque, ops::Index}; struct BackupEntry<S> { pub s: S, pub a: usize, pub q:...
; let mu = self.policy.evaluate((ns, na)); let residual = t.reward + self.gamma * (self.sigma * nqsna + (1.0 - self.sigma) * exp_nqs) - qa; self.update_backup(BackupEntry { s: s.clone(), a: t.action, q: qa, ...
{ 0.0 }
conditional_block
q_sigma.rs
use crate::{ domains::Transition, fa::StateActionUpdate, policies::EnumerablePolicy, utils::argmaxima, Enumerable, Function, Handler, Parameterised, }; use rand::thread_rng; use std::{collections::VecDeque, ops::Index}; struct
<S> { pub s: S, pub a: usize, pub q: f64, pub residual: f64, pub sigma: f64, pub pi: f64, pub mu: f64, } struct Backup<S> { n_steps: usize, entries: VecDeque<BackupEntry<S>>, } impl<S> Backup<S> { pub fn new(n_steps: usize) -> Backup<S> { Backup { n_steps,...
BackupEntry
identifier_name
q_sigma.rs
use crate::{ domains::Transition, fa::StateActionUpdate, policies::EnumerablePolicy, utils::argmaxima, Enumerable, Function, Handler, Parameterised, }; use rand::thread_rng; use std::{collections::VecDeque, ops::Index}; struct BackupEntry<S> { pub s: S, pub a: usize, pub q:...
pub fn clear(&mut self) { self.entries.clear(); } pub fn propagate(&self, gamma: f64) -> (f64, f64) { let mut g = self.entries[0].q; let mut z = 1.0; let mut isr = 1.0; for k in 0..self.n_steps { let b1 = &self.entries[k]; let b2 = &self.entries[k + 1]...
{ self.entries.push_back(entry); }
identifier_body
boto_sqs.py
# -*- coding: utf-8 -*- ''' Connection module for Amazon SQS .. versionadded:: 2014.7.0 :configuration: This module accepts explicit sqs credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no furthe...
ret = False if isinstance(attributes, string_types): attributes = json.loads(attributes) for attr, val in six.iteritems(attributes): attr_set = queue_obj.set_attribute(attr, val) if not attr_set: msg = 'Failed to set attribute {0} = {1} on queue {2}' log.e...
log.error('Queue {0} does not exist.'.format(name))
random_line_split
boto_sqs.py
# -*- coding: utf-8 -*- ''' Connection module for Amazon SQS .. versionadded:: 2014.7.0 :configuration: This module accepts explicit sqs credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no furthe...
(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if a queue exists. CLI example:: salt myminion boto_sqs.exists myqueue region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if conn.get_queue(name): return True ...
exists
identifier_name
boto_sqs.py
# -*- coding: utf-8 -*- ''' Connection module for Amazon SQS .. versionadded:: 2014.7.0 :configuration: This module accepts explicit sqs credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no furthe...
def delete(name, region=None, key=None, keyid=None, profile=None): ''' Delete an SQS queue. CLI example to delete a queue:: salt myminion boto_sqs.delete myqueue region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) queue_obj = conn.get_queue(n...
''' Create an SQS queue. CLI example to create a queue:: salt myminion boto_sqs.create myqueue region=us-east-1 ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) if not conn.get_queue(name): try: conn.create_queue(name) except boto.exce...
identifier_body
boto_sqs.py
# -*- coding: utf-8 -*- ''' Connection module for Amazon SQS .. versionadded:: 2014.7.0 :configuration: This module accepts explicit sqs credentials but can also utilize IAM roles assigned to the instance through Instance Profiles. Dynamic credentials are then automatically obtained from AWS API and no furthe...
return True def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Check to see if attributes are set on an SQS queue. CLI example:: salt myminion boto_sqs.get_attributes myqueue ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) i...
msg = 'Failed to delete queue {0}'.format(name) log.error(msg) return False
conditional_block
__init__.py
# -*- coding: utf-8 -*- from thumbnails.conf import settings from thumbnails.engines import DummyEngine from thumbnails.helpers import get_engine, generate_filename, get_cache_backend from thumbnails.images import SourceFile, Thumbnail __version__ = '0.5.1' def
(original, size, **options): """ Creates or gets an already created thumbnail for the given image with the given size and options. :param original: File-path, url or base64-encoded string of the image that you want an thumbnail. :param size: String with the wanted thumbnail siz...
get_thumbnail
identifier_name
__init__.py
# -*- coding: utf-8 -*- from thumbnails.conf import settings from thumbnails.engines import DummyEngine from thumbnails.helpers import get_engine, generate_filename, get_cache_backend from thumbnails.images import SourceFile, Thumbnail __version__ = '0.5.1' def get_thumbnail(original, size, **options):
""" Creates or gets an already created thumbnail for the given image with the given size and options. :param original: File-path, url or base64-encoded string of the image that you want an thumbnail. :param size: String with the wanted thumbnail size. On the form: ``200x200``, ``20...
identifier_body
__init__.py
# -*- coding: utf-8 -*- from thumbnails.conf import settings from thumbnails.engines import DummyEngine from thumbnails.helpers import get_engine, generate_filename, get_cache_backend from thumbnails.images import SourceFile, Thumbnail
def get_thumbnail(original, size, **options): """ Creates or gets an already created thumbnail for the given image with the given size and options. :param original: File-path, url or base64-encoded string of the image that you want an thumbnail. :param size: String with the wa...
__version__ = '0.5.1'
random_line_split
__init__.py
# -*- coding: utf-8 -*- from thumbnails.conf import settings from thumbnails.engines import DummyEngine from thumbnails.helpers import get_engine, generate_filename, get_cache_backend from thumbnails.images import SourceFile, Thumbnail __version__ = '0.5.1' def get_thumbnail(original, size, **options): """ ...
cache.set(thumbnail) return thumbnail
resolution_size = engine.calculate_alternative_resolution_size(resolution, size) image = engine.get_thumbnail(original, resolution_size, crop, options) thumbnail.save_alternative_resolution(resolution, image, options)
conditional_block
test_user.py
"""Users tests.""" from django.contrib.auth import get_user_model, authenticate from django.test import TestCase from django.test import RequestFactory from tests.utils import ModelTestCase from users.factory import UserFactory User = get_user_model() class EmailAuthenticationTest(TestCase): """Tests to make s...
(self): self.create_user() logged_in = self.client.login(**self.creds) self.assertTrue(logged_in) def test_authenticate_with_username_fails(self): self.creds['username'] = 'johndoe' self.create_user() self.creds.pop('email') logged_in = self.client.login(**se...
test_authenticate_with_email_succeeds
identifier_name
test_user.py
"""Users tests.""" from django.contrib.auth import get_user_model, authenticate from django.test import TestCase from django.test import RequestFactory from tests.utils import ModelTestCase from users.factory import UserFactory User = get_user_model() class EmailAuthenticationTest(TestCase): """Tests to make s...
def test_authenticate_with_django_authenticate(self): self.create_user() request = RequestFactory().get('/test') user = authenticate(request=request, **self.creds) self.assertIsNotNone(user) class UserModelTest(ModelTestCase): """Test the user model.""" model = User ...
self.creds['username'] = 'johndoe' self.create_user() self.creds.pop('email') logged_in = self.client.login(**self.creds) self.assertFalse(logged_in)
identifier_body
test_user.py
"""Users tests.""" from django.contrib.auth import get_user_model, authenticate from django.test import TestCase from django.test import RequestFactory from tests.utils import ModelTestCase from users.factory import UserFactory User = get_user_model() class EmailAuthenticationTest(TestCase): """Tests to make s...
'null': True, } } model_tests = { 'verbose_name': 'utilisateur', } @classmethod def setUpTestData(self): self.obj = UserFactory.create() def test_get_absolute_url(self): self.client.force_login(self.obj) url = self.obj.get_absolute_url() ...
'blank': True,
random_line_split
Scope.d.ts
import { TSESTree } from '@typescript-eslint/typescript-estree'; declare namespace Scope { interface ScopeManager { scopes: Scope[]; globalScope: Scope | null; acquire(node: TSESTree.Node, inner?: boolean): Scope | null; getDeclaredVariables(node: TSESTree.Node): Variable[]; } ...
type: 'block' | 'catch' | 'class' | 'for' | 'function' | 'function-expression-name' | 'global' | 'module' | 'switch' | 'with' | 'TDZ'; isStrict: boolean; upper: Scope | null; childScopes: Scope[]; variableScope: Scope; block: TSESTree.Node; variables: Variable[]; ...
random_line_split
create-release.js
#!/usr/bin/env node 'use strict' const yargs = require('yargs') const logger = require('../lib/utils/logger') const octopus = require('../lib/octopus-deploy') const createRelease = require('../lib/commands/simple-create-release') const args = yargs .usage('Usage:\n $0 [options]') .option('host', { describe: 'Th...
/* eslint-disable no-process-exit */ process.exit(1) /* eslint-enable no-process-exit */ })
logger.error('Failed to create release. Error:', err)
random_line_split
plus-one-linked-list.py
# Time: O(n) # Space: O(1) # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # Two pointers solution. class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """...
""" :type head: ListNode :rtype: ListNode """ def reverseList(head): dummy = ListNode(0) curr = head while curr: dummy.next, curr.next, curr = curr, dummy.next, curr.next return dummy.next rev_head = reverseList(hea...
identifier_body
plus-one-linked-list.py
# Time: O(n) # Space: O(1) # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # Two pointers solution. class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """...
(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """ def reverseList(head): dummy = ListNode(0) curr = head while curr: dummy.next, curr.next, curr = curr, dummy.next, curr.next return...
Solution2
identifier_name
plus-one-linked-list.py
# Time: O(n) # Space: O(1) # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # Two pointers solution. class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """...
curr = curr.next return reverseList(rev_head)
curr.next = ListNode(0)
conditional_block
plus-one-linked-list.py
# Time: O(n) # Space: O(1) # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # Two pointers solution. class Solution(object): def plusOne(self, head): """ :type head: ListNode :rtype: ListNode """...
rev_head = reverseList(head) curr, carry = rev_head, 1 while curr and carry: curr.val += carry carry = curr.val / 10 curr.val %= 10 if carry and curr.next is None: curr.next = ListNode(0) curr = curr.next retur...
random_line_split
account_unreconcile.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
if context.get('active_ids', False): obj_move_line._remove_move_reconcile(cr, uid, context['active_ids'], context=context) return {'type': 'ir.actions.act_window_close'} account_unreconcile() class account_unreconcile_reconcile(osv.osv_memory): _name = "account.unreconcile.reconcile" ...
def trans_unrec(self, cr, uid, ids, context=None): obj_move_line = self.pool.get('account.move.line') if context is None: context = {}
random_line_split
account_unreconcile.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
rec_ids = context['active_ids'] if rec_ids: obj_move_reconcile.unlink(cr, uid, rec_ids, context=context) return {'type': 'ir.actions.act_window_close'} account_unreconcile_reconcile() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
context = {}
conditional_block
account_unreconcile.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
(osv.osv_memory): _name = "account.unreconcile" _description = "Account Unreconcile" def trans_unrec(self, cr, uid, ids, context=None): obj_move_line = self.pool.get('account.move.line') if context is None: context = {} if context.get('active_ids', False): ob...
account_unreconcile
identifier_name
account_unreconcile.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
account_unreconcile_reconcile() # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
obj_move_reconcile = self.pool.get('account.move.reconcile') if context is None: context = {} rec_ids = context['active_ids'] if rec_ids: obj_move_reconcile.unlink(cr, uid, rec_ids, context=context) return {'type': 'ir.actions.act_window_close'}
identifier_body
conf.py
# -*- coding: utf-8 -*- # # Configuration file for the Sphinx documentation builder. # # This file does only contain a selection of the most common options. For a # full list see the documentation: # http://www.sphinx-doc.org/en/stable/config # -- Path setup ------------------------------------------------------------...
html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} # Add any paths that contain custom static files (such as style sheets) here, # relative to this direc...
random_line_split
test.ts
/** * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to...
// This file is required by karma.conf.js and loads recursively all the .spec and framework files import 'zone.js/dist/zone-testing'; import { getTestBed } from '@angular/core/testing'; import { BrowserDynamicTestingModule, platformBrowserDynamicTesting, } from '@angular/platform-browser-dynamic/testing'; // esl...
* limitations under the License. */
random_line_split
lib.rs
#![warn(missing_docs)] //! A `Pinboard` is a shared, mutable, eventually consistent, lock-free data-structure. This //! allows multiple threads to communicate in a decoupled way by publishing data to the pinboard //! which other threads can then read in an eventually consistent way. //! //! This is not a silver bulle...
#[test] fn single_producer_multi_consumer() { let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); scope.spawn(|_| consume(&t)); }).unwrap()...
{ let t = Pinboard::<u32>::new(0); crossbeam::scope(|scope| { scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| produce(&t)); scope.spawn(|_| consume(&t)); }).unwrap(); }
identifier_body
lib.rs
#![warn(missing_docs)] //! A `Pinboard` is a shared, mutable, eventually consistent, lock-free data-structure. This //! allows multiple threads to communicate in a decoupled way by publishing data to the pinboard //! which other threads can then read in an eventually consistent way. //! //! This is not a silver bulle...
use std::sync::atomic::Ordering::*; /// An instance of a `Pinboard`, holds a shared, mutable, eventually-consistent reference to a `T`. pub struct Pinboard<T: Clone + 'static>(Atomic<T>); impl<T: Clone + 'static> Pinboard<T> { /// Create a new `Pinboard` instance holding the given value. pub fn new(t: T) -> P...
extern crate crossbeam_epoch as epoch; use epoch::{Atomic, Owned, Shared, pin};
random_line_split
lib.rs
#![warn(missing_docs)] //! A `Pinboard` is a shared, mutable, eventually consistent, lock-free data-structure. This //! allows multiple threads to communicate in a decoupled way by publishing data to the pinboard //! which other threads can then read in an eventually consistent way. //! //! This is not a silver bulle...
<T: Clone + Display>(t: &Pinboard<T>) { loop { match t.read() { Some(_) => {} None => break, } std::thread::sleep(std::time::Duration::from_millis(1)); } } fn produce(t: &Pinboard<u32>) { for i in 1..100 { t...
consume
identifier_name
smart-answers.js
function browserSupportsHtml5HistoryApi() { return !! (history && history.replaceState && history.pushState); } $(document).ready(function() { //_gaq.push(['_trackEvent', 'Citizen-Format-Smartanswer', 'Load']); if(browserSupportsHtml5HistoryApi()) { var formSelector = ".current form"; initializeHistory(...
else { return false; } }; } $('#current-error').focus(); // helper functions function toJsonUrl(url) { var parts = url.split('?'); var json_url = parts[0].replace(/\/$/, "") + ".json"; if (parts[1]) { json_url += "?"; json_url += parts[1]; } return window.loc...
{ updateContent(event.state['html_fragment']); }
conditional_block
smart-answers.js
function browserSupportsHtml5HistoryApi() { return !! (history && history.replaceState && history.pushState); } $(document).ready(function() { //_gaq.push(['_trackEvent', 'Citizen-Format-Smartanswer', 'Load']); if(browserSupportsHtml5HistoryApi()) { var formSelector = ".current form"; initializeHistory(...
// replace all the questions currently in the page with whatever is returned for given url function reloadQuestions(url, params) { var url = toJsonUrl(url); addLoading('<p class="next-step">Loading next step&hellip;</p>'); $.ajax(url, { type: 'GET', dataType:'json', data: params, ...
{ window.location = url; }
identifier_body
smart-answers.js
function browserSupportsHtml5HistoryApi() { return !! (history && history.replaceState && history.pushState); } $(document).ready(function() { //_gaq.push(['_trackEvent', 'Citizen-Format-Smartanswer', 'Load']); if(browserSupportsHtml5HistoryApi()) { var formSelector = ".current form"; initializeHistory(...
reloadQuestions(href); return false; }); // manage next/back by tracking popstate event window.onpopstate = function (event) { if(event.state !== null) { updateContent(event.state['html_fragment']); } else { return false; } }; } $('#current-error').foc...
window._gaq && window._gaq.push(['_trackEvent', 'MS_smart_answer', href, 'Change Answer']);
random_line_split
smart-answers.js
function browserSupportsHtml5HistoryApi() { return !! (history && history.replaceState && history.pushState); } $(document).ready(function() { //_gaq.push(['_trackEvent', 'Citizen-Format-Smartanswer', 'Load']); if(browserSupportsHtml5HistoryApi()) { var formSelector = ".current form"; initializeHistory(...
(fragment){ $('.smart_answer #js-replaceable').html(fragment); $.event.trigger('smartanswerAnswer'); if ($(".outcome").length !== 0) { $.event.trigger('smartanswerOutcome'); } } function initializeHistory(data) { if (! browserSupportsHtml5HistoryApi() && window.location.pathname.match(/\/...
updateContent
identifier_name
Info.js
var ServerURL = "/ServerSide/"; function replaceNumbers(node) { if (node.nodeType==3) //Text nodes only node.nodeValue = node.nodeValue.replace(/[0-9]/g, getArabicNumber); } function getArabicNumber(n) { return String.fromCharCode(1632 + parseInt(n,10)); } function walk(node, func) { func(node); ...
function Popup(data) { // var mywindow = window.open('', 'my div', 'height=400,width=600'); // mywindow.document.write('<html><head><title>my div</title>'); /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/css" />'); // mywindow.document.write('</head><body >'); /...
{ Popup($(elem).html()); }
identifier_body
Info.js
var ServerURL = "/ServerSide/"; function replaceNumbers(node) { if (node.nodeType==3) //Text nodes only node.nodeValue = node.nodeValue.replace(/[0-9]/g, getArabicNumber); } function getArabicNumber(n) { return String.fromCharCode(1632 + parseInt(n,10)); } function
(node, func) { func(node); node = node.firstChild; while (node) { walk(node, func); node = node.nextSibling; } }; function PrintElem(elem) { Popup($(elem).html()); } function Popup(data) { // var mywindow = window.open('', 'my div', 'height=400,width=600'); // mywindow.document.write...
walk
identifier_name
Info.js
var ServerURL = "/ServerSide/"; function replaceNumbers(node) { if (node.nodeType==3) //Text nodes only node.nodeValue = node.nodeValue.replace(/[0-9]/g, getArabicNumber); } function getArabicNumber(n) { return String.fromCharCode(1632 + parseInt(n,10)); } function walk(node, func) { func(node); ...
}; function PrintElem(elem) { Popup($(elem).html()); } function Popup(data) { // var mywindow = window.open('', 'my div', 'height=400,width=600'); // mywindow.document.write('<html><head><title>my div</title>'); /*optional stylesheet*/ //mywindow.document.write('<link rel="stylesheet" href="main.css" type="text/c...
{ walk(node, func); node = node.nextSibling; }
conditional_block
Info.js
var ServerURL = "/ServerSide/"; function replaceNumbers(node) {
} function getArabicNumber(n) { return String.fromCharCode(1632 + parseInt(n,10)); } function walk(node, func) { func(node); node = node.firstChild; while (node) { walk(node, func); node = node.nextSibling; } }; function PrintElem(elem) { Popup($(elem).html()); } function Popup(...
if (node.nodeType==3) //Text nodes only node.nodeValue = node.nodeValue.replace(/[0-9]/g, getArabicNumber);
random_line_split
index.tsx
import React from 'react'; import intersection from 'lodash/intersection'; import uniq from 'lodash/uniq'; import xor from 'lodash/xor'; import BulkNotice from './bulkNotice'; type RenderProps = { /** * Are all rows on current page selected? */ isPageSelected: boolean; /** * Callback for toggling singl...
(props: Props, state: State) { return { ...state, selectedIds: intersection(state.selectedIds, props.pageIds), }; } handleRowToggle = (id: string) => { this.setState(state => ({ selectedIds: xor(state.selectedIds, [id]), isAllSelected: false, })); }; handleAllRowsToggle...
getDerivedStateFromProps
identifier_name
index.tsx
import React from 'react'; import intersection from 'lodash/intersection'; import uniq from 'lodash/uniq'; import xor from 'lodash/xor'; import BulkNotice from './bulkNotice'; type RenderProps = { /** * Are all rows on current page selected? */ isPageSelected: boolean; /** * Callback for toggling singl...
isPageSelected={isPageSelected} isAllSelected={isAllSelected} bulkLimit={bulkLimit} /> ), }; return children(renderProps); } } export default BulkController;
random_line_split
install.js
const exec = require('child_process').exec const path = require('path') const fs = require('fs') const execPath = process.execPath const binPath = path.dirname(execPath) const dep = path.join(execPath, '../../lib/node_modules/dep') const repository = 'https://github.com/depjs/dep.git' const bin = path.join(dep, 'bin/de...
process.stdout.write( 'exec: git' + [' clone', repository, dep].join(' ') + '\n' ) exec('git clone ' + repository + ' ' + dep, (e) => { if (e) throw e process.stdout.write('link: ' + bin + '\n') process.stdout.write(' => ' + path.join(binPath, 'dep') + '\n') fs.symlink(bin, path.join(binPath, 'dep'), (e) => ...
random_line_split
utility.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib
matplotlib.use('Agg') import seaborn as sns import matplotlib.pyplot as plt from matplotlib import rc x = np.arange(-10, 10, 0.1) y = np.minimum(x,2) z = np.minimum(0,x+2) fig, axes = plt.subplots(1, 2, sharey=True) fig.set_size_inches(9, 3) axes[0].plot(x,y) axes[1].plot(x,z) for ax in axes: ax.set_xlim([-4,5]) ...
random_line_split
utility.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib matplotlib.use('Agg') import seaborn as sns import matplotlib.pyplot as plt from matplotlib import rc x = np.arange(-10, 10, 0.1) y = np.minimum(x,2) z = np.minimum(0,x+2) fig, axes = plt.subplots(1, 2, sharey=True) fig.set_size_in...
axes[0].set_title("$\\theta_i=2$") axes[1].set_title('$\\theta_i=-2$') plt.savefig('../plots/utility.pdf', bbox_inches='tight') # plt.show()
ax.set_xlim([-4,5]) ax.set_ylim([-4,3]) ax.set_xlabel(u"Alocação ($o_i$)") ax.set_ylabel('Utilidade ($u_i$)')
conditional_block
htmllabelelement.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::activation::{Activatable, ActivationSource, synthetic_click_activation}; use dom::bindings::codegen::Bind...
fn canceled_activation(&self) { } // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, _event: &Event, _target: &EventTarget) { if let Some(e) = self.GetControl() { let elem = e.upcast::<Element>(); synthetic_click_acti...
// https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps
random_line_split
htmllabelelement.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::activation::{Activatable, ActivationSource, synthetic_click_activation}; use dom::bindings::codegen::Bind...
// https://html.spec.whatwg.org/multipage/#implicit-submission fn implicit_submission(&self, _ctrlKey: bool, _shiftKey: bool, _altKey: bool, _metaKey: bool) { //FIXME: Investigate and implement implicit submission for label elements // Issue filed at https://github.com/servo/servo/issues/8263 ...
{ if let Some(e) = self.GetControl() { let elem = e.upcast::<Element>(); synthetic_click_activation(elem, false, false, false, false...
identifier_body
htmllabelelement.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::activation::{Activatable, ActivationSource, synthetic_click_activation}; use dom::bindings::codegen::Bind...
(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-label-htmlfor make_getter!(HtmlFor, "for"); // https://html.spec.whatwg.org/multipage/#dom-label-htmlfor make_atomic_setter!(SetHtmlFor, "for"); // https://html.spec.whatwg.or...
GetForm
identifier_name
htmltitleelement.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 crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; use crate::dom::bindings::codegen::Bindings:...
let node = self.upcast::<Node>(); if tree_in_doc { node.owner_doc().title_changed(); } } }
{ s.bind_to_tree(tree_in_doc); }
conditional_block
htmltitleelement.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 crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; use crate::dom::bindings::codegen::Bindings:...
(&self, mutation: &ChildrenMutation) { if let Some(ref s) = self.super_type() { s.children_changed(mutation); } let node = self.upcast::<Node>(); if node.is_in_doc() { node.owner_doc().title_changed(); } } fn bind_to_tree(&self, tree_in_doc: bool)...
children_changed
identifier_name
htmltitleelement.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 crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; use crate::dom::bindings::codegen::Bindings:...
use crate::dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; #[dom_struct] pub struct HTMLTitleElement { htmlelement: HTMLElement, } impl HTMLTitleElement { fn new_inherited( local_name: LocalName, prefix: Option<Prefix>, document: &Do...
use crate::dom::bindings::str::DOMString; use crate::dom::document::Document; use crate::dom::htmlelement::HTMLElement; use crate::dom::node::{ChildrenMutation, Node};
random_line_split
htmltitleelement.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 crate::dom::bindings::codegen::Bindings::HTMLTitleElementBinding; use crate::dom::bindings::codegen::Bindings:...
} impl HTMLTitleElementMethods for HTMLTitleElement { // https://html.spec.whatwg.org/multipage/#dom-title-text fn Text(&self) -> DOMString { self.upcast::<Node>().child_text_content() } // https://html.spec.whatwg.org/multipage/#dom-title-text fn SetText(&self, value: DOMString) { ...
{ Node::reflect_node( Box::new(HTMLTitleElement::new_inherited( local_name, prefix, document, )), document, HTMLTitleElementBinding::Wrap, ) }
identifier_body
from_hex.py
# Copyright (C) 2009-2010 Sergey Koposov # This file is part of astrolibpy # # astrolibpy 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 ...
(arr, delim=':'): r=re.compile('\s*(\-?)(.+)%s(.+)%s(.+)'%(delim,delim)) ret=[] for a in arr: m = r.search(a) sign = m.group(1)=='-' if sign: sign=-1 else: sign=1 i1 = int(m.group(2)) i2 = int(m.group(3)) i3 = float(m.group(4)) val = sign*(int(i1)+int(i2)/60.+(float(i3))/3600.) ret.append(va...
from_hex
identifier_name
from_hex.py
# Copyright (C) 2009-2010 Sergey Koposov # This file is part of astrolibpy # # astrolibpy 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 ...
r=re.compile('\s*(\-?)(.+)%s(.+)%s(.+)'%(delim,delim)) ret=[] for a in arr: m = r.search(a) sign = m.group(1)=='-' if sign: sign=-1 else: sign=1 i1 = int(m.group(2)) i2 = int(m.group(3)) i3 = float(m.group(4)) val = sign*(int(i1)+int(i2)/60.+(float(i3))/3600.) ret.append(val) return numpy.ar...
identifier_body
from_hex.py
# Copyright (C) 2009-2010 Sergey Koposov # This file is part of astrolibpy # # astrolibpy 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 ...
val = sign*(int(i1)+int(i2)/60.+(float(i3))/3600.) ret.append(val) return numpy.array(ret)
i2 = int(m.group(3)) i3 = float(m.group(4))
random_line_split
from_hex.py
# Copyright (C) 2009-2010 Sergey Koposov # This file is part of astrolibpy # # astrolibpy 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 ...
i1 = int(m.group(2)) i2 = int(m.group(3)) i3 = float(m.group(4)) val = sign*(int(i1)+int(i2)/60.+(float(i3))/3600.) ret.append(val) return numpy.array(ret)
sign=1
conditional_block
pscrap.py
from nct.utils.alch import Session, LSession from nct.domain.instrument import Instrument import random import functools import time from nct.deploy.deploy import Deployer import cProfile INSTRUMENTS = ['GOOGL.O', 'TWTR.N', 'GS.N', 'BAC.N', 'IBM.N'] def profile_method(file_name = None): def gen_wrapper(func): ...
do_a_bunch()
conditional_block
pscrap.py
from nct.utils.alch import Session, LSession from nct.domain.instrument import Instrument import random import functools import time from nct.deploy.deploy import Deployer import cProfile INSTRUMENTS = ['GOOGL.O', 'TWTR.N', 'GS.N', 'BAC.N', 'IBM.N'] def profile_method(file_name = None): def gen_wrapper(func): ...
return wrapper return gen_wrapper def time_it(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.time() func(*args,**kwargs) print("It took {}".format(time.time() - start)) return wrapper HASH_CACHE = {} @profile_method(r"c:\temp\instrument_1...
f = func cProfile.runctx('f(*args,**kwargs)', globals(), locals(), file_name) print("Done writing")
identifier_body
pscrap.py
from nct.utils.alch import Session, LSession from nct.domain.instrument import Instrument import random import functools import time from nct.deploy.deploy import Deployer import cProfile INSTRUMENTS = ['GOOGL.O', 'TWTR.N', 'GS.N', 'BAC.N', 'IBM.N'] def profile_method(file_name = None): def gen_wrapper(func): ...
@functools.wraps(func) def wrapper(*args, **kwargs): start = time.time() func(*args,**kwargs) print("It took {}".format(time.time() - start)) return wrapper HASH_CACHE = {} @profile_method(r"c:\temp\instrument_123.out") def do_a_bunch(): s = LSession() name = INSTRUMENTS[in...
def time_it(func):
random_line_split
pscrap.py
from nct.utils.alch import Session, LSession from nct.domain.instrument import Instrument import random import functools import time from nct.deploy.deploy import Deployer import cProfile INSTRUMENTS = ['GOOGL.O', 'TWTR.N', 'GS.N', 'BAC.N', 'IBM.N'] def profile_method(file_name = None): def gen_wrapper(func): ...
(): s = LSession() name = INSTRUMENTS[int(random.random()*100)%len(INSTRUMENTS)] instr_id = s.query(Instrument).filter_by(name=name).one().id for _ in range(10000): s.query(Instrument).get(instr_id) s.close() import sys print (sys.version) Deployer(LSession).deploy() print ("Deployed") for ...
do_a_bunch
identifier_name
test_script.py
import glob import os import subprocess import sys from distutils.version import LooseVersion from typing import Iterable, List, Optional, Tuple from scripts.lib.zulip_tools import get_dev_uuid_var_path from version import PROVISION_VERSION ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(...
test_files.append(os.path.abspath(file)) if not test_files: test_files = sorted(glob.glob(os.path.join(test_dir, '*.js'))) return test_files def prepare_puppeteer_run() -> None: os.chdir(ZULIP_PATH) subprocess.check_call(['node', 'node_modules/puppeteer/install.js']) os.makedirs(...
file = os.path.join(test_dir, file)
conditional_block
test_script.py
import glob import os import subprocess import sys from distutils.version import LooseVersion from typing import Iterable, List, Optional, Tuple from scripts.lib.zulip_tools import get_dev_uuid_var_path from version import PROVISION_VERSION ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(...
os.chdir(ZULIP_PATH) subprocess.check_call(['node', 'node_modules/puppeteer/install.js']) os.makedirs('var/puppeteer', exist_ok=True) for f in glob.glob('var/puppeteer/puppeteer-failure*.png'): os.remove(f)
identifier_body
test_script.py
import glob import os import subprocess import sys from distutils.version import LooseVersion from typing import Iterable, List, Optional, Tuple from scripts.lib.zulip_tools import get_dev_uuid_var_path from version import PROVISION_VERSION ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(...
() -> Tuple[bool, Optional[str]]: version_file = get_version_file() if not os.path.exists(version_file): # If the developer doesn't have a version_file written by # a previous provision, then we don't do any safety checks # here on the assumption that the developer is managing # ...
get_provisioning_status
identifier_name
test_script.py
import glob import os import subprocess import sys from distutils.version import LooseVersion from typing import Iterable, List, Optional, Tuple from scripts.lib.zulip_tools import get_dev_uuid_var_path from version import PROVISION_VERSION ZULIP_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(...
sys.exit(1) def find_js_test_files(test_dir: str, files: Iterable[str]) -> List[str]: test_files = [] for file in files: for file_name in os.listdir(test_dir): if file_name.startswith(file): file = file_name break if not os.path.exists(fi...
print('If you really know what you are doing, use --force to run anyway.')
random_line_split
vec.rs
// Copyright 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-MIT or ...
() { let a = [1, 2, 3]; let b = &[4, 5, 6]; let c = @[7, 8, 9]; let d = ~[10, 11, 12]; let _z = 0; }
main
identifier_name
vec.rs
// Copyright 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-MIT or ...
{ let a = [1, 2, 3]; let b = &[4, 5, 6]; let c = @[7, 8, 9]; let d = ~[10, 11, 12]; let _z = 0; }
identifier_body
vec.rs
// Copyright 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-MIT or ...
}
random_line_split
main.rs
use itertools::Itertools; use std::fs; use std::io::{Read, Write}; use std::str; const PHF_SRC: &str = "\ // A stripped down `phf` crate fork. // // https://github.com/sfackler/rust-phf struct Map<V: 'static> { pub key: u64, pub disps: &'static [(u32, u32)], pub entries: &'static[(&'static str, V)], } i...
(name: &str) -> String { let mut change_case = false; let mut s = String::with_capacity(name.len()); for (idx, c) in name.chars().enumerate() { if idx == 0 { if c.is_digit(10) { s.push('N'); s.push(c); } else { s.push(c.to_upper...
to_enum_name
identifier_name
main.rs
use itertools::Itertools; use std::fs; use std::io::{Read, Write}; use std::str; const PHF_SRC: &str = "\ // A stripped down `phf` crate fork. // // https://github.com/sfackler/rust-phf struct Map<V: 'static> { pub key: u64, pub disps: &'static [(u32, u32)], pub entries: &'static[(&'static str, V)], } i...
} s }
{ s.push(c); }
conditional_block
main.rs
use itertools::Itertools; use std::fs; use std::io::{Read, Write}; use std::str; const PHF_SRC: &str = "\ // A stripped down `phf` crate fork. // // https://github.com/sfackler/rust-phf struct Map<V: 'static> { pub key: u64, pub disps: &'static [(u32, u32)], pub entries: &'static[(&'static str, V)], } i...
#[inline] fn hash(x: &str, key: u64) -> u64 { use std::hash::Hasher; let mut hasher = siphasher::sip::SipHasher13::new_with_keys(0, key); hasher.write(x.as_bytes()); hasher.finish() } #[inline] fn get_index(hash: u64, disps: &[(u32, u32)], len: usize) -> u32 { let (g, f1, f2) = split(hash); le...
random_line_split
main.rs
use itertools::Itertools; use std::fs; use std::io::{Read, Write}; use std::str; const PHF_SRC: &str = "\ // A stripped down `phf` crate fork. // // https://github.com/sfackler/rust-phf struct Map<V: 'static> { pub key: u64, pub disps: &'static [(u32, u32)], pub entries: &'static[(&'static str, V)], } i...
fn gen_map( spec_path: &str, enum_name: &str, map_name: &str, doc: &str, f: &mut fs::File, ) -> Result<(), Box<dyn std::error::Error>> { let mut spec = String::new(); fs::File::open(spec_path)?.read_to_string(&mut spec)?; let names: Vec<&str> = spec.split('\n').filter(|s| !s.is_empty(...
{ let f = &mut fs::File::create("../src/names.rs")?; writeln!(f, "// This file is autogenerated. Do not edit it!")?; writeln!(f, "// See ./codegen for details.\n")?; writeln!(f, "use std::fmt;\n")?; gen_map( "elements.txt", "ElementId", "ELEMENTS", "List of all SVG...
identifier_body
page_links_to_edge_list_wiki.py
import optparse import pickle #converts urls to wiki_id parser = optparse.OptionParser() parser.add_option('-i','--input', dest = 'input_file', help = 'input_file') parser.add_option('-o','--output', dest = 'output_file', help = 'output_file') (options, args) = parser.parse_args() if options.input_file is None: ...
input_file = options.input_file output_file = options.output_file #define the dictionary url:wiki_id wiki_from_url_dict = {} with open('../../datasets/dbpedia/page_ids_en_2016.ttl','r') as f: for line in f: line = line.split(' ') if line[0] == '#': continue url = line[...
options.output_file = raw_input('Enter output file:')
conditional_block
page_links_to_edge_list_wiki.py
import optparse import pickle #converts urls to wiki_id parser = optparse.OptionParser() parser.add_option('-i','--input', dest = 'input_file', help = 'input_file') parser.add_option('-o','--output', dest = 'output_file', help = 'output_file') (options, args) = parser.parse_args() if options.input_file is None: ...
wiki_id2 = local_id[url_2] except (KeyError, IndexError): wiki_id2 = max_wiki_id local_id[url_2] = wiki_id2 max_wiki_id +=1 output_file_write.write('%d %d\n' %(wiki_id1,wiki_id2)) print count ...
try: #check if a local id has already been assigned
random_line_split
marisa-build.rs
// Copyright (c) 2010-2013, Susumu Yata // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditi...
read_keys(input_file, &keyset); } catch (const marisa::Exception &ex) { std::cerr << ex.what() << ": failed to read keys" << std::endl; return 12; } marisa::Trie trie; try { trie.build(keyset, param_num_tries | param_tail_mode | param_node_order | param_cache_level); } catch (const m...
{ std::cerr << "error: failed to open: " << args[i] << std::endl; return 11; }
conditional_block
marisa-build.rs
// Copyright (c) 2010-2013, Susumu Yata // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditi...
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL ...
random_line_split
app.py
import os import random import time from flask import Flask, request, render_template, session, flash, redirect, \ url_for, jsonify from flask.ext.mail import Mail, Message from flask.ext.sqlalchemy import SQLAlchemy from celery import Celery app = Flask(__name__) app.config['SECRET_KEY'] = 'top-secret!' # Flask...
if __name__ == '__main__': app.run(debug=True)
task = long_task.AsyncResult(task_id) if task.state == 'PENDING': response = { 'state': task.state, 'current': 0, 'total': 1, 'status': 'Pending...' } elif task.state != 'FAILURE': response = { 'state': task.state, '...
identifier_body
app.py
import os import random import time from flask import Flask, request, render_template, session, flash, redirect, \ url_for, jsonify from flask.ext.mail import Mail, Message from flask.ext.sqlalchemy import SQLAlchemy from celery import Celery app = Flask(__name__) app.config['SECRET_KEY'] = 'top-secret!' # Flask...
else: # something went wrong in the background job response = { 'state': task.state, 'current': 1, 'total': 1, 'status': str(task.info), # this is the exception raised } return jsonify(response) if __name__ == '__main__': app.run(de...
response['result'] = task.info['result']
conditional_block
app.py
import os import random import time from flask import Flask, request, render_template, session, flash, redirect, \ url_for, jsonify from flask.ext.mail import Mail, Message from flask.ext.sqlalchemy import SQLAlchemy from celery import Celery app = Flask(__name__) app.config['SECRET_KEY'] = 'top-secret!' # Flask...
session['email'] = email # send the email msg = Message('Hello from Flask', recipients=[request.form['email']]) msg.body = 'This is a test email sent from a background Celery task.' if request.form['submit'] == 'Send': # send right away send_async_email.delay(msg) ...
@app.route('/', methods=['GET', 'POST']) def index(): if request.method == 'GET': return render_template('index.html', email=session.get('email', '')) email = request.form['email']
random_line_split
app.py
import os import random import time from flask import Flask, request, render_template, session, flash, redirect, \ url_for, jsonify from flask.ext.mail import Mail, Message from flask.ext.sqlalchemy import SQLAlchemy from celery import Celery app = Flask(__name__) app.config['SECRET_KEY'] = 'top-secret!' # Flask...
(msg): """Background task to send an email with Flask-Mail.""" with app.app_context(): mail.send(msg) @celery.task(bind=True) def long_task(self): """Background task that runs a long function with progress reports.""" verb = ['Starting up', 'Booting', 'Repairing', 'Loading', 'Checking'] ad...
send_async_email
identifier_name
NorthAmericaCountriesBundle_nl.js
/**
*/ "use strict";var l={"SPM":["SPM","Saint-Pierre en Miquelon"],"CYM":["CYM","Caymaneilanden"],"DOM":["DOM","Dominicaanse Republiek"],"VGB":["VGB","Maagdeneilanden, V.K."],"TCA":["TCA","Turks- en Caicoseilanden"],"HTI":["HTI","Ha\u00EFti"],"KNA":["KNA","Saint Kitts en Nevis"],"VCT":["VCT","Saint Vincent en de Grenadin...
* Copyright (c) 2014, 2016, Oracle and/or its affiliates. * The Universal Permissive License (UPL), Version 1.0
random_line_split
trait-inheritance-overloading-simple.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self, other: &MyInt) -> bool { !self.eq(other) } } impl MyNum for MyInt {} fn f<T:MyNum>(x: T, y: T) -> bool { return x == y; } fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y, z) = (mi(3), mi(5), mi(3)); assert!(x != y); assert_eq!(x, z); }
ne
identifier_name
trait-inheritance-overloading-simple.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn mi(v: int) -> MyInt { MyInt { val: v } } pub fn main() { let (x, y, z) = (mi(3), mi(5), mi(3)); assert!(x != y); assert_eq!(x, z); }
{ return x == y; }
identifier_body
trait-inheritance-overloading-simple.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT.
// except according to those terms. use std::cmp::Eq; trait MyNum : Eq { } #[deriving(Show)] struct MyInt { val: int } impl Eq for MyInt { fn eq(&self, other: &MyInt) -> bool { self.val == other.val } fn ne(&self, other: &MyInt) -> bool { !self.eq(other) } } impl MyNum for MyInt {} fn f<T:MyNum>(x: T, y: ...
// // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed
random_line_split
delegate.py
#!/usr/bin/env python # Encoding: UTF-8 """Part of qdex: a Pokédex using PySide and veekun's pokedex library. A query models for pokémon """ from PySide import QtGui, QtCore Qt = QtCore.Qt class PokemonDelegate(QtGui.QStyledItemDelegate): """Delegate for a Pokémon Shows summary information when the group o...
f, option, index): option.decorationSize = QtCore.QSize(0, 0) self.view.model()._hack_small_icons = True hint = super(PokemonNameDelegate, self).sizeHint(option, index) self.view.model()._hack_small_icons = False return hint def paint(self, painter, option, index): o...
Hint(sel
identifier_name
delegate.py
#!/usr/bin/env python # Encoding: UTF-8 """Part of qdex: a Pokédex using PySide and veekun's pokedex library. A query models for pokémon """ from PySide import QtGui, QtCore Qt = QtCore.Qt class PokemonDelegate(QtGui.QStyledItemDelegate): """Delegate for a Pokémon Shows summary information when the group o...
def paint(self, painter, option, index): index = self.indexToShow(index) super(PokemonDelegate, self).paint(painter, option, index) def sizeHint(self, option, index): hint = super(PokemonDelegate, self).sizeHint summaryHint = hint(option, self.indexToShow(index, True)) re...
Get the index to show instead of this one summary can be True to show the all-forms summary information (if the row is expandable at all), False to show the notmal data, or None to choose based on the state of the view It's not too easy to hijack the QItemDelegate pipeling with...
identifier_body
delegate.py
#!/usr/bin/env python # Encoding: UTF-8 """Part of qdex: a Pokédex using PySide and veekun's pokedex library. A query models for pokémon """ from PySide import QtGui, QtCore Qt = QtCore.Qt class PokemonDelegate(QtGui.QStyledItemDelegate): """Delegate for a Pokémon Shows summary information when the group o...
def sizeHint(self, option, index): hint = super(PokemonDelegate, self).sizeHint summaryHint = hint(option, self.indexToShow(index, True)) return hint(option, index).expandedTo(summaryHint) class PokemonNameDelegate(PokemonDelegate): """Delegate for the Pokémon icon/name column""" de...
super(PokemonDelegate, self).paint(painter, option, index)
random_line_split
delegate.py
#!/usr/bin/env python # Encoding: UTF-8 """Part of qdex: a Pokédex using PySide and veekun's pokedex library. A query models for pokémon """ from PySide import QtGui, QtCore Qt = QtCore.Qt class PokemonDelegate(QtGui.QStyledItemDelegate): """Delegate for a Pokémon Shows summary information when the group o...
def paint(self, painter, option, index): index = self.indexToShow(index) super(PokemonDelegate, self).paint(painter, option, index) def sizeHint(self, option, index): hint = super(PokemonDelegate, self).sizeHint summaryHint = hint(option, self.indexToShow(index, True)) re...
urn index
conditional_block
login_enforcement.py
# coding=utf-8 # # Copyright 2017 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
def update(self, **kwargs): """Update is not supported for Login Enforcement resource :raises: UnsupportedOperation """ raise UnsupportedOperation( "%s does not support the update method" % self.__class__.__name__ )
uper(Login_Enforcement, self).__init__(policy) self._meta_data['required_json_kind'] = 'tm:asm:policies:login-enforcement:login-enforcementstate' self._meta_data['required_load_parameters'] = set() self._meta_data['object_has_stats'] = False self._meta_data['minimum_version'] = '11.6.0'
identifier_body
login_enforcement.py
# coding=utf-8 # # Copyright 2017 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License");
# Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. fro...
# you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #
random_line_split
login_enforcement.py
# coding=utf-8 # # Copyright 2017 F5 Networks Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
(UnnamedResource): """BIG-IP® ASM Login Enforcement resource.""" def __init__(self, policy): super(Login_Enforcement, self).__init__(policy) self._meta_data['required_json_kind'] = 'tm:asm:policies:login-enforcement:login-enforcementstate' self._meta_data['required_load_parameters'] = se...
Login_Enforcement
identifier_name