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
middleware.rs
//! Traits to implement middleware types. //! //! This module defined the middleware traits for the closures that would be used as handlers and //! middlewares in the application. This provides nice compile time guarantees of the what each //! specific middleware can do and return. If anything else is returned then it ...
} /// Any logic to be executed per request after the response has been sent is a part of this /// middleware. /// /// This has access to the `Request` and `ShadowResponse` objects. /// /// Typical uses for this middleware could be in logging something after the request is served. pub trait AfterMiddleware: Send + Syn...
{ (*self)(req, res) }
identifier_body
middleware.rs
//! Traits to implement middleware types. //! //! This module defined the middleware traits for the closures that would be used as handlers and //! middlewares in the application. This provides nice compile time guarantees of the what each //! specific middleware can do and return. If anything else is returned then it ...
/// write a response from a `BeforeMiddleware`. You need to implement a `Handler` to do that. /// /// Typical uses for this middleware is for checking certain header or some form of authentication /// on the request before it is served by the application. pub trait BeforeMiddleware: Send + Sync + 'static { fn execu...
/// Implements the kind of middleware that is executed when a request has arrived but before it is /// passed on to the handler for being processed. /// /// You have access to the request here and can do some pre-processing as required, but you cannot
random_line_split
bootstrap.py
.lib import datastore_yaml from loaner.web_app.backend.lib import user from loaner.web_app.backend.lib import utils from loaner.web_app.backend.models import bootstrap_status_model from loaner.web_app.backend.models import config_model _ORG_UNIT_EXISTS_MSG = 'Org unit %s already exists, so cannot create.' _TASK_DESCR...
else: logging.info( 'Running bootstrap for an update from version %s to %s.', config_model.Config.get('running_version'), constants.APP_VERSION) run_status_dict = {} if requested_tasks: for function_name, kwargs in requested_tasks.iteritems(): _run_function_as_task(bootstra...
logging.info('Running bootstrap for a new deployment.')
conditional_block
bootstrap.py
.lib import datastore_yaml from loaner.web_app.backend.lib import user from loaner.web_app.backend.lib import utils from loaner.web_app.backend.models import bootstrap_status_model from loaner.web_app.backend.models import config_model _ORG_UNIT_EXISTS_MSG = 'Org unit %s already exists, so cannot create.' _TASK_DESCR...
(**kwargs): """Bootstraps Chrome device OUs. Args: **kwargs: keyword args including a user_email with which to run the Directory API client methods (required for BigQuery streaming). """ logging.info('Requesting delegated admin for bootstrap') client = directory.DirectoryApiClient(user_email=kwar...
bootstrap_chrome_ous
identifier_name
bootstrap.py
.models import config_model _ORG_UNIT_EXISTS_MSG = 'Org unit %s already exists, so cannot create.' _TASK_DESCRIPTIONS = { 'bootstrap_datastore_yaml': 'Importing datastore YAML file', 'bootstrap_chrome_ous': 'Creating Chrome OUs in Directory', 'bootstrap_bq_history': 'Configuring datastore history tables i...
"""Checks if the app is up to date and sets bootstrap to incomplete if not. Checks whether the running version is the same as the deployed version as an app that is not updated should trigger bootstrap moving back to an incomplete state, thus signaling that certain tasks need to be run again. Returns: Tru...
identifier_body
bootstrap.py
from loaner.web_app.backend.models import bootstrap_status_model from loaner.web_app.backend.models import config_model _ORG_UNIT_EXISTS_MSG = 'Org unit %s already exists, so cannot create.' _TASK_DESCRIPTIONS = { 'bootstrap_datastore_yaml': 'Importing datastore YAML file', 'bootstrap_chrome_ous': 'Creating C...
from loaner.web_app.backend.lib import datastore_yaml from loaner.web_app.backend.lib import user from loaner.web_app.backend.lib import utils
random_line_split
datalab-settings.ts
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law...
_idleTimoutIntervalChanged() { // TODO: Show success/error status to user this._busy = true; this._idleTimeoutUpdateStatus = ''; this._updateError = false; return SettingsManager.setUserSettingAsync('idleTimeoutInterval', this.idleTimeoutInterval) .then(() => this._idleTimeoutUpdateStatus ...
{ return SettingsManager.setUserSettingAsync('theme', this.theme) .then(() => { const e = new CustomEvent('ThemeChanged', {detail: this.theme}); document.dispatchEvent(e); }); }
identifier_body
datalab-settings.ts
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law...
.then(() => this._busy = false); } /** * On changing the theme, an event is fired to allow the host to reload the theme CSS. */ _themeChanged() { return SettingsManager.setUserSettingAsync('theme', this.theme) .then(() => { const e = new CustomEvent('ThemeChanged', {detail: this.the...
Utils.log.error('Could not get user settings from server.'); })
random_line_split
datalab-settings.ts
/* * Copyright 2017 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law...
() { this._busy = true; this._idleTimeoutUpdateStatus = ''; this._updateError = false; return SettingsManager.getUserSettingsAsync(true /*forceRefresh*/) .then((settings: common.UserSettings) => { this.theme = settings.theme; this.idleTimeoutInterval = settings.idleTimeoutInterval;...
loadSettings
identifier_name
action_plugin.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ action_plugins::{ check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev, lpurge, ltuer, lustre, ...
() -> action_plugins::Actions { let map = action_plugins::Actions::default() .add_plugin("start_unit", iml_systemd::start_unit) .add_plugin("stop_unit", iml_systemd::stop_unit) .add_plugin("enable_unit", iml_systemd::enable_unit) .add_plugin("disable_unit", iml_systemd::disable_unit)...
create_registry
identifier_name
action_plugin.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file.
action_plugins::{ check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev, lpurge, ltuer, lustre, ntp::{action_configure, is_ntp_configured}, ostpool, package, postoffice, stratagem::{ action_cloudsync, action_filesync, action_mir...
use crate::{
random_line_split
action_plugin.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{ action_plugins::{ check_kernel, check_stonith, firewall_cmd, high_availability, kernel_module, lamigo, ldev, lpurge, ltuer, lustre, ...
) .add_plugin("mount", lustre::client::mount) .add_plugin("mount_many", lustre::client::mount_many) .add_plugin("unmount", lustre::client::unmount) .add_plugin("unmount_many", lustre::client::unmount_many) .add_plugin("ha_resource_start", high_availability::start_resource...
{ let map = action_plugins::Actions::default() .add_plugin("start_unit", iml_systemd::start_unit) .add_plugin("stop_unit", iml_systemd::stop_unit) .add_plugin("enable_unit", iml_systemd::enable_unit) .add_plugin("disable_unit", iml_systemd::disable_unit) .add_plugin("restart_...
identifier_body
soundcloud.py
import asyncio import demjson from bot import user_steps, sender, get, downloader from message import Message client_id = ''#YOUR CLIENT ID async def search(query): global guest_client_id search_url = 'https://api.soundcloud.com/search?q=%s&facet=model&limit=30&offset=0&linked_partitioning=1&client_id='+c...
plugin = { "name": "Soundcloud", "desc": "Download a Music From Sound Cloud\n\n" "*For Start :*\n`/sc michael jackson billie jean`", "usage": ["/sc \\[`Search`]"], "run": run, "sudo": False, "patterns": ["^[/!#]sc (.*)$"] }
try: hide_keyboard = {'hide_keyboard': True, "selective": True} await sender(Message(chat_id).set_text("*Please Wait*\nLet me Save this Music For You", reply_to_message_id=message['message_id'], ...
conditional_block
soundcloud.py
import asyncio import demjson from bot import user_steps, sender, get, downloader from message import Message client_id = ''#YOUR CLIENT ID async def search(query): global guest_client_id search_url = 'https://api.soundcloud.com/search?q=%s&facet=model&limit=30&offset=0&linked_partitioning=1&client_id='+c...
(message, matches, chat_id, step): from_id = message['from']['id'] if step == 0: await sender( Message(chat_id).set_text("*Please Wait*\nI'm Searching all Music with this name", parse_mode="markdown")) user_steps[from_id] = {"name": "Soundcloud", "step": 1, "data": {}} i = 0 ...
run
identifier_name
soundcloud.py
import asyncio import demjson from bot import user_steps, sender, get, downloader from message import Message client_id = ''#YOUR CLIENT ID async def search(query): global guest_client_id search_url = 'https://api.soundcloud.com/search?q=%s&facet=model&limit=30&offset=0&linked_partitioning=1&client_id='+c...
parse_mode="markdown")] return [Message(chat_id).set_text("Select One Of these :", reply_to_message_id=message['message_id'], reply_markup=show_keyboard)] elif step == 1: try: hide_keyboard = {'hide_k...
from_id = message['from']['id'] if step == 0: await sender( Message(chat_id).set_text("*Please Wait*\nI'm Searching all Music with this name", parse_mode="markdown")) user_steps[from_id] = {"name": "Soundcloud", "step": 1, "data": {}} i = 0 show_keyboard = {'keyboard': []...
identifier_body
soundcloud.py
import asyncio import demjson from bot import user_steps, sender, get, downloader from message import Message client_id = ''#YOUR CLIENT ID async def search(query): global guest_client_id search_url = 'https://api.soundcloud.com/search?q=%s&facet=model&limit=30&offset=0&linked_partitioning=1&client_id='+c...
}
random_line_split
version.service.spec.ts
import { HttpClient } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { inject, TestBed } from '@angular/core/testing'; import { Observable } from 'rxjs/Rx'; import { Server } from '../models/server'; import { AppTestingModule } from '.....
import { getTestServer } from './testing'; import { VersionService } from './version.service'; export class MockedVersionService { public response: Observable<any>; public get(server: Server) { return this.response; } } describe('VersionService', () => { let httpClient: HttpClient; let httpTestingContr...
import { HttpServer } from './http-server.service';
random_line_split
version.service.spec.ts
import { HttpClient } from '@angular/common/http'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { inject, TestBed } from '@angular/core/testing'; import { Observable } from 'rxjs/Rx'; import { Server } from '../models/server'; import { AppTestingModule } from '.....
{ public response: Observable<any>; public get(server: Server) { return this.response; } } describe('VersionService', () => { let httpClient: HttpClient; let httpTestingController: HttpTestingController; let httpServer: HttpServer; let service: VersionService; let server: Server; beforeEach(()...
MockedVersionService
identifier_name
fat.rs
use crate::address::Align; #[repr(packed)] pub struct BPB { jmp_instr: [u8; 3], oem_identifier: [u8; 8], bytes_per_sector: u16, sectors_per_cluster: u8, resd_sectors: u16, fat_count: u8, root_dir_entry_count: u16, sector_count: u16, // if 0, then sector_count >= 65536. actual...
{ Free, Used, Bad, Reserved, End, Invalid, } pub enum FatFormat { Fat12, Fat16, Fat32, } impl FatFormat { pub fn cluster_type(&self, cluster: u32) -> ClusterType { match self { Self::Fat12 => match cluster { 0 => ClusterTy...
ClusterType
identifier_name
fat.rs
use crate::address::Align; #[repr(packed)] pub struct BPB { jmp_instr: [u8; 3], oem_identifier: [u8; 8], bytes_per_sector: u16, sectors_per_cluster: u8, resd_sectors: u16, fat_count: u8, root_dir_entry_count: u16, sector_count: u16, // if 0, then sector_count >= 65536. actual...
} else { None } } } #[repr(packed)] pub struct FatBPB { bpb: BPB, drive_number: u8, win_nt_flags: u8, signature: u8, // either 0x28 or 0x29 volume_id: u32, volume_label: [u8; 11], system_id: [u8; 8], boot_code: [u8; 448], partit...
{ Some((basename, Some(extension), oversized)) }
conditional_block
fat.rs
use crate::address::Align; #[repr(packed)] pub struct BPB { jmp_instr: [u8; 3], oem_identifier: [u8; 8], bytes_per_sector: u16, sectors_per_cluster: u8, resd_sectors: u16, fat_count: u8, root_dir_entry_count: u16, sector_count: u16, // if 0, then sector_count >= 65536. actual...
} if extension == [b' ', b' ', b' '] { Some((basename, None, oversized)) } else { Some((basename, Some(extension), oversized)) } } else { None } } } #[repr(packed)] pub struct FatBPB { bp...
basename[base_i] = c; base_i += 1;
random_line_split
fat.rs
use crate::address::Align; #[repr(packed)] pub struct BPB { jmp_instr: [u8; 3], oem_identifier: [u8; 8], bytes_per_sector: u16, sectors_per_cluster: u8, resd_sectors: u16, fat_count: u8, root_dir_entry_count: u16, sector_count: u16, // if 0, then sector_count >= 65536. actual...
} else if Self::is_replace_char(*c) { b'_' } else { *c } }) .filter(|c| Self::is_legal_dos_char(*c)); let mut ext_i = 0; ...
{ let mut parts = filename .rsplitn(2, |c| *c == b'.'); if let Some(name) = parts.next() { let mut basename = [b' '; 8]; let mut extension = [b' '; 3]; let mut oversized = false; let base = if let Some(b) = parts.next() { ...
identifier_body
es6.js
// es6 shim (function() { if( !String.prototype.startsWith ) { String.prototype.startsWith = function(s) { return this.indexOf(s) === 0; }; } if( !String.prototype.endsWith ) { String.prototype.endsWith = function(s) { var t = String(s); var index = this.lastIndexOf(t); return index >= 0 && index ...
return this.items(); }, clear: function() { this.k = []; this.v = []; this.size = 0; } }; // custom method Map.prototype.getKeyByValue = function(v) { var argk = this.keys(); var argv = this.values(); return argk[argv.indexOf(v)]; }; Map.prototype.toObject = function() {...
}, iterator: function() {
random_line_split
es6.js
// es6 shim (function() { if( !String.prototype.startsWith ) { String.prototype.startsWith = function(s) { return this.indexOf(s) === 0; }; } if( !String.prototype.endsWith ) { String.prototype.endsWith = function(s) { var t = String(s); var index = this.lastIndexOf(t); return index >= 0 && index ...
else { this.k.push(k); this.v.push(v); } this.size = this.k.length; }, "delete": function(k) { var i = this.k.indexOf(k); if( i >= 0 ) { this.k.remove(i); this.v.remove(i); this.size = this.k.length; return true; } return false; }, has: function(k)...
{ this.k[i] = v; }
conditional_block
http.src.js
define(['jquery','xing'],function($,xing) { var $body = $('body'), $progress = $($body.data('progressDisplay')), $status = $($body.data('statusMessage')), curPath = window.location.pathname, baseDir = curPath.substring(0, curPath.lastIndexOf('/')), s...
}, unstackCall = function() { if( --stackCount < 1 ) { stackCount = 0; $progress.hide(); } }, getErrorHandler = function( callback, doUnstack ) { return function( xhr ) { if( doUnstack ) { ...
{ $progress.show(); stackCount++; }
conditional_block
http.src.js
define(['jquery','xing'],function($,xing) { var $body = $('body'), $progress = $($body.data('progressDisplay')), $status = $($body.data('statusMessage')), curPath = window.location.pathname, baseDir = curPath.substring(0, curPath.lastIndexOf('/')), s...
; xing.http = { BasePath : baseDir, SitePath : sitePath, redirect : function( path ) { stackCall(); // show our processing loader when changing pages window.location.href = path.replace('~',this.BasePath); }, get : function( p...
random_line_split
map.rs
ROOM_MIN_Y: i32 = 8; pub const MAX_ROOMS: i32 = 30; pub const MAX_ROOM_MONSTERS: i32 = 3; pub const MAX_ROOM_ITEMS:i32 = 4; #[derive(Debug, RustcEncodable, RustcDecodable)] pub struct Tile { pub floor: Object, pub explored: bool, pub items: Vec<Object>, } impl Tile { pub fn new(floor: &ObjectClass) ...
} } let (stairs_x, stairs_y) = stairs; let mut stairs_up = items.get_class("stairs up").create_object(); stairs_up.set_pos(stairs_x, stairs_y); map[stairs_x as usize][stairs_y as usize].items.push(stairs_up); } for _ in 0..rand::thread_rng().gen_range(1,3) {...
{ let stairs_x = room.x1 + ((room.x2 - room.x1)/2); let stairs_y = room.y1 + ((room.y2 - room.y1)/2); stairs = (stairs_x, stairs_y); }
conditional_block
map.rs
ROOM_MIN_Y: i32 = 8; pub const MAX_ROOMS: i32 = 30; pub const MAX_ROOM_MONSTERS: i32 = 3; pub const MAX_ROOM_ITEMS:i32 = 4; #[derive(Debug, RustcEncodable, RustcDecodable)] pub struct Tile { pub floor: Object, pub explored: bool, pub items: Vec<Object>, } impl Tile { pub fn new(floor: &ObjectClass) ...
if blocks == object::Blocks::Full { return blocks } } blocks } pub type Map = Vec<Vec<Tile>>; #[derive(Clone, Copy, Debug)] struct Rect { x1: i32, y1: i32, x2: i32, y2: i32, } impl Rect { pub fn new(x: i32, y: i32, w: i32, h: i32) -> Self { Re...
{ // Because actors are stored in a separate place from the map, we need // to check both for actors marked as being in a place on the map, // as well as all actors in the map location to see if they block // If only one thing blocks fully we know nothing can see through that // tile, so we are don...
identifier_body
map.rs
ROOM_MIN_Y: i32 = 8; pub const MAX_ROOMS: i32 = 30; pub const MAX_ROOM_MONSTERS: i32 = 3; pub const MAX_ROOM_ITEMS:i32 = 4; #[derive(Debug, RustcEncodable, RustcDecodable)] pub struct Tile { pub floor: Object, pub explored: bool, pub items: Vec<Object>, } impl Tile { pub fn new(floor: &ObjectClass) ...
actors[consts::PLAYER].set_pos(1, room.y2 / 2); } } for _ in 0..rand::thread_rng().gen_range(1,2) { let room = rooms[rand::thread_rng().gen_range(0, rooms.len())]; let x = rand::thread_rng().gen_range(room.x1+1, room.x2); let y = rand::thread_rng().gen_range(room.y1+...
actor_types: &object::load::ObjectTypes, actors: &mut Vec<Object>) { for room in rooms { if room.x1 == 1 && room.y1 == 1 {
random_line_split
map.rs
ROOM_MIN_Y: i32 = 8; pub const MAX_ROOMS: i32 = 30; pub const MAX_ROOM_MONSTERS: i32 = 3; pub const MAX_ROOM_ITEMS:i32 = 4; #[derive(Debug, RustcEncodable, RustcDecodable)] pub struct Tile { pub floor: Object, pub explored: bool, pub items: Vec<Object>, } impl Tile { pub fn new(floor: &ObjectClass) ...
(x: i32, y: i32, map: &Map, actors: &[Object]) -> object::Blocks { // Because actors are stored in a separate place from the map, we need // to check both for actors marked as being in a place on the map, // as well as all objects in the map location to see if they block // If only one thing blocks ful...
is_blocked
identifier_name
linkedin.py
import os, re, requests from bs4 import BeautifulSoup from totalimpact.providers import provider from totalimpact.providers.provider import Provider, ProviderContentMalformedError, ProviderRateLimitError import logging logger = logging.getLogger('ti.providers.linkedin') class Linkedin(Provider): example_id = ...
(self): return True @property def provides_biblio(self): return True def aliases(self, aliases, provider_url_template=None, cache_enabled=True): return None def biblio(self, aliases, provider_url_template=Non...
provides_aliases
identifier_name
linkedin.py
import os, re, requests from bs4 import BeautifulSoup from totalimpact.providers import provider from totalimpact.providers.provider import Provider, ProviderContentMalformedError, ProviderRateLimitError import logging logger = logging.getLogger('ti.providers.linkedin') class Linkedin(Provider): example_id = ...
return False def member_items(self, linkedin_url, provider_url_template=None, cache_enabled=True): return [("url", linkedin_url)] @property def provides_aliases(self): return True @property def provides_biblio(self): retur...
return True
conditional_block
linkedin.py
import os, re, requests from bs4 import BeautifulSoup from totalimpact.providers import provider from totalimpact.providers.provider import Provider, ProviderContentMalformedError, ProviderRateLimitError import logging logger = logging.getLogger('ti.providers.linkedin') class Linkedin(Provider): example_id = ...
def is_relevant_alias(self, alias): (namespace, nid) = alias if (namespace == "url") and ("linkedin.com" in nid): return True return False def member_items(self, linkedin_url, provider_url_template=None, cache_enabled=True): ...
return True
identifier_body
linkedin.py
import os, re, requests from bs4 import BeautifulSoup from totalimpact.providers import provider from totalimpact.providers.provider import Provider, ProviderContentMalformedError, ProviderRateLimitError import logging logger = logging.getLogger('ti.providers.linkedin') class Linkedin(Provider): example_id = ...
aliases_url_template = "http://dx.doi.org/%s" biblio_url_template = "http://dx.doi.org/%s" def __init__(self): super(Linkedin, self).__init__() @property def provides_members(self): return True @property def provides_biblio(self): return True def is_releva...
url = "http://www.crossref.org/" descr = "An official Digital Object Identifier (DOI) Registration Agency of the International DOI Foundation."
random_line_split
PythonServer.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
elif work.op == Operation.SUBTRACT: val = work.num1 - work.num2 elif work.op == Operation.MULTIPLY: val = work.num1 * work.num2 elif work.op == Operation.DIVIDE: if work.num2 == 0: raise InvalidOperation(work.op, 'Cannot divide by 0') ...
val = work.num1 + work.num2
conditional_block
PythonServer.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
def zip(self): print('zip()') if __name__ == '__main__': handler = CalculatorHandler() processor = Calculator.Processor(handler) pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = reactor.listenTCP( 9090, TTwisted.ThriftServerFactory(processor, pfactory), ...
return self.log[key]
random_line_split
PythonServer.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
def calculate(self, logid, work): print('calculate(%d, %r)' % (logid, work)) if work.op == Operation.ADD: val = work.num1 + work.num2 elif work.op == Operation.SUBTRACT: val = work.num1 - work.num2 elif work.op == Operation.MULTIPLY: val = work....
print('add(%d,%d)' % (n1, n2)) return n1 + n2
identifier_body
PythonServer.py
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "L...
: implements(Calculator.Iface) def __init__(self): self.log = {} def ping(self): print('ping()') def add(self, n1, n2): print('add(%d,%d)' % (n1, n2)) return n1 + n2 def calculate(self, logid, work): print('calculate(%d, %r)' % (logid, work)) if w...
CalculatorHandler
identifier_name
table_caption.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/. */ //! CSS table formatting contexts. #![deny(unsafe_code)] use block::BlockFlow; use context::LayoutContext; use e...
(&mut self) -> &mut BlockFlow { &mut self.block_flow } fn as_block(&self) -> &BlockFlow { &self.block_flow } fn bubble_inline_sizes(&mut self) { self.block_flow.bubble_inline_sizes(); } fn assign_inline_sizes(&mut self, ctx: &LayoutContext) { debug!("assign_inl...
as_mut_block
identifier_name
table_caption.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/. */ //! CSS table formatting contexts. #![deny(unsafe_code)] use block::BlockFlow; use context::LayoutContext; use e...
fn compute_overflow(&self) -> Rect<Au> { self.block_flow.compute_overflow() } fn generated_containing_block_size(&self, flow: OpaqueFlow) -> LogicalSize<Au> { self.block_flow.generated_containing_block_size(flow) } fn iterate_through_fragment_border_boxes(&self, ...
{ self.block_flow.repair_style(new_style) }
identifier_body
table_caption.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/. */ //! CSS table formatting contexts. #![deny(unsafe_code)] use block::BlockFlow; use context::LayoutContext; use e...
self.block_flow.mutate_fragments(mutator) } } impl fmt::Debug for TableCaptionFlow { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "TableCaptionFlow: {:?}", self.block_flow) } }
} fn mutate_fragments(&mut self, mutator: &mut FnMut(&mut Fragment)) {
random_line_split
Playground.js
import React from 'react'; import styled from 'styled-components'; import { Button, Icon, Col, Tag, Typography } from 'antd'; import JSONEditor from './JSONEditor'; import EditorViewer from './EditorViewer'; import variations from './variations'; import { createImageChildren } from './CarouselSlideItem'; import ItemsCa...
</Button> } leftChevron={ <Button shape="circle"> <Icon type="left" /> </Button> } children={children} /> </div> <CenteredRow gutter={12}> <Col xs={24} md={12}> <Typo...
rightChevron={ <Button shape="circle"> <Icon type="right" />
random_line_split
Playground.js
import React from 'react'; import styled from 'styled-components'; import { Button, Icon, Col, Tag, Typography } from 'antd'; import JSONEditor from './JSONEditor'; import EditorViewer from './EditorViewer'; import variations from './variations'; import { createImageChildren } from './CarouselSlideItem'; import ItemsCa...
extends React.Component { state = { activeItemIndex: 0, activeVariation: variations[0], }; render() { const { activeVariation } = this.state; const { noOfChildren, wrapperStyle, componentProps, } = activeVariation.state; const children = createImageChildren(noOfChildre...
ItemsCarouselPlayground
identifier_name
servicedirectory_v1_generated_registration_service_list_services_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
(): # Create a client client = servicedirectory_v1.RegistrationServiceClient() # Initialize request argument(s) request = servicedirectory_v1.ListServicesRequest( parent="parent_value", ) # Make the request page_result = client.list_services(request=request) # Handle the respo...
sample_list_services
identifier_name
servicedirectory_v1_generated_registration_service_list_services_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END servicedirectory_v1_generated_RegistrationService_ListServices_sync]
print(response)
conditional_block
servicedirectory_v1_generated_registration_service_list_services_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# Initialize request argument(s) request = servicedirectory_v1.ListServicesRequest( parent="parent_value", ) # Make the request page_result = client.list_services(request=request) # Handle the response for response in page_result: print(response) # [END servicedirectory_v...
def sample_list_services(): # Create a client client = servicedirectory_v1.RegistrationServiceClient()
random_line_split
servicedirectory_v1_generated_registration_service_list_services_sync.py
# -*- coding: utf-8 -*- # Copyright 2022 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or...
# [END servicedirectory_v1_generated_RegistrationService_ListServices_sync]
client = servicedirectory_v1.RegistrationServiceClient() # Initialize request argument(s) request = servicedirectory_v1.ListServicesRequest( parent="parent_value", ) # Make the request page_result = client.list_services(request=request) # Handle the response for response in page_r...
identifier_body
sequence.py
""" Author: Eric J. Ma Affiliation: Massachusetts Institute of Technology """ from random import choice from generate_id import generate_id class Sequence(object): """ The Sequence object is the lowest level object in the pathogen simulator. It provides a container for storing seed sequences for the pathogens pre...
return sequence
letter = choice(['A', 'T', 'G', 'C']) sequence += letter
conditional_block
sequence.py
""" Author: Eric J. Ma Affiliation: Massachusetts Institute of Technology """
""" The Sequence object is the lowest level object in the pathogen simulator. It provides a container for storing seed sequences for the pathogens present in the environment. This can be subclassed to store seed sequences for other pathogens, rather than using a generated sequence. Note that when a virus r...
from random import choice from generate_id import generate_id class Sequence(object):
random_line_split
sequence.py
""" Author: Eric J. Ma Affiliation: Massachusetts Institute of Technology """ from random import choice from generate_id import generate_id class Sequence(object): """ The Sequence object is the lowest level object in the pathogen simulator. It provides a container for storing seed sequences for the pathogens pre...
def __repr__(self): return self.id def generate_sequence(self, length): """ This method will generate a sequence, and set the Sequence object's sequence to that sequence. """ sequence = '' for i in range(length): letter = choice(['A', 'T', 'G', 'C']) sequence += letter return sequence
""" Initialize the sequence with a random sequence of length 1000 if sequence is not specified. Otherwise, initialize sequence with a sequence that is specified. """ super(Sequence, self).__init__() self.sequence = None if sequence == None: self.sequence = self.generate_sequence(length) else: ...
identifier_body
sequence.py
""" Author: Eric J. Ma Affiliation: Massachusetts Institute of Technology """ from random import choice from generate_id import generate_id class Sequence(object): """ The Sequence object is the lowest level object in the pathogen simulator. It provides a container for storing seed sequences for the pathogens pre...
(self, length): """ This method will generate a sequence, and set the Sequence object's sequence to that sequence. """ sequence = '' for i in range(length): letter = choice(['A', 'T', 'G', 'C']) sequence += letter return sequence
generate_sequence
identifier_name
Clean.py
# Deletes the temp files and Compiler-Generated Directory import os import shutil """ Gets a list of files using a extension filter""" def getFiles(relevant_path): included_extenstions = ['pdb','txt','config','xml' ] file_names = [fn for fn in os.listdir(relevant_path) if any([fn.endswith(ext) for ext in inclu...
deleteDir("FastColoredTextBox\\bin") deleteDir("FastColoredTextBox\\obj")
random_line_split
Clean.py
# Deletes the temp files and Compiler-Generated Directory import os import shutil """ Gets a list of files using a extension filter""" def getFiles(relevant_path):
# get the files to delete from build directory files_to_delete = getFiles("Build") # delete the files for file in files_to_delete: os.remove("Build\\"+file) """ Deletes a directory along with all it's contents""" def deleteDir(path): if(os.path.isdir(path)): shutil.rmtree(path) else: print(...
included_extenstions = ['pdb','txt','config','xml' ] file_names = [fn for fn in os.listdir(relevant_path) if any([fn.endswith(ext) for ext in included_extenstions])] return file_names
identifier_body
Clean.py
# Deletes the temp files and Compiler-Generated Directory import os import shutil """ Gets a list of files using a extension filter""" def getFiles(relevant_path): included_extenstions = ['pdb','txt','config','xml' ] file_names = [fn for fn in os.listdir(relevant_path) if any([fn.endswith(ext) for ext in inclu...
# delete all directories deleteDir("SS.Ynote.Classic\\obj") deleteDir("Docking\\bin") deleteDir("Docking\\obj") deleteDir("FastColoredTextBox\\bin") deleteDir("FastColoredTextBox\\obj")
print("Directory Deosn't exist")
conditional_block
Clean.py
# Deletes the temp files and Compiler-Generated Directory import os import shutil """ Gets a list of files using a extension filter""" def getFiles(relevant_path): included_extenstions = ['pdb','txt','config','xml' ] file_names = [fn for fn in os.listdir(relevant_path) if any([fn.endswith(ext) for ext in inclu...
(path): if(os.path.isdir(path)): shutil.rmtree(path) else: print("Directory Deosn't exist") # delete all directories deleteDir("SS.Ynote.Classic\\obj") deleteDir("Docking\\bin") deleteDir("Docking\\obj") deleteDir("FastColoredTextBox\\bin") deleteDir("FastColoredTextBox\\obj")
deleteDir
identifier_name
twitter.py
from twython import Twython from config import APP_KEY, APP_SECRET def obtain_auth_url():
obtain_auth_url()
"""Used to app to tweet to my account NOT CALLED ANYWHERE""" twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() oauth_token = auth['oauth_token'] oauth_token_secret = auth['oauth_token_secret'] print "\n\n\nGo to the following URL to authorize app:" print auth...
identifier_body
twitter.py
from twython import Twython from config import APP_KEY, APP_SECRET def
(): """Used to app to tweet to my account NOT CALLED ANYWHERE""" twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() oauth_token = auth['oauth_token'] oauth_token_secret = auth['oauth_token_secret'] print "\n\n\nGo to the following URL to authorize app:" pr...
obtain_auth_url
identifier_name
twitter.py
from twython import Twython from config import APP_KEY, APP_SECRET def obtain_auth_url(): """Used to app to tweet to my account NOT CALLED ANYWHERE""" twitter = Twython(APP_KEY, APP_SECRET)
print "\n\n\nGo to the following URL to authorize app:" print auth['auth_url'] oauth_verifier = raw_input("\nEnter the pin: ") twitter = Twython(APP_KEY, APP_SECRET, oauth_token, oauth_token_secret) authorized = twitter.get_authorized_tokens(oauth_verifier) #write confirmed tokens to disk ...
auth = twitter.get_authentication_tokens() oauth_token = auth['oauth_token'] oauth_token_secret = auth['oauth_token_secret']
random_line_split
reward.py
#!/usr/bin/env python import matplotlib.pyplot as plt import sys import numpy from math import floor def movingAverage(x, N):
filename = "reports/configuration.confrewardRecordReport.txt" if (len(sys.argv) > 1): filename = sys.argv[1] with open(filename) as f: print f.readline() time = [] temp = [] avg = [] for line in f: entry = line.split(":") time.append(float(entry[0])) temp.append(float(entry[1])) windowSize = 100 avg = [...
cumsum = numpy.cumsum(numpy.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N])/N
identifier_body
reward.py
#!/usr/bin/env python import matplotlib.pyplot as plt import sys import numpy from math import floor def movingAverage(x, N): cumsum = numpy.cumsum(numpy.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N])/N filename = "reports/configuration.confrewardRecordReport.txt" if (len(sys.argv) > 1): filename = sys.argv[1]...
plt.show()
plt.plot(time, avg, 'ro')
random_line_split
reward.py
#!/usr/bin/env python import matplotlib.pyplot as plt import sys import numpy from math import floor def
(x, N): cumsum = numpy.cumsum(numpy.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N])/N filename = "reports/configuration.confrewardRecordReport.txt" if (len(sys.argv) > 1): filename = sys.argv[1] with open(filename) as f: print f.readline() time = [] temp = [] avg = [] for line in f: entry = line.split(":...
movingAverage
identifier_name
reward.py
#!/usr/bin/env python import matplotlib.pyplot as plt import sys import numpy from math import floor def movingAverage(x, N): cumsum = numpy.cumsum(numpy.insert(x, 0, 0)) return (cumsum[N:] - cumsum[:-N])/N filename = "reports/configuration.confrewardRecordReport.txt" if (len(sys.argv) > 1):
with open(filename) as f: print f.readline() time = [] temp = [] avg = [] for line in f: entry = line.split(":") time.append(float(entry[0])) temp.append(float(entry[1])) windowSize = 100 avg = [0] * (windowSize - 1) avg = avg + list( movingAverage(temp, windowSize)) ratio = 0.999 avg = avg[int(floor(l...
filename = sys.argv[1]
conditional_block
create-post.js
import { createNewPost, setPostContent } from '@wordpress/e2e-test-utils'; import { publishPost } from './publish-post'; /** * Create and publish a new post * * @since 2.2.0 * @since 3.3.0 Set the post's content with `setPostContent()`. * * @param {string} postType WP_Post type. * @param {string} title Po...
await publishPost(); return await page.evaluate( () => wp.data.select( 'core/editor' ).getCurrentPostId() ); }
{ await setPostContent( content ); }
conditional_block
create-post.js
import { createNewPost, setPostContent } from '@wordpress/e2e-test-utils'; import { publishPost } from './publish-post'; /** * Create and publish a new post * * @since 2.2.0 * @since 3.3.0 Set the post's content with `setPostContent()`. * * @param {string} postType WP_Post type. * @param {string} title Po...
( postType, title = 'Test Course', content = null ) { await createNewPost( { title, postType, } ); if ( content ) { await setPostContent( content ); } await publishPost(); return await page.evaluate( () => wp.data.select( 'core/editor' ).getCurrentPostId() ); }
createPost
identifier_name
create-post.js
import { createNewPost, setPostContent } from '@wordpress/e2e-test-utils'; import { publishPost } from './publish-post'; /** * Create and publish a new post * * @since 2.2.0 * @since 3.3.0 Set the post's content with `setPostContent()`. * * @param {string} postType WP_Post type. * @param {string} title Po...
{ await createNewPost( { title, postType, } ); if ( content ) { await setPostContent( content ); } await publishPost(); return await page.evaluate( () => wp.data.select( 'core/editor' ).getCurrentPostId() ); }
identifier_body
create-post.js
import { createNewPost, setPostContent } from '@wordpress/e2e-test-utils'; import { publishPost } from './publish-post'; /** * Create and publish a new post * * @since 2.2.0 * @since 3.3.0 Set the post's content with `setPostContent()`. * * @param {string} postType WP_Post type. * @param {string} title Po...
wp.data.select( 'core/editor' ).getCurrentPostId() ); }
random_line_split
conf.py
83/how-do-you-change-the-code-example-font-size-in-latex-pdf-output-with-sphinx/9955928 # Note: sizes are \footnotesize (8pt), \small (9pt), and \normalsize (10pt). #from sphinx.highlighting import PygmentsBridge #from pygments.formatters.latex import LatexFormatter # #class CustomLatexFormatter(LatexFormatter): # ...
# Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patte...
# The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs.
random_line_split
__openerp__.py
# -*- encoding: utf-8 -*- ############################################################################## # # Account Cut-off Base module for OpenERP
# Copyright (C) 2013 Akretion (http://www.akretion.com) # @author Alexis de Lattre <alexis.delattre@akretion.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either v...
random_line_split
kindex.js
/** * Created by way on 16/8/29. * knife 引入模块 * 可添加扩充、覆盖 k模块的功能 */ const $ = require('./knife'); ['width', 'height'].forEach(function (dimension) { var Dimension = dimension.replace(/./, function (m) { return m[0].toUpperCase(); }); $.fn['outer' + Dimension] = function (margin) { var elem = this; ...
return this.each(hasScrollTop ? function () { this.scrollTop = value } : function () { this.scrollTo(this.scrollX, value) }) } export default $;
if (value === undefined) return hasScrollTop ? this[0].scrollTop : this[0].pageYOffset
random_line_split
add2home.js
ina = w.devicePixelRatio && w.devicePixelRatio > 1; isSafari = (/Safari/i).test(nav.appVersion) && !(/CriOS/i).test(nav.appVersion); isStandalone = nav.standalone; OSVersion = nav.appVersion.match(/OS (\d+_\d+)/i); OSVersion = OSVersion && OSVersion[1] ? +OSVersion[1].replace('_', '.') : 0; lastVisit = +w.lo...
eSession', '1'); isSessionActive = true; close(); } function transitionEnd () { ballo
conditional_block
add2home.js
now; // If it is expired we need to reissue a new balloon isExpired = isReturningVisitor && lastVisit <= now; if ( options.hookOnLoad ) w.addEventListener('load', loaded, false); else if ( !options.hookOnLoad && options.autostart ) loaded(); } function loaded () { w.removeEventListener('load', loaded, f...
tY, posX =
identifier_name
add2home.js
options.hookOnLoad && options.autostart ) loaded(); } function loaded () { w.removeEventListener('load', loaded, false); if ( !isReturningVisitor ) w.localStorage.setItem('addToHome', Date.now()); else if ( options.expire && isExpired ) w.localStorage.setItem('addToHome', Date.now() + options.expire * 60000);...
if ( posY == matrix.m42 && posX == matrix.m41 ) return;
random_line_split
add2home.js
balloon.id = 'addToHomeScreen'; balloon.style.cssText += 'left:-9999px;-webkit-transition-property:-webkit-transform,opacity;-webkit-transition-duration:0;-webkit-transform:translate3d(0,0,0);position:' + (OSVersion < 5 ? 'absolute' : 'fixed'); // Localize message if ( options.message in intl ) { // You may fo...
identifier_body
requirePatch.js
/** * @license RequireJS Copyright (c) 2010, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /* * This file patches require.js to communicate with the build system. */ /*jslint nomen: false, plusplus: false, regexp: fa...
(path, encoding) { encoding = encoding || "utf-8"; var file = new java.io.File(path), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), stringBuffer, line; try { stringBuffer = new java.lang...
_readFile
identifier_name
requirePatch.js
/** * @license RequireJS Copyright (c) 2010, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /* * This file patches require.js to communicate with the build system. */ /*jslint nomen: false, plusplus: false, regexp: fa...
while (line !== null) { stringBuffer.append(line); stringBuffer.append(lineSeparator); line = input.readLine(); } //Make sure we return a JavaScript string and not a Java string. return String(stringBuffer.toString()); //Str...
{ encoding = encoding || "utf-8"; var file = new java.io.File(path), input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(file), encoding)), stringBuffer, line; try { stringBuffer = new java.lang.StringBuffer(); ...
identifier_body
requirePatch.js
/** * @license RequireJS Copyright (c) 2010, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /* * This file patches require.js to communicate with the build system. */ /*jslint nomen: false, plusplus: false, regexp: fa...
eval(contents); //Support anonymous modules. require.completeLoad(moduleName, context); } } //Mark the module loaded. context.loaded[moduleName] = true; require.checkLoaded(contextName); }; //Override a method provide...
//code in a require callback. contents = parse(url, contents); } if (contents) {
random_line_split
requirePatch.js
/** * @license RequireJS Copyright (c) 2010, The Dojo Foundation All Rights Reserved. * Available via the MIT or new BSD license. * see: http://github.com/jrburke/requirejs for details */ /* * This file patches require.js to communicate with the build system. */ /*jslint nomen: false, plusplus: false, regexp: fa...
}; }());
{ layer.buildFilePaths.push(url); layer.loadedFiles[url] = true; layer.modulesWithNames[name] = true; }
conditional_block
factory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
} #[test] fn test_create_vm() { let _vm = Factory::default().create(U256::zero()); } /// Create tests by injecting different VM factories #[macro_export] macro_rules! evm_test( (ignorejit => $name_test: ident: $name_jit: ident, $name_int: ident) => { #[test] #[ignore] #[cfg(feature = "jit")] fn $name_jit()...
{ Factory { evm: VMType::Interpreter, evm_cache: Arc::new(SharedCache::default()), } }
identifier_body
factory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
, VMType::Interpreter => if Self::can_fit_in_usize(gas) { Box::new(super::interpreter::Interpreter::<usize>::new(self.evm_cache.clone())) } else { Box::new(super::interpreter::Interpreter::<U256>::new(self.evm_cache.clone())) } } } /// Create fresh instance of VM /// Might choose implementation d...
{ Box::new(super::jit::JitEvm::default()) }
conditional_block
factory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(gas: U256) -> bool { gas == U256::from(gas.low_u64() as usize) } } impl Default for Factory { /// Returns jitvm factory #[cfg(all(feature = "jit", not(test)))] fn default() -> Factory { Factory { evm: VMType::Jit, evm_cache: Arc::new(SharedCache::default()), } } /// Returns native rust evm factory ...
can_fit_in_usize
identifier_name
factory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
/// RUST EVM Interpreter } impl fmt::Display for VMType { #[cfg(feature="jit")] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", match *self { VMType::Jit => "JIT", VMType::Interpreter => "INT" }) } #[cfg(not(feature="jit"))] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {...
/// Type of EVM to use. pub enum VMType { /// JIT EVM #[cfg(feature = "jit")] Jit,
random_line_split
opaque_types.rs
use rustc_data_structures::vec_map::VecMap; use rustc_infer::infer::InferCtxt; use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable}; use rustc_span::Span; use rustc_trait_selection::opaque_types::InferCtxtExt; use super::RegionInferenceContext; impl<'tcx> RegionInferenceContext<'tcx> { /// Resolv...
subst_regions.sort(); subst_regions.dedup(); let universal_concrete_type = infcx.tcx.fold_regions(concrete_type, &mut false, |region, _| match *region { ty::ReVar(vid) => subst_regions .iter() ...
{ opaque_ty_decls .into_iter() .map(|(opaque_type_key, concrete_type)| { let substs = opaque_type_key.substs; debug!(?concrete_type, ?substs); let mut subst_regions = vec![self.universal_regions.fr_static]; let universal_su...
identifier_body
opaque_types.rs
use rustc_data_structures::vec_map::VecMap; use rustc_infer::infer::InferCtxt; use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable}; use rustc_span::Span; use rustc_trait_selection::opaque_types::InferCtxtExt; use super::RegionInferenceContext; impl<'tcx> RegionInferenceContext<'tcx> { /// Resolv...
opaque_ty_decls: VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>>, span: Span, ) -> VecMap<OpaqueTypeKey<'tcx>, Ty<'tcx>> { opaque_ty_decls .into_iter() .map(|(opaque_type_key, concrete_type)| { let substs = opaque_type_key.substs; debug!(?concret...
#[instrument(skip(self, infcx))] pub(in crate::borrow_check) fn infer_opaque_types( &self, infcx: &InferCtxt<'_, 'tcx>,
random_line_split
opaque_types.rs
use rustc_data_structures::vec_map::VecMap; use rustc_infer::infer::InferCtxt; use rustc_middle::ty::{self, OpaqueTypeKey, Ty, TyCtxt, TypeFoldable}; use rustc_span::Span; use rustc_trait_selection::opaque_types::InferCtxtExt; use super::RegionInferenceContext; impl<'tcx> RegionInferenceContext<'tcx> { /// Resolv...
<T>(&self, tcx: TyCtxt<'tcx>, ty: T) -> T where T: TypeFoldable<'tcx>, { tcx.fold_regions(ty, &mut false, |region, _| match *region { ty::ReVar(vid) => { // Find something that we can name let upper_bound = self.approx_universal_upper_bound(vid); ...
name_regions
identifier_name
linux_shell.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import subprocess from devtoolslib.shell import Shell from devtoolslib import http_server class LinuxShell(Shell): """Wrapper around Mojo shell running ...
def Run(self, arguments): """Runs the shell with given arguments until shell exits, passing the stdout mingled with stderr produced by the shell onto the stdout. Returns: Exit code retured by the shell or None if the exit code cannot be retrieved. """ command = self.command_prefix +...
"""Serves the content of the local (host) directory, making it available to the shell under the url returned by the function. The server will run on a separate thread until the program terminates. The call returns immediately. Args: local_dir_path: path to the directory to be served port: ...
identifier_body
linux_shell.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import subprocess from devtoolslib.shell import Shell from devtoolslib import http_server class LinuxShell(Shell): """Wrapper around Mojo shell running ...
self.command_prefix = command_prefix if command_prefix else [] def ServeLocalDirectory(self, local_dir_path, port=0): """Serves the content of the local (host) directory, making it available to the shell under the url returned by the function. The server will run on a separate thread until the progr...
def __init__(self, executable_path, command_prefix=None): self.executable_path = executable_path
random_line_split
linux_shell.py
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import subprocess from devtoolslib.shell import Shell from devtoolslib import http_server class
(Shell): """Wrapper around Mojo shell running on Linux. Args: executable_path: path to the shell binary command_prefix: optional list of arguments to prepend to the shell command, allowing e.g. to run the shell under debugger. """ def __init__(self, executable_path, command_prefix=None): s...
LinuxShell
identifier_name
AdditionalCategoryKeys.ts
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free S...
random_line_split
controller.js
var model = require(__dirname + '/../models/model.js'); var controller = function() {}; //create new user function create(id)
function getUser(id, cb) { model.findOne({ //find by unique id id: id }, function(err, user) { if (err) { console.log(err); throw new Error('could not query db'); } if (!user) {//user already existed in database user = create(id); } cb(user); }); } function saveUser(u...
{ var newUser = new model({ id: id, currentCowntt: 0, apiCallsMade: 0 }); return newUser; }
identifier_body
controller.js
var model = require(__dirname + '/../models/model.js'); var controller = function() {}; //create new user function create(id) { var newUser = new model({ id: id, currentCowntt: 0, apiCallsMade: 0 }); return newUser; } function getUser(id, cb) { model.findOne({ //find by unique id id: id }, ...
if (err) { console.log(err); throw new Error('could not query db'); } if (!user) {//user already existed in database user = create(id); } cb(user); }); } function saveUser(user, cb) { user.save( function(saveErr) { if (saveErr) { console.log('saveError saving to deb...
random_line_split
controller.js
var model = require(__dirname + '/../models/model.js'); var controller = function() {}; //create new user function create(id) { var newUser = new model({ id: id, currentCowntt: 0, apiCallsMade: 0 }); return newUser; } function getUser(id, cb) { model.findOne({ //find by unique id id: id }, ...
(user, cb) { user.save( function(saveErr) { if (saveErr) { console.log('saveError saving to debugger: ' + saveErr); } cb(user); }); } controller.prototype.incrementCowntt = function(id, parentCB) { getUser(id, function (user) { user.currentCowntt += 1; user.apiCallsMade += 1; saveUs...
saveUser
identifier_name
controller.js
var model = require(__dirname + '/../models/model.js'); var controller = function() {}; //create new user function create(id) { var newUser = new model({ id: id, currentCowntt: 0, apiCallsMade: 0 }); return newUser; } function getUser(id, cb) { model.findOne({ //find by unique id id: id }, ...
if (!user) {//user already existed in database user = create(id); } cb(user); }); } function saveUser(user, cb) { user.save( function(saveErr) { if (saveErr) { console.log('saveError saving to debugger: ' + saveErr); } cb(user); }); } controller.prototype.incrementCowntt = ...
{ console.log(err); throw new Error('could not query db'); }
conditional_block
run.ts
'use strict'; import * as tl from 'azure-pipelines-task-lib/task'; import * as path from 'path'; import * as utils from './utils/utilities'; import { deploy } from './actions/deploy'; import { bake } from './actions/bake'; import { scale } from './actions/scale'; import { patch } from './actions/patch'; import { delet...
case 'promote': action_func = promote; break; case 'reject': action_func = reject; break; case 'createSecret': action_func = createSecret; break; default: tl.setResult(tl.TaskResult.Failed, 'Not a support...
{ const action = tl.getInput('action'); if (action === 'bake') { return bake(); } const connection = utils.getConnection(); let action_func = null; switch (action) { case 'deploy': action_func = deploy; break; case 'scale': action_func ...
identifier_body
run.ts
'use strict'; import * as tl from 'azure-pipelines-task-lib/task'; import * as path from 'path'; import * as utils from './utils/utilities'; import { deploy } from './actions/deploy'; import { bake } from './actions/bake'; import { scale } from './actions/scale'; import { patch } from './actions/patch'; import { delet...
(): Promise<void> { const action = tl.getInput('action'); if (action === 'bake') { return bake(); } const connection = utils.getConnection(); let action_func = null; switch (action) { case 'deploy': action_func = deploy; break; case 'scale': ...
run
identifier_name
run.ts
'use strict'; import * as tl from 'azure-pipelines-task-lib/task'; import * as path from 'path'; import * as utils from './utils/utilities'; import { deploy } from './actions/deploy'; import { bake } from './actions/bake'; import { scale } from './actions/scale'; import { patch } from './actions/patch'; import { delet...
default: tl.setResult(tl.TaskResult.Failed, 'Not a supported action, choose from "bake", "deploy", "patch", "scale", "delete", "promote", "reject"'); process.exit(1); } connection.open(); return action_func(connection.ignoreSSLErrors) .then(() => connection.close()) ...
action_func = reject; break; case 'createSecret': action_func = createSecret; break;
random_line_split
signer.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
p.push(CODES_FILENAME); let _ = restrict_permissions_owner(&p, true, false); p } pub fn execute(ws_conf: rpc::WsConfiguration, ui_conf: rpc::UiConfiguration) -> Result<String, String> { Ok(generate_token_and_url(&ws_conf, &ui_conf)?.message) } pub fn generate_token_and_url(ws_conf: &rpc::WsConfiguration, ui_conf:...
} pub fn codes_path(path: &Path) -> PathBuf { let mut p = path.to_owned();
random_line_split
signer.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> rpc_apis::SignerService { let signer_path = ws_conf.signer_path.clone(); let signer_enabled = ui_conf.enabled; rpc_apis::SignerService::new(move || { generate_new_token(&signer_path).map_err(|e| format!("{:?}", e)) }, signer_enabled) } pub fn c...
new_service
identifier_name
signer.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
pub fn execute(ws_conf: rpc::WsConfiguration, ui_conf: rpc::UiConfiguration) -> Result<String, String> { Ok(generate_token_and_url(&ws_conf, &ui_conf)?.message) } pub fn generate_token_and_url(ws_conf: &rpc::WsConfiguration, ui_conf: &rpc::UiConfiguration) -> Result<NewToken, String> { let code = generate_new_toke...
{ let mut p = path.to_owned(); p.push(CODES_FILENAME); let _ = restrict_permissions_owner(&p, true, false); p }
identifier_body
types.ts
// JIRA REST API Interfaces (Mappings) export interface JiraApiBaseItem { field: string; toString: string; }; export interface JiraApiIssueHistory { id: string; items: Array<JiraApiBaseItem>; created: string; }; export interface JiraApiIssueChangeLog { total: number; histories: Array<JiraApiIssueHistory...
teams?: Teams; };
random_line_split
utils.js
'use strict'; const http = require('http'); const selenium = require('selenium-standalone'); const nodeStatic = require('node-static'); let grid, staticServer; module.exports = { startStaticServer, stopStaticServer, startSelenium, stopSelenium }; function startStaticServer() { return new Promise((resolve...
} console.log('Started Selenium server'); grid = sel; resolve(sel); }); }); } function stopSelenium() { return new Promise((resolve, reject) => { grid.on('exit', () => { resolve(true); }); grid.kill(); }); } function stopStaticServer() { return new Promise((resolv...
random_line_split