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
dining_philosophers.rs
// http://rosettacode.org/wiki/Dining_philosophers //! A Rust implementation of a solution for the Dining Philosophers Problem. We prevent a deadlock //! by using Dijkstra's solution of making a single diner "left-handed." That is, all diners except
use std::thread; use std::time::Duration; use std::sync::{Mutex, Arc}; struct Philosopher { name: String, left: usize, right: usize, } impl Philosopher { fn new(name: &str, left: usize, right: usize) -> Philosopher { Philosopher { name: name.to_string(), left: left, ...
//! one pick up the chopstick "to their left" and then the chopstick "to their right." The //! remaining diner performs this in reverse.
random_line_split
RedirectUri.ts
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.apach...
return encodeURIComponent(redirectUri) + encodeURIComponent("/#" + currentLocation); }
{ // '_hash_' is a workaround for when uri encoding is not // sufficient to escape the # character properly. // The problem is that both the redirect and the application URL contain a hash. // The browser will consider anything after the first hash to be client-side. So // it se...
conditional_block
RedirectUri.ts
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.apach...
redirectUri += "?referrer=" + referrer + "&referrer_uri=" + referrerUri.replace('#', '_hash_'); } return encodeURIComponent(redirectUri) + encodeURIComponent("/#" + currentLocation); }
// The browser will consider anything after the first hash to be client-side. So // it sees the hash in the redirect param and stops.
random_line_split
setup.py
try: from setuptools import setup except ImportError: from distutils.core import setup setup(name='agarnet', packages=['agarnet'],
author='Gjum', author_email='code.gjum@gmail.com', url='https://github.com/Gjum/agarnet', license='GPLv3', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'Intended Audience :: Education', ...
py_modules=['agarnet'], version='0.2.4', description='agar.io client and connection toolkit', install_requires=['websocket-client>=0.32.0'],
random_line_split
__init__.py
7600)), }) SCHEMA_SERVICE_SAY = vol.Schema({ vol.Required(ATTR_MESSAGE): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(ATTR_CACHE): cv.boolean, vol.Optional(ATTR_LANGUAGE): cv.string, vol.Optional(ATTR_OPTIONS): dict, }) SCHEMA_SERVICE_CLEAR_CACHE = vol.Schema({}) @asyncio...
raise HomeAssistantError( "Invalid options found: %s", invalid_opts) options_key = ctypes.c_size_t(hash(frozenset(options))).value else: options_key = '-' key = KEY_PATTERN.format( msg_hash, language, options_key, engine).lower() ...
random_line_split
__init__.py
7600)), }) SCHEMA_SERVICE_SAY = vol.Schema({ vol.Required(ATTR_MESSAGE): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(ATTR_CACHE): cv.boolean, vol.Optional(ATTR_LANGUAGE): cv.string, vol.Optional(ATTR_OPTIONS): dict, }) SCHEMA_SERVICE_CLEAR_CACHE = vol.Schema({}) @asyncio...
(self, engine, message, cache=None, language=None, options=None): """Get URL for play message. This method is a coroutine. """ provider = self.providers[engine] msg_hash = hashlib.sha1(bytes(message, 'utf-8')).hexdigest() use_cache = cache if cache ...
async_get_url
identifier_name
__init__.py
, p_type) if platform is None: return try: if hasattr(platform, 'async_get_engine'): provider = yield from platform.async_get_engine( hass, p_config) else: provider = yield from hass.loop.run_in_executor( ...
"""Cleanup memcache.""" self.mem_cache.pop(key)
identifier_body
__init__.py
7600)), }) SCHEMA_SERVICE_SAY = vol.Schema({ vol.Required(ATTR_MESSAGE): cv.string, vol.Optional(ATTR_ENTITY_ID): cv.entity_ids, vol.Optional(ATTR_CACHE): cv.boolean, vol.Optional(ATTR_LANGUAGE): cv.string, vol.Optional(ATTR_OPTIONS): dict, }) SCHEMA_SERVICE_CLEAR_CACHE = vol.Schema({}) @asyncio...
tts.async_register_engine(p_type, provider, p_config) except Exception: # pylint: disable=broad-except _LOGGER.exception("Error setting up platform %s", p_type) return @asyncio.coroutine def async_say_handle(service): """Service handle for say....
_LOGGER.error("Error setting up platform %s", p_type) return
conditional_block
utmpx.rs
(c) Jian Zeng <anonymousknight96@gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // //! Aims to provide platform-independent methods to obtain login records //! //! **ONLY** support linux, macos and freebsd for the time being ...
(&self) -> String { chars2string!(self.inner.ut_host) } /// A.K.A. ut.ut_line pub fn tty_device(&self) -> String { chars2string!(self.inner.ut_line) } /// A.K.A. ut.ut_tv pub fn login_time(&self) -> Tm { time::at(Timespec::new(self.inner.ut_tv.tv_sec as i64, ...
host
identifier_name
utmpx.rs
(c) Jian Zeng <anonymousknight96@gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // //! Aims to provide platform-independent methods to obtain login records //! //! **ONLY** support linux, macos and freebsd for the time being ...
/// A.K.A. ut.ut_user pub fn user(&self) -> String { chars2string!(self.inner.ut_user) } /// A.K.A. ut.ut_host pub fn host(&self) -> String { chars2string!(self.inner.ut_host) } /// A.K.A. ut.ut_line pub fn tty_device(&self) -> String { chars2string!(self.inner.u...
{ chars2string!(self.inner.ut_id) }
identifier_body
utmpx.rs
that was distributed with this source code. // //! Aims to provide platform-independent methods to obtain login records //! //! **ONLY** support linux, macos and freebsd for the time being //! //! # Examples: //! //! ``` //! use uucore::utmpx::Utmpx; //! for ut in Utmpx::iter_all_records() { //! if ut.is_user_proc...
{ endutxent(); None }
conditional_block
utmpx.rs
(c) Jian Zeng <anonymousknight96@gmail.com> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. // //! Aims to provide platform-independent methods to obtain login records //! //! **ONLY** support linux, macos and freebsd for the time being ...
pub const UT_LINESIZE: usize = 16; pub const UT_NAMESIZE: usize = 32; pub const UT_IDSIZE: usize = 8; pub const UT_HOSTSIZE: usize = 128; pub use libc::EMPTY; pub use libc::BOOT_TIME; pub use libc::OLD_TIME; pub use libc::NEW_TIME; pub use libc::USER_PROCESS; pub use libc::INIT_...
random_line_split
auth.service.js
'use strict'; angular.module('myjamApp') .factory('Auth', function Auth($location, $rootScope, $http, User, $cookieStore, $q) { var currentUser = {}; if($cookieStore.get('token')) { currentUser = User.get(); } return { /** * Authenticate user and save token * * @par...
var cb = callback || angular.noop; return User.changePassword({ id: currentUser._id }, { oldPassword: oldPassword, newPassword: newPassword }, function(user) { return cb(user); }, function(err) { return cb(err); }).$promise; }, ...
* @param {String} newPassword * @param {Function} callback - optional * @return {Promise} */ changePassword: function(oldPassword, newPassword, callback) {
random_line_split
main.rs
extern crate px8; extern crate sdl2; extern crate time; extern crate rand; #[macro_use] extern crate log; extern crate fern; extern crate nalgebra; use std::sync::{Arc, Mutex}; use px8::px8::math; use px8::frontend; use px8::gfx; use px8::cartridge; use px8::px8::RustPlugin; use px8::config::Players; use nalgebra::Ve...
} fn main() { let logger_config = fern::DispatchConfig { format: Box::new(|msg: &str, level: &log::LogLevel, _location: &log::LogLocation| { format!("[{}][{}] {}", time::now().strftime("%Y-%m-%d][%H:%M:%S").unwrap(), level, msg) ...
{ screen.lock().unwrap().cls(); for fighter in self.fighters.iter_mut() { fighter.draw(screen.clone()); } return 0.; }
identifier_body
main.rs
extern crate px8; extern crate sdl2; extern crate time; extern crate rand; #[macro_use] extern crate log; extern crate fern; extern crate nalgebra; use std::sync::{Arc, Mutex}; use px8::px8::math; use px8::frontend; use px8::gfx; use px8::cartridge; use px8::px8::RustPlugin; use px8::config::Players; use nalgebra::Ve...
let war = FourmisWar::new("./fourmiswar.dpx8".to_string()); let mut frontend = match frontend::Frontend::init(px8::gfx::Scale::Scale4x, false, true, true) { Err(error) => panic!("{:?}", error), Ok(frontend) => frontend, }; frontend.px8.register(war); frontend.start("./gamecontro...
{ panic!("Failed to initialize global logger: {}", e); }
conditional_block
main.rs
extern crate px8; extern crate sdl2; extern crate time; extern crate rand; #[macro_use] extern crate log; extern crate fern; extern crate nalgebra; use std::sync::{Arc, Mutex}; use px8::px8::math; use px8::frontend; use px8::gfx; use px8::cartridge; use px8::px8::RustPlugin; use px8::config::Players; use nalgebra::Ve...
(x: u32, y: u32) -> Fighter { Fighter { pos: Vector2::new(x, y) } } fn update(&mut self) { } fn draw(&mut self, screen: Arc<Mutex<gfx::Screen>>) { screen.lock().unwrap().pset(self.pos.x as i32, self.pos.y as i32, 8); } } pub struct FourmisWar { pub sprite_...
new
identifier_name
main.rs
extern crate px8; extern crate sdl2; extern crate time; extern crate rand; #[macro_use] extern crate log; extern crate fern; extern crate nalgebra; use std::sync::{Arc, Mutex}; use px8::px8::math; use px8::frontend; use px8::gfx; use px8::cartridge; use px8::px8::RustPlugin; use px8::config::Players; use nalgebra::Ve...
self.fighters.push(Fighter::new(40, 50)); match cartridge::Cartridge::parse(self.sprite_filename.clone(), false) { Ok(c) => screen.lock().unwrap().set_sprites(c.gfx.sprites), Err(e) => panic!("Impossible to load the assets {:?}", e), } return 0.; } fn u...
} } impl RustPlugin for FourmisWar { fn init(&mut self, screen: Arc<Mutex<gfx::Screen>>) -> f64 {
random_line_split
vendor-list.js
/*global angular*/ (function () { angular .module('simplAdmin.vendors') .controller('VendorListCtrl', ['vendorService', 'translateService', VendorListCtrl]); function Ve
endorService, translateService) { var vm = this; vm.tableStateRef = {}; vm.vendors = []; vm.translate = translateService; vm.getVendors = function getVendors(tableState) { vm.tableStateRef = tableState; vm.isLoading = true; vendorService.getVe...
ndorListCtrl(v
identifier_name
vendor-list.js
/*global angular*/ (function () { angular .module('simplAdmin.vendors') .controller('VendorListCtrl', ['vendorService', 'translateService', VendorListCtrl]); function VendorListCtrl(vendorService, translateService) { var vm = this; vm.tableStateRef = {}; vm.vendors = []...
vendorService.deleteVendor(vendor) .then(function (result) { vm.getVendors(vm.tableStateRef); toastr.success(vendor.name + ' has been deleted'); }) .catch(function (respons...
}; vm.deleteVendor = function deleteVendor(vendor) { bootbox.confirm('Are you sure you want to delete this vendor: ' + simplUtil.escapeHtml(vendor.name), function (result) { if (result) {
random_line_split
vendor-list.js
/*global angular*/ (function () { angular .module('simplAdmin.vendors') .controller('VendorListCtrl', ['vendorService', 'translateService', VendorListCtrl]); function VendorListCtrl(vendorService, translateService) { var vm = this; vm.tableStateRef = {}; vm.vendors = []...
}); }; } })();
vendorService.deleteVendor(vendor) .then(function (result) { vm.getVendors(vm.tableStateRef); toastr.success(vendor.name + ' has been deleted'); }) .catch(function (respons...
conditional_block
vendor-list.js
/*global angular*/ (function () { angular .module('simplAdmin.vendors') .controller('VendorListCtrl', ['vendorService', 'translateService', VendorListCtrl]); function VendorListCtrl(vendorService, translateService) {
.then(function (result) { vm.getVendors(vm.tableStateRef); toastr.success(vendor.name + ' has been deleted'); }) .catch(function (response) { toastr.error(response....
var vm = this; vm.tableStateRef = {}; vm.vendors = []; vm.translate = translateService; vm.getVendors = function getVendors(tableState) { vm.tableStateRef = tableState; vm.isLoading = true; vendorService.getVendors(tableState).then(function (r...
identifier_body
inversedocumentfrequencyvectorcreator.py
import math from ..df import DocumentFrequencyVectorCreator from . import InverseDocumentFrequencyVector class InverseDocumentFrequencyVectorCreator(DocumentFrequencyVectorCreator): """Creates inverse-document-frequency vectors Inherits from :class:`recommender.vector.abstractvector.VectorCreator` :par...
(self): """Creates a view in the database required for building idf-vectors """ with self._get_db_connection() as conn: self._create_log_function(conn) c = conn.cursor() c.execute( ''' CREATE VIEW IF NOT EXISTS [InverseDocumentF...
_create_inverse_document_frequency_view
identifier_name
inversedocumentfrequencyvectorcreator.py
import math from ..df import DocumentFrequencyVectorCreator from . import InverseDocumentFrequencyVector class InverseDocumentFrequencyVectorCreator(DocumentFrequencyVectorCreator): """Creates inverse-document-frequency vectors Inherits from :class:`recommender.vector.abstractvector.VectorCreator` :par...
def _create_vector(self, document_id=None): vector = InverseDocumentFrequencyVector() with self._get_db_connection() as conn: cursor = conn.cursor() self._create_log_function(conn) values = self._get_vector_values_from_db(cursor) for value i...
super(InverseDocumentFrequencyVectorCreator, self).__init__(db_connection_str) self._create_inverse_document_frequency_view() pass
identifier_body
inversedocumentfrequencyvectorcreator.py
import math from ..df import DocumentFrequencyVectorCreator from . import InverseDocumentFrequencyVector class InverseDocumentFrequencyVectorCreator(DocumentFrequencyVectorCreator): """Creates inverse-document-frequency vectors Inherits from :class:`recommender.vector.abstractvector.VectorCreator` :para...
c = conn.cursor() c.execute( ''' CREATE VIEW IF NOT EXISTS [InverseDocumentFrequency] AS SELECT [term_id] , [name] , log10 ( ...
with self._get_db_connection() as conn: self._create_log_function(conn)
random_line_split
inversedocumentfrequencyvectorcreator.py
import math from ..df import DocumentFrequencyVectorCreator from . import InverseDocumentFrequencyVector class InverseDocumentFrequencyVectorCreator(DocumentFrequencyVectorCreator): """Creates inverse-document-frequency vectors Inherits from :class:`recommender.vector.abstractvector.VectorCreator` :par...
return vector def _get_vector_values_from_db(self, c): c.execute( ''' SELECT [term_id] , [name] , [value] FROM [InverseDocumentFrequency] ; ''') vector_values = [...
vector.add_to_vector(value)
conditional_block
description.py
# ---------------------------------------------------------------------- # Numenta Platform for Intelligent Computing (NuPIC) # Copyright (C) 2011-2015, Numenta, Inc. Unless you have an agreement # with Numenta, Inc., for a separate license for this software code, the # following terms and conditions apply: # # This p...
# it under the terms of the GNU Affero Public License version 3 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Affero...
random_line_split
vmmToVmmUpdateNetworkMappingInput.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
() { return { required: false, serializedName: 'VmmToVmm', type: { name: 'Composite', className: 'VmmToVmmUpdateNetworkMappingInput', modelProperties: { instanceType: { required: true, serializedName: 'instanceType', type: { ...
mapper
identifier_name
vmmToVmmUpdateNetworkMappingInput.js
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ '...
* @returns {object} metadata of VmmToVmmUpdateNetworkMappingInput * */ mapper() { return { required: false, serializedName: 'VmmToVmm', type: { name: 'Composite', className: 'VmmToVmmUpdateNetworkMappingInput', modelProperties: { instanceType: { ...
*
random_line_split
decl.rs
use joker::track::*; use joker::token::StringLiteral; use id::Id; use fun::Fun; use patt::{Patt, CompoundPatt}; use expr::Expr; use punc::Semi; #[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)] pub enum Import { // ES6: more import forms ForEffect(Option<Span>, StringLiteral) } #[derive(D...
{ // ES6: more export forms Var(Option<Span>, Vec<Dtor>, Semi), Decl(Decl) } #[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)] pub enum Decl { Fun(Fun<Id>), Let(Option<Span>, Vec<Dtor>, Semi), Const(Option<Span>, Vec<ConstDtor>, Semi) } #[derive(Debug, PartialEq, Clone, Tr...
Export
identifier_name
decl.rs
use joker::track::*; use joker::token::StringLiteral; use id::Id; use fun::Fun; use patt::{Patt, CompoundPatt}; use expr::Expr; use punc::Semi; #[derive(Debug, PartialEq, Clone, TrackingRef, TrackingMut, Untrack)] pub enum Import { // ES6: more import forms ForEffect(Option<Span>, StringLiteral) } #[derive(D...
(lhs @ Patt::Compound(_), None) => Err(lhs), (Patt::Compound(patt), Some(rhs)) => { Ok(Dtor::from_compound_init(patt, rhs)) } } } } impl DtorExt for ConstDtor { fn from_compound_init(lhs: CompoundPatt<Id>, rhs: Expr) -> ConstDtor { ConstDtor::...
random_line_split
DiffCompare.py
to link the code of this program with any version of the * # * OpenSSL library which is distributed under a license identical to that * # * listed in the included docs/licenses/OpenSSL.txt file, and distribute * # * linked combinations including the two. * # * ...
def _attaching_widgets(self): self.table.attach(self.combo_scan, 0, 1, 0, 1, yoptions=0) self.table.attach( self.btn_open_scan, 1, 2, 0, 1, yoptions=0, xoptions=0) self.table.attach(self.exp_scan, 0, 2, 1, 2) def _set_scrolled(self): self.scrolled.set_border_widt...
random_line_split
DiffCompare.py
IGSectionLabel from zenmapGUI.higwidgets.higtables import HIGTable from zenmapGUI.higwidgets.higbuttons import HIGButton from zenmapCore.NmapParser import NmapParser from zenmapCore.UmitLogging import log import zenmapCore.I18N import zenmapCore.Diff from zenmapGUI.FileChoosers import ResultsFileSingleChooserDialog ...
"""This method is called whenever the diff output might have changed, such as when a different scan was selected in one of the choosers.""" log.debug("Refresh diff.") if (self.ndiff_process is not None and self.ndiff_process.poll() is None): # Put this in the list of...
identifier_body
DiffCompare.py
* # * Work may not be combined (even as part of a larger work) with plain GPL * # * software. The terms, conditions, and exceptions of this license must * # * be included as well. This license is incompatible with some other open * # * source licenses as well. In some cases we can relicense portions of * #...
_text_changed_cb
identifier_name
DiffCompare.py
gtk.STOCK_OPEN) self.exp_scan = gtk.Expander(_("Scan Output")) self.scrolled = gtk.ScrolledWindow() self.txt_scan_result = gtk.TextView() self.txg_tag = gtk.TextTag("scan_style") def get_buffer(self): return self.txt_scan_result.get_buffer() def show_scan(self, widget):...
error_text = _( "The ndiff process terminated with status code %d." ) % status stderr = self.ndiff_process.stderr.read() if len(stderr) > 0: error_text += "\n\n" + stderr alert = HIGAlertDialog( ...
conditional_block
3_07_oscillating_objects.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 5-07: Oscillating Objects use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct Model { // An array of type Oscillator oscillators: Vec<Oscillator>, } #[derive(Clone)] struct Oscillator { ...
} fn model(app: &App) -> Model { let rect = Rect::from_w_h(640.0, 360.0); app.new_window() .size(rect.w() as u32, rect.h() as u32) .view(view) .build() .unwrap(); //let oscillators = vec![Oscillator::new(app.window_rect()); 10]; let oscillators = (0..10).map(|_| Oscillat...
.rgba(0.5, 0.5, 0.5, 0.5) .stroke(BLACK) .stroke_weight(2.0); }
random_line_split
3_07_oscillating_objects.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 5-07: Oscillating Objects use nannou::prelude::*; fn main() { nannou::app(model).update(update).run(); } struct
{ // An array of type Oscillator oscillators: Vec<Oscillator>, } #[derive(Clone)] struct Oscillator { angle: Vector2, velocity: Vector2, amplitude: Vector2, } impl Oscillator { fn new(rect: Rect) -> Self { let angle = vec2(0.0, 0.0); let velocity = vec2(random_f32() * 0.1 - 0....
Model
identifier_name
3_07_oscillating_objects.rs
// The Nature of Code // Daniel Shiffman // http://natureofcode.com // // Example 5-07: Oscillating Objects use nannou::prelude::*; fn main()
struct Model { // An array of type Oscillator oscillators: Vec<Oscillator>, } #[derive(Clone)] struct Oscillator { angle: Vector2, velocity: Vector2, amplitude: Vector2, } impl Oscillator { fn new(rect: Rect) -> Self { let angle = vec2(0.0, 0.0); let velocity = vec2(random_f3...
{ nannou::app(model).update(update).run(); }
identifier_body
server_lib_same_variables_clear_test.py
# Copyright 2017 The TensorFlow Authors. 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...
self.assertAllEqual([[4]], sess_2.run(v2)) # Connects to the same target. Device memory for the variables would have # been released, so they will be uninitialized. sess_2 = session.Session(server.target) with self.assertRaises(errors_impl.FailedPreconditionError): sess_2.run(v2) # Rein...
@test_util.run_deprecated_v1 def testSameVariablesClear(self): server = server_lib.Server.create_local_server() # Creates a graph with 2 variables. v0 = variables.Variable([[2, 1]], name="v0") v1 = variables.Variable([[1], [2]], name="v1") v2 = math_ops.matmul(v0, v1) # Verifies that both se...
identifier_body
server_lib_same_variables_clear_test.py
# Copyright 2017 The TensorFlow Authors. 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...
server = server_lib.Server.create_local_server() # Creates a graph with 2 variables. v0 = variables.Variable([[2, 1]], name="v0") v1 = variables.Variable([[1], [2]], name="v1") v2 = math_ops.matmul(v0, v1) # Verifies that both sessions connecting to the same target return # the same result...
# "server_lib_test.py" when this is no longer the case. @test_util.run_deprecated_v1 def testSameVariablesClear(self):
random_line_split
server_lib_same_variables_clear_test.py
# Copyright 2017 The TensorFlow Authors. 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...
test.main()
conditional_block
server_lib_same_variables_clear_test.py
# Copyright 2017 The TensorFlow Authors. 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...
(test.TestCase): # Verifies behavior of tf.Session.reset(). # TODO(b/34465411): Starting multiple servers with different configurations # in the same test is flaky. Move this test case back into # "server_lib_test.py" when this is no longer the case. @test_util.run_deprecated_v1 def testSameVariablesClear(...
SameVariablesClearTest
identifier_name
main.rs
use std::io; struct PrioData { lists: Vec<PrioList>, } struct PrioList { name: String, items: Vec<String>, } impl PrioList { fn new(name: &str, items: Vec<String>) -> PrioList { PrioList { name: name.to_string(), items: items.clone(), } } fn add_item(&m...
} fn main() { let mut data = PrioData { lists: vec![PrioList::new("High", vec!["something".to_string(), "something else".to_string()])] }; loop { let prompt = "What do you want to do? (Type \"back\" at any time to return to the previos menu)"; let choices = vec![ "1. V...
{ self.items.push(new_item.to_string()); }
identifier_body
main.rs
use std::io; struct PrioData { lists: Vec<PrioList>, } struct PrioList { name: String, items: Vec<String>, } impl PrioList { fn new(name: &str, items: Vec<String>) -> PrioList { PrioList { name: name.to_string(), items: items.clone(), } } fn add_item(&m...
if new_item == "back" { break; } list.add_item(&new_item); } } fn create_priority_list(data: &PrioData) { println!("create list!"); } fn switch_board(prompt: &str, choices: Vec<String>) -> String { println!("\n{}", prompt); for choice in choices { println!(...
random_line_split
main.rs
use std::io; struct PrioData { lists: Vec<PrioList>, } struct PrioList { name: String, items: Vec<String>, } impl PrioList { fn new(name: &str, items: Vec<String>) -> PrioList { PrioList { name: name.to_string(), items: items.clone(), } } fn add_item(&m...
(prompt: &str, choices: Vec<String>) -> String { println!("\n{}", prompt); for choice in choices { println!("{}", choice); } let choice = read_line(); choice.to_string() } fn read_line() -> String{ let mut line = String::new(); io::stdin().read_line(&mut line) .ok() ...
switch_board
identifier_name
login.js
var userData = [ {'fName':'Justin', 'lName' : 'Gil', 'age': 70, 'gender': 'M', 'phone': '949-111-1111', 'profilePic': '../pix/justin.jpeg', 'city' : 'San Diego', 'add' : '55 Serenity' , 'Bio': 'I like soccer and long walks on the beach.', 'userIndex' : 1, 'username': 'justin', 'password': 'lol', 'state' : 'CA',...
}); $("#login").click(function() { var invalidAccountWarning = document.getElementById("invalid_account_warning"); invalidAccountWarning.style.display = "none"; var username = document.getElementById("inputted_username").value; var password = document.getElementById("inputted_password").value; var...
invalidAccountWarning.style.display = "none";
random_line_split
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to m...
/// Begin a layout debug trace. If this has not been called, /// creating debug scopes has no effect. pub fn begin_trace(flow_root: FlowRef) { assert!(state_key.get().is_none()); let flow_trace = json::encode(&flow_root.deref()); let state = State { scope_stack: vec![box ScopeData::new("root".to_...
{ unsafe { DEBUG_ID_COUNTER.fetch_add(1, SeqCst) as u16 } }
identifier_body
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to m...
; #[macro_export] macro_rules! layout_debug_scope( ($($arg:tt)*) => ( if cfg!(not(ndebug)) { layout_debug::Scope::new(format!($($arg)*)) } else { layout_debug::Scope } ) ) #[deriving(Encodable)] struct ScopeData { name: String, pre: String, post: Str...
Scope
identifier_name
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to m...
pub fn begin_trace(flow_root: FlowRef) { assert!(state_key.get().is_none()); let flow_trace = json::encode(&flow_root.deref()); let state = State { scope_stack: vec![box ScopeData::new("root".to_string(), flow_trace)], flow_root: flow_root, }; state_key.replace(Some(RefCell::new(sta...
random_line_split
layout_debug.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/. */ //! Supports writing a trace file created during each layout scope //! that can be viewed by an external tool to m...
} Scope } } #[cfg(not(ndebug))] impl Drop for Scope { fn drop(&mut self) { let maybe_refcell = state_key.get(); match maybe_refcell { Some(refcell) => { let mut state = refcell.borrow_mut(); let mut current_scope = state.scope_stack.p...
{}
conditional_block
main.rs
#![cfg(not(test))] extern crate zaldinar; extern crate getopts; macro_rules! print_err { ($($arg:tt)*) => ( { use std::io::prelude::*; if let Err(e) = write!(&mut ::std::io::stderr(), "{}\n", format_args!($($arg)*)) { panic!("Failed to write to stderr.\ ...
() { let result = main_exits(); std::process::exit(result); } /// Separate function from main to ensure that everything is cleaned up by exiting scope before /// program exits using std::process::exit(); fn main_exits() -> i32 { // Because env::current_exe() will change if the executing file is moved, we n...
main
identifier_name
main.rs
#![cfg(not(test))] extern crate zaldinar; extern crate getopts; macro_rules! print_err { ($($arg:tt)*) => ( { use std::io::prelude::*; if let Err(e) = write!(&mut ::std::io::stderr(), "{}\n", format_args!($($arg)*)) { panic!("Failed to write to stderr.\ ...
fn get_program() -> io::Result<PathBuf> { // This joins current_dir() and current_exe(), resulting in an absolute path to of the current // executable let mut buf = try!(env::current_dir()); buf.push(&try!(env::current_exe())); return Ok(buf); } fn main() { let result = main_exits(); std...
{ println!("Can't restart using execv on this platform!"); return 1; }
identifier_body
main.rs
#![cfg(not(test))] extern crate zaldinar; extern crate getopts; macro_rules! print_err { ($($arg:tt)*) => ( { use std::io::prelude::*; if let Err(e) = write!(&mut ::std::io::stderr(), "{}\n", format_args!($($arg)*)) { panic!("Failed to write to stderr.\ ...
}; let mut opts = getopts::Options::new(); opts.optopt("c", "config", "set config file name", "FILE"); opts.optflag("h", "help", "print this help menu"); opts.optflag("v", "version", "print program version"); // TODO: Bug getopts to use OsString let matches = match opts.parse(args.collect::...
let display_program = match args.next() { // TODO: some error catching of lossy strings here or not? Some(v) => v, None => original_program.as_os_str().to_string_lossy().into_owned(),
random_line_split
05-payments-history.js
/** * Example 05 - How to retrieve your payments history. */ const express = require('express'); const { createMollieClient } = require('@mollie/api-client'); const app = express(); const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); app.get('/', (req, res) => { let paymen...
}); }); app.listen(8000, () => console.log('Example app listening on port 8000.'));
`); }) .catch(error => { // Do some proper error handling. res.send(error);
random_line_split
05-payments-history.js
/** * Example 05 - How to retrieve your payments history. */ const express = require('express'); const { createMollieClient } = require('@mollie/api-client'); const app = express(); const mollieClient = createMollieClient({ apiKey: 'test_dHar4XY7LxsDOtmnkVtjNVWXLSlXsM' }); app.get('/', (req, res) => { let paymen...
mollieClient.payments .all(paymentParameters) .then(payments => { res.send(` <ul> ${payments .map( payment => `<li> Payment ID: ${payment.id}<br /> Method: ${payment.method}<br /> Amount: ${payment.amount...
{ paymentParameters = { ...paymentParameters, from: req.query.from, }; }
conditional_block
geoip.py
# # ident/geoio.py # # Copyright (C) 2011 Damien Churchill <damoxc@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version.
# # You should have received a copy of the GNU General Public License # along with this program. If not, write to: # The Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor # Boston, MA 02110-1301, USA. # import GeoIP import logging from vsmtpd.hooks import hook from vsmtpd.plugins.plugin im...
# # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details.
random_line_split
geoip.py
# # ident/geoio.py # # Copyright (C) 2011 Damien Churchill <damoxc@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # Thi...
(self, connection): country = self.gi.country_code_by_addr(connection.remote_ip) connection.notes['geoip_country'] = country
connect
identifier_name
geoip.py
# # ident/geoio.py # # Copyright (C) 2011 Damien Churchill <damoxc@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # Thi...
def __init__(self): self.gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE) @hook def connect(self, connection): country = self.gi.country_code_by_addr(connection.remote_ip) connection.notes['geoip_country'] = country
identifier_body
user-profile.component.ts
import { Component, OnInit } from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; import {FormGroup, FormBuilder, Validators} from '@angular/forms'; import { AuthService } from '../../services/auth.service'; import { ValidatorService } from...
styleUrls: ['./user-profile.component.css'], providers: [ValidatorService] }) export class UserProfileComponent implements OnInit { public userForm: FormGroup; public formErrors; private user; constructor(public fb: FormBuilder, public authService: AuthService, public validator...
@Component({ selector: 'app-user-profile', templateUrl: './user-profile.component.html',
random_line_split
user-profile.component.ts
import { Component, OnInit } from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; import {FormGroup, FormBuilder, Validators} from '@angular/forms'; import { AuthService } from '../../services/auth.service'; import { ValidatorService } from...
ngOnInit() { this.user = this.authService.thisUser; this.formErrors = this.validatorService.getFormErrors(); console.log(this.user) this.buildForm(); } private buildForm() { this.userForm = this.fb.group({ "name": [ this.user.name, [ Validators.required, ...
{ }
identifier_body
user-profile.component.ts
import { Component, OnInit } from '@angular/core'; import {ActivatedRoute, Router} from '@angular/router'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; import {FormGroup, FormBuilder, Validators} from '@angular/forms'; import { AuthService } from '../../services/auth.service'; import { ValidatorService } from...
implements OnInit { public userForm: FormGroup; public formErrors; private user; constructor(public fb: FormBuilder, public authService: AuthService, public validatorService: ValidatorService, public router: Router, public toastr: ToastsManager) { } ...
UserProfileComponent
identifier_name
drawphone.js
// // Drawphone // import Game from "./game.js"; class Drawphone { constructor(devModeEnabled) { this.games = []; this.locked = false; this.minutesUntilRestart; //add the dev game if (devModeEnabled) { this.newGame("ffff"); } } newGame(forceCod...
} return false; } generateCode() { let code; do { //generate 4 letter code code = ""; const possible = "abcdefghijklmnopqrstuvwxyz"; for (let i = 0; i < 4; i++) { code += possible.charAt( Math.f...
{ return this.games[i]; }
conditional_block
drawphone.js
// // Drawphone // import Game from "./game.js"; class Drawphone { constructor(devModeEnabled) { this.games = []; this.locked = false; this.minutesUntilRestart; //add the dev game if (devModeEnabled) { this.newGame("ffff"); } } newGame(forceCod...
Math.floor(Math.random() * possible.length) ); } //make sure the code is not already in use } while (this.findGame(code)); return code; } removeGame(code) { const game = this.findGame(code); const index = this.games.in...
code = ""; const possible = "abcdefghijklmnopqrstuvwxyz"; for (let i = 0; i < 4; i++) { code += possible.charAt(
random_line_split
drawphone.js
// // Drawphone // import Game from "./game.js"; class Drawphone { constructor(devModeEnabled) { this.games = []; this.locked = false; this.minutesUntilRestart; //add the dev game if (devModeEnabled) { this.newGame("ffff"); } } newGame(forceCod...
removeGame(code) { const game = this.findGame(code); const index = this.games.indexOf(game); if (index > -1) { this.games.splice(index, 1); } } lock() { this.locked = true; this.minutesUntilRestart = 16; const interval = setInterval((...
{ let code; do { //generate 4 letter code code = ""; const possible = "abcdefghijklmnopqrstuvwxyz"; for (let i = 0; i < 4; i++) { code += possible.charAt( Math.floor(Math.random() * possible.length) ); ...
identifier_body
drawphone.js
// // Drawphone // import Game from "./game.js"; class Drawphone {
(devModeEnabled) { this.games = []; this.locked = false; this.minutesUntilRestart; //add the dev game if (devModeEnabled) { this.newGame("ffff"); } } newGame(forceCode) { if (this.locked) return false; let newCode; if (forceC...
constructor
identifier_name
watch_directory.py
"""Working example of the ReadDirectoryChanges API which will track changes made to a directory. Can either be run from a command-line, with a comma-separated list of paths to watch, or used as a module, either via the watch_path generator or via the Watcher threads, one thread per path. Examples: watch_director...
(sizer_requests, n_sizers): for n in range (n_sizers): sizer_requests.put (None) if __name__ == '__main__': """If run from the command line, use the thread-based routine to watch the current directory (default) or a list of directories specified on the command-line separated by commas, eg wat...
stop_sizers
identifier_name
watch_directory.py
"""Working example of the ReadDirectoryChanges API which will track changes made to a directory. Can either be run from a command-line, with a comma-separated list of paths to watch, or used as a module, either via the watch_path generator or via the Watcher threads, one thread per path. Examples: watch_director...
watch_directory.py c:/temp,c:/ """ PATH_TO_WATCH = "." N_SIZERS = 5 try: path_to_watch = sys.argv[1] or PATH_TO_WATCH except IndexError: path_to_watch = PATH_TO_WATCH path_to_watch = os.path.abspath (path_to_watch) sizer_requests = Queue.Queue () sizer_results = Queue.Queue () si...
separated by commas, eg
random_line_split
watch_directory.py
"""Working example of the ReadDirectoryChanges API which will track changes made to a directory. Can either be run from a command-line, with a comma-separated list of paths to watch, or used as a module, either via the watch_path generator or via the Watcher threads, one thread per path. Examples: watch_director...
full_filename = os.path.join (path_to_watch, file) if not os.path.exists (full_filename): file_type = "<deleted>" elif os.path.isdir (full_filename): file_type = 'folder' else: file_type = 'file' yield (file_type, full_filename, ACTIONS.get (action, "Unknown")) cl...
FILE_LIST_DIRECTORY = 0x0001 hDir = win32file.CreateFile ( path_to_watch, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None ) while True: results = win32file.ReadDirectoryChangesW ( ...
identifier_body
watch_directory.py
"""Working example of the ReadDirectoryChanges API which will track changes made to a directory. Can either be run from a command-line, with a comma-separated list of paths to watch, or used as a module, either via the watch_path generator or via the Watcher threads, one thread per path. Examples: watch_director...
yield (file_type, full_filename, ACTIONS.get (action, "Unknown")) class Watcher (threading.Thread): def __init__ (self, path_to_watch, results_queue, **kwds): threading.Thread.__init__ (self, **kwds) self.setDaemon (1) self.path_to_watch = path_to_watch self.results_queue = results_queue ...
file_type = 'file'
conditional_block
Latin1Supplement.js
/* * /MathJax/jax/element/mml/optable/Latin1Supplement.js * * Copyright (c) 2009-2016 The MathJax Consortium * * 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....
(function(a){var c=a.mo.OPTYPES;var b=a.TEXCLASS;MathJax.Hub.Insert(a.mo.prototype,{OPTABLE:{postfix:{"\u00B0":c.ORD,"\u00B4":c.ACCENT,"\u00B8":c.ACCENT}}});MathJax.Ajax.loadComplete(a.optableDir+"/Latin1Supplement.js")})(MathJax.ElementJax.mml);
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */
random_line_split
region_IO.py
"""Auto-generated file, do not edit by hand. IO metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_IO = PhoneMetadata(id='IO', country_code=246, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='3\\d{6}', possible_number_pattern='\\d{7...
premium_rate=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), shared_cost=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), personal_number=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'), voip=PhoneNumberDesc(national_nu...
mobile=PhoneNumberDesc(national_number_pattern='38\\d{5}', possible_number_pattern='\\d{7}', example_number='3801234'), toll_free=PhoneNumberDesc(national_number_pattern='NA', possible_number_pattern='NA'),
random_line_split
nodes.py
#!/usr/bin/python3 # nodes.py is to recursively gather page links # from magnolia RESTful output of nodes. # Example usage: # curl --user '...' -H 'Accept: application/json' 'http://localhost:8080/mjdf38i3tv0b56vz/.rest/nodes/v1/website/testing-site-destroyer?depth=999&excludeNodeTypes=mgnl:resource,mgnl:metaData,mgnl:...
for line in sys.stdin: nodes(json.loads(line))
for n in v: nodes(n)
conditional_block
nodes.py
#!/usr/bin/python3 # nodes.py is to recursively gather page links # from magnolia RESTful output of nodes. # Example usage: # curl --user '...' -H 'Accept: application/json' 'http://localhost:8080/mjdf38i3tv0b56vz/.rest/nodes/v1/website/testing-site-destroyer?depth=999&excludeNodeTypes=mgnl:resource,mgnl:metaData,mgnl:...
(d): for k, v in d.items(): if k == "path": print(v.replace("/"+args.site,args.domain)) elif k == "nodes": if v is not None: for n in v: nodes(n) for line in sys.stdin: nodes(json.loads(line))
nodes
identifier_name
nodes.py
#!/usr/bin/python3 # nodes.py is to recursively gather page links # from magnolia RESTful output of nodes. # Example usage: # curl --user '...' -H 'Accept: application/json' 'http://localhost:8080/mjdf38i3tv0b56vz/.rest/nodes/v1/website/testing-site-destroyer?depth=999&excludeNodeTypes=mgnl:resource,mgnl:metaData,mgnl:...
for line in sys.stdin: nodes(json.loads(line))
for k, v in d.items(): if k == "path": print(v.replace("/"+args.site,args.domain)) elif k == "nodes": if v is not None: for n in v: nodes(n)
identifier_body
nodes.py
#!/usr/bin/python3 # nodes.py is to recursively gather page links # from magnolia RESTful output of nodes. # Example usage: # curl --user '...' -H 'Accept: application/json' 'http://localhost:8080/mjdf38i3tv0b56vz/.rest/nodes/v1/website/testing-site-destroyer?depth=999&excludeNodeTypes=mgnl:resource,mgnl:metaData,mgnl:...
if v is not None: for n in v: nodes(n) for line in sys.stdin: nodes(json.loads(line))
if k == "path": print(v.replace("/"+args.site,args.domain)) elif k == "nodes":
random_line_split
panelSlider.js
$.widget( "alexandra.panelSlider", { options: { currentView: null, // The panel currently in focus panels:[] // All panels added to the navigation system }, //The constructor of the panelSLide widget _create: function() { var tempThis=this; this.element.addClass("pan...
}, //The function that actually does all the sliding //If the goingBack variable is true the sliding will happen from left to right, and vice versa slide: function(panelToShow, goingBack){ /* Making sure that only registered objects can act as panels. Might be a little...
{ if(this.options.panels[i]==panel){ if(panel==this.options.currentView){ $("#"+panel).hide(); this.options.currentView= i-1<0 ? this.options.panels[1] : this.options.panels[i-1]; $("#"+this.options.currentView).show(); ...
conditional_block
panelSlider.js
$.widget( "alexandra.panelSlider", { options: { currentView: null, // The panel currently in focus panels:[] // All panels added to the navigation system }, //The constructor of the panelSLide widget _create: function() { var tempThis=this; this.element.addClass("pan...
var urlRegex = '/^(https?://)?([da-z.-]+).([a-z.]{2,6})([/w .-]*)*/?$/'; var res = url.match(urlRegex); if(res==null){ var newView=$.inArray(url,tempThis.options.panels); if(newView>-1){ var curView=$.inArray...
event.preventDefault(); event.stopPropagation(); var url = $(this).attr('href');
random_line_split
emulate_binary.py
#! /usr/bin/env python # Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notic...
def atoi_hook(emulator, state): print("[+] atoi hooked!") # int atoi(const char *nptr); cc = state['cc'] # Read parameters. nptr = cc.parameters[0] # Emulate function behavior. value = int(read_c_string(emulator, nptr, max_length=1024)) # Save result. cc.return_value = value ...
if '--' in argv: prg_options = argv[1:argv.index('--')] prg_arguments = argv[argv.index('--')+1:] else: prg_options = argv[1:] prg_arguments = [] return prg_options, prg_arguments
identifier_body
emulate_binary.py
#! /usr/bin/env python # Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notic...
name, size, returns = symbols_by_addr[addr] symbols_by_name[name] = (addr, size, returns) return symbols_by_addr, symbols_by_name def setup_argv(emulator, argv, base_addr): addr_size = emulator.arch_info.address_size // 8 argv_entry_addr = {} # Copy arguments into the stack but firs...
symbols_by_addr = load_symbols(binary_path) symbols_by_name = {} for addr in symbols_by_addr:
random_line_split
emulate_binary.py
#! /usr/bin/env python # Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notic...
if start & 0x1 == 0x0: # ARCH_ARM_MODE_ARM atoi_addr = 0x10388 printf_addr = 0x10358 state = { 'cc': cc, } ctx_init = { 'registers': { arch.flags_register(): arch.flags_default_value(), arch.stack_pointer_register(): sp, ...
atoi_addr = 0x10394 printf_addr = 0x1035c
conditional_block
emulate_binary.py
#! /usr/bin/env python # Copyright (c) 2014, Fundacion Dr. Manuel Sadosky # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notic...
(emulator, argv, base_addr): addr_size = emulator.arch_info.address_size // 8 argv_entry_addr = {} # Copy arguments into the stack but first leave space for the argv # array (null-terminated). addr = base_addr + (len(argv) + 1) * addr_size for index, arg in enumerate(argv): argv_entry_...
setup_argv
identifier_name
sqlitestorage.py
(engineDir, exist_ok=True) dbPath = os.path.join(engineDir, 'db.sqlite3') E.conn = sqlite3.connect(dbPath) E.fields = list(Record.fields.keys()) E.createTables(E.conn) @staticmethod def createTables(conn): cur = conn.cursor() sql = "SELECT name FROM sqlite...
@staticmethod def load(id): """ Load the content of the record from disk, parse it, and return a record instance. """ fields = ','.join(E.fields) table = E.recordTbl sql = 'SELECT %s FROM %s WHERE id LIKE ?' % (fields, table) cur = E.conn.cursor()...
""" Do a database transaction rollback """ E.conn.rollback()
identifier_body
sqlitestorage.py
(engineDir, exist_ok=True) dbPath = os.path.join(engineDir, 'db.sqlite3') E.conn = sqlite3.connect(dbPath) E.fields = list(Record.fields.keys()) E.createTables(E.conn) @staticmethod def createTables(conn): cur = conn.cursor() sql = "SELECT name FROM sqlite...
try: cur = E.conn.cursor() cur.execute('begin') cur.execute(sql, vals) if commit: E.commit() return record except: return None @staticmethod def allIds(): """ Return a generator which yields IDs of ...
if record == oldRecord: return # update keys = [] for k in E.fields: vnew = getattr(record, k) vold = getattr(oldRecord, k) if vnew != vold: keys.append(k) vals = [data[k] for k in keys] ...
conditional_block
sqlitestorage.py
(engineDir, exist_ok=True) dbPath = os.path.join(engineDir, 'db.sqlite3') E.conn = sqlite3.connect(dbPath) E.fields = list(Record.fields.keys()) E.createTables(E.conn) @staticmethod def createTables(conn): cur = conn.cursor() sql = "SELECT name FROM sqlite...
(id): """ Return all IDs that starts with 'id' """ table = E.recordTbl sql = 'select id from %s where id like ?' % table val = [id + '%'] cur = E.conn.cursor() cur.execute(sql, val) ids = cur.fetchall() ids = [x[0] for x in ids] r...
matchId
identifier_name
sqlitestorage.py
)') cur.execute('CREATE INDEX record_time_idx ON record (time)') cur.execute('CREATE INDEX record_mtime_idx ON record (mtime)') conn.commit() @staticmethod def commit(): """ Do a database transaction commit """ E.conn.commit() @staticmethod def rollback(...
random_line_split
issue-6815.ts
import {expect} from "chai"; import {Connection} from "../../../src/connection/Connection"; import {EntityManager} from "../../../src/entity-manager/EntityManager"; import { createTestingConnections, closeTestingConnections, reloadTestingDatabases, } from "../../utils/test-utils"; import {ChildEntity} from ...
before(async () => connections = await createTestingConnections({ entities: [__dirname + "/entity/*{.js,.ts}"], schemaCreate: true, dropSchema: true, enabledDrivers: ["cockroachdb", "mariadb", "mssql", "mysql", "postgres"] })); beforeEach(() => reloadTestingDatabases(connec...
random_line_split
issue-6815.ts
import {expect} from "chai"; import {Connection} from "../../../src/connection/Connection"; import {EntityManager} from "../../../src/entity-manager/EntityManager"; import { createTestingConnections, closeTestingConnections, reloadTestingDatabases, } from "../../utils/test-utils"; import {ChildEntity} from ...
}) )); });
{ expect(loaded.childId).to.equal(child.id); }
conditional_block
__init__.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Addons modules by CLEARCORP S.A. # Copyright (C) 2009-TODAY CLEARCORP S.A. (<http://clearcorp.co.cr>). # # This program is free software: you can redistribute...
import wizard
random_line_split
SqlStepper.amd.js
;modjewel.define("weinre/target/SqlStepper", function(require, exports, module) { // Generated by CoffeeScript 1.3.3 var Binding, SqlStepper, executeSql, ourErrorCallback, runStep; Binding = require('../common/Binding'); module.exports = SqlStepper = (function() { function
(steps) { var context; if (!(this instanceof SqlStepper)) { return new SqlStepper(steps); } this.__context = {}; context = this.__context; context.steps = steps; } SqlStepper.prototype.run = function(db, errorCallback) { var context; context = this.__context; if (context.h...
SqlStepper
identifier_name
SqlStepper.amd.js
;modjewel.define("weinre/target/SqlStepper", function(require, exports, module) { // Generated by CoffeeScript 1.3.3 var Binding, SqlStepper, executeSql, ourErrorCallback, runStep; Binding = require('../common/Binding'); module.exports = SqlStepper = (function() { function SqlStepper(steps) { var context; ...
this.__context = {}; context = this.__context; context.steps = steps; } SqlStepper.prototype.run = function(db, errorCallback) { var context; context = this.__context; if (context.hasBeenRun) { throw new Ex(arguments, "stepper has already been run"); } context.hasBeenRun = tr...
{ return new SqlStepper(steps); }
conditional_block
SqlStepper.amd.js
;modjewel.define("weinre/target/SqlStepper", function(require, exports, module) { // Generated by CoffeeScript 1.3.3 var Binding, SqlStepper, executeSql, ourErrorCallback, runStep; Binding = require('../common/Binding'); module.exports = SqlStepper = (function() { function SqlStepper(steps) { var context; ...
require("../common/MethodNamer").setNamesForClass(module.exports); });
step = context.steps[context.currentStep]; return step.call(this, resultSet); };
random_line_split
SqlStepper.amd.js
;modjewel.define("weinre/target/SqlStepper", function(require, exports, module) { // Generated by CoffeeScript 1.3.3 var Binding, SqlStepper, executeSql, ourErrorCallback, runStep; Binding = require('../common/Binding'); module.exports = SqlStepper = (function() { function SqlStepper(steps)
SqlStepper.prototype.run = function(db, errorCallback) { var context; context = this.__context; if (context.hasBeenRun) { throw new Ex(arguments, "stepper has already been run"); } context.hasBeenRun = true; context.db = db; context.errorCallback = errorCallback; context.nextSt...
{ var context; if (!(this instanceof SqlStepper)) { return new SqlStepper(steps); } this.__context = {}; context = this.__context; context.steps = steps; }
identifier_body
app.ts
import * as express from "express" import * as path from "path" import * as logger from "morgan" import * as favicon from "serve-favicon" import * as bodyparser from "body-parser" import * as mongoose from "mongoose" import * as dotenv from "dotenv" dotenv.config({ path: path.join(__dirname, "config", ".env") })
mongoose.connect(process.env.DATABASE_URL) const app: express.Application = express() app.disable("x-powered-by") app.use(logger("dev")) app.use(bodyparser.json()) app.use(bodyparser.urlencoded({ extended: true })) app.use("/api/invoices", InvoicesRouter) if (app.get("env") === "production") { app.use(express....
import "./models/invoice" import { InvoicesRouter } from "./routes/invoices" import { IndexRouter } from "./routes/index"
random_line_split
app.ts
import * as express from "express" import * as path from "path" import * as logger from "morgan" import * as favicon from "serve-favicon" import * as bodyparser from "body-parser" import * as mongoose from "mongoose" import * as dotenv from "dotenv" dotenv.config({ path: path.join(__dirname, "config", ".env") }) impo...
app.use(function(error: any, request: express.Request, response: express.Response, next: express.NextFunction) { response.status(error.status || 500) response.json({ error: {}, message: error.message }) }) export { app }
{ app.use(function(error: any, request: express.Request, response: express.Response, next: express.NextFunction) { response.status(error.status || 500) response.json({ error: error, message: error.message }) }) }
conditional_block
draw_cache.rs
use std::cell::RefCell; use std::fmt; use ggez::{ graphics::{BlendMode, DrawParam, Drawable}, Context, GameResult, }; pub trait TryIntoDrawable<T> where T: Drawable, { fn try_into_drawable(&self, ctx: &mut Context) -> GameResult<T>; } pub struct DrawCache<T, U> where T: TryIntoDrawable<U>, ...
(data: T) -> Self { Self { data, cache: RefCell::new(None), } } } impl<T, U> AsRef<T> for DrawCache<T, U> where T: TryIntoDrawable<U>, U: Drawable, { fn as_ref(&self) -> &T { &self.data } } impl<T, U> fmt::Debug for DrawCache<T, U> where T: Try...
new
identifier_name
draw_cache.rs
use std::cell::RefCell; use std::fmt; use ggez::{ graphics::{BlendMode, DrawParam, Drawable}, Context, GameResult, }; pub trait TryIntoDrawable<T> where T: Drawable, { fn try_into_drawable(&self, ctx: &mut Context) -> GameResult<T>; } pub struct DrawCache<T, U> where T: TryIntoDrawable<U>, ...
}
random_line_split
draw_cache.rs
use std::cell::RefCell; use std::fmt; use ggez::{ graphics::{BlendMode, DrawParam, Drawable}, Context, GameResult, }; pub trait TryIntoDrawable<T> where T: Drawable, { fn try_into_drawable(&self, ctx: &mut Context) -> GameResult<T>; } pub struct DrawCache<T, U> where T: TryIntoDrawable<U>, ...
fn set_blend_mode(&mut self, mode: Option<BlendMode>) { if let Some(ref mut drawable) = *self.cache.get_mut() { drawable.set_blend_mode(mode); } } fn get_blend_mode(&self) -> Option<BlendMode> { match *self.cache.borrow() { None => None, Some(...
{ let is_cached = self.cache.borrow().is_some(); if !is_cached { let drawable = self.data.try_into_drawable(ctx)?; self.cache.replace(Some(drawable)); } self.cache .borrow_mut() .as_mut() .unwrap() .draw_ex(ctx, para...
identifier_body
util.ts
/// <reference path="../../typings/jquery/jquery.d.ts" /> /** * @brief ユーティリティ */ /** * @brief POSTリクエストで、APIを呼び出す * * @param apiName API名 * @param param リクエストパラメータ * @param successFunc 成功時に呼ばれる関数 * @param errorFunc エラー時に呼ばれる関数(省略可能) * * @note エラー処理はダイアログが表示される */ export function post(apiName, param, succe...
conditional_block
util.ts
/// <reference path="../../typings/jquery/jquery.d.ts" /> /** * @brief ユーティリティ */ /** * @brief POSTリクエストで、APIを呼び出す * * @param apiName API名 * @param param リクエストパラメータ * @param successFunc 成功時に呼ばれる関数 * @param errorFunc エラー時に呼ばれる関数(省略可能) * * @note エラー処理はダイアログが表示される */ export function post(apiName, param, succe...
identifier_body
util.ts
/// <reference path="../../typings/jquery/jquery.d.ts" /> /** * @brief ユーティリティ */ /** * @brief POSTリクエストで、APIを呼び出す * * @param apiName API名 * @param param リクエストパラメータ * @param successFunc 成功時に呼ばれる関数 * @param errorFunc エラー時に呼ばれる関数(省略可能) * * @note エラー処理はダイアログが表示される */ export function post(apiName, param, succe...
t)); } } }
.append(cellConten
identifier_name
util.ts
/// <reference path="../../typings/jquery/jquery.d.ts" /> /** * @brief ユーティリティ */
* @brief POSTリクエストで、APIを呼び出す * * @param apiName API名 * @param param リクエストパラメータ * @param successFunc 成功時に呼ばれる関数 * @param errorFunc エラー時に呼ばれる関数(省略可能) * * @note エラー処理はダイアログが表示される */ export function post(apiName, param, successFunc, errorFunc) { errorFunc = errorFunc || function(error, errorMessage) { alert(erro...
/**
random_line_split