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
token_request_handler.d.ts
import { AuthorizationServiceConfiguration } from './authorization_service_configuration'; import { QueryStringUtils } from './query_string_utils'; import { RevokeTokenRequest } from './revoke_token_request'; import { TokenRequest } from './token_request'; import { TokenResponse } from './token_response'; import { Requ...
performTokenRequest(configuration: AuthorizationServiceConfiguration, request: TokenRequest): Promise<TokenResponse>; }
random_line_split
token_request_handler.d.ts
import { AuthorizationServiceConfiguration } from './authorization_service_configuration'; import { QueryStringUtils } from './query_string_utils'; import { RevokeTokenRequest } from './revoke_token_request'; import { TokenRequest } from './token_request'; import { TokenResponse } from './token_response'; import { Requ...
implements TokenRequestHandler { readonly requestor: Requestor; readonly utils: QueryStringUtils; constructor(requestor?: Requestor, utils?: QueryStringUtils); private isTokenResponse; performRevokeTokenRequest(configuration: AuthorizationServiceConfiguration, request: RevokeTokenRequest): Promise<...
BaseTokenRequestHandler
identifier_name
ptr.rs
/*! Typed virtual address. */ use std::{cmp, fmt, hash, mem, str}; use std::marker::PhantomData; use crate::Pod; use super::image::{Va, SignedVa}; /// Typed virtual address. #[repr(transparent)] pub struct Ptr<T: ?Sized = ()> { va: Va, marker: PhantomData<fn() -> T> } impl<T: ?Sized> Ptr<T> { // Work around uns...
impl<T: ?Sized> fmt::Display for Ptr<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let buf = Ptr::fmt(*self); f.write_str(unsafe { str::from_utf8_unchecked(&buf) }) } } #[cfg(feature = "serde")] impl<T: ?Sized> serde::Serialize for Ptr<T> { fn serialize<S: serde::Serializer>(&self, serializer: S) ...
random_line_split
ptr.rs
/*! Typed virtual address. */ use std::{cmp, fmt, hash, mem, str}; use std::marker::PhantomData; use crate::Pod; use super::image::{Va, SignedVa}; /// Typed virtual address. #[repr(transparent)] pub struct Ptr<T: ?Sized = ()> { va: Va, marker: PhantomData<fn() -> T> } impl<T: ?Sized> Ptr<T> { // Work around uns...
(&self, rhs: &Ptr<T>) -> bool { self.va == rhs.va } } impl<T: ?Sized> PartialOrd for Ptr<T> { fn partial_cmp(&self, rhs: &Ptr<T>) -> Option<cmp::Ordering> { self.va.partial_cmp(&rhs.va) } } impl<T: ?Sized> Ord for Ptr<T> { fn cmp(&self, rhs: &Ptr<T>) -> cmp::Ordering { self.va.cmp(&rhs.va) } } impl<T: ?Sized...
eq
identifier_name
ptr.rs
/*! Typed virtual address. */ use std::{cmp, fmt, hash, mem, str}; use std::marker::PhantomData; use crate::Pod; use super::image::{Va, SignedVa}; /// Typed virtual address. #[repr(transparent)] pub struct Ptr<T: ?Sized = ()> { va: Va, marker: PhantomData<fn() -> T> } impl<T: ?Sized> Ptr<T> { // Work around uns...
} impl<T: ?Sized> Eq for Ptr<T> {} impl<T: ?Sized> PartialEq for Ptr<T> { fn eq(&self, rhs: &Ptr<T>) -> bool { self.va == rhs.va } } impl<T: ?Sized> PartialOrd for Ptr<T> { fn partial_cmp(&self, rhs: &Ptr<T>) -> Option<cmp::Ordering> { self.va.partial_cmp(&rhs.va) } } impl<T: ?Sized> Ord for Ptr<T> { fn cmp(&...
{ Ptr::NULL }
identifier_body
ptr.rs
/*! Typed virtual address. */ use std::{cmp, fmt, hash, mem, str}; use std::marker::PhantomData; use crate::Pod; use super::image::{Va, SignedVa}; /// Typed virtual address. #[repr(transparent)] pub struct Ptr<T: ?Sized = ()> { va: Va, marker: PhantomData<fn() -> T> } impl<T: ?Sized> Ptr<T> { // Work around uns...
else { b'a' + (digit - 10) }; s[i + 2] = chr; } return s; } } impl<T> Ptr<[T]> { /// Decays the pointer from `[T]` to `T`. pub const fn decay(self) -> Ptr<T> { Ptr { va: self.va, marker: Ptr::<T>::MARKER } } /// Pointer arithmetic, gets the pointer of an element at the specified index. pub const fn at(s...
{ b'0' + digit }
conditional_block
solflag.py
# solflag.py: # # Copyright (C) 2007 # ASTRON (Netherlands Institute for Radio Astronomy) # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public L...
(db, elements, stations, directions=None): result = None if directions is None: for i in range(0, len(elements)): (ampl, phase) = solfetch.fetch(db, stations, parm="Gain:%s" % elements[i]) # Allocate result array if necessary. if result is None: ...
__fetch
identifier_name
solflag.py
# solflag.py: # # Copyright (C) 2007 # ASTRON (Netherlands Institute for Radio Astronomy) # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public L...
else: for i in range(0, len(elements)): for j in range(0, len(directions)): # Fetch solutions. (ampl, phase) = solfetch.fetch(db, stations, parm="DirectionalGain:%s" % elements[i], direction=directions[j]) ...
for i in range(0, len(elements)): (ampl, phase) = solfetch.fetch(db, stations, parm="Gain:%s" % elements[i]) # Allocate result array if necessary. if result is None: result = numpy.zeros((len(elements), 1, len(stations), ampl.shape...
conditional_block
solflag.py
# solflag.py: # # Copyright (C) 2007 # ASTRON (Netherlands Institute for Radio Astronomy) # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public L...
assert(result[i][j].shape == ampl.shape) result[i][j] = ampl return result
# Copy solutions into result array.
random_line_split
solflag.py
# solflag.py: # # Copyright (C) 2007 # ASTRON (Netherlands Institute for Radio Astronomy) # P.O.Box 2, 7990 AA Dwingeloo, The Netherlands # # This file is part of the LOFAR software suite. # The LOFAR software suite is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public L...
parm="DirectionalGain:%s" % elements[i], direction=directions[j]) # Allocate result array if necessary. if result is None: result = numpy.zeros((len(elements), len(directions), len(stations), ampl.shape[...
result = None if directions is None: for i in range(0, len(elements)): (ampl, phase) = solfetch.fetch(db, stations, parm="Gain:%s" % elements[i]) # Allocate result array if necessary. if result is None: result = numpy.zeros((len(elements)...
identifier_body
test_generator.py
import unittest from vsvbp.container import Item, Bin, Instance from vsvbp.generator import generator
def setUp(self): self.i1 = Item([1,2,9]); self.i2 = Item([4,5,3]) self.i3 = Item([0,1,0]); self.i4 = Item([9,8,7]) self.i1.size = 1; self.i2.size = 2; self.i3.size = 3; self.i4.size = 0; self.items = [self.i4, self.i3, self.i2, self.i1] self.b1=Bin([5,8,4]); self.b2=Bin([100,...
class ItemBinTestCase(unittest.TestCase):
random_line_split
test_generator.py
import unittest from vsvbp.container import Item, Bin, Instance from vsvbp.generator import generator class ItemBinTestCase(unittest.TestCase):
def setUp(self): self.i1 = Item([1,2,9]); self.i2 = Item([4,5,3]) self.i3 = Item([0,1,0]); self.i4 = Item([9,8,7]) self.i1.size = 1; self.i2.size = 2; self.i3.size = 3; self.i4.size = 0; self.items = [self.i4, self.i3, self.i2, self.i1] self.b1=Bin([5,8,4]); self.b2=Bin([100,0,10...
identifier_body
test_generator.py
import unittest from vsvbp.container import Item, Bin, Instance from vsvbp.generator import generator class ItemBinTestCase(unittest.TestCase): def
(self): self.i1 = Item([1,2,9]); self.i2 = Item([4,5,3]) self.i3 = Item([0,1,0]); self.i4 = Item([9,8,7]) self.i1.size = 1; self.i2.size = 2; self.i3.size = 3; self.i4.size = 0; self.items = [self.i4, self.i3, self.i2, self.i1] self.b1=Bin([5,8,4]); self.b2=Bin([100,0,100]); self...
setUp
identifier_name
model.ts
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { Point } from "../../utils/geometry"; imp...
} export function isLocateable(element: SModelElement): element is SModelElement & Locateable { return (element as any)['position'] !== undefined; } export function isMoveable(element: SModelElement): element is SModelElement & Locateable { return element.hasFeature(moveFeature) && isLocateable(element); }
* An element that can be placed at a specific location using its position * property. */ export interface Locateable extends SModelExtension { position: Point
random_line_split
model.ts
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { Point } from "../../utils/geometry"; imp...
(element: SModelElement): element is SModelElement & Locateable { return (element as any)['position'] !== undefined; } export function isMoveable(element: SModelElement): element is SModelElement & Locateable { return element.hasFeature(moveFeature) && isLocateable(element); }
isLocateable
identifier_name
model.ts
/* * Copyright (C) 2017 TypeFox and others. * * 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 */ import { Point } from "../../utils/geometry"; imp...
{ return element.hasFeature(moveFeature) && isLocateable(element); }
identifier_body
BindProperty.ts
/// <reference path="../../../../declarations/jquery/jquery.d.ts" /> /// <reference path="../logging/logmanager.ts" /> namespace a7 { export function bindProperty(selector: string = null) { return function (target: any, propertyKey: string) { var _val: JQuery; var getter = func...
enumerable: true, configurable: true }); } } } }
random_line_split
BindProperty.ts
/// <reference path="../../../../declarations/jquery/jquery.d.ts" /> /// <reference path="../logging/logmanager.ts" /> namespace a7 { export function bindProperty(selector: string = null) {
if (!_val.length) { this._logger.error('Could not auto bind property ' + propertyKey + '. Could not find html element via selectors' + selector ? ' ' + selector + ', ' : '' + ' [name=' + actualName + '] or [name=' + camelizedName + ']'); } ...
return function (target: any, propertyKey: string) { var _val: JQuery; var getter = function () { if (!_val) { var actualName = propertyKey.indexOf('_') == 0 ? propertyKey.substr(1, propertyKey.length - 1) : propertyKey, cam...
identifier_body
BindProperty.ts
/// <reference path="../../../../declarations/jquery/jquery.d.ts" /> /// <reference path="../logging/logmanager.ts" /> namespace a7 { export function bi
elector: string = null) { return function (target: any, propertyKey: string) { var _val: JQuery; var getter = function () { if (!_val) { var actualName = propertyKey.indexOf('_') == 0 ? propertyKey.substr(1, propertyKey.length - 1) : propertyKey, ...
ndProperty(s
identifier_name
BindProperty.ts
/// <reference path="../../../../declarations/jquery/jquery.d.ts" /> /// <reference path="../logging/logmanager.ts" /> namespace a7 { export function bindProperty(selector: string = null) { return function (target: any, propertyKey: string) { var _val: JQuery; var getter = func...
} } }
Object.defineProperty(target, propertyKey, { get: getter, set: function (newVal) { _val = newVal; }, enumerable: true, configurable: true }); }
conditional_block
hostkeys.py
We don't bother to check for comments or empty lines. All of that should be taken care of before sending the line to us. @param line: a line from an OpenSSH known_hosts file @type line: str """ log = get_logger('paramiko.hostkeys') fields = line.split(' ') if l...
values
identifier_name
hostkeys.py
import binascii from Crypto.Hash import SHA, HMAC try: import UserDict import DictMixin except: from collections import UserDict #from collections import MutableMapping as DictMixin from collections import Mapping as DictMixin from paramiko.common import * from paramiko.dsskey import DSSKey from p...
def __repr__(self): return '<HostKeyEntry %r: %r>' % (self.hostnames, self.key) class HostKeys (DictMixin): """ Representation of an openssh-style "known hosts" file. Host keys can be read from one or more files, and then individual hosts can be looked up to verify server keys during SS...
""" Returns a string in OpenSSH known_hosts file format, or None if the object is not in a valid state. A trailing newline is included. """ if self.valid: return '%s %s %s\n' % (','.join(self.hostnames), self.key.get_name(), self.key.get_base64()) ...
identifier_body
hostkeys.py
binascii from Crypto.Hash import SHA, HMAC try: import UserDict import DictMixin except: from collections import UserDict #from collections import MutableMapping as DictMixin from collections import Mapping as DictMixin from paramiko.common import * from paramiko.dsskey import DSSKey from paramik...
if len(entries) == 0: return None return SubDict(hostname, entries, self) def check(self, hostname, key): """ Return True if the given key is associated with the given hostname in this dictionary. @param hostname: hostname (or IP) of the SSH server ...
entries.append(e)
conditional_block
hostkeys.py
import binascii from Crypto.Hash import SHA, HMAC try: import UserDict import DictMixin except: from collections import UserDict #from collections import MutableMapping as DictMixin from collections import Mapping as DictMixin from paramiko.common import * from paramiko.dsskey import DSSKey from p...
@since: 1.5.3 """ def __init__(self, filename=None): """ Create a new HostKeys object, optionally loading keys from an openssh style host-key file. @param filename: filename to load host keys from, or C{None} @type filename: str """ # emulate a dict ...
to calling L{lookup}.
random_line_split
sniffer_task.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 std::comm::{channel, Receiver, Sender}; use std::task::TaskBuilder; use resource_task::{TargetedLoadResponse}; pub type SnifferTask = Sender<TargetedLoadResponse>; pub fn new_sniffer_task() -> SnifferTask { let(sen, rec) = channel(); let builder = TaskBuilder::new().named("SnifferManager"); builder.sp...
//! A task that sniffs data
random_line_split
sniffer_task.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! A task that sniffs data use std::comm::{channel, Receiver, Sender}; use std::task::TaskBuilder; use resource_t...
(self) { loop { match self.data_receiver.recv_opt() { Ok(snif_data) => { let _ = snif_data.consumer.send_opt(snif_data.load_response); } Err(_) => break, } } } }
start
identifier_name
usecase_spadderPluginTester.py
# -*- coding: iso-8859-1 -*- # Copyright (C) 2011-2014 EDF R&D # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later versio...
# Author(s): Guillaume Boulant (23/03/2011) # # This script illustrates the standard use case of the component # SPADDERPluginTester from within a SALOME script. This component is # dedicated to test purpose only import salome import SPADDERPluginTest # We first have to update the SALOME components list by loading t...
random_line_split
image_spec.js
describe("Image", function() { beforeEach(function() { $("body").append($('<div id="sandbox"></div>')); }); afterEach(function() { $('#sandbox').remove(); $('.ui-dialog').remove(); }); it("add image into item content by factory", function() { $('#sandbox').wikimate({}); $('#sandbox').wiki...
$('.new-image').click(); var done = $('.ui-button').filter(function(i, button) { return $(button).text() == "Done"; }); done.click(); expect($('#sandbox .item').length).toEqual(0); }); });
$('#sandbox').wikimate({}); $('#sandbox').wikimate('newItem', {type: 'factory'});
random_line_split
test_support.py
a == b): raise TestFailed, "%r == %r" % (a, b) def sortdict(dict): "Like repr(dict), but in sorted order." items = dict.items() items.sort() reprpairs = ["%r: %r" % pair for pair in items] withcommas = ", ".join(reprpairs) return "{%s}" % withcommas def check_syntax(statement): try...
for refleaks. """
random_line_split
test_support.py
TEST_FN_ENCODING exists for the platform. if have_unicode: # Assuming sys.getfilesystemencoding()!=sys.getdefaultencoding() # TESTFN_UNICODE is a filename that can be encoded using the # file system encoding, but *not* with the default (ascii) encoding if isinstance('', unicode): ...
maxsize = int((max_memuse - overhead) / memuse) if maxsize < minsize: # Really ought to print 'test skipped' or something if verbose: sys.stderr.write("Skipping %s because of memory " "constraint\n" ...
conditional_block
test_support.py
verbose = 1 # Flag set to 0 by regrtest.py use_resources = None # Flag set to [] by regrtest.py max_memuse = 0 # Disable bigmem tests (they will still be run with # small sizes, to make sure they work.) # _original_stdout is meant to hold stdout at the time regrtes...
"""Test skipped because it requested a disallowed resource. This is raised when a test calls requires() for a resource that has not be enabled. It is used to distinguish between expected and unexpected skips. """
identifier_body
test_support.py
, treat as if # the resource was set if sys._getframe().f_back.f_globals.get("__name__") == "__main__": return if not is_resource_enabled(resource): if msg is None: msg = "Use of the `%s' resource not enabled" % resource raise ResourceDenied(msg) def bind_port(sock, host...
(x, y): # fuzzy comparison function if type(x) == type(0.0) or type(y) == type(0.0): try: x, y = coerce(x, y) fuzz = (abs(x) + abs(y)) * FUZZ if abs(x-y) <= fuzz: return 0 except: pass elif type(x) == type(y) and type(x) in (type(()...
fcmp
identifier_name
referencesForClassMembersExtendingGenericClass.ts
/// <reference path='fourslash.ts'/> ////class Base<T> { //// [|{| "isWriteAccess": true, "isDefinition": true |}a|]: this; //// [|{| "isWriteAccess": true, "isDefinition": true |}method|]<U>(a?:T, b?:U): this { } ////} ////class MyClass extends Base<number> { //// [|{| "isWriteAccess": true, "isDefini...
verify.referenceGroups(m2, [ { definition: "(method) Base<T>.method<U>(a?: T, b?: U): this", ranges: [m0] }, { definition: "(method) MyClass.method(): void", ranges: [m1] }, { definition: "(method) MyClass.method(): void", ranges: [m2] } ]);
random_line_split
sdreactor.py
""" The SyncDaemon reactor -- a less power-hungry version of twisted's gtk2reactor """ # # This is the quickest way to make twisted's Gtk2Reactor use # timeout_add_seconds instead of timeout_add; the former uses high-resolution # timers, which are more power-intensive. # It's pretty much verbatim from their source. fr...
def doIteration(self, delay): """ Process some events """ log.msg(channel='system', event='iteration', reactor=self) if self.__pending(): self.__iteration(0) return # nothing to do, must delay if delay == 0: return # shoul...
Gtk2Reactor.__init__(self, use_gtk) # ugh... why would somebody make these private? self.__iteration = self._Gtk2Reactor__iteration self.__pending = self._Gtk2Reactor__pending self.__run = self._Gtk2Reactor__run
identifier_body
sdreactor.py
""" The SyncDaemon reactor -- a less power-hungry version of twisted's gtk2reactor """ # # This is the quickest way to make twisted's Gtk2Reactor use # timeout_add_seconds instead of timeout_add; the former uses high-resolution # timers, which are more power-intensive. # It's pretty much verbatim from their source. fr...
(self): """ Run simulation loops and reschedule callbacks. """ if self._simtag is not None: gobject.source_remove(self._simtag) self.runUntilCurrent() timeout = min(self.timeout(), 0.1) if timeout is None: timeout = 0.1 # grumble ...
simulate
identifier_name
sdreactor.py
""" The SyncDaemon reactor -- a less power-hungry version of twisted's gtk2reactor """ # # This is the quickest way to make twisted's Gtk2Reactor use # timeout_add_seconds instead of timeout_add; the former uses high-resolution # timers, which are more power-intensive. # It's pretty much verbatim from their source. fr...
# nothing to do, must delay if delay == 0: return # shouldn't delay, so just return self.doIterationTimer = gobject.timeout_add_seconds( int(delay), self.doIterationTimeout) # This will either wake up from IO or from a timeout. self.__iteration(1) # block...
self.__iteration(0) return
conditional_block
sdreactor.py
""" The SyncDaemon reactor -- a less power-hungry version of twisted's gtk2reactor """ # # This is the quickest way to make twisted's Gtk2Reactor use # timeout_add_seconds instead of timeout_add; the former uses high-resolution # timers, which are more power-intensive. # It's pretty much verbatim from their source. fr...
self.doIterationTimer = gobject.timeout_add_seconds( int(delay), self.doIterationTimeout) # This will either wake up from IO or from a timeout. self.__iteration(1) # block # note: with the .simulate timer below, delays > 0.1 will always be # woken up by the .simulate ...
random_line_split
mcbd.py
#! python3 ''' mcbd.py - Saves and loads pieces of text from/to the clipboard to/from a shelf type file. Usage: python3 mcbd.py save <keyword> - saves clipboard for keyword. python3 mcbd.py <keyword> - loads to clipboard for keyword. python3 mcbd.py list - loads all keywords to clipboard. ...
(): print(textwrap.dedent( ''' Usage: python3 mcbd.py save <keyword> - saves clipboard for keyword. python3 mcbd.py <keyword> - loads to clipboard for keyword. python3 mcbd.py list - loads all keywords to clipboard. python3 mcbd.py delete <keyword> - dele...
print_usage
identifier_name
mcbd.py
#! python3 ''' mcbd.py - Saves and loads pieces of text from/to the clipboard to/from a shelf type file. Usage: python3 mcbd.py save <keyword> - saves clipboard for keyword. python3 mcbd.py <keyword> - loads to clipboard for keyword. python3 mcbd.py list - loads all keywords to clipboard. ...
elif sys.argv[1] in mcbShelf: pyperclip.copy(mcbShelf[sys.argv[1]]) print('copied to clipboard for keyword:', sys.argv[1]) else: print('no such keyword:', sys.argv[1]) print_usage() else: print_usage() mcbShelf.close()
mcbShelf.clear() print('all keywords deleted')
conditional_block
mcbd.py
#! python3 ''' mcbd.py - Saves and loads pieces of text from/to the clipboard to/from a shelf type file. Usage: python3 mcbd.py save <keyword> - saves clipboard for keyword. python3 mcbd.py <keyword> - loads to clipboard for keyword. python3 mcbd.py list - loads all keywords to clipboard. ...
''' ''' Extend the multiclipboard program in this chapter so that it has a delete <keyword> command line argument that will delete a keyword from the shelf. Then add a delete command line argument that will delete all keywords. ''' import pyperclip import shelve import sys import textwrap def print_usage(): print...
you need to copy and paste, you have to keep highlighting and copying the same few things over and over again. You can write a Python program to keep track of multiple pieces of text.
random_line_split
mcbd.py
#! python3 ''' mcbd.py - Saves and loads pieces of text from/to the clipboard to/from a shelf type file. Usage: python3 mcbd.py save <keyword> - saves clipboard for keyword. python3 mcbd.py <keyword> - loads to clipboard for keyword. python3 mcbd.py list - loads all keywords to clipboard. ...
mcbShelf = shelve.open('mcb') # file created if not already existing # save or delete specified keywords if len(sys.argv) == 3: if sys.argv[1].lower() == 'save': mcbShelf[sys.argv[2]] = pyperclip.paste() print('clipboard saved under keyword:', sys.argv[2]) elif sys.argv[1].lower() == 'delete'...
print(textwrap.dedent( ''' Usage: python3 mcbd.py save <keyword> - saves clipboard for keyword. python3 mcbd.py <keyword> - loads to clipboard for keyword. python3 mcbd.py list - loads all keywords to clipboard. python3 mcbd.py delete <keyword> - deletes for ...
identifier_body
LoginPage.js
/** * Created by uzysjung on 2016. 10. 21.. */ import React, { PropTypes,Component } from 'react'; import Box from '../../components/widget/Box' import { Link, browserHistory } from 'react-router' import superagent from 'superagent'; import { Form , FormGroup, Col, Button, FormControl, Checkbox, ControlLabel , PageH...
if ( password && password.length < 5 ) { this.setState({error: 'Password must be longer than 5 characters'}); return; } superagent.post('/api/login').send({login_email: email, login_pw: password}).end((err, result) => { if (!err) { localStora...
{ this.setState({error: 'Insert Password'}); return; }
conditional_block
LoginPage.js
/** * Created by uzysjung on 2016. 10. 21.. */ import React, { PropTypes,Component } from 'react'; import Box from '../../components/widget/Box' import { Link, browserHistory } from 'react-router' import superagent from 'superagent'; import { Form , FormGroup, Col, Button, FormControl, Checkbox, ControlLabel , PageHe...
<FormGroup controlId="formHorizontalPassword"> <Col componentClass={ControlLabel} sm={2}> Password </Col> <Col sm={10}> <For...
<Col sm={10}> <FormControl type="email" placeholder="Email" value={this.state.email} onChange={this.handleForChange} /> </Col> </FormGroup>
random_line_split
LoginPage.js
/** * Created by uzysjung on 2016. 10. 21.. */ import React, { PropTypes,Component } from 'react'; import Box from '../../components/widget/Box' import { Link, browserHistory } from 'react-router' import superagent from 'superagent'; import { Form , FormGroup, Col, Button, FormControl, Checkbox, ControlLabel , PageH...
() { return ( <div style={styleLogin.panel}> <PageHeader style={styleLogin.header}>Weapon Management System</PageHeader> <Box title="Login" status="info" solid ...
render
identifier_name
LoginPage.js
/** * Created by uzysjung on 2016. 10. 21.. */ import React, { PropTypes,Component } from 'react'; import Box from '../../components/widget/Box' import { Link, browserHistory } from 'react-router' import superagent from 'superagent'; import { Form , FormGroup, Col, Button, FormControl, Checkbox, ControlLabel , PageH...
componentWillMount() { const { authenticated, replace, redirect } = this.props; if (authenticated) { replace(redirect) } } componentDidMount() { } handleFormSubmit = (e) => { e.preventDefault(); const { email, password } = this.state; se...
{ super(props); this.state = { email : '', password : '' } }
identifier_body
prune.py
# -*- encoding: utf-8 -*- """A utility that tries saved genetic tests and removes those failing""" import asyncio import yaml from pathlib import Path from logzero import logger from rizza import entity_tester from rizza import genetic_tester def genetic_prune(conf, entity='All'): """Check all saved genetic_teste...
async def _async_prune_all(conf, loop, sem): """Construct all the prune tasks, and await them""" tasks = [ asyncio.ensure_future(_async_prune(conf, entity, loop, sem)) for entity in list(entity_tester.EntityTester.pull_entities()) ] await asyncio.wait(tasks) def async_genetic_prune(...
"""Run an individual prune task""" async with sem: await loop.run_in_executor( None, # use default executor genetic_prune, conf, entity # function and args )
identifier_body
prune.py
# -*- encoding: utf-8 -*- """A utility that tries saved genetic tests and removes those failing""" import asyncio import yaml from pathlib import Path from logzero import logger from rizza import entity_tester from rizza import genetic_tester def genetic_prune(conf, entity='All'): """Check all saved genetic_teste...
conf, entity, method ).run_best() if result == -1: logger.debug('{} failed.'.format(test)) to_remove.append(test) else: logger.debug('{} passed.'.format(test)) ...
if mode == 'positive': logger.debug('Running test {}'.format(method)) result = genetic_tester.GeneticEntityTester(
random_line_split
prune.py
# -*- encoding: utf-8 -*- """A utility that tries saved genetic tests and removes those failing""" import asyncio import yaml from pathlib import Path from logzero import logger from rizza import entity_tester from rizza import genetic_tester def
(conf, entity='All'): """Check all saved genetic_tester tests for an entity, prune failures""" if entity == 'All': for target in list(entity_tester.EntityTester.pull_entities()): genetic_prune(conf, target) else: test_file = conf.base_dir.joinpath( 'data/genetic_tests...
genetic_prune
identifier_name
prune.py
# -*- encoding: utf-8 -*- """A utility that tries saved genetic tests and removes those failing""" import asyncio import yaml from pathlib import Path from logzero import logger from rizza import entity_tester from rizza import genetic_tester def genetic_prune(conf, entity='All'): """Check all saved genetic_teste...
else: test_file = conf.base_dir.joinpath( 'data/genetic_tests/{}.yaml'.format(entity)) logger.debug('Current target file: {}'.format(test_file)) to_remove = [] if test_file.exists() and test_file.stat().st_size > 10: logger.debug('Beginning tests for {}'.form...
for target in list(entity_tester.EntityTester.pull_entities()): genetic_prune(conf, target)
conditional_block
test_wmi_check.py
Test Win32_OperatingSystem_attr = { 'BootDevice': "\\Device\\HarddiskVolume1", 'BuildNumber': "9600", 'BuildType': "Multiprocessor Free", 'Caption': "Microsoft Windows Server 2012 R2 Standard Evaluation", 'CodeSet': "1252", 'CountryCode': "1", 'CreationClassName': "Win32_OperatingSystem", ...
def test_check(self): """ Collect WMI metrics + `constant_tags` """ # Run check config = { 'instances': [self.CONFIG] } self.run_check(config) # Test metrics for _, mname, _ in self.CONFIG['metrics']: self.assertMetr...
import sys sys.modules['wmi'] = Mocked_WMI( { 'Win32_OperatingSystem': Mocked_Win32_Service(**Win32_OperatingSystem_attr), 'Win32_PerfFormattedData_PerfProc_Process': Mocked_Win32_Service(**Win32_PerfFormattedData_PerfProc_Process_attr), ...
identifier_body
test_wmi_check.py
Test Win32_OperatingSystem_attr = { 'BootDevice': "\\Device\\HarddiskVolume1", 'BuildNumber': "9600", 'BuildType': "Multiprocessor Free", 'Caption': "Microsoft Windows Server 2012 R2 Standard Evaluation", 'CodeSet': "1252", 'CountryCode': "1", 'CreationClassName': "Win32_OperatingSystem", ...
(self): # Mocking `wmi` Python package import sys sys.modules['wmi'] = Mocked_WMI( { 'Win32_OperatingSystem': Mocked_Win32_Service(**Win32_OperatingSystem_attr), 'Win32_PerfFormattedData_PerfProc_Process': Mocked_Win32_Service(**Win...
setUp
identifier_name
test_wmi_check.py
\\HarddiskVolume1", 'BuildNumber': "9600", 'BuildType': "Multiprocessor Free", 'Caption': "Microsoft Windows Server 2012 R2 Standard Evaluation", 'CodeSet': "1252", 'CountryCode': "1", 'CreationClassName': "Win32_OperatingSystem", 'CSCreationClassName': "Win32_ComputerSystem", 'CSName': ...
self.assertMetric(mname, tags=['commandline:c:\\program_files_(x86)\\google' '\\chrome\\application\\chrome.exe"'], count=1)
conditional_block
test_wmi_check.py
_OperatingSystem_attr = { 'BootDevice': "\\Device\\HarddiskVolume1", 'BuildNumber': "9600", 'BuildType': "Multiprocessor Free", 'Caption': "Microsoft Windows Server 2012 R2 Standard Evaluation", 'CodeSet': "1252", 'CountryCode': "1", 'CreationClassName': "Win32_OperatingSystem", 'CSCreat...
self.run_check(config) # Test metrics for _, mname, _ in self.TAG_QUERY_CONFIG['metrics']: self.assertMetric(mname, tags=['commandline:c:\\program_files_(x86)\\google'
random_line_split
PluginModuleType.js
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import type {Fiber} from 'react-reconciler/src/ReactFiber'; import type { DispatchConfig, ReactSyntheticEvent,
export type AnyNativeEvent = Event | KeyboardEvent | MouseEvent | Touch; export type PluginName = string; export type PluginModule<NativeEvent> = { eventTypes: EventTypes, extractEvents: ( topLevelType: TopLevelType, targetInst: Fiber, nativeTarget: NativeEvent, nativeEventTarget: EventTarget, )...
} from './ReactSyntheticEventType'; import type {TopLevelType} from './TopLevelEventTypes'; export type EventTypes = {[key: string]: DispatchConfig};
random_line_split
send_summary_mails.py
from django.core.management.base import BaseCommand, CommandError from optparse import make_option from django.template.loader import render_to_string from django.conf import settings from preferences.models import UserPreferences from summaries.models import Unseen from django.contrib.sites.models import Site from op...
"links": unseen_links, "site": Site.objects.get_current() }) email_body_html = render_to_string("summaries/body.html", { "user": user, "links": unseen_links, "site": Site.objects.get_curre...
"user": user,
random_line_split
send_summary_mails.py
from django.core.management.base import BaseCommand, CommandError from optparse import make_option from django.template.loader import render_to_string from django.conf import settings from preferences.models import UserPreferences from summaries.models import Unseen from django.contrib.sites.models import Site from op...
(self, *args, **options): if not len(args) == 1: raise CommandError("Give a period please") period = args[0] if not period in ("daily", "weekly", "monthly"): raise CommandError("Period must be daily, weekly or monthly.") users = [preference.user for preference ...
handle
identifier_name
send_summary_mails.py
from django.core.management.base import BaseCommand, CommandError from optparse import make_option from django.template.loader import render_to_string from django.conf import settings from preferences.models import UserPreferences from summaries.models import Unseen from django.contrib.sites.models import Site from op...
unseen_models.delete()
conditional_block
send_summary_mails.py
from django.core.management.base import BaseCommand, CommandError from optparse import make_option from django.template.loader import render_to_string from django.conf import settings from preferences.models import UserPreferences from summaries.models import Unseen from django.contrib.sites.models import Site from op...
"links": unseen_links, "site": Site.objects.get_current() }) email_body_html = render_to_string("summaries/body.html", { "user": user, "links": unseen_links, "site": Site.objects.get_curre...
if not len(args) == 1: raise CommandError("Give a period please") period = args[0] if not period in ("daily", "weekly", "monthly"): raise CommandError("Period must be daily, weekly or monthly.") users = [preference.user for preference in UserPreference...
identifier_body
index.d.ts
// Type definitions for verror 1.10 // Project: https://github.com/davepacheco/node-verror // Definitions by: Sven Reglitzki <https://github.com/svi3c>, Maxime Toumi-M <https://github.com/max4t> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* * VError([cause], fmt[, arg...]): Like JavaScript's b...
} declare namespace VError { interface Info { [key: string]: any; } interface Options { cause?: Error | null; name?: string; strict?: boolean; constructorOpt?(...args: any[]): void; info?: Info; } /* * SError is like VError, but stricter about t...
random_line_split
index.d.ts
// Type definitions for verror 1.10 // Project: https://github.com/davepacheco/node-verror // Definitions by: Sven Reglitzki <https://github.com/svi3c>, Maxime Toumi-M <https://github.com/max4t> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /* * VError([cause], fmt[, arg...]): Like JavaScript's b...
extends VError {} } export = VError;
WError
identifier_name
dpy.py
(model, '_'), full_model_name(model))) self.stream.write('\n') for model in self.models: fields = [f for f, m in model._meta.get_fields_with_model() if m is None] for f in fields: if getattr(f, 'auto_now_add', False): rais...
self.stream.write(' return %s(**kw)\n\n' % full_model_name(model, '_')) #~ self.start_serialization() self.stream.write('\n') model = None all_models = [] for obj in queryset: if isinstance(obj, ContentType): ...
if isinstance(f, models.DecimalField): self.stream.write( ' if %s is not None: %s = Decimal(%s)\n' % ( f.attname, f.attname, f.attname)) elif isinstance(f, models.ForeignKey) and f.rel.to is Conten...
conditional_block
dpy.py
meta.parents.items()[0] child_fields = [f for f in fields if f != pf] if child_fields: attrs = ',' + ','.join([ '%s=%s' % (f.attname, f.attname) for f in child_fields]) else: attrs = '...
DummyDeserializedObject
identifier_name
dpy.py
# otherwise Django would also try to create a parent_model record. for f, m in child_model._meta.get_fields_with_model(): if m is None or not issubclass(m, child_model): #~ if m is None or m is child_model or not issubclass(m,parent_model): if f.name in kw: ...
# specify also field values of parent_model. Ignore these silently
random_line_split
dpy.py
lino_babel_field', False): continue elif isinstance(f, (dbutils.BabelCharField, dbutils.BabelTextField)): self.stream.write( ' if %s is not None: kw.update(bv2kw(%r,%s))\n' % ( f.attname, f...
""" Imitates DeserializedObject required by loaddata. Unlike normal DeserializedObject, we *don't want* to bypass pre_save and validation methods on the individual objects. """ def __init__(self, deserializer, object): self.object = object #~ self.name = name self.deserial...
identifier_body
NeatContextProfiles.js
/** * @author Vladimir Kozhin <affka@affka.ru> * @license MIT */ 'use strict'; const Jii = require('../../BaseJii'); const InvalidConfigException = require('../../exceptions/InvalidConfigException'); const Collection = require('../../base/Collection'); const _clone = require('lodash/clone'); const INeatContextProf...
() { super.init(); this.neat = Jii.app.get(this.neat); } /** * * @param {string} profileName * @param {string} collectionName * @param {object} [params] * @returns {Promise.<T>} */ getCollection(profileName, collectionName, params) { params = params ||...
init
identifier_name
NeatContextProfiles.js
/** * @author Vladimir Kozhin <affka@affka.ru> * @license MIT */ 'use strict'; const Jii = require('../../BaseJii'); const InvalidConfigException = require('../../exceptions/InvalidConfigException'); const Collection = require('../../base/Collection'); const _clone = require('lodash/clone'); const INeatContextProf...
return collection; }); } } module.exports = NeatContextProfiles;
{ collection.set(this.data[collectionName]); this.data[collectionName] = null; // Mark as exists record (not isNew) collection.each(model => { model.setOldAttributes(_clone(model.getAttributes())); }); /...
conditional_block
NeatContextProfiles.js
/** * @author Vladimir Kozhin <affka@affka.ru> * @license MIT */ 'use strict'; const Jii = require('../../BaseJii'); const InvalidConfigException = require('../../exceptions/InvalidConfigException'); const Collection = require('../../base/Collection'); const _clone = require('lodash/clone'); const INeatContextProf...
collection.each(model => { model.setOldAttributes(_clone(model.getAttributes())); }); /*return new Collection(this.data[collectionName], { modelClass: binding.serverModel || binding.clientModel })*/ } ...
{ params = params || {}; /** @typedef {NeatComet.bindings.BindingServer} bingind */ /*var binding = this.neat.engine.profilesDefinition[profileName] && this.neat.engine.profilesDefinition[profileName][name] || null; if (!binding) { throw new InvalidConfigException('Not found c...
identifier_body
NeatContextProfiles.js
/** * @author Vladimir Kozhin <affka@affka.ru> * @license MIT */ 'use strict'; const Jii = require('../../BaseJii'); const InvalidConfigException = require('../../exceptions/InvalidConfigException'); const Collection = require('../../base/Collection'); const _clone = require('lodash/clone'); const INeatContextProf...
this.neat = Jii.app.get(this.neat); } /** * * @param {string} profileName * @param {string} collectionName * @param {object} [params] * @returns {Promise.<T>} */ getCollection(profileName, collectionName, params) { params = params || {}; /** @typedef ...
init() { super.init();
random_line_split
timeout.d.ts
/** * * Errors if Observable does not emit a value in given time span. * * <span class="informal">Timeouts on Observable that doesn't emit values fast enough.</span> * * <img src="./img/timeout.png" width="100%"> * * `timeout` operator accepts as an argument either a number or a Date. * * If number was provid...
import { MonoTypeOperatorFunction, SchedulerLike } from '../types';
random_line_split
system.rs
use arguments::Arguments; use mcpat; use std::path::Path; use Result; use server::Address; /// A McPAT system. pub struct System { backend: mcpat::System, } impl System { /// Open a system. #[inline] pub fn
<T: AsRef<Path>>(path: T) -> Result<System> { let backend = ok!(mcpat::open(path)); { let system = backend.raw(); if system.number_of_L2s > 0 && system.Private_L2 == 0 { raise!("shared L2 caches are currently not supported"); } } Ok(Sys...
open
identifier_name
system.rs
use arguments::Arguments; use mcpat; use std::path::Path; use Result; use server::Address; /// A McPAT system. pub struct System { backend: mcpat::System, } impl System { /// Open a system. #[inline] pub fn open<T: AsRef<Path>>(path: T) -> Result<System> { let backend = ok!(mcpat::open(path))...
Ok(ok!(self.backend.compute())) } /// Return the number of cores. pub fn cores(&self) -> usize { let system = self.backend.raw(); if system.homogeneous_cores != 0 { 1 } else { system.number_of_cores as usize } } /// Return the number of L3 caches. pu...
pub fn compute<'l>(&'l self) -> Result<mcpat::Processor<'l>> {
random_line_split
system.rs
use arguments::Arguments; use mcpat; use std::path::Path; use Result; use server::Address; /// A McPAT system. pub struct System { backend: mcpat::System, } impl System { /// Open a system. #[inline] pub fn open<T: AsRef<Path>>(path: T) -> Result<System> { let backend = ok!(mcpat::open(path))...
/// Perform the computation of area and power. #[inline] pub fn compute<'l>(&'l self) -> Result<mcpat::Processor<'l>> { Ok(ok!(self.backend.compute())) } /// Return the number of cores. pub fn cores(&self) -> usize { let system = self.backend.raw(); if system.homogeneo...
{ mcpat::optimize_for_clock_rate(true); if arguments.get::<bool>("caching").unwrap_or(false) { let Address(host, port) = arguments.get::<String>("server") .and_then(|s| Address::parse(&s)) .unwrap_o...
identifier_body
system.rs
use arguments::Arguments; use mcpat; use std::path::Path; use Result; use server::Address; /// A McPAT system. pub struct System { backend: mcpat::System, } impl System { /// Open a system. #[inline] pub fn open<T: AsRef<Path>>(path: T) -> Result<System> { let backend = ok!(mcpat::open(path))...
} }
{ system.number_of_L3s as usize }
conditional_block
lib.rs
// Copyright 2015 Corey Farwell // // 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 wr...
) { let rss_str = "\ <rss>\ <channel>\ </channel>\ </rss>"; assert!(Rss::from_str(rss_str).is_err()); } #[test] fn test_read_one_channel() { let rss_str = "\ <rss>\ <channel>\ <ti...
est_read_one_channel_no_properties(
identifier_name
lib.rs
// Copyright 2015 Corey Farwell // // 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 wr...
assert_eq!(rss.to_string(), "<?xml version=\'1.0\' encoding=\'UTF-8\'?><rss version=\'2.0\'><channel><title>My Blog</title><link>http://myblog.com</link><description>Where I write stuff</description><item><title>My first post!</title><link>http://myblog.com/post1</link><description>This is my first post</descri...
let rss = Rss(channel);
random_line_split
message-bus.service.spec.ts
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { MessageBus, MessageBusFactory } from './message-bus.service'; class Event1 { } class Event2 { } describe('MessageBus', () => { it('should instantiate from factory', () => { const ...
});
random_line_split
message-bus.service.spec.ts
/* * Squidex Headless CMS * * @license * Copyright (c) Squidex UG (haftungsbeschränkt). All rights reserved. */ import { MessageBus, MessageBusFactory } from './message-bus.service'; class E
{ } class Event2 { } describe('MessageBus', () => { it('should instantiate from factory', () => { const messageBus = MessageBusFactory(); expect(messageBus).toBeDefined(); }); it('should instantiate', () => { const messageBus = new MessageBus(); expect(messageBus).toBeDef...
vent1
identifier_name
ui.js
var ui = (function () { function buildOnlineUsersList(users) { var div = '<h1>Online users</h1>' var ul = '<ul id="online-users">'; for (var i = users.length - 1; i >= 0; i--) { var li = $('<li class = "online-user" data-username=' + users[i].username + '/>'); li.te...
}());
random_line_split
ui.js
var ui = (function () { function buildOnlineUsersList(users) { var div = '<h1>Online users</h1>' var ul = '<ul id="online-users">'; for (var i = users.length - 1; i >= 0; i--) { var li = $('<li class = "online-user" data-username=' + users[i].username + '/>'); li.te...
essageContent, senderUsername) { var li = '<li class = "message">'; li += '<div><h2>' + senderUsername + ': '; // Adding colors to the messages if (localStorage.getItem("username") == senderUsername) { li += '<span class="blue-message">'; } else { ...
pendRecievedMessage(m
identifier_name
ui.js
var ui = (function () { function buildOnlineUsersList(users) {
function buildMessages(users) { var div = ''; div += '<form id="form-send-message">' + '<input type = "text" name="content" autofocus/>' + '</form>'; //div += '<form id="sendFileForm" enctype="multipart/form-data">' + // '<input name="file" type="file...
var div = '<h1>Online users</h1>' var ul = '<ul id="online-users">'; for (var i = users.length - 1; i >= 0; i--) { var li = $('<li class = "online-user" data-username=' + users[i].username + '/>'); li.text(users[i].username); li.prepend('<img src="' + users[i...
identifier_body
ui.js
var ui = (function () { function buildOnlineUsersList(users) { var div = '<h1>Online users</h1>' var ul = '<ul id="online-users">'; for (var i = users.length - 1; i >= 0; i--) {
ul += '</ul>'; div += ul; //div += '</div>'; return div; } function buildMessages(users) { var div = ''; div += '<form id="form-send-message">' + '<input type = "text" name="content" autofocus/>' + '</form>'; //div += '<form id="send...
var li = $('<li class = "online-user" data-username=' + users[i].username + '/>'); li.text(users[i].username); li.prepend('<img src="' + users[i].profilePicture + '" width="30" height = "50" />'); if (users[i].messagesState) { li.addClass("unr...
conditional_block
_config.js
export default { props: { things: [ { id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }, { id: 4, name: 'd' }, { id: 5, name: 'e' } ] }, html: ` <div>a</div> <div>b</div> <div>c</div> <div>d</div> <div>e</div> `,
({ assert, component, raf }) { let divs = document.querySelectorAll('div'); divs.forEach(div => { div.getBoundingClientRect = function() { const index = [...this.parentNode.children].indexOf(this); const top = index * 30; return { left: 0, right: 100, top, bottom: top + 20 };...
test
identifier_name
_config.js
export default { props: { things: [ { id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }, { id: 4, name: 'd' }, { id: 5, name: 'e' } ] }, html: ` <div>a</div> <div>b</div> <div>c</div> <div>d</div> <div>e</div> `, test({ assert, component, raf }) { let divs = document.q...
component.things = [ { id: 5, name: 'e' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }, { id: 4, name: 'd' }, { id: 1, name: 'a' } ]; divs = document.querySelectorAll('div'); assert.equal(divs[0].dy, 120); assert.equal(divs[4].dy, -120); raf.tick(50); assert.equal(divs[0].dy, 60); assert...
});
random_line_split
_config.js
export default { props: { things: [ { id: 1, name: 'a' }, { id: 2, name: 'b' }, { id: 3, name: 'c' }, { id: 4, name: 'd' }, { id: 5, name: 'e' } ] }, html: ` <div>a</div> <div>b</div> <div>c</div> <div>d</div> <div>e</div> `, test({ assert, component, raf })
{ id: 4, name: 'd' }, { id: 1, name: 'a' } ]; divs = document.querySelectorAll('div'); assert.equal(divs[0].dy, 120); assert.equal(divs[4].dy, -120); raf.tick(50); assert.equal(divs[0].dy, 60); assert.equal(divs[4].dy, -60); raf.tick(100); assert.equal(divs[0].dy, 0); assert.equal(divs[4].d...
{ let divs = document.querySelectorAll('div'); divs.forEach(div => { div.getBoundingClientRect = function() { const index = [...this.parentNode.children].indexOf(this); const top = index * 30; return { left: 0, right: 100, top, bottom: top + 20 }; }; }); component.thi...
identifier_body
types.ts
import { Alert } from 'app/types/unified-alerting'; export enum SortOrder { AlphaAsc = 1, AlphaDesc, Importance, TimeAsc, TimeDesc, } export enum ShowOption { Current = 'current', RecentChanges = 'changes', } export enum GroupMode { Default = 'default', Custom = 'custom', } export interface AlertL...
error: boolean; } export interface UnifiedAlertListOptions { maxItems: number; sortOrder: SortOrder; dashboardAlerts: boolean; groupMode: GroupMode; groupBy: string[]; alertName: string; showInstances: boolean; folder: { id: number; title: string }; stateFilter: StateFilter; alertInstanceLabelFil...
random_line_split
api.js
import {HttpClient} from 'aurelia-fetch-client'; import * as messages from './messages'; import {EventAggregator} from 'aurelia-event-aggregator'; export class Api { static
() { return [EventAggregator]; } constructor(ea) { this.ea = ea; this.socket = io(); this.client = new HttpClient(); this.gameId = null; this.dataPromise = null; } init() { this.socket.on('game-state', (args) => { this.ea.publish(new messages.StateSync(args.state)); }); } retrieveData() { if ...
inject
identifier_name
api.js
import {HttpClient} from 'aurelia-fetch-client'; import * as messages from './messages'; import {EventAggregator} from 'aurelia-event-aggregator'; export class Api { static inject() { return [EventAggregator]; } constructor(ea) { this.ea = ea; this.socket = io(); this.client = new HttpClient(); this.gameId ...
reject(new Error(error)); }); }); } }
random_line_split
_gcp_job.py
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
self._context = context self._api = self._create_api(context) def _create_api(self, context): raise Exception('_create_api must be defined in a derived class') def __repr__(self): """Returns a representation for the job for showing in the notebook. """ return 'Job %s/%s %s' % (self._conte...
context = datalab.context.Context.default()
conditional_block
_gcp_job.py
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
(self, context): raise Exception('_create_api must be defined in a derived class') def __repr__(self): """Returns a representation for the job for showing in the notebook. """ return 'Job %s/%s %s' % (self._context.project_id, self._job_id, self.state)
_create_api
identifier_name
_gcp_job.py
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
"""Returns a representation for the job for showing in the notebook. """ return 'Job %s/%s %s' % (self._context.project_id, self._job_id, self.state)
"""Represents a BigQuery Job. """ def __init__(self, job_id, context): """Initializes an instance of a Job. Args: job_id: the BigQuery job ID corresponding to this job. context: a Context object providing project_id and credentials. """ super(GCPJob, self).__init__(job_id) if conte...
identifier_body
_gcp_job.py
# Copyright 2016 Google Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
Args: job_id: the BigQuery job ID corresponding to this job. context: a Context object providing project_id and credentials. """ super(GCPJob, self).__init__(job_id) if context is None: context = datalab.context.Context.default() self._context = context self._api = self._create...
random_line_split
Spec.js
'use strict'; var _createClass = (function () { function defineProperties(target, props)
return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new ...
{ for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
identifier_body
Spec.js
'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProp...
} var Immutable = require('immutable'); var Spec = (function () { function Spec(root) { _classCallCheck(this, Spec); this._root = root; } _createClass(Spec, [{ key: 'toJS', value: function toJS() { return this._root.toJS(); } }]); return Spec...
{ throw new TypeError('Cannot call a class as a function'); }
conditional_block
Spec.js
'use strict'; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProp...
})(); Spec.FileExtension = { GHERKIN: '.feature' }; module.exports = Spec;
random_line_split
Spec.js
'use strict'; var _createClass = (function () { function
(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor...
defineProperties
identifier_name
tests.py
from django.core.urlresolvers import reverse from rest_framework import status
from rest_framework.test import APITestCase from rest_framework.test import APIRequestFactory from beer_api.models import * class TestGlassTypePost(APITestCase): def test_auth_fail(self): url = '/glass_types/' data = { 'glass_type': 'Mug', 'description': 'A cup with a handle.' } res...
from rest_framework.test import force_authenticate
random_line_split
tests.py
from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import force_authenticate from rest_framework.test import APITestCase from rest_framework.test import APIRequestFactory from beer_api.models import * class TestGlassTypePost(APITestCase): def test_auth_f...
(self): user = User.objects.create_user('test','test@test.com','testpass') self.client.login(username='test',password='testpass') url = '/glass_types/' data = { 'glass_type': 'Mug', 'description': 'A cup with a handle.' } response = self.client.post(url,data,format='json') self.asser...
test_auth_pass
identifier_name
tests.py
from django.core.urlresolvers import reverse from rest_framework import status from rest_framework.test import force_authenticate from rest_framework.test import APITestCase from rest_framework.test import APIRequestFactory from beer_api.models import * class TestGlassTypePost(APITestCase): def test_auth_f...
user = User.objects.create_user('test','test@test.com','testpass') self.client.login(username='test',password='testpass') url = '/glass_types/' data = { 'glass_type': 'Mug', 'description': 'A cup with a handle.' } response = self.client.post(url,data,format='json') self.assertEqual(resp...
identifier_body
setup.py
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=4 shiftwidth=4 autoindent smartindent: #from distutils.core import setup import os import logging import setuptools import distutils.cmd import subprocess # TODO add check to make sure required libs are present (eg sqlite3) _PACKAGE_NAME = 'python...
def run(self): """Create the virtualenv.""" # TODO finish automating virtualenv... manual is ok for now self.announce('Running virtualenv.', level=2) print "Creating virtual env in:", _VIRTUALENV_DIR # TODO check to make sure parent dir exists # TODO what do to if a...
pass
identifier_body
setup.py
#!/usr/bin/env python # vim: set filetype=python expandtab tabstop=4 shiftwidth=4 autoindent smartindent: #from distutils.core import setup import os import logging import setuptools import distutils.cmd import subprocess # TODO add check to make sure required libs are present (eg sqlite3) _PACKAGE_NAME = 'python...
(self): pass def finalize_options(self): pass def run(self): """Create the virtualenv.""" # TODO finish automating virtualenv... manual is ok for now self.announce('Running virtualenv.', level=2) print "Creating virtual env in:", _VIRTUALENV_DIR # TODO c...
initialize_options
identifier_name