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 |
|---|---|---|---|---|
test_timer.py | from unittest import TestCase
from common.timer import timed
@timed
def fib(n):
ls = [1, 1]
if n == 0:
return 0
if n <= 2:
return ls[n - 1]
for i in range(3, n + 1):
tmp = ls[1]
ls[1] = ls[0] + ls[1]
ls[0] = tmp
return ls[-1]
class Test(TestCase):
| def test_timed(self):
# timed should not do anything to the decorated method,
# just make some calls to verify that the function works unaffected
self.assertEqual(0, fib(0))
self.assertEqual(1, fib(1))
self.assertEqual(1, fib(2))
self.assertEqual(2, fib(3))
self.a... | identifier_body | |
test_timer.py | from unittest import TestCase
from common.timer import timed
@timed
def fib(n):
ls = [1, 1]
if n == 0:
return 0
if n <= 2:
return ls[n - 1]
for i in range(3, n + 1):
|
return ls[-1]
class Test(TestCase):
def test_timed(self):
# timed should not do anything to the decorated method,
# just make some calls to verify that the function works unaffected
self.assertEqual(0, fib(0))
self.assertEqual(1, fib(1))
self.assertEqual(1, fib(2))
... | tmp = ls[1]
ls[1] = ls[0] + ls[1]
ls[0] = tmp | conditional_block |
test_timer.py | from unittest import TestCase
from common.timer import timed
@timed
def fib(n):
ls = [1, 1]
if n == 0:
return 0
if n <= 2:
return ls[n - 1]
for i in range(3, n + 1):
tmp = ls[1]
ls[1] = ls[0] + ls[1]
ls[0] = tmp
return ls[-1]
class | (TestCase):
def test_timed(self):
# timed should not do anything to the decorated method,
# just make some calls to verify that the function works unaffected
self.assertEqual(0, fib(0))
self.assertEqual(1, fib(1))
self.assertEqual(1, fib(2))
self.assertEqual(2, fib(3)... | Test | identifier_name |
test_timer.py | from unittest import TestCase
from common.timer import timed
@timed
def fib(n):
ls = [1, 1]
if n == 0:
return 0
if n <= 2:
return ls[n - 1]
for i in range(3, n + 1):
tmp = ls[1]
ls[1] = ls[0] + ls[1]
ls[0] = tmp
return ls[-1]
class Test(TestCase):
def... | self.assertEqual(1, fib(2))
self.assertEqual(2, fib(3))
self.assertEqual(3, fib(4))
self.assertEqual(5, fib(5)) | # timed should not do anything to the decorated method,
# just make some calls to verify that the function works unaffected
self.assertEqual(0, fib(0))
self.assertEqual(1, fib(1)) | random_line_split |
draggable.ts | /// <reference path="../../typings/_custom.d.ts" />
import {Directive, EventEmitter, HostListener} from 'angular2/angular2';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ElementRef} from 'angular2/core';
@Directive({
selector: '[draggable]'
})
export class Draggable {
mousedrag;
mouseup = n... |
constructor(public element: ElementRef) {
this.element.nativeElement.style.position = 'relative';
this.element.nativeElement.style.cursor = 'pointer';
this.mousedrag = this.mousedown._subject.map(event => {
event.preventDefault();
return {
left: event.clientX - this.element.na... | { this.mousemove.next(event); } | identifier_body |
draggable.ts | /// <reference path="../../typings/_custom.d.ts" />
import {Directive, EventEmitter, HostListener} from 'angular2/angular2';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ElementRef} from 'angular2/core';
@Directive({
selector: '[draggable]'
})
export class Draggable {
mousedrag;
mouseup = n... |
@HostListener('mouseup', ['$event'])
onMouseup(event) { this.mouseup.next(event); }
@HostListener('mousedown', ['$event'])
onMousedown(event) { this.mousedown.next(event); }
@HostListener('mousemove', ['$event'])
onMousemove(event) { this.mousemove.next(event); }
constructor(public element: ElementRef... | random_line_split | |
draggable.ts | /// <reference path="../../typings/_custom.d.ts" />
import {Directive, EventEmitter, HostListener} from 'angular2/angular2';
import {DOM} from 'angular2/src/core/dom/dom_adapter';
import {ElementRef} from 'angular2/core';
@Directive({
selector: '[draggable]'
})
export class Draggable {
mousedrag;
mouseup = n... | (event) { this.mousemove.next(event); }
constructor(public element: ElementRef) {
this.element.nativeElement.style.position = 'relative';
this.element.nativeElement.style.cursor = 'pointer';
this.mousedrag = this.mousedown._subject.map(event => {
event.preventDefault();
return {
... | onMousemove | identifier_name |
models.py | match_service
logger = logging.getLogger(__name__)
class TicketManager(models.Manager):
def create_ticket(self, ticket=None, **kwargs):
"""
Create a new ``Ticket``. Additional arguments are passed to the
``create()`` function. Return the newly created ``Ticket``.
"""
if ... | objects = TicketManager()
class Meta:
abstract = True
def __str__(self):
return self.ticket
@property
def name(self):
return self._meta.verbose_name
def consume(self):
"""
Consume a ``Ticket`` by populating the ``consumed`` field with
the curre... | user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('user'),
on_delete=models.CASCADE)
expires = models.DateTimeField(_('expires'))
consumed = models.DateTimeField(_('consumed'), null=True)
| random_line_split |
models.py | _service
logger = logging.getLogger(__name__)
class TicketManager(models.Manager):
def create_ticket(self, ticket=None, **kwargs):
"""
Create a new ``Ticket``. Additional arguments are passed to the
``create()`` function. Return the newly created ``Ticket``.
"""
if not ti... |
try:
if not match_service(t.service, service):
raise InvalidService("%s %s for service %s is invalid for "
"service %s" % (t.name, ticket, t.service, service))
except AttributeError:
pass
try:
if renew and not t.is_pr... | raise InvalidService("Service %s is not a valid %s URL" %
(service, t.name)) | conditional_block |
models.py | _service
logger = logging.getLogger(__name__)
class TicketManager(models.Manager):
def create_ticket(self, ticket=None, **kwargs):
"""
Create a new ``Ticket``. Additional arguments are passed to the
``create()`` function. Return the newly created ``Ticket``.
"""
if not ti... |
def is_consumed(self):
"""
Check a ``Ticket``s consumed state, consuming it in the process.
"""
if self.consumed is None:
self.consume()
return False
return True
def is_expired(self):
"""
Check a ``Ticket``s expired state. Return... | """
Consume a ``Ticket`` by populating the ``consumed`` field with
the current datetime. A consumed ``Ticket`` is invalid for future
authentication attempts.
"""
self.consumed = now()
self.save() | identifier_body |
models.py | _service
logger = logging.getLogger(__name__)
class TicketManager(models.Manager):
def create_ticket(self, ticket=None, **kwargs):
"""
Create a new ``Ticket``. Additional arguments are passed to the
``create()`` function. Return the newly created ``Ticket``.
"""
if not ti... | :
verbose_name = _('service ticket')
verbose_name_plural = _('service tickets')
def is_primary(self):
"""
Check the credential origin for a ``ServiceTicket``. If the ticket was
issued from the presentation of the user's primary credentials,
return ``True``, otherwise... | Meta | identifier_name |
stepper-button.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, HostListener, Input} from '@angular/core';
import {CdkStepper} from './stepper';
/** Button that... |
}
/** Button that moves to the previous step in a stepper workflow. */
@Directive({
selector: 'button[cdkStepperPrevious]',
host: {
'[type]': 'type',
}
})
export class CdkStepperPrevious {
/** Type of the previous button. Defaults to "button" if not specified. */
@Input() type: string = 'button';
con... | {
this._stepper.next();
} | identifier_body |
stepper-button.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, HostListener, Input} from '@angular/core';
import {CdkStepper} from './stepper';
/** Button that... | (public _stepper: CdkStepper) {}
// We have to use a `HostListener` here in order to support both Ivy and ViewEngine.
// In Ivy the `host` bindings will be merged when this class is extended, whereas in
// ViewEngine they're overwritten.
// TODO(crisbeto): we move this back into `host` once Ivy is turned on by... | constructor | identifier_name |
stepper-button.ts | /**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {Directive, HostListener, Input} from '@angular/core';
import {CdkStepper} from './stepper';
/** Button that... | export class CdkStepperPrevious {
/** Type of the previous button. Defaults to "button" if not specified. */
@Input() type: string = 'button';
constructor(public _stepper: CdkStepper) {}
// We have to use a `HostListener` here in order to support both Ivy and ViewEngine.
// In Ivy the `host` bindings will b... | random_line_split | |
javascript.js | (function (){
"use strict";
(function() {
var $bordered = $('.bordered');
window.setInterval(function() {
var top = window.pageYOffset || document.documentElement.scrollTop;
if(top > 0) {
$bordered.fadeOut('fast');
} else if(top == 0 && !$bor... |
$("#cennik button").on("click", toggle);
})();
(function(){
"use strict";
//
// deep linking for tracking google analytics
// requested by michael, should not be also standard deep linking
//
function setDeeplinking(event){
window.location.hash = $(event.target).data("target");... | {
cennik.modal("toggle");
ponuka.modal("toggle");
} | identifier_body |
javascript.js | (function (){
"use strict";
(function() {
var $bordered = $('.bordered');
window.setInterval(function() {
var top = window.pageYOffset || document.documentElement.scrollTop;
if(top > 0) | else if(top == 0 && !$bordered.is(':visible')) {
$bordered.fadeIn("fast");
}
}, 200);
})();
$(function() {
$('.scroll').click(function(e) {
e.preventDefault();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == t... | {
$bordered.fadeOut('fast');
} | conditional_block |
javascript.js | (function (){
"use strict";
(function() {
var $bordered = $('.bordered');
window.setInterval(function() {
var top = window.pageYOffset || document.documentElement.scrollTop;
if(top > 0) {
$bordered.fadeOut('fast');
} else if(top == 0 && !$bor... | (event){
window.location.hash = "";
}
$("nav .menu").on("click", setDeeplinking);
$("#try").on("click", setDeeplinking);
$('#cennik').on('hidden.bs.modal', clearDeeplinking);
$('#ponuka').on('hidden.bs.modal', clearDeeplinking);
$('#kontakt').on('hidden.bs.modal', clearDeeplinking);
})();
... | clearDeeplinking | identifier_name |
javascript.js | (function (){
"use strict";
(function() {
var $bordered = $('.bordered');
window.setInterval(function() {
var top = window.pageYOffset || document.documentElement.scrollTop;
if(top > 0) {
$bordered.fadeOut('fast');
} else if(top == 0 && !$bor... | })();
(function(){
"use strict";
//
// toggle popups from pricing dialog to the partners dialog
//
var cennik = $("#cennik");
var ponuka = $("#ponuka");
function toggle(){
cennik.modal("toggle");
ponuka.modal("toggle");
}
$("#cennik button").on("click", toggle);
})();
... | random_line_split | |
plugin.js | /**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
( function() {
CKEDITOR.plugins.add( 'templates', {
requires: 'dialog',
// jscs:disable maximumLineLength
lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,de-ch,el... | }
if ( toLoad.length )
CKEDITOR.scriptLoader.load( toLoad, callback );
else
setTimeout( callback, 0 );
};
} )();
/**
* The templates definition set to use. It accepts a list of names separated by
* comma. It must match definitions loaded with the {@link #templates_files} setting.
*
* config.templat... | toLoad.push( templateFiles[ i ] );
loadedTemplatesFiles[ templateFiles[ i ] ] = 1;
}
| conditional_block |
plugin.js | /**
* @license Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
| // jscs:disable maximumLineLength
lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,de-ch,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,tt,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE%
// jscs:enable maximum... | ( function() {
CKEDITOR.plugins.add( 'templates', {
requires: 'dialog', | random_line_split |
mod.rs | pub mod packet;
use std::net;
use std::io;
use std::time::Duration;
use time;
use protocol::raknet;
macro_rules! check_raknet_packet {
() => {};
}
#[derive(Clone, Debug)]
pub struct ServerInfo {
pub name: String,
pub protocol_version: String,
pub client_version: String,
pub players_count: u32,
... | use_security: false
}.into(), raknet::types::Reliability::Reliable)?;
//println!("{:?}", self.session.receive_packet()?);
let listen_addr = self.session.listen_address().clone();
self.session.send_encapsulate(&raknet::packet::ClientHandshake {
client_addr: list... | {
self.session.set_read_timeout(Some(Duration::from_millis(500)))?;
let mtu = self.find_mtu()?;
self.session.mtu = mtu as usize;
self.session.set_read_timeout(Some(Duration::from_secs(5)))?;
self.session.send_packet(&raknet::packet::OfflineConnectionRequest2 {
magi... | identifier_body |
mod.rs | pub mod packet;
use std::net;
use std::io;
use std::time::Duration;
use time;
use protocol::raknet;
macro_rules! check_raknet_packet {
() => {};
}
#[derive(Clone, Debug)]
pub struct ServerInfo {
pub name: String,
pub protocol_version: String,
pub client_version: String,
pub players_count: u32,
... | (&mut self) -> io::Result<u16> {
for mtu in (1..(1500 - 46 + 1) / 10).rev() {
self.session.send_packet(&raknet::packet::OfflineConnectionRequest1 {
magic: raknet::types::Magic,
protocol_version: 8,
mtu: vec![0; mtu * 10]
}.into())?;
... | find_mtu | identifier_name |
mod.rs | pub mod packet;
use std::net;
use std::io;
use std::time::Duration;
use time;
use protocol::raknet;
macro_rules! check_raknet_packet {
() => {};
}
#[derive(Clone, Debug)]
pub struct ServerInfo {
pub name: String,
pub protocol_version: String,
pub client_version: String,
pub players_count: u32,
... | for mtu in (1..(1500 - 46 + 1) / 10).rev() {
self.session.send_packet(&raknet::packet::OfflineConnectionRequest1 {
magic: raknet::types::Magic,
protocol_version: 8,
mtu: vec![0; mtu * 10]
}.into())?;
match self.session.receive_... | fn find_mtu(&mut self) -> io::Result<u16> { | random_line_split |
addNewAfter.node.tsx | import { NG } from '@web-companions/fc';
import { svg } from 'lit-html';
import { nodeRender } from 'utils/directives';
export const addNewAfterNode = NG({ render: nodeRender })(() => {
return svg/*html*/ ` | <path stroke="none" d="M0 0h24v24H0z" fill="none"></path>
<path d="M14 3v4a1 1 0 0 0 1 1h4"></path>
<path d="M17 21h-10a2 2 0 0 1 -2 -2v-14a2 2 0 0 1 2 -2h7l5 5v11a2 2 0 0 1 -2 2z"></path>
<line x1="12" y1="11" x2="12" y2="17"></line>
<line x1="9" y1="14" x2="15" y2="14"></line>
</svg>... | <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-tabler icon-tabler-file-plus" width="24" height="24" viewBox="0 0 24 24" stroke-width="1" stroke="currentColor" fill="none" stroke-linecap="round" stroke-linejoin="round"> | random_line_split |
manifests.py | """Manifest clonning tools.."""
import json
import requests
import six
import time
import uuid
import zipfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from nailgun import entit... |
def clone():
"""Clone the cached manifest and return a ``Manifest`` object.
Is hightly recommended to use this with the ``with`` statement to make that
the content of the manifest (file-like object) is closed properly::
with clone() as manifest:
# my fancy stuff
"""
return M... | self.content.close() | conditional_block |
manifests.py | """Manifest clonning tools.."""
import json
import requests
import six
import time
import uuid
import zipfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from nailgun import entit... | ():
"""Returns a ``Manifest`` object filed with the template manifest.
Make sure to remove the manifest after its usage otherwiser the Satellite 6
server will not accept it anymore on any other organization.
Is hightly recommended to use this with the ``with`` statement to make that
the content of... | original_manifest | identifier_name |
manifests.py | """Manifest clonning tools.."""
import json
import requests
import six
import time
import uuid
import zipfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from nailgun import entit... | result = upload_manifest_locked(org_id, manifests.clone())
subscription_id = result[id']
"""
if interface not in [INTERFACE_API, INTERFACE_CLI]:
raise ValueError(
'upload manifest with interface "{0}" not supported'
.format(interface)
)
if interface =... |
# or in one line with default interface | random_line_split |
manifests.py | """Manifest clonning tools.."""
import json
import requests
import six
import time
import uuid
import zipfile
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding
from nailgun import entit... |
# Cache the ManifestCloner in order to avoid downloading the manifest template
# every single time.
_manifest_cloner = ManifestCloner()
class Manifest(object):
"""Class that holds the contents of a manifest with a generated filename
based on ``time.time``.
To ensure that the manifest content is closed... | """Returns the original manifest as a file-like object.
Be aware that using the original manifest and not removing it
afterwards will make impossible to import it on any other Organization.
Make sure to close the returned file-like object in order to clean up
the memory used to store i... | identifier_body |
floatobject.rs | use libc::{c_int, c_double};
use object::*;
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub static mut PyFloat_Type: PyTypeObject;
}
#[inline(always)]
pub unsafe fn PyFloat_Check(op : *mut PyObject) -> c_int {
PyObject_TypeCheck(op, &mut PyFloat_Type)
}
#[inline(always)]
pub unsafe fn PyFloat_Ch... | pub fn PyFloat_GetInfo() -> *mut PyObject;
pub fn PyFloat_FromString(arg1: *mut PyObject) -> *mut PyObject;
pub fn PyFloat_FromDouble(arg1: c_double) -> *mut PyObject;
pub fn PyFloat_AsDouble(arg1: *mut PyObject) -> c_double;
} | pub fn PyFloat_GetMin() -> c_double; | random_line_split |
floatobject.rs | use libc::{c_int, c_double};
use object::*;
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub static mut PyFloat_Type: PyTypeObject;
}
#[inline(always)]
pub unsafe fn | (op : *mut PyObject) -> c_int {
PyObject_TypeCheck(op, &mut PyFloat_Type)
}
#[inline(always)]
pub unsafe fn PyFloat_CheckExact(op : *mut PyObject) -> c_int {
(Py_TYPE(op) == &mut PyFloat_Type) as c_int
}
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub fn PyFloat_GetMax() -> c_double;
pub ... | PyFloat_Check | identifier_name |
floatobject.rs | use libc::{c_int, c_double};
use object::*;
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub static mut PyFloat_Type: PyTypeObject;
}
#[inline(always)]
pub unsafe fn PyFloat_Check(op : *mut PyObject) -> c_int |
#[inline(always)]
pub unsafe fn PyFloat_CheckExact(op : *mut PyObject) -> c_int {
(Py_TYPE(op) == &mut PyFloat_Type) as c_int
}
#[cfg_attr(windows, link(name="pythonXY"))] extern "C" {
pub fn PyFloat_GetMax() -> c_double;
pub fn PyFloat_GetMin() -> c_double;
pub fn PyFloat_GetInfo() -> *mut PyObject;... | {
PyObject_TypeCheck(op, &mut PyFloat_Type)
} | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup, Command
except ImportError:
from distutils.core import setup, Command
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
datadir = os.path.dirname(__file__)
with op... | (self):
pass
def finalize_options(self):
pass
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py', '-v'])
raise SystemExit(errno)
#data_files = [(path, [os.path.join(path, f) for f in files])
# for dir, dirs, fi... | initialize_options | identifier_name |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup, Command
except ImportError:
from distutils.core import setup, Command
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
datadir = os.path.dirname(__file__)
with op... |
def run(self):
import sys
import subprocess
errno = subprocess.call([sys.executable, 'runtests.py', '-v'])
raise SystemExit(errno)
#data_files = [(path, [os.path.join(path, f) for f in files])
# for dir, dirs, files in os.walk(datadir)]
#print(data_files)
setup(
name='pro... | pass | identifier_body |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup, Command
except ImportError:
from distutils.core import setup, Command
if sys.argv[-1] == 'publish':
os.system('python setup.py sdist upload')
sys.exit()
datadir = os.path.dirname(__file__)
with op... | long_description=readme + '\n\n' + history,
author='Wes Turner',
author_email='wes@wrd.nu',
url='https://github.com/westurner/provis',
packages=[
'provis',
],
package_dir={'provis': 'provis'},
include_package_data=True,
#data_files = data_files,
install_requires=[
],
... | description=(
'Infrastructure Provisioning Scripts, Configuration, and Tests'), | random_line_split |
setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
try:
from setuptools import setup, Command
except ImportError:
from distutils.core import setup, Command
if sys.argv[-1] == 'publish':
|
datadir = os.path.dirname(__file__)
with open(os.path.join(datadir, 'README.rst')) as f:
readme = f.read()
with open(os.path.join(datadir, 'HISTORY.rst')) as f:
history = f.read().replace('.. :changelog:', '')
class PyTestCommand(Command):
user_options = []
def initialize_options(self):
p... | os.system('python setup.py sdist upload')
sys.exit() | conditional_block |
events_test.py | # This file is a part of MediaDrop (http://www.mediadrop.net),
# Copyright 2009-2014 MediaDrop contributors
# For the exact contribution history, see the git revision log.
# The source code contained in this file is licensed under the GPLv3 or
# (at your option) any later version.
# See LICENSE.txt in the main project ... | unittest.main(defaultTest='suite') | conditional_block | |
events_test.py | # This file is a part of MediaDrop (http://www.mediadrop.net),
# Copyright 2009-2014 MediaDrop contributors
# For the exact contribution history, see the git revision log.
# The source code contained in this file is licensed under the GPLv3 or
# (at your option) any later version.
# See LICENSE.txt in the main project ... |
def probe(self):
self.observers_called += 1
def test_can_notify_all_observers(self):
self.event.post_observers.append(self.probe)
self.event.pre_observers.append(self.probe)
assert_equals(0, self.observers_called)
self.event()
assert_equals(2, ... | self.observers_called = 0
self.event = Event() | identifier_body |
events_test.py | # This file is a part of MediaDrop (http://www.mediadrop.net),
# Copyright 2009-2014 MediaDrop contributors
# For the exact contribution history, see the git revision log.
# The source code contained in this file is licensed under the GPLv3 or
# (at your option) any later version.
# See LICENSE.txt in the main project ... | assert_equals([1, None, 5, 'some value'], list(event()))
import unittest
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(EventTest))
suite.addTest(unittest.makeSuite(FetchFirstResultEventTest))
suite.addTest(unittest.makeSuite(GeneratorEventTest))
return suite
... | random_line_split | |
events_test.py | # This file is a part of MediaDrop (http://www.mediadrop.net),
# Copyright 2009-2014 MediaDrop contributors
# For the exact contribution history, see the git revision log.
# The source code contained in this file is licensed under the GPLv3 or
# (at your option) any later version.
# See LICENSE.txt in the main project ... | (self):
self.event.post_observers.append(self.probe)
self.event.pre_observers.append(self.probe)
assert_equals(0, self.observers_called)
self.event()
assert_equals(2, self.observers_called)
class FetchFirstResultEventTest(PythonicTestCase):
def test_returns_first_n... | test_can_notify_all_observers | identifier_name |
gulpfile.js | var fs = require('fs');
var gulp = require('gulp');
var $ = require('gulp-load-plugins')();
var del = require('del');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var runSequence = require('run-sequence');
var babelify = require('babeli... | var env = 'dev';
gulp.task('clean:dev', function() {
return del(['.tmp']);
});
gulp.task('clean:dist', function() {
return del(['dist']);
});
gulp.task('create-config', function(cb) {
fs.writeFile('app/config.json', JSON.stringify({
env: env,
}), cb);
});
gulp.task('scripts', function() {
var bundler ... | var mocha = require('gulp-mocha');
// require hook
require("babel/register");
| random_line_split |
brainruck.rs | use std::os;
use std::str;
use std::fmt;
fn main() {
let args = os::args();
if args.len() == 1 {
fail!("no arguments");
}
run(tokenize(parse_args(args)));
}
fn parse_args(args: ~[~str]) -> ~str {
args[1]
}
fn tokenize(text: ~str) -> Vec<Token> {
let mut tokens: Vec<Token> = Vec:... |
#[test]
fn testArgParser() {
assert_eq!(parse_args(["brainruck".to_owned(), "><+-.,[]".to_owned()].to_owned()),
"><+-.,[]".to_owned());
}
| {
// Check the tokenizer is getting the right outputs.
assert_eq!(tokenize("><+-.,[]".to_owned()).as_slice(),
[Right, Left, Plus, Minus, Out, In, Jump, Loop].as_slice());
// Make sure junk is ignored.
assert_eq!(tokenize(">a<b+c-d. ,1[2]3 ".to_owned()).as_slice(),
[Right, ... | identifier_body |
brainruck.rs | use std::os;
use std::str;
use std::fmt;
fn main() {
let args = os::args();
if args.len() == 1 {
fail!("no arguments");
}
run(tokenize(parse_args(args)));
}
fn parse_args(args: ~[~str]) -> ~str {
args[1]
}
fn tokenize(text: ~str) -> Vec<Token> {
let mut tokens: Vec<Token> = Vec:... | {
Right,
Left,
Plus,
Minus,
Out,
In,
Jump,
Loop
}
impl fmt::Show for Token {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f.buf, "{}", match *self {
Right => '>',
Left => '<',
Plus => '+',
Minus => '-',
... | Token | identifier_name |
brainruck.rs | use std::os;
use std::str;
use std::fmt;
fn main() {
let args = os::args();
if args.len() == 1 {
fail!("no arguments");
}
run(tokenize(parse_args(args)));
}
fn parse_args(args: ~[~str]) -> ~str {
args[1]
}
fn tokenize(text: ~str) -> Vec<Token> {
let mut tokens: Vec<Token> = Vec:... |
In => {
match std::io::stdin().read_byte() {
Ok(b) => {*data.get_mut(pointer) = b},
Err(e) => {fail!("{}", e)}
}
token_index += 1;
},
Jump => {
// Jump to end of the loop when t... | None => {}
}
token_index += 1;
}, | random_line_split |
object-lifetime-default-elision.rs | // Test various cases where the old rules under lifetime elision
// yield slightly different results than the new rules.
#![allow(dead_code)]
trait SomeTrait {
fn dummy(&self) { }
}
struct SomeStruct<'a> {
r: Box<dyn SomeTrait+'a>
}
fn deref<T>(ss: &T) -> T {
// produces the type of a deref without worr... | <'a>(ss: &'a Box<dyn SomeTrait>) -> Box<dyn SomeTrait> {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b> fn(&'a Box<SomeTrait+'b>) -> Box<SomeTrait+'a>
//
// Under new rules the result is:
//
// for<'a> fn(&'a Box<SomeTrait+'static>) -> Box<SomeTrait+'st... | load0 | identifier_name |
object-lifetime-default-elision.rs | // Test various cases where the old rules under lifetime elision
// yield slightly different results than the new rules. |
#![allow(dead_code)]
trait SomeTrait {
fn dummy(&self) { }
}
struct SomeStruct<'a> {
r: Box<dyn SomeTrait+'a>
}
fn deref<T>(ss: &T) -> T {
// produces the type of a deref without worrying about whether a
// move out would actually be legal
loop { }
}
fn load0<'a>(ss: &'a Box<dyn SomeTrait>) -> ... | random_line_split | |
object-lifetime-default-elision.rs | // Test various cases where the old rules under lifetime elision
// yield slightly different results than the new rules.
#![allow(dead_code)]
trait SomeTrait {
fn dummy(&self) { }
}
struct SomeStruct<'a> {
r: Box<dyn SomeTrait+'a>
}
fn deref<T>(ss: &T) -> T {
// produces the type of a deref without worr... |
fn load3<'a,'b>(ss: &'a dyn SomeTrait) -> &'b dyn SomeTrait {
// Under old rules, the fully elaborated types of input/output were:
//
// for<'a,'b,'c>fn(&'a (SomeTrait+'c)) -> &'b (SomeTrait+'a)
//
// Based on the input/output types, the compiler could infer that
// 'c : 'a
// 'b :... | {
// Same as `load1` but with an explicit name thrown in for fun.
ss
} | identifier_body |
db.js | var nano = require('nano');
var Q = require('q');
var exp = {
setup : setup,
nano : nano
}
function setup(config){
var d = Q.defer();
nano = nano(config.couchdbUrl);
function fin(){
design(config)
.then(function (cfg) {
var theDb = nano.db.use('liblib')
var dbq = {
view : fu... |
});
return d.promise;
},
fetch : Q.nbind(theDb.fetch, theDb),
insert : Q.nbind(theDb.insert, theDb),
list : Q.nbind(theDb.list, theDb),
get : Q.nbind(theDb.get, theDb),
destroy : Q.nbind(theDb.destroy, theDb)
}
var ret = {
config :... | {
d.resolve(data);
} | conditional_block |
db.js | var nano = require('nano');
var Q = require('q');
var exp = {
setup : setup,
nano : nano
}
function setup(config){
var d = Q.defer();
nano = nano(config.couchdbUrl);
function fin(){
design(config)
.then(function (cfg) {
var theDb = nano.db.use('liblib')
var dbq = {
view : fu... | })
}
nano.db.get('liblib', function(err, body){
if(err){
nano.db.create('liblib', function(err, body){
if(err){
d.reject(new Error("couchDB problem: " + err));
} else {
fin();
}
});
} else {
fin();
}
});
return d.promise;
}
function... | random_line_split | |
db.js | var nano = require('nano');
var Q = require('q');
var exp = {
setup : setup,
nano : nano
}
function setup(config){
var d = Q.defer();
nano = nano(config.couchdbUrl);
function | (){
design(config)
.then(function (cfg) {
var theDb = nano.db.use('liblib')
var dbq = {
view : function(view, params){
var d = Q.defer();
var design;
if(/\//.test(view)){
design = view.split('/')[0];
view = view.split('/')[1];
... | fin | identifier_name |
db.js | var nano = require('nano');
var Q = require('q');
var exp = {
setup : setup,
nano : nano
}
function setup(config){
var d = Q.defer();
nano = nano(config.couchdbUrl);
function fin(){
design(config)
.then(function (cfg) {
var theDb = nano.db.use('liblib')
var dbq = {
view : fu... | }
}
}, '_design/liblib', function (err, res) {
d.resolve(config);
});
return d.promise;
}
module.exports = exp
| {
var d = Q.defer();
nano.db.use(config.dbName).insert({
views : {
all : {
map : function(doc){
emit(doc.id);
}
}
},
lists : {
ul : function (head, req) {
provides('html', function(){
html = "<html><body><ul>\n";
while (row = getRow... | identifier_body |
about_monkey_patching.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Related to AboutOpenClasses in the Ruby Koans
#
from runner.koan import *
class AboutMonkeyPatching(Koan):
class | :
def bark(self):
return "WOOF"
def test_as_defined_dogs_do_bark(self):
fido = self.Dog()
self.assertEqual('WOOF', fido.bark())
# ------------------------------------------------------------------
# Add a new method to an existing class.
def test_after_patching_dog... | Dog | identifier_name |
about_monkey_patching.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Related to AboutOpenClasses in the Ruby Koans
#
from runner.koan import *
class AboutMonkeyPatching(Koan):
class Dog:
def bark(self):
return "WOOF"
def test_as_defined_dogs_do_bark(self):
fido = self.Dog()
self.assertEqual... | self.assertEqual('WOOF', fido.bark())
# ------------------------------------------------------------------
def test_most_built_in_classes_cannot_be_monkey_patched(self):
try:
int.is_even = lambda self: (self % 2) == 0
except Exception as ex:
err_msg = ex.args[0]... | def wag(self): return "HAPPY"
self.Dog.wag = wag
fido = self.Dog()
self.assertEqual('HAPPY', fido.wag()) | random_line_split |
about_monkey_patching.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Related to AboutOpenClasses in the Ruby Koans
#
from runner.koan import *
class AboutMonkeyPatching(Koan):
class Dog:
def bark(self):
return "WOOF"
def test_as_defined_dogs_do_bark(self):
fido = self.Dog()
self.assertEqual... |
# ------------------------------------------------------------------
class MyInt(int): pass
def test_subclasses_of_built_in_classes_can_be_be_monkey_patched(self):
self.MyInt.is_even = lambda self: (self % 2) == 0
self.assertEqual(False, self.MyInt(1).is_even())
self.assertEqual... | try:
int.is_even = lambda self: (self % 2) == 0
except Exception as ex:
err_msg = ex.args[0]
self.assertRegex(err_msg, "can't set attributes of built-in/extension type 'int'") | identifier_body |
de_LU@euro.js | (function(window, factory) {
if (typeof define === 'function' && define.amd) | else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (window.LocaleData = {}))['de_LU@euro'] = factory();
}
}(typeof window !== "undefined" ? window : this, function() {
return {
"LC_ADDRESS": {
... | {
define([], function() {
return factory();
});
} | conditional_block |
de_LU@euro.js | (function(window, factory) {
if (typeof define === 'function' && define.amd) {
define([], function() {
return factory();
});
} else if (typeof module === 'object' && typeof module.exports === 'object') {
module.exports = factory();
} else {
(window.LocaleData || (... | "tel_dom_fmt": null,
"int_select": "00",
"int_prefix": "352"
},
"LC_TIME": {
"date_fmt": "%a %b %e %H:%M:%S %Z %Y",
"abday": [
"So",
"Mo",
"Di",
"Mi",
"Do",
... | "height": 297,
"width": 210
},
"LC_TELEPHONE": {
"tel_int_fmt": "+%c %a %l", | random_line_split |
uglify-js-tests.ts | /// <reference path="uglify-js.d.ts" />
/// <reference path="../node/node.d.ts" />
import * as UglifyJS from 'uglify-js';
import * as fs from 'fs';
var result = UglifyJS.minify("/path/to/file.js");
console.log(result.code); // minified output
// if you need to pass code instead of file name
var result = UglifyJS.mini... | toplevel: toplevel
});
});
toplevel.figure_out_scope()
var compressor = UglifyJS.Compressor({});
var compressed_ast = toplevel.transform(compressor);
compressed_ast.figure_out_scope();
compressed_ast.compute_char_frequency();
compressed_ast.mangle_names();
var stream = UglifyJS.OutputStream({});
compres... | random_line_split | |
org-sidebar.ts | /// <reference path="../apimanPlugin.ts"/>
/// <reference path="../rpc.ts"/>
module Apiman {
export var OrgSidebarController = _module.controller("Apiman.OrgSidebarController",
['Logger', '$uibModal', '$scope', 'OrgSvcs', (Logger, $uibModal, $scope, OrgSvcs) => {
$scope.updateOrgDescription = fun... | });
};
// ----- Delete --------------------->>>>
// Add check for ability to delete, show/hide Delete option
$scope.canDelete = function() {};
// Call delete, open modal
$scope.callDelete = function(size) {
var modalInstance = ... | updateOrganizationBean,
function(success) {
},
function(error) {
Logger.error("Unable to update org description: {0}", error);
| random_line_split |
action.py | # -*- coding: utf-8 -*-
import re
import logging
from completor.utils import check_subseq
from .utils import parse_uri
word_pat = re.compile(r'([\d\w]+)', re.U)
word_ends = re.compile(r'[\d\w]+$', re.U)
logger = logging.getLogger("completor")
# [
# [{
# u'range': {
# u'start': {u'line': 273, u'ch... |
def gen_hover_doc(ft, value):
if ft not in escape_types:
return value
lines = []
for l in value.split("\n"):
if _shouldHidden(l):
continue
lines.append(escapes.sub(r"\1", l).replace(' ', ' '))
return "\n".join(lines)
def filter_items(items, input_data):
... | for item in hiddenLines:
if item in line:
return True
return False | identifier_body |
action.py | # -*- coding: utf-8 -*-
import re
import logging
from completor.utils import check_subseq
from .utils import parse_uri
word_pat = re.compile(r'([\d\w]+)', re.U)
word_ends = re.compile(r'[\d\w]+$', re.U)
logger = logging.getLogger("completor")
# [
# [{
# u'range': {
# u'start': {u'line': 273, u'ch... |
start = item['range']['start']
res.append({
'filename': uri,
'lnum': start['line'] + 1,
'col': start['character'] + 1,
'name': name,
})
return res
# [
# [
# {
# u'newText': u'',
# u'range': {
# ... | uri = uri.replace('%21', '!') | conditional_block |
action.py | # -*- coding: utf-8 -*-
import re
import logging
from completor.utils import check_subseq
from .utils import parse_uri
word_pat = re.compile(r'([\d\w]+)', re.U)
word_ends = re.compile(r'[\d\w]+$', re.U)
logger = logging.getLogger("completor")
# [
# [{
# u'range': {
# u'start': {u'line': 273, u'ch... | # }
# }, {
# u'newText': u'',
# u'range': {
# u'start': {u'line': 9, u'character': 0},
# u'end': {u'line': 10, u'character': 0}
# }
# }, {
# u'newText': u'\tfmt.Println()\n',
# u'range': {
# ... | random_line_split | |
action.py | # -*- coding: utf-8 -*-
import re
import logging
from completor.utils import check_subseq
from .utils import parse_uri
word_pat = re.compile(r'([\d\w]+)', re.U)
word_ends = re.compile(r'[\d\w]+$', re.U)
logger = logging.getLogger("completor")
# [
# [{
# u'range': {
# u'start': {u'line': 273, u'ch... | (ft, value):
if ft not in escape_types:
return value
lines = []
for l in value.split("\n"):
if _shouldHidden(l):
continue
lines.append(escapes.sub(r"\1", l).replace(' ', ' '))
return "\n".join(lines)
def filter_items(items, input_data):
target = ''
... | gen_hover_doc | identifier_name |
parser.js | this.peek().type === type) {
return this.advance();
} else {
throw new Error('expected "' + type + '", but got "' + this.peek().type + '"');
}
},
/**
* Accept the given `type`.
*
* @param {String} type
* @api private
*/
accept: function(type){
if (this.peek().type === ... | {
for (var i = 0, len = block.nodes.length; i < len; ++i) {
tag.block.push(block.nodes[i]);
}
} | conditional_block | |
parser.js | title'];
/**
* Parser prototype.
*/
Parser.prototype = {
/**
* Return the next token object.
*
* @return {Object}
* @api private
*/
advance: function(){
return this.lexer.advance();
},
/**
* Skip `n` tokens.
*
* @param {Number} n
* @api private
*/
skip: function(n){... | }
},
/**
* Accept the given `type`.
*
* @param {String} type
* @api private
*/
accept: function(type){
if (this.peek().type === type) {
return this.advance();
}
},
/**
* tag
* | doctype
* | mixin
* | include
* | filter
* | comment
* | text
* ... | expect: function(type){
if (this.peek().type === type) {
return this.advance();
} else {
throw new Error('expected "' + type + '", but got "' + this.peek().type + '"'); | random_line_split |
topic_index.py | def iter_dfs(self) :
for project in self._projects :
yield project
def getParent(self, project) :
"""
@return: None or project.parent
"""
try :
parentProjectName = project.parent.name.encode('utf-8')
except AttributeError :
par... |
def getAncestorsAndProject(self, project) :
return self.getAncestorProjects(project) + [project]
#---
class PageTree(object) :
def __init__(self, project, allPages) :
self._project = project
self._pages = list(allPages)
self._pagesByTitle = {} # title -> page
for page... | def _iterAncestors(project) :
parent = self.getParent(project)
if parent is None :
return
yield parent
for a in _iterAncestors(parent) :
yield a
return list(reversed(list(_iterAncestors(project)))) | identifier_body |
topic_index.py | def iter_dfs(self) :
for project in self._projects :
yield project
def getParent(self, project) :
"""
@return: None or project.parent
"""
try :
parentProjectName = project.parent.name.encode('utf-8')
except AttributeError :
par... | (self, page) :
def _iterAncestors(page) :
parent = self.getParent(page)
if parent is None :
return
yield parent
for a in _iterAncestors(parent) :
yield a
return list(reversed(list(_iterAncestors(page))))
def getAncest... | getAncestorPages | identifier_name |
topic_index.py | ))
def iter_dfs(self) :
for project in self._projects :
yield project
def getParent(self, project) :
"""
@return: None or project.parent
"""
try :
parentProjectName = project.parent.name.encode('utf-8')
except AttributeError :
... | yield ""
yield "h1. %s" % (topicParentPage,)
yield ""
yield "Diese Seite wurde automatisch generiert. Manuelle Änderungen an dieser Seite werden beim nächsten Lauf überschrieben werdern!"
yield ""
yield "h2. In diesem Projekt"
yield ""
yield "{{child_pages}}"
yield ""
yield "h2. ... | """
yield "{{>toc}}" | random_line_split |
topic_index.py | def iter_dfs(self) :
for project in self._projects :
yield project
def getParent(self, project) :
"""
@return: None or project.parent
"""
try :
parentProjectName = project.parent.name.encode('utf-8')
except AttributeError :
par... |
return parentProject
def getBreadcrumbTrail(self, project, encoding = 'utf-8') :
"""
@return: (..., parentName, projectName)
"""
return list(p.name.encode(encoding) for p in self.getAncestorsAndProject(project))
def getAncestorProjects(self, project) :
def _it... | parentProject = self._projectsByName.get(parentProjectName, None)
if 0 :
print "DEBUG: parentName = %r" % (parentProjectName,)
print "DEBUG: parentObject %r" % (parentProject,) | conditional_block |
index.ts | import { Option, Player, Difficulty } from "../models";
export type Action =
INextPlayer
| ISelectOption
| ICheckWinner
| IResetGame
| ISetDifficulty;
// Next Player
interface INextPlayer { | export const nextPlayer = (): INextPlayer => {
return {
type: "NEXT_PLAYER"
}
};
// Select Option
interface ISelectOption {
type: "SELECT_OPTION";
option: Option;
}
export const selectOption = (option: Option): ISelectOption => {
return {
type: "SELECT_OPTION",
option: opt... | type: "NEXT_PLAYER";
}
| random_line_split |
overlord-dynamic-config-dialog.tsx | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... |
componentDidMount() {
this.getConfig();
this.historyQueryManager.runQuery(`dummy`);
}
async getConfig() {
let config: Record<string, any> | undefined;
try {
const configResp = await axios.get('/druid/indexer/v1/worker');
config = configResp.data || {};
} catch (e) {
AppTo... | {
super(props);
this.state = {
historyRecords: [],
};
this.historyQueryManager = new QueryManager({
processQuery: async () => {
const historyResp = await axios(`/druid/indexer/v1/worker/history?count=100`);
return historyResp.data;
},
onStateChange: ({ result }) ... | identifier_body |
overlord-dynamic-config-dialog.tsx | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | extends React.PureComponent<
OverlordDynamicConfigDialogProps,
OverlordDynamicConfigDialogState
> {
private historyQueryManager: QueryManager<string, any>;
constructor(props: OverlordDynamicConfigDialogProps) {
super(props);
this.state = {
historyRecords: [],
};
this.historyQueryManager... | OverlordDynamicConfigDialog | identifier_name |
overlord-dynamic-config-dialog.tsx | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you ... | type: 'json',
},
{
name: 'autoScaler',
type: 'json',
},
]}
model={dynamicConfig}
onChange={m => this.setState({ dynamicConfig: m })}
/>
</SnitchDialog>
);
}
} | {
name: 'selectStrategy', | random_line_split |
uint.rs | // Copyright 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-MIT or ... |
#[cfg(target_endian = "little")]
pub fn to_be(x: uint) -> uint {
bswap(x)
}
#[cfg(target_endian = "big")]
pub fn to_le(x: uint) -> uint {
bswap(x)
}
#[cfg(target_endian = "little")]
pub fn to_le(x: uint) -> uint {
x
}
| {
x
} | identifier_body |
uint.rs | // Copyright 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-MIT or ... | #[inline(always)]
pub fn add_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::add_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[cfg(target_word_size = "32")]
#[inline(always)]
pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::sub_with_overflow(x a... | }
#[cfg(target_word_size = "64")] | random_line_split |
uint.rs | // Copyright 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-MIT or ... | (x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u32::sub_with_overflow(x as u32, y as u32);
(a as uint, b)
}
#[cfg(target_word_size = "64")]
#[inline(always)]
pub fn sub_with_overflow(x: uint, y: uint) -> (uint, bool) {
let (a, b) = ::u64::sub_with_overflow(x as u64, y as u64);
(a as uint, b)
}
#[... | sub_with_overflow | identifier_name |
nycmta.py | #sudo -H pip2 install gtfs-realtime-bindings
from google.transit import gtfs_realtime_pb2
import urllib
from pprint import pprint
#sudo -H pip2 install protobuf_to_dict
from protobuf_to_dict import protobuf_to_dict
from itertools import chain
#for deciding if the arduino should light up
import datetime
#for comparing ... |
#send the lights to arduino
def light_send():
#ser.write(light_string)
#figure out the current date and time
d = datetime.datetime.now()
#during the week
if d.weekday() in range(0, 6):
#is it between 7am and 9pm
#DONT USE () FOR HOURS
if d.hour in range(8, 22):
... | for item in arrival_list:
#convert the number to a number and see if it is in this
if 1 <= int(item) <= 8:
#if it is, add it to the list to send to the arduino
light_list.append(light_one)
elif 8 < int(item) <= 12:
light_list.append(light_two)
elif 12 ... | identifier_body |
nycmta.py | #sudo -H pip2 install gtfs-realtime-bindings
from google.transit import gtfs_realtime_pb2
import urllib
from pprint import pprint
#sudo -H pip2 install protobuf_to_dict
from protobuf_to_dict import protobuf_to_dict
from itertools import chain
#for deciding if the arduino should light up
import datetime
#for comparing ... |
else:
ser.write(off_string)
print "lights would be off"
print off_string
#on the weekend
elif d.weekday() in range(5, 7):
#between 8am and 10pm
if d.hour in range (9, 22):
ser.write(light_string);
print "lights would be on week... | ser.write(light_string)
print "lights would be on weekday"
print light_string | conditional_block |
nycmta.py | #sudo -H pip2 install gtfs-realtime-bindings
from google.transit import gtfs_realtime_pb2
import urllib
from pprint import pprint
#sudo -H pip2 install protobuf_to_dict
from protobuf_to_dict import protobuf_to_dict
from itertools import chain
#for deciding if the arduino should light up
import datetime
#for comparing ... |
print "sleeping for 20 seconds"
time.sleep(20) | random_line_split | |
nycmta.py | #sudo -H pip2 install gtfs-realtime-bindings
from google.transit import gtfs_realtime_pb2
import urllib
from pprint import pprint
#sudo -H pip2 install protobuf_to_dict
from protobuf_to_dict import protobuf_to_dict
from itertools import chain
#for deciding if the arduino should light up
import datetime
#for comparing ... | (station_ID, station_URL):
try:
#grabs the feed
feed = gtfs_realtime_pb2.FeedMessage()
response = urllib.urlopen(station_URL)
feed.ParseFromString(response.read())
#turns the feed into a dictionary
useful_dict = protobuf_to_dict(feed)
#this is the list of s... | grabber | identifier_name |
VerifiedSeller.tsx | import { VerifiedIcon } from "@artsy/palette"
import { VerifiedSeller_artwork } from "__generated__/VerifiedSeller_artwork.graphql"
import React from "react"
import { createFragmentContainer } from "react-relay"
import { graphql } from "react-relay"
import { TrustSignal, TrustSignalProps } from "./TrustSignal"
interfa... |
export const VerifiedSeller: React.FC<VerifiedSellerProps> = ({
artwork,
...other
}) => {
return (
!artwork.is_biddable &&
artwork.partner &&
artwork.partner.isVerifiedSeller && (
<TrustSignal
Icon={<VerifiedIcon />}
label="Verified seller"
description={`${artwork.partne... | random_line_split | |
ToDataFrameWithDatasetColumn.py | # Tai Sakuma <tai.sakuma@gmail.com>
import pandas as pd
from .ToTupleListWithDatasetColumn import ToTupleListWithDatasetColumn
##__________________________________________________________________||
class ToDataFrameWithDatasetColumn:
def __init__(self, summaryColumnNames,
datasetColumnName = 'co... | self.to_tuple_list = ToTupleListWithDatasetColumn(
summaryColumnNames = summaryColumnNames,
datasetColumnName = datasetColumnName)
def __repr__(self):
name_value_pairs = (
('summaryColumnNames', self.summaryColumnNames),
('datasetColumnName', self.d... |
self.summaryColumnNames = summaryColumnNames
self.datasetColumnName = datasetColumnName | random_line_split |
ToDataFrameWithDatasetColumn.py | # Tai Sakuma <tai.sakuma@gmail.com>
import pandas as pd
from .ToTupleListWithDatasetColumn import ToTupleListWithDatasetColumn
##__________________________________________________________________||
class ToDataFrameWithDatasetColumn:
def __init__(self, summaryColumnNames,
datasetColumnName = 'co... |
header = tuple_list[0]
contents = tuple_list[1:]
return pd.DataFrame(contents, columns = header)
##__________________________________________________________________||
| return None | conditional_block |
ToDataFrameWithDatasetColumn.py | # Tai Sakuma <tai.sakuma@gmail.com>
import pandas as pd
from .ToTupleListWithDatasetColumn import ToTupleListWithDatasetColumn
##__________________________________________________________________||
class ToDataFrameWithDatasetColumn:
def __init__(self, summaryColumnNames,
datasetColumnName = 'co... |
def combine(self, dataset_readers_list):
tuple_list = self.to_tuple_list.combine(dataset_readers_list)
if tuple_list is None:
return None
header = tuple_list[0]
contents = tuple_list[1:]
return pd.DataFrame(contents, columns = header)
##________________________... | name_value_pairs = (
('summaryColumnNames', self.summaryColumnNames),
('datasetColumnName', self.datasetColumnName),
)
return '{}({})'.format(
self.__class__.__name__,
', '.join(['{} = {!r}'.format(n, v) for n, v in name_value_pairs]),
) | identifier_body |
ToDataFrameWithDatasetColumn.py | # Tai Sakuma <tai.sakuma@gmail.com>
import pandas as pd
from .ToTupleListWithDatasetColumn import ToTupleListWithDatasetColumn
##__________________________________________________________________||
class ToDataFrameWithDatasetColumn:
def __init__(self, summaryColumnNames,
datasetColumnName = 'co... | (self):
name_value_pairs = (
('summaryColumnNames', self.summaryColumnNames),
('datasetColumnName', self.datasetColumnName),
)
return '{}({})'.format(
self.__class__.__name__,
', '.join(['{} = {!r}'.format(n, v) for n, v in name_value_pairs]),
... | __repr__ | identifier_name |
local.js | /**
* This is specifically for the builder where the
* dependencies have been resolved and you just want
* to access the component.jsons locally.
*/
var semver = require('semver');
var fs = require('graceful-fs');
var join = require('path').join;
var resolve = require('path').resolve;
var debug = require('debug')(... | options = Object.create(options || {});
this.out = resolve(options.out
|| options.dir
|| 'components')
debug('checking local components at %s', this.out);
Remote.call(this, options)
}
Local.prototype.name = 'local';
/**
* Local resolution is a little different than other remotes.
* In particular, ... | function Local(options) {
if (!(this instanceof Local))
return new Local(options)
| random_line_split |
local.js | /**
* This is specifically for the builder where the
* dependencies have been resolved and you just want
* to access the component.jsons locally.
*/
var semver = require('semver');
var fs = require('graceful-fs');
var join = require('path').join;
var resolve = require('path').resolve;
var debug = require('debug')(... |
function noLeadingDot(x) {
return x[0] !== '.';
}
function readdir(root) {
return function (done) {
fs.readdir(root, done)
}
}
function read(filename) {
return function (done) {
fs.readFile(filename, 'utf8', done)
}
}
| {
return semver.valid(x, true);
} | identifier_body |
local.js | /**
* This is specifically for the builder where the
* dependencies have been resolved and you just want
* to access the component.jsons locally.
*/
var semver = require('semver');
var fs = require('graceful-fs');
var join = require('path').join;
var resolve = require('path').resolve;
var debug = require('debug')(... | (filename) {
return function (done) {
fs.readFile(filename, 'utf8', done)
}
}
| read | identifier_name |
polyfills.ts | /**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported... | // import 'intl/locale-data/jsonp/en'; | */ | random_line_split |
unzip.d.ts | import * as _ from "../index";
declare module "../index" {
interface LoDashStatic {
/**
* This method is like _.zip except that it accepts an array of grouped elements and creates an array
* regrouping the elements to their pre-zip configuration.
*
* @param array The arra... |
interface LoDashExplicitWrapper<TValue> {
/**
* @see _.unzip
*/
unzip<T>(this: LoDashExplicitWrapper<T[][] | List<List<T>> | null | undefined>): LoDashExplicitWrapper<T[][]>;
}
} | */
unzip<T>(this: LoDashImplicitWrapper<T[][] | List<List<T>> | null | undefined>): LoDashImplicitWrapper<T[][]>;
} | random_line_split |
chromeManifestModify.js | }
}
}
function copyModifyFile(to,flagContent,flagBackground,isWebExt){
if(flagContent){
const cont = fs.readFileSync(path.join(__dirname,'../src/extension/contentScriptModify.js')).toString()
const contPath = path.join(to,contentScriptName)
if(fs.existsSync(contPath)) fs.unlinkSync(contPath)
fs... | infos.browser_action.enable = infos.browser_action.show
delete infos.browser_action.show
}
if(infos.browser_action.hide){
infos.browser_action.disable = infos.browser_action.hide
delete infos.browser_action.hide
}
}
delete in... | random_line_split | |
chromeManifestModify.js | }
}
}
function copyModifyFile(to,flagContent,flagBackground,isWebExt){
if(flagContent){
const cont = fs.readFileSync(path.join(__dirname,'../src/extension/contentScriptModify.js')).toString()
const contPath = path.join(to,contentScriptName)
if(fs.existsSync(contPath)) fs.unlinkSync(contPath)
fs... | }
if(infos.optional_permissions){
infos.permissions = [...new Set([...(infos.permissions || []),...infos.optional_permissions])]
}
if(!infos.content_security_policy){
infos.content_security_policy = "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
if(isWebExt && infos.permis... | {
const isWebExt = !extensionId.match(/(^[a-z]+$)|(_chrome_$)/)
cache = new Set()
if(!verPath){
verPath = getPath2(extensionId) || getPath1(extensionId) //getPath1(extensionId)
}
const manifestPath = path.join(verPath, 'manifest.json')
const exists = fs.existsSync(manifestPath)
if (exists) {
cons... | identifier_body |
chromeManifestModify.js | }
}
}
function copyModifyFile(to,flagContent,flagBackground,isWebExt){
if(flagContent){
const cont = fs.readFileSync(path.join(__dirname,'../src/extension/contentScriptModify.js')).toString()
const contPath = path.join(to,contentScriptName)
if(fs.existsSync(contPath)) fs.unlinkSync(contPath)
fs... | (verPath,fname,isWebExt){
const dirName = path.dirname(fname)
const backStr = dirName == '.' ? dirName : dirName.split(/[\/\\]/).map(x=>'..').join('/')
console.log(verPath,fname,dirName,backStr)
const fullPath = path.join(verPath,dirName,path.basename(fname).split("?")[0])
if(cache.has(fullPath) || !fs.exists... | htmlModify | identifier_name |
chromeManifestModify.js | }
}
}
function copyModifyFile(to,flagContent,flagBackground,isWebExt){
if(flagContent){
const cont = fs.readFileSync(path.join(__dirname,'../src/extension/contentScriptModify.js')).toString()
const contPath = path.join(to,contentScriptName)
if(fs.existsSync(contPath)) fs.unlinkSync(contPath)
fs... |
if(infos.options_page){
htmlModify(verPath,infos.options_page,isWebExt)
flagBackground = true
}
if(infos.options_ui && infos.options_ui.page){
if(!infos.options_page) infos.options_page = infos.options_ui.page
htmlModify(verPath,infos.options_ui.page,isWebExt)
... | {
if(infos.background.persistent === false && !['jpkfjicglakibpenojifdiepckckakgk','occjjkgifpmdgodlplnacmkejpdionan'].includes(extensionId)){
infos.background.persistent = true
}
if(infos.background.page){
htmlModify(verPath,infos.background.page,isWebExt)
}
... | conditional_block |
pipeline.js | /**
* grunt/pipeline.js
*
* The order in which your css, javascript, and template files should be
* compiled and linked from your views and static HTML files.
*
* (Note that you can take advantage of Grunt-style wildcard/glob/splat expressions
* for matching multiple files.)
*/
// CSS files to inject in orde... | 'js/dependencies/jquery-2.1.1.min.js',
'js/dependencies/**/*.js',
// '!js/dependencies/language/**',
// '!js/vendor/*.js',
// All of the rest of your client-side js files
// will be injected here in no particular order.
// 'js/**/*.js'
];
// Client-side HTML templates are injected using the sources bel... | 'js/dependencies/sails.io.js',
// Dependencies like jQuery, or Angular are brought in here | random_line_split |
reward.rs | // Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed ... | // Copyright 2021 The Grin Developers
// | random_line_split | |
reward.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | <K, B>(
keychain: &K,
builder: &B,
key_id: &Identifier,
fees: u64,
test_mode: bool,
) -> Result<(Output, TxKernel), Error>
where
K: Keychain,
B: ProofBuild,
{
let value = reward(fees);
// TODO: proper support for different switch commitment schemes
let switch = SwitchCommitmentType::Regular;
let commit = key... | output | identifier_name |
reward.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... | let msg = features.kernel_sig_msg()?;
let sig = match test_mode {
true => {
let test_nonce = secp::key::SecretKey::from_slice(&secp, &[1; 32])?;
aggsig::sign_from_key_id(
&secp,
keychain,
&msg,
value,
&key_id,
Some(&test_nonce),
Some(&pubkey),
)?
}
false => {
aggsig::sign... | {
let value = reward(fees);
// TODO: proper support for different switch commitment schemes
let switch = SwitchCommitmentType::Regular;
let commit = keychain.commit(value, key_id, switch)?;
trace!("Block reward - Pedersen Commit is: {:?}", commit,);
let proof = proof::create(keychain, builder, value, key_id, sw... | identifier_body |
reward.rs | // Copyright 2021 The Grin Developers
//
// 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 agree... |
false => {
aggsig::sign_from_key_id(&secp, keychain, &msg, value, &key_id, None, Some(&pubkey))?
}
};
let kernel = TxKernel {
features: KernelFeatures::Coinbase,
excess,
excess_sig: sig,
};
Ok((output, kernel))
}
| {
let test_nonce = secp::key::SecretKey::from_slice(&secp, &[1; 32])?;
aggsig::sign_from_key_id(
&secp,
keychain,
&msg,
value,
&key_id,
Some(&test_nonce),
Some(&pubkey),
)?
} | conditional_block |
columnOptionsMock.ts | /*
* Copyright 2017 TWO SIGMA OPEN SOURCE, 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 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 languag... | random_line_split | |
FileItem.tsx | import React from 'react'
import cx from 'classnames'
import {Fade} from '../ui'
import {LayerRender} from '../types'
import VisibilityButton from './VisibilityButton'
type Props = LayerRender & {showFilenames: boolean}
const TYPE_UNKNOWN = 'unknown'
const STYLE = 'flex items-center h2 mb2 pl3 br3 overflow-hidden b... | {
const {id, side, type, converter, filename, color, showFilenames} = props
return (
<li className={STYLE}>
<p className={cx(TYPE_STYLE, {[TYPE_STYLE_EXPANDED]: showFilenames})}>
{type || TYPE_UNKNOWN}
</p>
<Fade in={showFilenames}>
<p className={FILENAME_STYLE}>{filename}</p... | identifier_body | |
FileItem.tsx | import React from 'react'
import cx from 'classnames'
import {Fade} from '../ui'
import {LayerRender} from '../types'
import VisibilityButton from './VisibilityButton'
type Props = LayerRender & {showFilenames: boolean}
const TYPE_UNKNOWN = 'unknown'
const STYLE = 'flex items-center h2 mb2 pl3 br3 overflow-hidden b... | (props: Props): JSX.Element {
const {id, side, type, converter, filename, color, showFilenames} = props
return (
<li className={STYLE}>
<p className={cx(TYPE_STYLE, {[TYPE_STYLE_EXPANDED]: showFilenames})}>
{type || TYPE_UNKNOWN}
</p>
<Fade in={showFilenames}>
<p className={F... | FileItem | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.