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
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> Map...
<T>(arg: T) -> &SomeType where T: Fn(// First arg A, // Second argument B, C, D, /* pre comment */ E /* last comment */) -> &SomeType { arg(a, b, c, d, e) } fn foo() -> ! {} pub fn http_fetch_async(listener:Box< AsyncCORSResponseListener+Send >, script_chan: Box<ScriptChan+Sen...
generic
identifier_name
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> Map...
// #2003 mod foo { fn __bindgen_test_layout_i_open0_c_open1_char_a_open2_char_close2_close1_close0_instantiation() { foo(); } }
formatted_comment = rewrite_comment(comment, block_style, width, offset, formatting_fig); } } }
random_line_split
fn-simple.rs
// rustfmt-normalize_comments: true fn simple(/*pre-comment on a function!?*/ i: i32/*yes, it's possible! */ ,response: NoWay /* hose */) { fn op(x: Typ, key : &[u8], upd : Box<Fn(Option<&memcache::Item>) -> (memcache::Status, Result<memcache::Item, Option<String>>)>) -> Map...
pub fn http_fetch_async(listener:Box< AsyncCORSResponseListener+Send >, script_chan: Box<ScriptChan+Send>) { } fn some_func<T:Box<Trait+Bound>>(val:T){} fn zzzzzzzzzzzzzzzzzzzz<Type, NodeType> (selff: Type, mut handle: node::Handle<IdRef<'id, Node<K, V>>, Type, NodeType>) ...
{}
identifier_body
number_pipe.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Pipe, PipeTransform} from '@angular/core'; import {NumberFormatStyle, NumberFormatter} from '../facade/intl...
* "EUR" for the euro. `symbolDisplay` is a boolean indicating whether to use the currency * symbol (e.g. $) or the currency code (e.g. USD) in the output. The default for this value * is `false`. * For more information about `digitInfo` see {@link DecimalPipe} * * ### Example * * {@example core/pipes/ts/number_...
random_line_split
number_pipe.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Pipe, PipeTransform} from '@angular/core'; import {NumberFormatStyle, NumberFormatter} from '../facade/intl...
if (isPresent(parts[1])) { // min integer digits minInt = NumberWrapper.parseIntAutoRadix(parts[1]); } if (isPresent(parts[3])) { // min fraction digits minFraction = NumberWrapper.parseIntAutoRadix(parts[3]); } if (isPresent(parts[5])) { // max fraction digits maxFraction = Nu...
{ throw new Error(`${digits} is not a valid digit info for number pipes`); }
conditional_block
number_pipe.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Pipe, PipeTransform} from '@angular/core'; import {NumberFormatStyle, NumberFormatter} from '../facade/intl...
throw new Error(`${digits} is not a valid digit info for number pipes`); } if (isPresent(parts[1])) { // min integer digits minInt = NumberWrapper.parseIntAutoRadix(parts[1]); } if (isPresent(parts[3])) { // min fraction digits minFraction = NumberWrapper.parseIntAutoRadix(parts[3]);...
{ if (isBlank(value)) return null; // Convert strings to numbers value = isString(value) && NumberWrapper.isNumeric(value) ? +value : value; if (!isNumber(value)) { throw new InvalidPipeArgumentException(pipe, value); } let minInt: number; let minFraction: number; let maxFraction: number; if (styl...
identifier_body
number_pipe.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Pipe, PipeTransform} from '@angular/core'; import {NumberFormatStyle, NumberFormatter} from '../facade/intl...
(value: any, digits: string = null): string { return formatNumber(PercentPipe, value, NumberFormatStyle.Percent, digits); } } /** * WARNING: this pipe uses the Internationalization API. * Therefore it is only reliable in Chrome and Opera browsers. For other browsers please use an * polyfill, for example: [htt...
transform
identifier_name
target_nrf51.py
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited 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 ...
(self, transport): super(NRF51, self).__init__(transport, self.memoryMap) def resetn(self): """ reset a core. After a call to this function, the core is running """ #Regular reset will kick NRF out of DBG mode logging.debug("target_nrf51.reset: enable reset p...
__init__
identifier_name
target_nrf51.py
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited 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 ...
def resetn(self): """ reset a core. After a call to this function, the core is running """ #Regular reset will kick NRF out of DBG mode logging.debug("target_nrf51.reset: enable reset pin") self.writeMemory(RESET, RESET_ENABLE) #reset logging...
super(NRF51, self).__init__(transport, self.memoryMap)
identifier_body
target_nrf51.py
""" mbed CMSIS-DAP debugger Copyright (c) 2006-2013 ARM Limited 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 ...
) def __init__(self, transport): super(NRF51, self).__init__(transport, self.memoryMap) def resetn(self): """ reset a core. After a call to this function, the core is running """ #Regular reset will kick NRF out of DBG mode logging.debug("target_...
memoryMap = MemoryMap( FlashRegion( start=0, length=0x40000, blocksize=0x400, isBootMemory=True), RamRegion( start=0x20000000, length=0x4000)
random_line_split
useToggleRefinement.test.tsx
import { renderHook } from '@testing-library/react-hooks'; import { createInstantSearchTestWrapper } from '../../../../../test/utils'; import { useToggleRefinement } from '../useToggleRefinement'; describe('useToggleRefinement', () => { test('returns the connector render state', async () => { const wrapper = cr...
value: { count: null, isRefined: false, name: 'test', offFacetValue: { count: 0, isRefined: false, }, onFacetValue: { count: null, isRefined: false, }, }, }); await waitForNextUpdate(); // InstantSe...
expect(result.current).toEqual({ canRefine: false, createURL: expect.any(Function), refine: expect.any(Function), sendEvent: expect.any(Function),
random_line_split
lib.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/. */ #[cfg(target_os = "android")] extern crate android_injected_glue; #[cfg(target_os = "android")] extern crate andro...
// If not Android, expose the C-API #[cfg(not(target_os = "android"))] mod capi; #[cfg(not(target_os = "android"))] pub use capi::*; // If Android, expose the JNI-API #[cfg(target_os = "android")] mod jniapi; #[cfg(target_os = "android")] pub use jniapi::*;
mod gl_glue;
random_line_split
yyyymmddDate.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isYyyymmddDate; /** * Check if is a valid yyyy.mm.dd date * This will match : yyyy.mm.dd | yyyy/mm/dd | yyyy-mm-dd | yyyy mm dd * @param {String} date The date to check * @return {Boolean} true if is val...
{ return (/^\d{4}[\-\/\s\.]?((((0[13578])|(1[02]))[\-\/\s\.]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s\.]?(([0-2][0-9])|(30)))|(02[\-\/\s\.]?[0-2][0-9]))$/.test(date) ); }
identifier_body
yyyymmddDate.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isYyyymmddDate; /** * Check if is a valid yyyy.mm.dd date * This will match : yyyy.mm.dd | yyyy/mm/dd | yyyy-mm-dd | yyyy mm dd * @param {String} date The date to check * @return {Boolean} true if is val...
(date) { return (/^\d{4}[\-\/\s\.]?((((0[13578])|(1[02]))[\-\/\s\.]?(([0-2][0-9])|(3[01])))|(((0[469])|(11))[\-\/\s\.]?(([0-2][0-9])|(30)))|(02[\-\/\s\.]?[0-2][0-9]))$/.test(date) ); }
isYyyymmddDate
identifier_name
yyyymmddDate.js
"use strict";
value: true }); exports.default = isYyyymmddDate; /** * Check if is a valid yyyy.mm.dd date * This will match : yyyy.mm.dd | yyyy/mm/dd | yyyy-mm-dd | yyyy mm dd * @param {String} date The date to check * @return {Boolean} true if is valid, false if not * @example js * import isYyyymmddDate fr...
Object.defineProperty(exports, "__esModule", {
random_line_split
media_queries.rs
Size2D, TypedSize2D}; use media_queries::MediaType; use parser::ParserContext; use properties::ComputedValues; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError};...
, } } } } } impl ToCss for Expression { fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: Write, { let (s, l) = match self.0 { ExpressionKind::Width(Range::Min(ref l)) => ("(min-width: ", l), ExpressionKind::...
{ value == *width }
conditional_block
media_queries.rs
Size2D, TypedSize2D}; use media_queries::MediaType; use parser::ParserContext; use properties::ComputedValues; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError};...
"width" => { ExpressionKind::Width(Range::Eq(specified::Length::parse_non_negative(context, input)?)) }, _ => return Err(input.new_custom_error(SelectorParseErrorKind::UnexpectedIdent(name.clone()))) })) }) } /// Evaluate t...
ExpressionKind::Width(Range::Max(specified::Length::parse_non_negative(context, input)?)) },
random_line_split
media_queries.rs
Size2D, TypedSize2D}; use media_queries::MediaType; use parser::ParserContext; use properties::ComputedValues; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError};...
/// Take into account a viewport rule taken from the stylesheets. pub fn account_for_viewport_rule(&mut self, constraints: &ViewportConstraints) { self.viewport_size = constraints.size; } /// Return the media type of the current device. pub fn media_type(&self) -> MediaType { self...
{ self.device_pixel_ratio }
identifier_body
media_queries.rs
Size2D, TypedSize2D}; use media_queries::MediaType; use parser::ParserContext; use properties::ComputedValues; use selectors::parser::SelectorParseErrorKind; use std::fmt::{self, Write}; use std::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use style_traits::{CSSPixel, CssWriter, DevicePixel, ToCss, ParseError};...
(&self, _color: RGBA) { // Servo doesn't implement this quirk (yet) } /// Whether a given animation name may be referenced from style. pub fn animation_name_may_be_referenced(&self, _: &KeyframesName) -> bool { // Assume it is, since we don't have any good way to prove it's not. tru...
set_body_text_color
identifier_name
code_generator_v8.py
dir sys.path.insert(1, third_party_dir) import jinja2 from idl_definitions import Visitor import idl_types from idl_types import IdlType import v8_callback_interface import v8_dictionary from v8_globals import includes, interfaces import v8_interface import v8_types import v8_union from v8_utilities import capitalize...
raise ValueError('%s is not an IDL dictionary')
conditional_block
code_generator_v8.py
, os.pardir)) templates_dir = os.path.normpath(os.path.join( module_path, os.pardir, 'templates')) # Make sure extension is .py, not .pyc or .pyo, so doesn't depend on caching module_pyname = os.path.splitext(module_filename)[0] + '.py' # jinja2 is in chromium's third_party directory. # Insert at 1 so at front to ...
def
CodeGeneratorBase.__init__(self, info_provider, cache_dir, output_dir)
identifier_body
code_generator_v8.py
_code( definitions, definition_name, definitions.dictionaries[definition_name]) raise ValueError('%s is not in IDL definitions' % definition_name) def generate_interface_code(self, definitions, interface_name, interface): # Store other interfaces for introspection ...
################################################################################ def main(argv): # If file itself executed, cache templates try:
random_line_split
code_generator_v8.py
.output_dir, 'V8%s.h' % definition_name) cpp_path = posixpath.join(self.output_dir, 'V8%s.cpp' % definition_name) return header_path, cpp_path def generate_code_internal(self, definitions, definition_name): if definition_name in definitions.interfaces: ...
exposed_if
identifier_name
import_graded_essays.py
from django.core.management.base import BaseCommand from django.conf import settings from django.utils import timezone #from http://jamesmckay.net/2009/03/django-custom-managepy-commands-not-committing-transactions/ #Fix issue where db data in manage.py commands is not refreshed at all once they start running from dja...
(BaseCommand): args = "<filename>" help = "Poll grading controller and send items to be graded to ml" def handle(self, *args, **options): """ Read from file """ parser = SafeConfigParser() parser.read(args[0]) print("Starting import...") print("Rea...
Command
identifier_name
import_graded_essays.py
from django.core.management.base import BaseCommand from django.conf import settings from django.utils import timezone #from http://jamesmckay.net/2009/03/django-custom-managepy-commands-not-committing-transactions/ #Fix issue where db data in manage.py commands is not refreshed at all once they start running from dja...
for row in xrange(1, len(raw_lines)): rubric_score_row=[] for score_item in raw_lines[row].strip().split("\t"): rubric_score_row.append(int(score_item)) rubric_scores.append(rubric_score_row) for i in range(0, min(essay_limit, len(...
combined_raw = open(settings.REPO_PATH / rubric_scores_file).read() raw_lines = combined_raw.splitlines()
random_line_split
import_graded_essays.py
from django.core.management.base import BaseCommand from django.conf import settings from django.utils import timezone #from http://jamesmckay.net/2009/03/django-custom-managepy-commands-not-committing-transactions/ #Fix issue where db data in manage.py commands is not refreshed at all once they start running from dja...
essay_file = parser.get(header_name, 'essay_file') essay_limit = int(parser.get(header_name, 'essay_limit')) state = parser.get(header_name, "state") next_grader_type = parser.get(header_name, "next_grader") add_grader = parser.get(header_name, "add_grader_object") == "True" ...
args = "<filename>" help = "Poll grading controller and send items to be graded to ml" def handle(self, *args, **options): """ Read from file """ parser = SafeConfigParser() parser.read(args[0]) print("Starting import...") print("Reading config from fi...
identifier_body
import_graded_essays.py
from django.core.management.base import BaseCommand from django.conf import settings from django.utils import timezone #from http://jamesmckay.net/2009/03/django-custom-managepy-commands-not-committing-transactions/ #Fix issue where db data in manage.py commands is not refreshed at all once they start running from dja...
print ("Successfully imported {0} essays using configuration in file {1}.".format( min(essay_limit, len(text)), args[0], ))
student_id+=1
conditional_block
index.d.ts
// Type definitions for Tether-Shepherd v1.2.0 // Project: http://github.hubspot.com/shepherd/ // Definitions by: Matt Gibbs <https://github.com/mtgibbs> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace TetherShepherd { interface ShepherdStatic { on(eventName: string, handler: Function, context?: any): any; off(eventName: string, handler?: Function): any; once(eventName: string, handler: Function, context?: any): any; activeTour: IShepherdTour; Tour: IShe...
random_line_split
MainMenu.ts
import { app, Menu, MenuItemConstructorOptions } from 'electron' /** * Create a template for the menu. * @returns Template. */ const createTemplate = (): MenuItemConstructorOptions[] => { const isMac = process.platform === 'darwin' return [ ...(isMac ? [ { label: app.name, ...
() { require('electron').shell.openExternal('https://electronjs.org') } } ] } ] as MenuItemConstructorOptions[] } /** * Create and set main menu. */ export const createMainMenu = () => { const template = Menu.buildFromTemplate(createTemplate()) Menu.setApplicationMenu(te...
click
identifier_name
MainMenu.ts
import { app, Menu, MenuItemConstructorOptions } from 'electron' /** * Create a template for the menu. * @returns Template. */ const createTemplate = (): MenuItemConstructorOptions[] => { const isMac = process.platform === 'darwin' return [ ...(isMac ? [ { label: app.name, ...
{ type: 'separator' }, { role: 'resetzoom' }, { role: 'zoomin' }, { role: 'zoomout' }, { type: 'separator' }, { role: 'togglefullscreen' } ] }, { role: 'window', submenu: [ ...(isMac ? [ { role: 'close' }, ...
{ role: 'reload' }, { role: 'forcereload' }, /// #if env == 'DEBUG' { role: 'toggledevtools' }, /// #endif
random_line_split
MainMenu.ts
import { app, Menu, MenuItemConstructorOptions } from 'electron' /** * Create a template for the menu. * @returns Template. */ const createTemplate = (): MenuItemConstructorOptions[] => { const isMac = process.platform === 'darwin' return [ ...(isMac ? [ { label: app.name, ...
} ] } ] as MenuItemConstructorOptions[] } /** * Create and set main menu. */ export const createMainMenu = () => { const template = Menu.buildFromTemplate(createTemplate()) Menu.setApplicationMenu(template) }
{ require('electron').shell.openExternal('https://electronjs.org') }
identifier_body
CrawlerStartButton.tsx
import React, { useState } from 'react'; import { css } from '@emotion/css'; import { Button, CodeEditor, Modal, useTheme2 } from '@grafana/ui'; import { GrafanaTheme2 } from '@grafana/data'; import { getBackendSrv, config } from '@grafana/runtime'; export const CrawlerStartButton = () => { const styles = getStyles(...
getBackendSrv() .post('/api/admin/crawler/start', body) .then((v) => { console.log('GOT', v); onDismiss(); }); }; return ( <> <Modal title={'Start crawler'} isOpen={open} onDismiss={onDismiss}> <div className={styles.wrap}> <CodeEditor h...
theme: config.theme2.isLight ? 'light' : 'dark', }); const onDismiss = () => setOpen(false); const doStart = () => {
random_line_split
OracleLogBackup.py
#!/usr/bin/env python # # VM Backup extension # # Copyright 2014 Microsoft Corporation # # 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 # # U...
recoveryFileDest = logbackup.oracleParameter['db_recovery_file_dest'] dbName = logbackup.oracleParameter['db_name'] print(' logbackup: Archive log backup started at ', datetime.now().strftime("%Y%m%d%H%M%S")) os.system('cp -R -f ' + recoveryFileDest[0] + '/' + dbName[0] + '/a...
sleep(1)
conditional_block
OracleLogBackup.py
#!/usr/bin/env python # # VM Backup extension # # Copyright 2014 Microsoft Corporation # # 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 # # U...
(): print("logbackup: Taking a backup") backupPath = setLocation() if 'oracle' in logbackup.name.lower(): backupOracle = logbackup.command + " -s / as sysdba @" + "/var/lib/waagent/Microsoft.Azure.RecoveryServices.VMSnapshotLinux-1.0.9164.0/main/workloadPatch/scripts/logbackup.sql " + backupPath ...
takeBackup
identifier_name
OracleLogBackup.py
#!/usr/bin/env python # # VM Backup extension # # Copyright 2014 Microsoft Corporation # # 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 # # U...
# *.db_name='CDB1' def parameterFileParser(): regX = re.compile(r"\*\..+=.+") parameterFile = open(logbackup.parameterFilePath, 'r') contents = parameterFile.read() for match in regX.finditer(contents): keyParameter = match.group().split('=')[0].lstrip('*\.') valueParameter = [name.strip...
# Example of Parameter File Content:
random_line_split
OracleLogBackup.py
#!/usr/bin/env python # # VM Backup extension # # Copyright 2014 Microsoft Corporation # # 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 # # U...
def setLocation(): nowTimestamp = datetime.now() nowTimestamp = nowTimestamp.strftime("%Y%m%d%H%M%S") fullPath = logbackup.baseLocation + nowTimestamp os.system('mkdir -m777 '+ fullPath) return fullPath def takeBackup(): print("logbackup: Taking a backup") backupPath = setLocation() ...
regX = re.compile(r"\*\..+=.+") parameterFile = open(logbackup.parameterFilePath, 'r') contents = parameterFile.read() for match in regX.finditer(contents): keyParameter = match.group().split('=')[0].lstrip('*\.') valueParameter = [name.strip('\'') for name in match.group().split('=')[1].spl...
identifier_body
test_multipoint_expected_improvement.py
import GPy import numpy as np from scipy.optimize import check_grad from emukit.bayesian_optimization.acquisitions import MultipointExpectedImprovement from emukit.model_wrappers import GPyModelWrapper # Tolerance needs to be quite high since the q-EI is also an approximation. TOL = 5e-3 # Tolerance for the gradient ...
# Set current minimum to a random number smaller than the mean: current_minimum = np.random.uniform() # Compute acquisition: qei_analytic, _, _ = MultipointExpectedImprovement(None)._get_acquisition(mu, Sigma, current_minimum) acq_fast = MultipointExpectedImprovement(None, fast_compute=True, eps=1e...
random_line_split
test_multipoint_expected_improvement.py
import GPy import numpy as np from scipy.optimize import check_grad from emukit.bayesian_optimization.acquisitions import MultipointExpectedImprovement from emukit.model_wrappers import GPyModelWrapper # Tolerance needs to be quite high since the q-EI is also an approximation. TOL = 5e-3 # Tolerance for the gradient ...
(): """ Check the q-EI acquisition function gradients with numeric differentiation """ x_init = np.random.rand(3, 1) y_init = np.random.rand(3, 1) # Make GPy model gpy_model = GPy.models.GPRegression(x_init, y_init) model = GPyModelWrapper(gpy_model) x0 = np.array([0.45, 0.55]) ...
test_acquisition_gradient_multipoint_expected_improvement
identifier_name
test_multipoint_expected_improvement.py
import GPy import numpy as np from scipy.optimize import check_grad from emukit.bayesian_optimization.acquisitions import MultipointExpectedImprovement from emukit.model_wrappers import GPyModelWrapper # Tolerance needs to be quite high since the q-EI is also an approximation. TOL = 5e-3 # Tolerance for the gradient ...
grad_error = check_grad( lambda x: lp.evaluate(x[:, None]).flatten(), lambda x: lp.evaluate_with_gradients(x[:, None])[1].flatten(), x0 ) assert np.all(grad_error < tol)
identifier_body
BlendMode.ts
* </ul> */ class BlendMode { /** * Adds the values of the constituent colors of the display object to the * colors of its background, applying a ceiling of 0xFF. This setting is * commonly used for animating a lightening dissolve between two objects. * * <p>For example, if the display object has a pixel wi...
* <ul> * <li> The <code>blendMode</code> property of the * flash.display.DisplayObject class.</li> * <li> The <code>blendMode</code> parameter of the <code>draw()</code> * method of the flash.display.BitmapData class</li>
random_line_split
BlendMode.ts
Object class.</li> * <li> The <code>blendMode</code> parameter of the <code>draw()</code> * method of the flash.display.BitmapData class</li> * </ul> */ class
{ /** * Adds the values of the constituent colors of the display object to the * colors of its background, applying a ceiling of 0xFF. This setting is * commonly used for animating a lightening dissolve between two objects. * * <p>For example, if the display object has a pixel with an RGB value of * 0xAAA...
BlendMode
identifier_name
ecr.py
an "AS IS" BASIS, # 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. from __future__ import absolute_import, division, print_function, unicode_literals import json from c7n.actions import Re...
(QueryResourceManager): class resource_type(TypeInfo): service = 'ecr' enum_spec = ('describe_repositories', 'repositories', None) name = "repositoryName" arn = id = "repositoryArn" arn_type = 'repository' filter_name = 'repositoryNames' filter_type = 'list' ...
ECR
identifier_name
ecr.py
Names' filter_type = 'list' def augment(self, resources): client = local_session(self.session_factory).client('ecr') results = [] for r in resources: try: r['Tags'] = client.list_tags_for_resource( resourceArn=r['repositoryArn']).get('...
client.set_repository_policy( repositoryName=resource['repositoryName'], policyText=json.dumps(p))
conditional_block
ecr.py
an "AS IS" BASIS, # 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. from __future__ import absolute_import, division, print_function, unicode_literals import json from c7n.actions import Re...
if self.data.get('state') is False and 'rules' in self.data: raise PolicyValidationError( "set-lifecycle can't use statements and state: false") elif self.data.get('state', True) and not self.data.get('rules'): raise PolicyValidationError( "set-lif...
rules={ 'type': 'array', 'items': LIFECYCLE_RULE_SCHEMA}) def validate(self):
random_line_split
ecr.py
an "AS IS" BASIS, # 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. from __future__ import absolute_import, division, print_function, unicode_literals import json from c7n.actions import Re...
@ECR.action_registry.register('remove-tag') class ECRRemoveTags(tags.RemoveTag): permissions = ('ecr:UntagResource',) def process_resource_set(self, client, resources, tags): for r in resources: try: client.untag_resource(resourceArn=r['repositoryArn'], tagKeys=tags) ...
for r in resources: try: client.tag_resource(resourceArn=r['repositoryArn'], tags=tags) except client.exceptions.RepositoryNotFoundException: pass
identifier_body
domstringmap.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DO...
// https://html.spec.whatwg.org/multipage/#dom-domstringmap-nameditem fn NamedGetter(&self, name: DOMString) -> Option<DOMString> { self.element.get_custom_attr(name) } // https://html.spec.whatwg.org/multipage/#the-domstringmap-interface:supported-property-names fn SupportedPropertyNames...
{ self.element.set_custom_attr(name, value) }
identifier_body
domstringmap.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DO...
.cloned() .collect() } }
fn SupportedPropertyNames(&self) -> Vec<DOMString> { self.element .supported_prop_names_custom_attr() .iter()
random_line_split
domstringmap.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::DOMStringMapBinding; use crate::dom::bindings::codegen::Bindings::DO...
(element: &HTMLElement) -> DomRoot<DOMStringMap> { let window = window_from_node(element); reflect_dom_object( Box::new(DOMStringMap::new_inherited(element)), &*window, DOMStringMapBinding::Wrap, ) } } // https://html.spec.whatwg.org/multipage/#domstringm...
new
identifier_name
test_bootstrap.js
// Copyright 2011 Software Freedom Conservancy. 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 req...
* <script> * goog.require('goog.debug.Logger'); * </script> * <script> * window.onload = function() { * goog.debug.Logger.getLogger('').info( * 'The page has finished loading'); * }; * </script> * </head> * <body></body> * </html> */ (function() { ...
* * <html> * <head> * <script src="test_bootstrap.js"></script>
random_line_split
test_bootstrap.js
// Copyright 2011 Software Freedom Conservancy. 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 req...
})();
{ document.write('<script type="text/javascript" src="' + directoryPath + files[j] + '"></script>'); }
conditional_block
tostr.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. use crate::{ bif::NativeFunc, path::ConcretePath, tree::Tree, value::{Value, ValueData...
; impl NativeFunc for ToStr { fn compute(&self, value: Value, tree: &Tree) -> Fallible<Value> { Ok(Value::from_string(match value.data { ValueData::String(s) => s, ValueData::Integer(i) => format!("{}", i), ValueData::Float(f) => format!("{}", f), ValueData::...
ToStr
identifier_name
tostr.rs
// This Source Code Form is subject to the terms of the GNU General Public // License, version 3. If a copy of the GPL was not distributed with this file, // You can obtain one at https://www.gnu.org/licenses/gpl.txt. use crate::{ bif::NativeFunc, path::ConcretePath, tree::Tree, value::{Value, ValueData...
} fn find_all_possible_inputs( &self, _value_type: (), _tree: &Tree, _out: &mut Vec<ConcretePath>, ) -> Fallible<()> { Ok(()) } fn box_clone(&self) -> Box<dyn NativeFunc + Send + Sync> { Box::new((*self).clone()) } }
}))
random_line_split
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection; // Internal Dependencies ------------------------------------------------------ use ::c...
(&self, command: Command) -> ActionGroup { MessageActions::Send::private( &command.message, "Usage: `!ip`".to_string() ) } } // Helpers -------------------------------------------------------------------- fn resolve_ip() -> Result<String, String> { let client = Client...
usage
identifier_name
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection; // Internal Dependencies ------------------------------------------------------ use ::c...
fn help(&self) -> &str { "Post the bot's current IP address onto the channel." } fn usage(&self, command: Command) -> ActionGroup { MessageActions::Send::private( &command.message, "Usage: `!ip`".to_string() ) } } // Helpers -------------------------...
{ let response = match resolve_ip() { Ok(ip) => format!( "{} has requested my public IP address which is: {}.", command.member.nickname, ip ), Err(_) => "{} has requested my public IP address, but the lookup failed.".to_string(...
identifier_body
ip.rs
// STD Dependencies ----------------------------------------------------------- use std::io::Read; // External Dependencies ------------------------------------------------------ use hyper::Client; use hyper::header::Connection;
use ::action::{ActionGroup, MessageActions}; // Command Implementation ----------------------------------------------------- pub struct Handler; impl CommandHandler for Handler { delete_command_message!(); fn run(&self, command: Command) -> ActionGroup { let response = match resolve_ip() { ...
// Internal Dependencies ------------------------------------------------------ use ::command::{Command, CommandHandler};
random_line_split
activation.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::C...
fn exit_formal_activation_state(&self) { self.as_element().set_active_state(false); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } } /// Whether an activation was initiated via the click() method #[derive(PartialEq)] ...
{ self.as_element().set_active_state(true); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); }
identifier_body
activation.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::C...
use crate::dom::element::Element; use crate::dom::event::{Event, EventBubbles, EventCancelable}; use crate::dom::eventtarget::EventTarget; use crate::dom::mouseevent::MouseEvent; use crate::dom::node::window_from_node; use crate::dom::window::ReflowReason; use script_layout_interface::message::ReflowGoal; use script_tr...
use crate::dom::bindings::str::DOMString;
random_line_split
activation.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::C...
target.dispatch_event(event); // Step 5 if let Some(a) = activatable { if event.DefaultPrevented() { a.canceled_activation(); } else { // post click activation a.activation_behavior(event, target); } } // Step 6 element.set_click_in_...
{ event.set_trusted(false); }
conditional_block
activation.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 https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::EventBinding::EventMethods; use crate::dom::bindings::inheritance::C...
(&self) { self.as_element().set_active_state(true); let win = window_from_node(self.as_element()); win.reflow(ReflowGoal::Full, ReflowReason::ElementStateChanged); } fn exit_formal_activation_state(&self) { self.as_element().set_active_state(false); let win = window_fr...
enter_formal_activation_state
identifier_name
Gruntfile.js
/** * configuration for grunt tasks * @module Gruntfile */ module.exports = function(grunt) { /** load tasks */ require('load-grunt-tasks')(grunt); /** config for build paths */ var config = { dist: { dir: 'dist/', StoreFactory: 'dist/StoreFactory.js', ngStoreFactory: 'dist/ngStore.js...
ngSession: { options: { banner: 'angular.module("ngStore", [])\n' + '.service("ngStore", [\n' + 'function() {\n\n', footer: '\n\n' + 'return new StoreFactory();\n\n}' + '\n]);' }, src: (function() { return [ ...
dest: config.dist.StoreFactory, },
random_line_split
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
}; match byte { b':' => { let packet_len_str = String::from_utf8(buffer).unwrap(); let packet_len = u64::from_str_radix(&packet_len_str, 10).unwrap(); let mut packet = String::new(); self.take(packet_...
let byte = match try!(self.read(&mut buf)) { 0 => return Ok(None), // EOF 1 => buf[0], _ => unreachable!(),
random_line_split
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
<'a>(&mut self) -> io::Result<Option<Json>> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; let byte = match try...
read_json_packet
identifier_name
protocol.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/. */ //! Low-level wire protocol implementation. Currently only supports //! [JSON packets] //! (https://wiki.mozilla.o...
fn read_json_packet<'a>(&mut self) -> io::Result<Option<Json>> { // https://wiki.mozilla.org/Remote_Debugging_Protocol_Stream_Transport // In short, each JSON packet is [ascii length]:[JSON data of given length] let mut buffer = vec!(); loop { let mut buf = [0]; ...
{ let s = encode(obj).unwrap().replace("__type__", "type"); println!("<- {}", s); self.write_all(s.len().to_string().as_bytes()).unwrap(); self.write_all(&[':' as u8]).unwrap(); self.write_all(s.as_bytes()).unwrap(); }
identifier_body
test.process.ts
export class Test_ProcessTest { static run(assert: any) { let next = () => { this.run_2(assert, assert.async()) }; let p = new TestProcess((login, newUser, error) => { login('dogi'); }) .then() .login(user => { assert.ok(true); assert.equal(user, 'dogi'); next(); ...
} public then() { return this.login({}); } private login(c) { return { login: (cb: (user: string) => void) => { c.login = cb; return this.newUser(c); } } } private newUser(c) { return { newUser: (cb: (user: string) => void) => { c.newUser = cb; return this.onError(c); } } } private onError(c...
go(c) { return { go: () => { this.perform(c.login, c.newUser, c.onError); } }
random_line_split
test.process.ts
export class Test_ProcessTest { static run(assert: any) { let next = () => { this.run_2(assert, assert.async()) }; let p = new TestProcess((login, newUser, error) => { login('dogi'); }) .then() .login(user => { assert.ok(true); assert.equal(user, 'dogi'); next();...
(c) { return { onError: (cb: (error: string) => void) => { c.onError = cb; return this.go(c); } } } }
onError
identifier_name
check_print.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
else : res = { 'date_due' : False, 'name' : False, 'amount_original' : False, 'amount_due' : False, 'amount' : False, } result.append(res) return result ...
res = { 'date_due' : voucher_lines[i].date_due, 'name' : voucher_lines[i].name, 'amount_original' : voucher_lines[i].amount_original and voucher_lines[i].amount_original or False, 'amount_unreconciled' : voucher_lines[i].amount_unreconciled...
conditional_block
check_print.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
(self, amount): if len(amount) < 100: stars = 100 - len(amount) return ' '.join([amount,'*'*stars]) else: return amount def get_lines(self, voucher_lines): result = [] self.number_lines = len(voucher_lines) for i in range(0, min(10,self.number_lines)...
fill_stars
identifier_name
check_print.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
'time': time, 'get_lines': self.get_lines, 'fill_stars' : self.fill_stars, }) def fill_stars(self, amount): if len(amount) < 100: stars = 100 - len(amount) return ' '.join([amount,'*'*stars]) else: return amount def get_lines...
super(report_print_check, self).__init__(cr, uid, name, context) self.number_lines = 0 self.number_add = 0 self.localcontext.update({
random_line_split
check_print.py
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU...
for i in range(0, min(10,self.number_lines)): if i < self.number_lines: res = { 'date_due' : voucher_lines[i].date_due, 'name' : voucher_lines[i].name, 'amount_original' : voucher_lines[i].amount_original and voucher_lines[i...
def __init__(self, cr, uid, name, context): super(report_print_check, self).__init__(cr, uid, name, context) self.number_lines = 0 self.number_add = 0 self.localcontext.update({ 'time': time, 'get_lines': self.get_lines, 'fill_stars' : self.fill_stars,...
identifier_body
map_remove_entry_listener_codec.py
from hazelcast.serialization.bits import * from hazelcast.protocol.client_message import ClientMessage from hazelcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.map_message_type import * REQUEST_TYPE = MAP_REMOVEENTRYLISTENER RESPONSE_TYPE = 101 RETRYA...
(name, registration_id): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(registration_id) return data_size def encode_request(name, registration_id): """ Encode request into client_message""" client_message = Cl...
calculate_size
identifier_name
map_remove_entry_listener_codec.py
from hazelcast.serialization.bits import * from hazelcast.protocol.client_message import ClientMessage from hazelcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.map_message_type import * REQUEST_TYPE = MAP_REMOVEENTRYLISTENER RESPONSE_TYPE = 101 RETRYA...
parameters['response'] = client_message.read_bool() return parameters
random_line_split
map_remove_entry_listener_codec.py
from hazelcast.serialization.bits import * from hazelcast.protocol.client_message import ClientMessage from hazelcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.map_message_type import * REQUEST_TYPE = MAP_REMOVEENTRYLISTENER RESPONSE_TYPE = 101 RETRYA...
def encode_request(name, registration_id): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, registration_id)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_...
""" Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(registration_id) return data_size
identifier_body
provenance.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...
(id: EthDappId) -> Self { DappId(id.into()) } } impl Into<EthDappId> for DappId { fn into(self) -> EthDappId { Into::<String>::into(self).into() } } #[cfg(test)] mod tests { use serde_json; use super::{DappId, Origin}; #[test] fn should_serialize_origin() { // given let o1 = Origin::Rpc("test service"...
from
identifier_name
provenance.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...
// given let id = DappId("testapp".into()); // when let res = serde_json::to_string(&id).unwrap(); // then assert_eq!(res, r#""testapp""#); } #[test] fn should_deserialize_dapp_id() { // given let id = r#""testapp""#; // when let res: DappId = serde_json::from_str(id).unwrap(); // then a...
fn should_serialize_dapp_id() {
random_line_split
ingest_push.py
from cProfile import Profile from optparse import make_option from django.conf import settings from django.core.management.base import (BaseCommand, CommandError) from treeherder.etl.buildapi import (Builds4hJobsProcess, PendingJobsProcess,...
option_list = BaseCommand.option_list + ( make_option('--profile-file', action='store', dest='profile_file', default=None, help='Profile command and write result to profile file'), make_option('--filter-job-group', ...
help = "Ingests a single push into treeherder" args = '<project> <changeset>'
random_line_split
ingest_push.py
from cProfile import Profile from optparse import make_option from django.conf import settings from django.core.management.base import (BaseCommand, CommandError) from treeherder.etl.buildapi import (Builds4hJobsProcess, PendingJobsProcess,...
if options['profile_file']: profiler = Profile() profiler.runcall(self._handle, *args, **options) profiler.dump_stats(options['profile_file']) else: self._handle(*args, **options)
identifier_body
ingest_push.py
from cProfile import Profile from optparse import make_option from django.conf import settings from django.core.management.base import (BaseCommand, CommandError) from treeherder.etl.buildapi import (Builds4hJobsProcess, PendingJobsProcess,...
self._handle(*args, **options)
conditional_block
ingest_push.py
from cProfile import Profile from optparse import make_option from django.conf import settings from django.core.management.base import (BaseCommand, CommandError) from treeherder.etl.buildapi import (Builds4hJobsProcess, PendingJobsProcess,...
(BaseCommand): """Management command to ingest data from a single push.""" help = "Ingests a single push into treeherder" args = '<project> <changeset>' option_list = BaseCommand.option_list + ( make_option('--profile-file', action='store', dest='profil...
Command
identifier_name
classes-cross-crate.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
{ let mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
identifier_body
classes-cross-crate.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
() { let mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
main
identifier_name
classes-cross-crate.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { let mut nyan = cat(0u, 2, ~"nyan"); nyan.eat(); assert!((!nyan.eat())); for _ in range(1u, 10u) { nyan.speak(); }; assert!((nyan.eat())); }
random_line_split
select-demo-module.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import {FormsModule, ReactiveFo...
import {RouterModule} from '@angular/router'; import {SelectDemo} from './select-demo'; @NgModule({ imports: [ CommonModule, FormsModule, MatButtonModule, MatCardModule, MatFormFieldModule, MatIconModule, MatInputModule, MatSelectModule, MatToolbarModule, ReactiveFormsModule, ...
import {MatIconModule} from '@angular/material/icon'; import {MatInputModule} from '@angular/material/input'; import {MatSelectModule} from '@angular/material/select'; import {MatToolbarModule} from '@angular/material/toolbar';
random_line_split
select-demo-module.ts
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import {FormsModule, ReactiveFo...
{ }
SelectDemoModule
identifier_name
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
RTF: TReadTransportFactory + 'static, IPF: TInputProtocolFactory + 'static, WTF: TWriteTransportFactory + 'static, OPF: TOutputProtocolFactory + 'static, { r_trans_factory: RTF, i_proto_factory: IPF, w_trans_factory: WTF, o_proto_factory: OPF, processor: Arc<PRC>, worker_pool: Th...
where PRC: TProcessor + Send + Sync + 'static,
random_line_split
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
} }
{ warn!("processor completed with error: {:?}", e); break; }
conditional_block
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
/// Listen for incoming connections on `listen_address`. /// /// `listen_address` should be in the form `host:port`, /// for example: `127.0.0.1:8080`. /// /// Return `()` if successful. /// /// Return `Err` when the server cannot bind to `listen_address` or there /// is an unrecov...
{ TServer { r_trans_factory: read_transport_factory, i_proto_factory: input_protocol_factory, w_trans_factory: write_transport_factory, o_proto_factory: output_protocol_factory, processor: Arc::new(processor), worker_pool: ThreadPool::with_...
identifier_body
threaded.rs
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may n...
<PRC>( processor: Arc<PRC>, i_prot: Box<TInputProtocol>, o_prot: Box<TOutputProtocol>, ) where PRC: TProcessor, { let mut i_prot = i_prot; let mut o_prot = o_prot; loop { let r = processor.process(&mut *i_prot, &mut *o_prot); if let Err(e) = r { warn!("processor c...
handle_incoming_connection
identifier_name
OpenSSL_TripleDES.py
"""OpenSSL/M2Crypto 3DES implementation.""" from cryptomath import * from TripleDES import * if m2cryptoLoaded: def new(key, mode, IV): return OpenSSL_TripleDES(key, mode, IV) class OpenSSL_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mo...
return context def encrypt(self, plaintext): TripleDES.encrypt(self, plaintext) context = self._createContext(1) ciphertext = m2.cipher_update(context, plaintext) m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] ...
context = m2.cipher_ctx_new() cipherType = m2.des_ede3_cbc() m2.cipher_init(context, cipherType, self.key, self.IV, encrypt)
random_line_split
OpenSSL_TripleDES.py
"""OpenSSL/M2Crypto 3DES implementation.""" from cryptomath import * from TripleDES import * if m2cryptoLoaded:
m2.cipher_ctx_free(context) self.IV = ciphertext[-self.block_size:] return ciphertext def decrypt(self, ciphertext): TripleDES.decrypt(self, ciphertext) context = self._createContext(0) #I think M2Crypto has a bug - it fails to decrypt and...
def new(key, mode, IV): return OpenSSL_TripleDES(key, mode, IV) class OpenSSL_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "openssl") self.key = key self.IV = IV def _createContext(self, encrypt): ...
conditional_block
OpenSSL_TripleDES.py
"""OpenSSL/M2Crypto 3DES implementation.""" from cryptomath import * from TripleDES import * if m2cryptoLoaded: def new(key, mode, IV):
class OpenSSL_TripleDES(TripleDES): def __init__(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "openssl") self.key = key self.IV = IV def _createContext(self, encrypt): context = m2.cipher_ctx_new() cipherType = m2.des_e...
return OpenSSL_TripleDES(key, mode, IV)
identifier_body
OpenSSL_TripleDES.py
"""OpenSSL/M2Crypto 3DES implementation.""" from cryptomath import * from TripleDES import * if m2cryptoLoaded: def new(key, mode, IV): return OpenSSL_TripleDES(key, mode, IV) class OpenSSL_TripleDES(TripleDES): def
(self, key, mode, IV): TripleDES.__init__(self, key, mode, IV, "openssl") self.key = key self.IV = IV def _createContext(self, encrypt): context = m2.cipher_ctx_new() cipherType = m2.des_ede3_cbc() m2.cipher_init(context, cipherType, self....
__init__
identifier_name
forms.py
# coding: utf-8 # 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/. from django import forms from lib.l10n_utils.dotlang import _, _lazy from bedrock.mozorg.forms import...
def clean_superpriority(self): cleaned_data = super(FraudReportForm, self).clean() honeypot = cleaned_data.pop('superpriority', None) if honeypot: raise forms.ValidationError( _('Your submission could not be processed'))
cleaned_data = super(FraudReportForm, self).clean() attachment = cleaned_data.get("input_attachment") if attachment: if attachment._size > FRAUD_REPORT_FILE_SIZE_LIMIT: raise forms.ValidationError( _("Attachment must not exceed 5MB")) return atta...
identifier_body
forms.py
# coding: utf-8 # 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/. from django import forms from lib.l10n_utils.dotlang import _, _lazy from bedrock.mozorg.forms import...
raise forms.ValidationError( _('Your submission could not be processed'))
conditional_block
forms.py
# coding: utf-8 # 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/. from django import forms from lib.l10n_utils.dotlang import _, _lazy from bedrock.mozorg.forms import...
'invalid': _lazy(u'Please enter a valid email address'), }, widget=forms.TextInput( attrs={ 'size': 20, 'class': 'fill-width' } ) ) superpriority = forms.BooleanField(widget=HoneyPotWidget, required=False) def clean...
max_length=80, required=False, error_messages={
random_line_split
forms.py
# coding: utf-8 # 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/. from django import forms from lib.l10n_utils.dotlang import _, _lazy from bedrock.mozorg.forms import...
(self): cleaned_data = super(FraudReportForm, self).clean() honeypot = cleaned_data.pop('superpriority', None) if honeypot: raise forms.ValidationError( _('Your submission could not be processed'))
clean_superpriority
identifier_name
classList.js
/** * Tabby v7.4.6 * Simple, mobile-first toggle tabs., by Chris Ferdinandi. * http://github.com/cferdinandi/tabby * * Free to use under the MIT License. * http://gomakethings.com/mit/ */ /* * classList.js: Cross-browser full element.classList implementation. * 2014-01-31 * * By Eli Grey, http://eligrey.co...
classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [], i = 0, len = classes.length; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute("class", this.toString()); }; }, classListProto = ClassList[protoProp] = [], ...
random_line_split
english.py
'cat', 'catalog', 'catch', 'category', 'cattle', 'caught', 'cause', 'caution', 'cave', 'ceiling', 'celery', 'cement', 'census', 'century', 'cereal', 'certain', 'chair', 'chalk', 'champion', 'change', 'chaos', 'chapter', 'charge', 'chase', 'chat', 'cheap', 'check', 'cheese', 'chef', 'cherry', 'chest', 'chicken', 'chief'...
'casual',
random_line_split
edit.rs
#![allow(deprecated)] use gpgme; use std::io::prelude::*; use gpgme::{ edit::{self, EditInteractionStatus, Editor}, Error, Result, }; use self::common::passphrase_cb; #[macro_use] mod common; #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum TestEditorState { Start, Fingerprint, Expire, Val...
Ok(State::Quit) => state, Ok(State::Primary) | Err(_) => Ok(State::Quit), _ => Err(Error::GENERAL), } } else if (status.args() == Ok(edit::KEY_VALID)) && (state == Ok(State::Expire)) { Ok(State::Valid) } else if (status.args() == Ok...
Ok(State::Start) => Ok(State::Fingerprint), Ok(State::Fingerprint) => Ok(State::Expire), Ok(State::Valid) => Ok(State::Uid), Ok(State::Uid) => Ok(State::Primary),
random_line_split
edit.rs
#![allow(deprecated)] use gpgme; use std::io::prelude::*; use gpgme::{ edit::{self, EditInteractionStatus, Editor}, Error, Result, }; use self::common::passphrase_cb; #[macro_use] mod common; #[derive(Debug, Copy, Clone, Eq, PartialEq)] enum TestEditorState { Start, Fingerprint, Expire, Val...
( state: Result<Self::State>, status: EditInteractionStatus<'_>, need_response: bool, ) -> Result<Self::State> { use self::TestEditorState as State; println!("[-- Code: {:?}, {:?} --]", status.code, status.args()); if !need_response { return state; } if ...
next_state
identifier_name
create.py
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
return database_operations.Await(op, 'Creating database')
return op
conditional_block