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
result.rs
use std::error::Error; use std::fmt; use std::fmt::Display; use std::ptr; use env::NapiEnv; use sys::{napi_create_error, napi_create_range_error, napi_create_type_error, napi_status, napi_value}; use value::{NapiString, NapiValue}; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NapiErrorKind { In...
NapiErrorKind::EscapeCalledTwice => { "NapiError: escape called twice" } NapiErrorKind::ApplicationError => "NapiError: application error", } } } impl Display for NapiError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { write...
NapiErrorKind::PendingException => "NapiError: pending exception", NapiErrorKind::Cancelled => "NapiError: cancelled",
random_line_split
gerrit.py
CB = None reviewArg = None startCB = None startArg = None summaryCB = None summaryArg = None _gerrit_notify = None def reconfigService(self, server, username, reviewCB=DEFAULT_REVIEW, startCB=None, port=29418, reviewArg=None, startArg=None, su...
self.sendCodeReview(project, revision, result) return
conditional_block
gerrit.py
= None startCB = None startArg = None summaryCB = None summaryArg = None _gerrit_notify = None def reconfigService(self, server, username, reviewCB=DEFAULT_REVIEW, startCB=None, port=29418, reviewArg=None, startArg=None, summaryCB=DEFAULT_SUMMARY...
sendCodeReview
identifier_name
gerrit.py
is DEFAULT_REVIEW and summaryCB is DEFAULT_SUMMARY: reviewCB = None summaryCB = defaultSummaryCB if reviewCB is DEFAULT_REVIEW: reviewCB = None if summaryCB is DEFAULT_SUMMARY: summaryCB = None # Parameters. self.gerrit_server = server ...
labels = result.get('labels', None) if labels: assert gerrit_version if gerrit_version < LooseVersion("2.6"):
random_line_split
gerrit.py
errit_version_time = 0 self.gerrit_identity_file = identity_file self.reviewCB = reviewCB self.reviewArg = reviewArg self.startCB = startCB self.startArg = startArg self.summaryCB = summaryCB self.summaryArg = summaryArg self.builders = builders se...
reactor.spawnProcess(*arg, **kw)
identifier_body
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mps...
(self, c: Customer) { println!("Barber {:?} is cutting hair of customer {:?}.", self.id, c.id); thread::sleep_ms(c.hair_length); self.to_shop.clone().send(Message::BarberFree(self)).unwrap(); } } impl Barbershop { fn new(num_chairs: usize) -> Barbershop { let (tx, rx) = mpsc::ch...
cut_hair
identifier_name
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mps...
fn hire_barber(&mut self, id: i32) { let b = Barber::new(id, self); self.barber_free(b); } fn serve_customer(&mut self) { if self.free_barbers.len() == 0 { return; } if self.waiting_customers.len() == 0 { return; } ...
{ let (tx, rx) = mpsc::channel::<Message>(); Barbershop{ tx: tx, rx: rx, num_chairs: num_chairs, waiting_customers: VecDeque::<Customer>::new(), free_barbers: VecDeque::<Barber>::new(), } }
identifier_body
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mps...
let b = self.free_barbers.pop_front().unwrap(); let c = self.waiting_customers.pop_front().unwrap(); thread::spawn(move || b.cut_hair(c)); } fn barber_free(&mut self, b: Barber) { self.free_barbers.push_back(b); self.serve_customer(); } fn new_customer(&mut s...
{ return; }
conditional_block
sleeping_barbers.rs
use std::thread; use std::sync::mpsc; use std::collections::VecDeque; use rand; use rand::distributions::{IndependentSample, Range}; struct Barber { id: i32, to_shop: mpsc::Sender<Message>, } struct Customer { id: i32, hair_length: u32, } struct Barbershop { tx: mpsc::Sender<Message>, rx: mps...
} thread::sleep_ms(10000); }
hair_length: hair_lengths.ind_sample(&mut rng), }; println!("Customer {:?} arrives at shop.", i); to_shop.send(Message::CustomerArrives(c)).unwrap(); thread::sleep_ms(customer_interval.ind_sample(&mut rng));
random_line_split
File.py
# Copyright 1999 by Jeffrey Chang. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Code for more fancy file handles. Classes: UndoHandle File object decorator with sup...
if self._parser.data: str = self._parser.data elif is_newline: str = '\n' else: str = '' return str
self._parser.data = '' # clear the parser's data (don't reset) self._parser.feed(str)
random_line_split
File.py
# Copyright 1999 by Jeffrey Chang. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Code for more fancy file handles. Classes: UndoHandle File object decorator with sup...
(self): return self def next(self): next = self.readline() if not next: raise StopIteration return next def readlines(self, *args, **keywds): lines = self._saved + self._handle.readlines(*args,**keywds) self._saved = [] return lines def ...
__iter__
identifier_name
File.py
# Copyright 1999 by Jeffrey Chang. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Code for more fancy file handles. Classes: UndoHandle File object decorator with sup...
def readline(self, *args, **keywds): if self._saved: line = self._saved.pop(0) else: line = self._handle.readline(*args,**keywds) return line def read(self, size=-1): if size == -1: saved = "".join(self._saved) self._saved[:] = [...
lines = self._saved + self._handle.readlines(*args,**keywds) self._saved = [] return lines
identifier_body
File.py
# Copyright 1999 by Jeffrey Chang. All rights reserved. # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. """Code for more fancy file handles. Classes: UndoHandle File object decorator with sup...
return line def read(self, size=-1): if size == -1: saved = "".join(self._saved) self._saved[:] = [] else: saved = '' while size > 0 and self._saved: if len(self._saved[0]) <= size: size = size - len(self._...
line = self._handle.readline(*args,**keywds)
conditional_block
listener.js
'use strict' const { EventEmitter } = require('events') const { Multiaddr } = require('multiaddr') /** * @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener */ /** * @param {import('../')} libp2p * @returns {Listener} a transport listener */ module.exports = (libp2p) => { const listen...
/** @type Listener */ const listener = Object.assign(new EventEmitter(), { close: () => Promise.resolve(), listen, getAddrs }) // Remove listeningAddrs when a peer disconnects libp2p.connectionManager.on('peer:disconnect', (connection) => { const deleted = listeningAddrs.delete(connection.r...
{ const addrs = [] for (const addr of listeningAddrs.values()) { addrs.push(addr) } return addrs }
identifier_body
listener.js
'use strict' const { EventEmitter } = require('events') const { Multiaddr } = require('multiaddr') /** * @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener */ /** * @param {import('../')} libp2p * @returns {Listener} a transport listener */ module.exports = (libp2p) => { const listen...
}) return listener }
{ // Announce listen addresses change listener.emit('close') }
conditional_block
listener.js
'use strict' const { EventEmitter } = require('events') const { Multiaddr } = require('multiaddr') /** * @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener */ /** * @param {import('../')} libp2p * @returns {Listener} a transport listener */ module.exports = (libp2p) => { const listen...
() { const addrs = [] for (const addr of listeningAddrs.values()) { addrs.push(addr) } return addrs } /** @type Listener */ const listener = Object.assign(new EventEmitter(), { close: () => Promise.resolve(), listen, getAddrs }) // Remove listeningAddrs when a peer disconn...
getAddrs
identifier_name
listener.js
'use strict' const { EventEmitter } = require('events') const { Multiaddr } = require('multiaddr') /** * @typedef {import('libp2p-interfaces/src/transport/types').Listener} Listener */ /**
* @returns {Listener} a transport listener */ module.exports = (libp2p) => { const listeningAddrs = new Map() /** * Add swarm handler and listen for incoming connections * * @param {Multiaddr} addr * @returns {Promise<void>} */ async function listen (addr) { const addrString = String(addr).s...
* @param {import('../')} libp2p
random_line_split
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_, ..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } ...
() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
use_bang_macro_as_attr
identifier_name
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_, ..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } ...
#[my_macro] fn use_bang_macro_as_attr() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
random_line_split
trace_faulty_macros.rs
// compile-flags: -Z trace-macros #![recursion_limit = "4"] macro_rules! my_faulty_macro { () => { my_faulty_macro!(bcd); //~ ERROR no rules }; } macro_rules! pat_macro { () => { pat_macro!(A{a:a, b:0, c:_, ..}); }; ($a:pat) => { $a //~ ERROR expected expression }; } ...
#[my_macro] fn use_bang_macro_as_attr() {} #[derive(Debug)] //~ ERROR `derive` may only be applied to `struct`s fn use_derive_macro_as_attr() {}
{ my_faulty_macro!(); my_recursive_macro!(); test!(); non_exisiting!(); derive!(Debug); let a = pat_macro!(); }
identifier_body
Checkbox.ts
/// <amd-dependency path="../dom/form/Checkbox" /> import CheckboxValue = require('./CheckboxValue'); import has = require('../../has'); import Widget = require('../Widget'); interface Checkbox extends Widget { get:Checkbox.Getters; on:Checkbox.Events; set:Checkbox.Setters; } module Checkbox { export interface E...
export = Checkbox;
{ Checkbox = <typeof Checkbox> require('../dom/form/Checkbox'); }
conditional_block
Checkbox.ts
/// <amd-dependency path="../dom/form/Checkbox" /> import CheckboxValue = require('./CheckboxValue');
on:Checkbox.Events; set:Checkbox.Setters; } module Checkbox { export interface Events extends Widget.Events {} export interface Getters extends Widget.Getters { (key:'isChecked'):boolean; (key:'isDisabled'):boolean; (key:'value'):CheckboxValue; } export interface Setters extends Widget.Setters { (key:'is...
import has = require('../../has'); import Widget = require('../Widget'); interface Checkbox extends Widget { get:Checkbox.Getters;
random_line_split
TestForwardDecl.py
"""Test that a forward-declared class works when its complete definition is in a library""" import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ForwardDeclTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp...
(self, dictionary=None): self.build(dictionary=dictionary) # Create a target by the debugger. target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) # Create the breakpoint inside function 'main'. breakpoint = target.Breakpo...
do_test
identifier_name
TestForwardDecl.py
"""Test that a forward-declared class works when its complete definition is in a library""" import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ForwardDeclTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp...
def do_test(self, dictionary=None): self.build(dictionary=dictionary) # Create a target by the debugger. target = self.dbg.CreateTarget(self.getBuildArtifact("a.out")) self.assertTrue(target, VALID_TARGET) # Create the breakpoint inside function 'main'. breakpoint...
TestBase.setUp(self) # Find the line number to break inside main(). self.source = 'main.m' self.line = line_number(self.source, '// Set breakpoint 0 here.') self.shlib_names = ["Container"]
identifier_body
TestForwardDecl.py
"""Test that a forward-declared class works when its complete definition is in a library""" import lldb from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class ForwardDeclTestCase(TestBase): mydir = TestBase.compute_mydir(__file__) def setUp...
dict(CFLAGS_EXTRAS="-dwarf-version=5 -mllvm -accel-tables=Dwarf"))
accelerator tables""" self.do_test(
random_line_split
__main__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """McGill Robotics ROS Bagger. This tool can: 1. Record the specified topics into 15 second bags to the specified directory. 2. Merge previously recorded bags from the specified directory. By default, all the topics defined in your project's 'topics' f...
(): """Runs the CLI.""" try: topics_path = os.environ["TOPICS_PATH"] except KeyError: print("E: TOPICS_PATH environment variable not set") sys.exit(2) topics = TopicList(topics_path) args = Parser(topics, __doc__, __version__) status = args.cmd( topics=args.enab...
main
identifier_name
__main__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """McGill Robotics ROS Bagger. This tool can: 1. Record the specified topics into 15 second bags to the specified directory. 2. Merge previously recorded bags from the specified directory. By default, all the topics defined in your project's 'topics' f...
main()
conditional_block
__main__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """McGill Robotics ROS Bagger. This tool can: 1. Record the specified topics into 15 second bags to the specified directory. 2. Merge previously recorded bags from the specified directory. By default, all the topics defined in your project's 'topics' f...
topics = TopicList(topics_path) args = Parser(topics, __doc__, __version__) status = args.cmd( topics=args.enabled, name=args.name, dir=args.dir, args=args.raw).run() sys.exit(status) if __name__ == "__main__": main()
random_line_split
__main__.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """McGill Robotics ROS Bagger. This tool can: 1. Record the specified topics into 15 second bags to the specified directory. 2. Merge previously recorded bags from the specified directory. By default, all the topics defined in your project's 'topics' f...
if __name__ == "__main__": main()
"""Runs the CLI.""" try: topics_path = os.environ["TOPICS_PATH"] except KeyError: print("E: TOPICS_PATH environment variable not set") sys.exit(2) topics = TopicList(topics_path) args = Parser(topics, __doc__, __version__) status = args.cmd( topics=args.enabled, nam...
identifier_body
phpunit-coverage.js
var coveragePlugin = ActiveBuild.UiPlugin.extend({ id: 'build-php_unit-coverage-chart', css: 'col-xs-12', title: Lang.get('coverage'), lastData: null, displayOnUpdate: false, rendered: false, chartData: null, register: function () {...
}); }, render: function () { var self = this; var container = $('<div id="php_unit-coverage" style="width: 100%; height: 300px"></div>'); container.append('<canvas id="php_unit-coverage-chart" style="width: 100%; height: 300px"></canvas>'); $(document).on('shown....
{ query(); }
conditional_block
phpunit-coverage.js
var coveragePlugin = ActiveBuild.UiPlugin.extend({ id: 'build-php_unit-coverage-chart', css: 'col-xs-12', title: Lang.get('coverage'), lastData: null, displayOnUpdate: false, rendered: false, chartData: null, register: function () {...
labels: [], datasets: [ { label: Lang.get('classes'), borderColor: "#555299", backgroundColor: "#555299", data: [] }, { label: ...
self.chartData = {
random_line_split
jquery.tabs.js
height",isNaN(parseInt(_19.height))?"":(cc.height()-_1a.outerHeight())); _1b._size("width",cc.width()); } if(_18.tabs.length){ var d1=ul.outerWidth(true)-ul.width(); var li=ul.children("li:first"); var d2=li.outerWidth(true)-li.width(); var _1d=_1a.width()-_1a.children(".tabs-tool:not(.tabs-tool-hidden)")._outerWidth()...
if(_40.index<0){ _40.index=0; } var ul=$(_3f).children("div.tabs-header").find("ul.tabs"); var _43=$(_3f).children("div.tabs-panels"); var tab=$("<li>"+"<a href=\"javascript:;\" class=\"tabs-inner\">"+"<span class=\"tabs-title\"></span>"+"<span class=\"tabs-icon\"></span>"+"</a>"+"</li>"); if(!pp){ pp=$("<div></div>")...
{ _40.index=_42.length; }
conditional_block
jquery.tabs.js
40.icon:undefined),onLoad:function(){ if(_40.onLoad){ _40.onLoad.apply(this,arguments); } _41.options.onLoad.call(_3f,$(this)); },onBeforeOpen:function(){ if(_40.onBeforeOpen){ if(_40.onBeforeOpen.call(this)==false){ return false; } } var p=$(_3f).tabs("getSelected"); if(p){ if(p[0]!=this){ $(_3f).tabs("unselect",_4d(_...
{ return _65(_7f,_80)!=null; }
identifier_body
jquery.tabs.js
0.index+")")); _42.splice(_40.index,0,pp); } pp.panel($.extend({},_40,{tab:tab,border:false,noheader:true,closed:true,doSize:false,iconCls:(_40.icon?_40.icon:undefined),onLoad:function(){ if(_40.onLoad){ _40.onLoad.apply(this,arguments); } _41.options.onLoad.call(_3f,$(this)); },onBeforeOpen:function(){ if(_40.onBefore...
_7a
identifier_name
jquery.tabs.js
}; function _2(_3){ var _4=$.data(_3,"tabs").options; if(!_4.showHeader){ return; } var _5=$(_3).children("div.tabs-header"); var _6=_5.children("div.tabs-tool:not(.tabs-tool-hidden)"); var _7=_5.children("div.tabs-scroller-left"); var _8=_5.children("div.tabs-scroller-right"); var _9=_5.children("div.tabs-wrap"); if(_...
var w=0; $(c).children().each(function(){ w+=$(this).outerWidth(true); }); return w;
random_line_split
Tag.d.ts
import * as React from "react"; import { ReactAttr, ReactDivAttr, FCProps, FCReturn } from "../../../typings/shared"; export type TagTypeName = "red" | "magenta" | "purple" | "blue" | "cyan" | "teal" | "green" | "gray" | "cool-gray" | "warm-gray" | "high-contrast"; export d...
declare function Tag(props: FCProps<FilterTagProps>): FCReturn; // tslint:disable:unified-signatures declare function Tag(props: FCProps<ChipTagProps>): FCReturn; export default Tag;
random_line_split
EventTypes.js
/* Copyright (C) 2011-2014 Mattias Ekendahl. Used under MIT license, see full details at https://github.com/developedbyme/dbm/blob/master/LICENSE.txt */ dbm.registerClass("dbm.thirdparty.facebook.constants.EventTypes", null, function(objectFunctions, staticFunctions, ClassReference) { //console.log("dbm.thirdparty.fac...
});
random_line_split
20171116030715_insert_users.js
const crypto = require('crypto'); exports.up = function(knex) { const now = new Date(); // Internal user for requests within the backend. // Log in is disabled for this user. const internalUser = { username: '_internal', passwordHash: '', passwordSalt: '', createdAt: now, updatedAt: now, ...
return knex('users').whereIn('username', ['admin', '_internal']).del(); };
random_line_split
fibers.ts
import Fiber = require('fibers'); const sleepFiberTest = () => { const sleep = (ms: number) => { const fiber = Fiber.current!; setTimeout(() => fiber.run(), ms); Fiber.yield(); }; Fiber(() => { console.log('wait... ' + new Date()); sleep(1000); console.log('ok... ' + new Date()); }).ru...
}); for (let ii = inc.run(1); ii <= 10; ii = inc.run(1)) { console.log(ii); } }; const fibonacciGeneratorFiberTest = () => { const Fibonacci = () => { // Create a new fiber which yields sequential Fibonacci numbers const fiber = Fiber(() => { for (let [curr, prev] = [0, 1]; ; [curr, prev] =...
{ total += Fiber.yield(total); }
conditional_block
fibers.ts
import Fiber = require('fibers'); const sleepFiberTest = () => { const sleep = (ms: number) => { const fiber = Fiber.current!; setTimeout(() => fiber.run(), ms); Fiber.yield(); };
console.log('ok... ' + new Date()); }).run(); console.log('back in sleepFiberTest'); }; const generatorFiberTest = () => { const inc = Fiber((start: number) => { let total = start; while (true) { total += Fiber.yield(total); } }); for (let ii = inc.run(1); ii <= 10; ii = inc.run(1)) {...
Fiber(() => { console.log('wait... ' + new Date()); sleep(1000);
random_line_split
TodoItem.tsx
/** * @Copyright (c) Microsoft Corporation. All rights reserved. * * @file TodoItem.tsx */ import * as React from 'react'; import { Compare } from '@microsoft/sp-client-base'; import { Checkbox, Button, ButtonType, FocusZone, FocusZoneDirection, DocumentCardActivity, css } from 'office-ui-fabric-rea...
ITodoPerson, ItemOperationCallback } from '../ITodoWebPartProps'; import * as strings from 'todoStep2Strings'; import styles from '../style/Todo.module.scss'; /** * The props for TodoItem component. */ export interface ITodoItemProps { /** * The current Todo item to be rendered. */ item: ITodoTask; ...
ITodoTask,
random_line_split
TodoItem.tsx
/** * @Copyright (c) Microsoft Corporation. All rights reserved. * * @file TodoItem.tsx */ import * as React from 'react'; import { Compare } from '@microsoft/sp-client-base'; import { Checkbox, Button, ButtonType, FocusZone, FocusZoneDirection, DocumentCardActivity, css } from 'office-ui-fabric-rea...
extends React.Component<ITodoItemProps, ITodoItemState> { private static ANIMATION_TIMEOUT: number = 200; private _animationTimeoutId: number; constructor(props: ITodoItemProps) { super(props); this._handleToggleChanged = this._handleToggleChanged.bind(this); this._handleClick = this._handleClick....
TodoItem
identifier_name
model.py
# !/usr/bin/python # @package model # @author Attila Borcs # # Class for the deep neural net. Each class function wrapped with # a decorator function using python @property for unifying # the DNN functionalities when tensorflow graph initializer # called (tf.global_variables_initializer()) import functools impor...
return getattr(self, attribute) return decorator class Model: """ This class responsible to build and wrap all of the functionalities of the tensor graph. Attributes of prediction, optimization and loss function will be stored under tensorflow variable scope. """ def __init__(sel...
with tf.variable_scope(name, *args, **kwargs): setattr(self, attribute, function(self))
conditional_block
model.py
# !/usr/bin/python # @package model # @author Attila Borcs # # Class for the deep neural net. Each class function wrapped with # a decorator function using python @property for unifying # the DNN functionalities when tensorflow graph initializer # called (tf.global_variables_initializer()) import functools impor...
@define_scope def error(self): mistakes = tf.not_equal( tf.argmax(self.label, 1), tf.argmax(self.prediction, 1)) return tf.reduce_mean(tf.cast(mistakes, tf.float32))
logprob = tf.log(self.prediction + 1e-12) cross_entropy = -tf.reduce_sum(self.label * logprob) optimizer = tf.train.AdamOptimizer(1e-4) return optimizer.minimize(cross_entropy)
identifier_body
model.py
# !/usr/bin/python # @package model # @author Attila Borcs # # Class for the deep neural net. Each class function wrapped with # a decorator function using python @property for unifying # the DNN functionalities when tensorflow graph initializer # called (tf.global_variables_initializer()) import functools impor...
return optimizer.minimize(cross_entropy) @define_scope def error(self): mistakes = tf.not_equal( tf.argmax(self.label, 1), tf.argmax(self.prediction, 1)) return tf.reduce_mean(tf.cast(mistakes, tf.float32))
@define_scope def optimize(self): logprob = tf.log(self.prediction + 1e-12) cross_entropy = -tf.reduce_sum(self.label * logprob) optimizer = tf.train.AdamOptimizer(1e-4)
random_line_split
model.py
# !/usr/bin/python # @package model # @author Attila Borcs # # Class for the deep neural net. Each class function wrapped with # a decorator function using python @property for unifying # the DNN functionalities when tensorflow graph initializer # called (tf.global_variables_initializer()) import functools impor...
(self): x = self.image x_image = tf.reshape(x, [-1, prm.mnist_img_size, prm.mnist_img_size, 1]) self.hidden_1 = slim.conv2d(x_image, 5, [prm.conv_size, prm.conv_size]) pool_1 = slim.max_pool2d(self.hidden_1, [prm.max_po...
prediction
identifier_name
SessionOperationExecutor.ts
import { OperationExecutor } from "./OperationExecutor"; import { InMemoryDocumentSessionOperations } from "../Session/InMemoryDocumentSessionOperations"; import { DocumentStoreBase } from "../DocumentStoreBase"; import * as deprecate from "deprecate"; import { throwError } from "../../Exceptions"; /** * For i...
(databaseName: string): never { return throwError("InvalidOperationException", "The method is not supported."); } }
forDatabase
identifier_name
SessionOperationExecutor.ts
import { OperationExecutor } from "./OperationExecutor"; import { InMemoryDocumentSessionOperations } from "../Session/InMemoryDocumentSessionOperations"; import { DocumentStoreBase } from "../DocumentStoreBase"; import * as deprecate from "deprecate"; import { throwError } from "../../Exceptions"; /** * For i...
}
{ return throwError("InvalidOperationException", "The method is not supported."); }
identifier_body
SessionOperationExecutor.ts
import { OperationExecutor } from "./OperationExecutor"; import { InMemoryDocumentSessionOperations } from "../Session/InMemoryDocumentSessionOperations";
import * as deprecate from "deprecate"; import { throwError } from "../../Exceptions"; /** * For internal session use only */ export class SessionOperationExecutor extends OperationExecutor { private readonly _session: InMemoryDocumentSessionOperations; /** * This constructor should not be used...
import { DocumentStoreBase } from "../DocumentStoreBase";
random_line_split
tracker.py
_collision = False if (this_bbox[TOP][0] * .9 > other_bbox[BOTTOM][0] * 1.1): has_collision = False if (this_bbox[RIGHT][1] * 1.1 < other_bbox[LEFT][1] * 0.9): has_collision = False if (this_bbox[LEFT][1] * 0.9 > other_bbox[RIGHT][1] * 1.1): ...
if (estimated_target_count - last_target_count) > 1: estimated_target_count = last_target_count + 1 last_target_change_time = frame_time # Clip to the user-supplied maximum: estimated_target_count = min(estimated_target_count, MAX_TARGETS) # The estimated_target_count at this p...
estimated_target_count = last_target_count - 1
random_line_split
tracker.py
= False if (this_bbox[TOP][0] * .9 > other_bbox[BOTTOM][0] * 1.1): has_collision = False if (this_bbox[RIGHT][1] * 1.1 < other_bbox[LEFT][1] * 0.9): has_collision = False if (this_bbox[LEFT][1] * 0.9 > other_bbox[RIGHT][1] * 1.1): has_...
(frame, running_average_image, running_average_in_display_color_depth, difference, last_target_count, last_target_change_time, last_frame_entity_list): if difference is None: return __init_tracker(frame) ...
track_object
identifier_name
tracker.py
= False if (this_bbox[TOP][0] * .9 > other_bbox[BOTTOM][0] * 1.1): has_collision = False if (this_bbox[RIGHT][1] * 1.1 < other_bbox[LEFT][1] * 0.9): has_collision = False if (this_bbox[LEFT][1] * 0.9 > other_bbox[RIGHT][1] * 1.1): has_...
# Now we have targets that are NOT computed from bboxes -- just # movement weights (according to kmeans). If any two targets are # within the same "bbox count", average them into a single target. # (Any kmeans targets not within a bbox are also kept.) trimmed_center_points = [] removed_center...
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) flags = cv2.KMEANS_RANDOM_CENTERS compactness, labels, centers = cv2.kmeans( points, 2, None, criteria, 10, flags) for center_point in centers: center_points.append(center_point)
conditional_block
tracker.py
if (this_bbox[RIGHT][1] * 1.1 < other_bbox[LEFT][1] * 0.9): has_collision = False if (this_bbox[LEFT][1] * 0.9 > other_bbox[RIGHT][1] * 1.1): has_collision = False if has_collision: # merge these two bboxes into one, then start over: ...
for this_bbox in bbox_list: # Collision detect every other bbox: for other_bbox in bbox_list: if this_bbox is other_bbox: continue # Skip self # Assume a collision to start out with: has_collision = True # These coords are in screen coords, so > ...
identifier_body
nested-matchs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} pub fn main() { foo(); }
{ match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{:?}", bar); } None::<int> => { println!("hello"); } }
identifier_body
nested-matchs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} None::<int> => { println!("hello"); } } } pub fn main() { foo(); }
random_line_split
nested-matchs.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
() -> ! { fail!(); } fn foo() { match Some::<int>(5) { Some::<int>(_x) => { let mut bar; match None::<int> { None::<int> => { bar = 5; } _ => { baz(); } } println!("{:?}", bar); } None::<int> => { println!("hello"); } } } pub fn main() { foo(); }
baz
identifier_name
driver.py
this host """ cctxt = self.client.prepare() return cctxt.call(context, 'get_vpn_services_on_host', host=host) def update_status(self, context, status): """Update local status. This method call updates status attribute of VPNServices. """ cct...
ip.netns.delete(kwargs['ns_name'])
conditional_block
driver.py
import constants from neutron_lib.plugins import directory from neutron_vpnaas.services.vpn import device_drivers from neutron_vpnaas.services.vpn.device_drivers import fedora_strongswan_ipsec from neutron_vpnaas.services.vpn.device_drivers import ipsec from neutron_vpnaas.services.vpn.device_drivers import strongswan...
for process_id in sync_router_ids: if process_id not in vpn_router_ids: self.destroy_process(process_id) def _cleanup_stale_vpn_processes(self, vpn_router_ids): process_ids = [pid for pid in self.processes if pid not in vpn_router_ids] for ...
def _delete_vpn_processes(self, sync_router_ids, vpn_router_ids):
random_line_split
driver.py
import constants from neutron_lib.plugins import directory from neutron_vpnaas.services.vpn import device_drivers from neutron_vpnaas.services.vpn.device_drivers import fedora_strongswan_ipsec from neutron_vpnaas.services.vpn.device_drivers import ipsec from neutron_vpnaas.services.vpn.device_drivers import strongswan...
def is_status_updated(self, process, previous_status): if process.updated_pending_status: return True if process.status != previous_status['status']: return True if (process.connection_status != previous_status['ipsec_site_connections']): ...
process_ids = [pid for pid in self.processes if pid not in vpn_router_ids] for process_id in process_ids: self.destroy_process(process_id)
identifier_body
driver.py
return cctxt.call(context, 'update_status', status=status) @six.add_metaclass(abc.ABCMeta) class NuageIPsecDriver(device_drivers.DeviceDriver): def __init__(self, vpn_service, host): self.conf = vpn_service.conf self.host = host self.conn = n_rpc.create_connection(new=True) self....
create_process
identifier_name
location-sel.js
(function() { var LocationSelector, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor()
ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; LocationSelector = (function(_super) { __extends(LocationSelector, _super); function LocationSelector() { return LocationSelector.__super__.constructor.apply(this, arguments);...
{ this.constructor = child; }
identifier_body
location-sel.js
(function() { var LocationSelector, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); chil...
() { return LocationSelector.__super__.constructor.apply(this, arguments); } LocationSelector.prototype.className = 'location-selector'; LocationSelector.prototype.events = { 'click .bit': 'handleClick' }; LocationSelector.prototype.render = function() { this.$el.html...
LocationSelector
identifier_name
location-sel.js
(function() { var LocationSelector, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); chil...
LocationSelector.prototype.className = 'location-selector'; LocationSelector.prototype.events = { 'click .bit': 'handleClick' }; LocationSelector.prototype.render = function() { this.$el.html(''); return this.draw(); }; LocationSelector.prototype.draw = function()...
random_line_split
helpers.ts
import React from 'react'; import _ from 'lodash'; import {DEFAULT_LIST_CONFIG, LOOKUP_FIELDS, FB_URL, IG_URL} from './constants'; import * as fields from './components/fields'; export const onEventCapture = (event?) => { if (event) { event.preventDefault(); event.stopPropagation(); } }; expor...
export function validateRequiredFormFields(contact) { return validateRequiredField(contact) && validateMinRequiredField(contact); } export function validateRequiredField(contact) { const REQUIRED_CONTACT_FIELDS = getContactType(contact) === 'person' ? ['first_name', 'last_name'] : ['organisation']; ...
{ return _.some([contact.first_name, contact.last_name], (v) => !_.isEmpty(v)) ? 'person' : 'organisation'; }
identifier_body
helpers.ts
import React from 'react'; import _ from 'lodash'; import {DEFAULT_LIST_CONFIG, LOOKUP_FIELDS, FB_URL, IG_URL} from './constants'; import * as fields from './components/fields'; export const onEventCapture = (event?) => { if (event) { event.preventDefault(); event.stopPropagation(); } }; expor...
/* globals __SUPERDESK_CONFIG__: true */ const listConfig = __SUPERDESK_CONFIG__.contactList || DEFAULT_LIST_CONFIG; var specs = listConfig[area] || []; var contents = specs.map((field, index) => { if (fields[field]) { return fields[field](itemProps); } console.w...
{ return; }
conditional_block
helpers.ts
import React from 'react'; import _ from 'lodash'; import {DEFAULT_LIST_CONFIG, LOOKUP_FIELDS, FB_URL, IG_URL} from './constants'; import * as fields from './components/fields'; export const onEventCapture = (event?) => { if (event) { event.preventDefault(); event.stopPropagation(); } }; expor...
(contact) { return validateRequiredField(contact) && validateMinRequiredField(contact); } export function validateRequiredField(contact) { const REQUIRED_CONTACT_FIELDS = getContactType(contact) === 'person' ? ['first_name', 'last_name'] : ['organisation']; let invalid = _.some(REQUIRED_CONTACT_FI...
validateRequiredFormFields
identifier_name
helpers.ts
import React from 'react'; import _ from 'lodash'; import {DEFAULT_LIST_CONFIG, LOOKUP_FIELDS, FB_URL, IG_URL} from './constants'; import * as fields from './components/fields'; export const onEventCapture = (event?) => { if (event) { event.preventDefault(); event.stopPropagation(); } }; expor...
listRefElement.offsetHeight * 0.5); } } } };
(listRefElement.clientHeight - activeElement.clientHeight) || distanceOfSelItemFromVisibleTop < 0) { $(listRefElement).scrollTop($(listRefElement).scrollTop() + distanceOfSelItemFromVisibleTop -
random_line_split
donation-options.js
const React = require('react'); class
extends React.Component { constructor(props) { super(props); this.state = {selectedDonationOption: 'option1', btnActiveID: "donation-option-1"}; } btnIsActive = (value) => { return 'btn btn-primary ' + ((value===this.state.btnActiveID) ? 'active':''); } handleDonationOptionChange = (changeEvent) => { th...
DonationOptions
identifier_name
donation-options.js
const React = require('react'); class DonationOptions extends React.Component { constructor(props) { super(props); this.state = {selectedDonationOption: 'option1', btnActiveID: "donation-option-1"}; } btnIsActive = (value) => { return 'btn btn-primary ' + ((value===this.state.btnActiveID) ? 'active':''); } ...
</div> </div> </div> </div> ) } } export default DonationOptions;
{ return( <div className="btn-group donation-buttons"> <div className="row"> <div className="col-xs-12 p-0"> <div className="col-xs-4"> <label className={this.btnIsActive("donation-option-1")}> <input type="checkbox" name="options" className="donation-options" id="donation-option-...
identifier_body
donation-options.js
const React = require('react'); class DonationOptions extends React.Component { constructor(props) { super(props); this.state = {selectedDonationOption: 'option1', btnActiveID: "donation-option-1"}; } btnIsActive = (value) => { return 'btn btn-primary ' + ((value===this.state.btnActiveID) ? 'active':''); } ...
<div className="btn-group donation-buttons"> <div className="row"> <div className="col-xs-12 p-0"> <div className="col-xs-4"> <label className={this.btnIsActive("donation-option-1")}> <input type="checkbox" name="options" className="donation-options" id="donation-option-1" value="opt...
render() { return(
random_line_split
productGridItems.js
import React, { Component } from "react"; import PropTypes from "prop-types"; import { Components } from "@reactioncommerce/reaction-components"; import { formatPriceString } from "/client/api"; class ProductGridItems extends Component { static propTypes = { additionalMedia: PropTypes.func, canEdit: PropType...
{this.renderOverlay()} </div> {this.renderAdditionalMedia()} </a> {!this.props.isSearch && this.renderNotices()} {this.renderGridContent()} </div> </li> ); if (this.props.canEdit) { return ( this.props.connectDrop...
{ const productItem = ( <li className={`product-grid-item ${this.renderPinned()} ${this.props.weightClass()} ${this.props.isSelected()}`} data-id={this.props.product._id} id={this.props.product._id} > <div className={this.renderHoverClassName()}> <span className...
identifier_body
productGridItems.js
import React, { Component } from "react"; import PropTypes from "prop-types"; import { Components } from "@reactioncommerce/reaction-components"; import { formatPriceString } from "/client/api"; class ProductGridItems extends Component { static propTypes = { additionalMedia: PropTypes.func, canEdit: PropType...
return this.props.product.isVisible ? "" : "not-visible"; } renderOverlay() { if (this.props.product.isVisible === false) { return ( <div className="product-grid-overlay" /> ); } } renderMedia() { if (this.props.media() === false) { return ( <span className="p...
random_line_split
productGridItems.js
import React, { Component } from "react"; import PropTypes from "prop-types"; import { Components } from "@reactioncommerce/reaction-components"; import { formatPriceString } from "/client/api"; class ProductGridItems extends Component { static propTypes = { additionalMedia: PropTypes.func, canEdit: PropType...
return productItem; } } export default ProductGridItems;
{ return ( this.props.connectDropTarget( this.props.connectDragSource(productItem) ) ); }
conditional_block
productGridItems.js
import React, { Component } from "react"; import PropTypes from "prop-types"; import { Components } from "@reactioncommerce/reaction-components"; import { formatPriceString } from "/client/api"; class ProductGridItems extends Component { static propTypes = { additionalMedia: PropTypes.func, canEdit: PropType...
() { const productItem = ( <li className={`product-grid-item ${this.renderPinned()} ${this.props.weightClass()} ${this.props.isSelected()}`} data-id={this.props.product._id} id={this.props.product._id} > <div className={this.renderHoverClassName()}> <span classN...
render
identifier_name
layer.ts
// // Copyright 2019 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 applica...
return this.color; } }
{ const idx = this.ids.indexOf(interval.id); const brighter = d3.hsl(this.color).brighter(1); const darker = d3.hsl(this.color).darker(2); const color = d3.interpolateHsl(brighter, darker)(idx / (this.ids.length - 1)); return color; }
conditional_block
layer.ts
// // Copyright 2019 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 applica...
(interval: Interval) { if (this.interpolate) { const idx = this.ids.indexOf(interval.id); const brighter = d3.hsl(this.color).brighter(1); const darker = d3.hsl(this.color).darker(2); const color = d3.interpolateHsl(brighter, darker)(idx / (this.ids.length - 1)); return color...
getIntervalColor
identifier_name
layer.ts
// // Copyright 2019 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 applica...
parent?: string; initialized: boolean; } /** * Client-side collection interval representation, for rendering. * TODO(tracked) Make templated and remove casts of intervals member */ export class Layer implements LayerProps { // Flag used to indicate when a Layer is new and has no initial render data initiali...
interpolate: boolean; borderRadius: number; drawEdges: boolean;
random_line_split
layer.ts
// // Copyright 2019 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 applica...
}
{ if (this.interpolate) { const idx = this.ids.indexOf(interval.id); const brighter = d3.hsl(this.color).brighter(1); const darker = d3.hsl(this.color).darker(2); const color = d3.interpolateHsl(brighter, darker)(idx / (this.ids.length - 1)); return color; } return th...
identifier_body
stateHelper.provider.ts
import { copy, module } from 'angular'; import { StateRegistry } from '@uirouter/core'; import { INestedState } from './state.provider'; export class StateHelper implements ng.IServiceProvider { private registeredStates: string[] = []; public static $inject = ['$stateRegistryProvider']; constructor(private $sta...
} export const STATE_HELPER = 'spinnaker.core.navigation.stateHelper.provider'; module(STATE_HELPER, []).provider('stateHelper', StateHelper);
{ return this; }
identifier_body
stateHelper.provider.ts
import { copy, module } from 'angular'; import { StateRegistry } from '@uirouter/core'; import { INestedState } from './state.provider'; export class StateHelper implements ng.IServiceProvider { private registeredStates: string[] = []; public static $inject = ['$stateRegistryProvider']; constructor(private $sta...
private fixStateViews(state: INestedState) { const views = state.views || {}; const replaced: string[] = []; Object.keys(views).forEach(key => { const relative: RegExpMatchArray = key.match('../'); if (relative && relative.length && typeof state.parent === 'string') { const relativePa...
if (state.parent) { state.name = `${state.parent}.${state.name}`; } }
random_line_split
stateHelper.provider.ts
import { copy, module } from 'angular'; import { StateRegistry } from '@uirouter/core'; import { INestedState } from './state.provider'; export class StateHelper implements ng.IServiceProvider { private registeredStates: string[] = []; public static $inject = ['$stateRegistryProvider']; constructor(private $sta...
}); replaced.forEach(key => delete views[key]); } public $get(): StateHelper { return this; } } export const STATE_HELPER = 'spinnaker.core.navigation.stateHelper.provider'; module(STATE_HELPER, []).provider('stateHelper', StateHelper);
{ const relativePath: string = state.parent .split('.') .slice(0, -1 - relative.length) .join('.') + '.'; views[key.replace(/(..\/)+/, relativePath)] = views[key]; replaced.push(key); }
conditional_block
stateHelper.provider.ts
import { copy, module } from 'angular'; import { StateRegistry } from '@uirouter/core'; import { INestedState } from './state.provider'; export class StateHelper implements ng.IServiceProvider { private registeredStates: string[] = []; public static $inject = ['$stateRegistryProvider']; constructor(private $sta...
(state: INestedState) { const views = state.views || {}; const replaced: string[] = []; Object.keys(views).forEach(key => { const relative: RegExpMatchArray = key.match('../'); if (relative && relative.length && typeof state.parent === 'string') { const relativePath: string = s...
fixStateViews
identifier_name
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; ...
#[derive(Debug, Hash, PartialEq, Eq)] pub struct ImageView { pub(crate) image: vk::Image, pub(crate) raw: vk::ImageView, pub(crate) range: SubresourceRange, } #[derive(Debug, Hash)] pub struct Sampler(pub vk::Sampler); #[derive(Debug, Hash)] pub struct RenderPass { pub raw: vk::RenderPass, pub att...
pub(crate) ty: vk::ImageType, pub(crate) flags: vk::ImageCreateFlags, pub(crate) extent: vk::Extent3D, }
random_line_split
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; ...
(raw: vk::DescriptorPool, device: &Arc<RawDevice>) -> Self { DescriptorPool { raw, device: Arc::clone(device), temp_raw_sets: Vec::new(), temp_raw_layouts: Vec::new(), temp_layout_bindings: Vec::new(), } } pub(crate) fn finish(self) ->...
new
identifier_name
native.rs
use crate::{Backend, RawDevice, ROUGH_MAX_ATTACHMENT_COUNT}; use ash::{version::DeviceV1_0, vk}; use hal::{ device::OutOfMemory, image::{Extent, SubresourceRange}, pso, }; use inplace_it::inplace_or_alloc_from_iter; use parking_lot::Mutex; use smallvec::SmallVec; use std::{collections::HashMap, sync::Arc}; ...
}) } unsafe fn reset(&mut self) { assert_eq!( Ok(()), self.device .raw .reset_descriptor_pool(self.raw, vk::DescriptorPoolResetFlags::empty()) ); } } #[derive(Debug, Hash)] pub struct QueryPool(pub vk::QueryPool);
{ if let Err(e) = self.device.raw.free_descriptor_sets(self.raw, sets) { error!("free_descriptor_sets error {}", e); } }
conditional_block
recipes.resolver.ts
import { NotFoundException } from '@nestjs/common'; import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql'; import { PubSub } from 'apollo-server-express'; import { NewRecipeInput } from './dto/new-recipe.input'; import { RecipesArgs } from './dto/recipes.args'; import { Recipe } from './models...
if (!recipe) { throw new NotFoundException(id); } return recipe; } @Query(returns => [Recipe]) recipes(@Args() recipesArgs: RecipesArgs): Promise<Recipe[]> { return this.recipesService.findAll(recipesArgs); } @Mutation(returns => Recipe) async addRecipe( @Args('newRecipeData') ne...
async recipe(@Args('id') id: string): Promise<Recipe> { const recipe = await this.recipesService.findOneById(id);
random_line_split
recipes.resolver.ts
import { NotFoundException } from '@nestjs/common'; import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql'; import { PubSub } from 'apollo-server-express'; import { NewRecipeInput } from './dto/new-recipe.input'; import { RecipesArgs } from './dto/recipes.args'; import { Recipe } from './models...
return recipe; } @Query(returns => [Recipe]) recipes(@Args() recipesArgs: RecipesArgs): Promise<Recipe[]> { return this.recipesService.findAll(recipesArgs); } @Mutation(returns => Recipe) async addRecipe( @Args('newRecipeData') newRecipeData: NewRecipeInput, ): Promise<Recipe> { const r...
{ throw new NotFoundException(id); }
conditional_block
recipes.resolver.ts
import { NotFoundException } from '@nestjs/common'; import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql'; import { PubSub } from 'apollo-server-express'; import { NewRecipeInput } from './dto/new-recipe.input'; import { RecipesArgs } from './dto/recipes.args'; import { Recipe } from './models...
() { return pubSub.asyncIterator('recipeAdded'); } }
recipeAdded
identifier_name
recipes.resolver.ts
import { NotFoundException } from '@nestjs/common'; import { Args, Mutation, Query, Resolver, Subscription } from '@nestjs/graphql'; import { PubSub } from 'apollo-server-express'; import { NewRecipeInput } from './dto/new-recipe.input'; import { RecipesArgs } from './dto/recipes.args'; import { Recipe } from './models...
}
{ return pubSub.asyncIterator('recipeAdded'); }
identifier_body
views.py
import copy from django.db.models.fields.related import ForeignKey, OneToOneField from rest_framework import mixins from rest_framework.generics import ( GenericAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView, RetrieveUpdateDestroyAPIView ) from api.generics.serializers import ( DynamicFieldsMode...
for filter_field in filter_fields: found = False try: declared_filters = self.filter_class.declared_filters for key in declared_filters: if filter_field == key: found = True if found is False: ...
filter_fields.pop('q_fields')
conditional_block
views.py
import copy from django.db.models.fields.related import ForeignKey, OneToOneField from rest_framework import mixins from rest_framework.generics import ( GenericAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView, RetrieveUpdateDestroyAPIView ) from api.generics.serializers import ( DynamicFieldsMode...
def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.destroy(request, *args, **kwargs)
return self.update(request, *args, **kwargs)
identifier_body
views.py
import copy from django.db.models.fields.related import ForeignKey, OneToOneField from rest_framework import mixins from rest_framework.generics import ( GenericAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView, RetrieveUpdateDestroyAPIView ) from api.generics.serializers import ( DynamicFieldsMode...
return getattr(self, 'fields', ()) def filter_queryset(self, queryset, *args, **kwargs): """ Prefetches based on 'fields' GET arg """ filter_fields = copy.deepcopy(self.request.query_params) if 'fields' in filter_fields: filter_fields.pop('fields') ...
pass # Assign it again self.fields = tuple(fields)
random_line_split
views.py
import copy from django.db.models.fields.related import ForeignKey, OneToOneField from rest_framework import mixins from rest_framework.generics import ( GenericAPIView, ListAPIView, ListCreateAPIView, RetrieveAPIView, RetrieveUpdateDestroyAPIView ) from api.generics.serializers import ( DynamicFieldsMode...
(self, queryset, *args, **kwargs): """ Prefetches based on 'fields' GET arg """ filter_fields = copy.deepcopy(self.request.query_params) if 'fields' in filter_fields: filter_fields.pop('fields') if 'format' in filter_fields: filter_fields.pop('for...
filter_queryset
identifier_name
audio.rs
ll::AUDIO_S32MSB as isize, /// 32-bit floating point samples, little-endian F32LSB = ll::AUDIO_F32LSB as isize, /// 32-bit floating point samples, big-endian F32MSB = ll::AUDIO_F32MSB as isize } impl AudioFormat { fn from_ll(raw: ll::SDL_AudioFormat) -> Option<AudioFormat> { use self::Audi...
(n: u64) -> Option<AudioStatus> { FromPrimitive::from_i64(n as i64) } } #[derive(Copy, Clone)] pub struct DriverIterator { length: i32, index: i32 } impl Iterator for DriverIterator { type Item = &'static str; #[inline] fn next(&mut self) -> Option<&'static str> { if self.index >= self.le...
from_u64
identifier_name
audio.rs
ll::AUDIO_S32MSB as isize, /// 32-bit floating point samples, little-endian F32LSB = ll::AUDIO_F32LSB as isize, /// 32-bit floating point samples, big-endian F32MSB = ll::AUDIO_F32MSB as isize } impl AudioFormat { fn from_ll(raw: ll::SDL_AudioFormat) -> Option<AudioFormat> { use self::Audi...
impl ExactSizeIterator for DriverIterator { } /// Gets an iterator of all audio drivers compiled into the SDL2 library. #[inline] pub fn drivers() -> DriverIterator { // This function is thread-safe and doesn't require the audio subsystem to be initialized. // The list of drivers are read-only and statically c...
let l = self.length as usize; (l, Some(l)) } }
random_line_split
refeicao.service.ts
import { Injectable } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; import { AngularFireAuth } from 'angularfire2/auth'; //import firebase namespace for functions that aren't in AngularFire2 import * as firebase from 'firebase/app'...
}
{ return new Promise((resolve,reject)=>{ firebase.database().ref('refeicoes/') .orderByChild('timestamp') .equalTo(timestamp) .once('value') .then(snap => { if (snap.val() !== null) resolve(true); else resolve(false) }) .catch(reason => reject(reason)); ...
identifier_body
refeicao.service.ts
import { Injectable } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; import { AngularFireAuth } from 'angularfire2/auth'; //import firebase namespace for functions that aren't in AngularFire2 import * as firebase from 'firebase/app'...
{ constructor(private db: AngularFireDatabase, private _admin: AdminService) { } add(refeicao: any): firebase.Promise<any> { //Additional info refeicao['created_at'] = moment().valueOf(); refeicao['updated_at'] = moment().valueOf(); refeicao['created_by'] = this._admin.email; refeicao['vagas'...
RefeicaoService
identifier_name
refeicao.service.ts
import { Injectable } from '@angular/core'; import { AngularFireDatabase, FirebaseListObservable, FirebaseObjectObservable } from 'angularfire2/database'; import { AngularFireAuth } from 'angularfire2/auth'; //import firebase namespace for functions that aren't in AngularFire2 import * as firebase from 'firebase/app'...
refeicao['queue_released'] = 0; refeicao['users_count'] = 0; refeicao['usersVeg_count'] = 0; return Promise.all([ firebase.database().ref(`refeicoes/`).push(refeicao), firebase.database().ref('refeicoes/count').transaction(count => count + 1) ]); } edit(key: string, formValues: any)...
refeicao['sold_out'] = false; refeicao['queue_count'] = 0;
random_line_split
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. /*! `Worker` provides a mechanism to run tasks asynchronously (i.e. in the background) with some additional features, for example, ticks. A worker contains: - A runner (which should implement the `Runnable` trait): to run tasks one by one or in batc...
worker.stop(); drop(rx); } }
let (tx, rx) = mpsc::channel(); lazy_worker.start(BatchRunner { ch: tx }); assert!(rx.recv_timeout(Duration::from_secs(3)).is_ok());
random_line_split
mod.rs
// Copyright 2016 TiKV Project Authors. Licensed under Apache-2.0. /*! `Worker` provides a mechanism to run tasks asynchronously (i.e. in the background) with some additional features, for example, ticks. A worker contains: - A runner (which should implement the `Runnable` trait): to run tasks one by one or in batc...
() { let worker = Builder::new("test-worker-busy") .pending_capacity(3) .create(); let mut lazy_worker = worker.lazy_build("test-busy"); let scheduler = lazy_worker.scheduler(); for i in 0..3 { scheduler.schedule(i).unwrap(); } assert_...
test_pending_capacity
identifier_name