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
graph.py
import os import json from subprocess import check_output, CalledProcessError #Constants _TREE_PATH="data/graph/" def renderGraph(query): """ Returns the path to a svg file that contains the graph render of the query. Creates the svg file itself if it does not already exist. "...
#Load bucketTable bucketTableFile=open(_TREE_PATH+str(qhash)+"/lookup.json",'r+') bucketTable = json.loads(bucketTableFile.read()) if query not in bucketTable.keys(): #File is not cache! Create PNG in bucket. filename=str(len(os.listdir(_TREE_PATH+str(qhash))))+".svg" fn=qu...
os.makedirs(_TREE_PATH+str(qhash)) #Create the lookup table for the bucket. bucketTableFile=open(_TREE_PATH+str(qhash)+"/lookup.json",'w') bucketTableFile.write("{}") bucketTableFile.close()
conditional_block
sl.js
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'liststyle', 'sl', { armenian: 'Armenian numbering', bulletedTitle: 'Bulleted List Properties', circle: 'Circle', decimal: 'Decimal (1, 2, 3, etc.)...
} );
type: 'Type', upperAlpha: 'Upper Alpha (A, B, C, D, E, etc.)', upperRoman: 'Upper Roman (I, II, III, IV, V, etc.)', validateStartNumber: 'List start number must be a whole number.'
random_line_split
lib.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(private_no_mangle_fns)] #![feature(proc_macro)] #![cfg_attr(feature = "strict", deny(warnings))] #![feature(global_allocator)] #![feature(concat_idents)] #[macro_use] extern crate lazy_static; extern crate base64 as base64_crate; extern crate libc; ...
() { cmds::initial_keys(); } include!(concat!(env!("OUT_DIR"), "/c_exports.rs")); #[cfg(test)] pub use functions::{lispsym, make_string, make_unibyte_string, Fcons, Fsignal};
rust_initial_keys
identifier_name
lib.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(private_no_mangle_fns)] #![feature(proc_macro)] #![cfg_attr(feature = "strict", deny(warnings))] #![feature(global_allocator)] #![feature(concat_idents)] #[macro_use] extern crate lazy_static; extern crate base64 as base64_crate; extern crate libc; ...
mod keyboard; mod keymap; mod lists; mod marker; mod math; mod minibuf; mod multibyte; mod numbers; mod obarray; mod objects; mod process; mod strings; mod symbols; mod threads; mod util; mod vectors; mod windows; #[cfg(all(not(test), target_os = "macos"))] use alloc_unexecmacosx::OsxUnexecAlloc; #[cfg(all(not(test),...
mod hashtable; mod indent; mod interactive;
random_line_split
lib.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] #![allow(private_no_mangle_fns)] #![feature(proc_macro)] #![cfg_attr(feature = "strict", deny(warnings))] #![feature(global_allocator)] #![feature(concat_idents)] #[macro_use] extern crate lazy_static; extern crate base64 as base64_crate; extern crate libc; ...
include!(concat!(env!("OUT_DIR"), "/c_exports.rs")); #[cfg(test)] pub use functions::{lispsym, make_string, make_unibyte_string, Fcons, Fsignal};
{ cmds::initial_keys(); }
identifier_body
problem2.rs
/// Represents a matrix in row-major order pub type Matrix = Vec<Vec<f32>>; /// Computes the product of the inputs `mat1` and `mat2`. pub fn
(mat1: &Matrix, mat2: &Matrix) -> Matrix { assert!(mat1.len() != 0 && mat2.len() != 0); assert!(mat1[0].len() != 0 && mat2[0].len() != 0); assert_eq!(mat1[0].len(), mat2.len()); println!("{:?}", mat1); println!("{:?}", mat2); let mut product = vec![vec![0.; mat2[0].len()]; mat1.len()]; for ...
mat_mult
identifier_name
problem2.rs
/// Represents a matrix in row-major order pub type Matrix = Vec<Vec<f32>>; /// Computes the product of the inputs `mat1` and `mat2`. pub fn mat_mult(mat1: &Matrix, mat2: &Matrix) -> Matrix { assert!(mat1.len() != 0 && mat2.len() != 0); assert!(mat1[0].len() != 0 && mat2[0].len() != 0); assert_eq!(mat1[0]....
}
product
random_line_split
problem2.rs
/// Represents a matrix in row-major order pub type Matrix = Vec<Vec<f32>>; /// Computes the product of the inputs `mat1` and `mat2`. pub fn mat_mult(mat1: &Matrix, mat2: &Matrix) -> Matrix
{ assert!(mat1.len() != 0 && mat2.len() != 0); assert!(mat1[0].len() != 0 && mat2[0].len() != 0); assert_eq!(mat1[0].len(), mat2.len()); println!("{:?}", mat1); println!("{:?}", mat2); let mut product = vec![vec![0.; mat2[0].len()]; mat1.len()]; for i in 0..mat1.len() { for j in 0.....
identifier_body
managefiles.py
Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A...
else: xbmcgui.Dialog().ok(addon_name, "Connection to VPN being attempted and has been aborted. Try again in a few seconds.") setAPICommand("Disconnect") # Generate the VPN provider files if action == "generate": # Only used during development to create loca...
if xbmcgui.Dialog().yesno(addon_name, "Resetting the VPN provider will disconnect and reset all VPN connections, and then remove any files that have been created. Continue?"): suspendConfigUpdate() # Disconnect so that live files are not being modified resetVPNConnections...
conditional_block
managefiles.py
Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A...
try: if xbmcvfs.exists(path+".key"): xbmcvfs.delete(path + ".key") if xbmcvfs.exists(path + ".txt"): xbmcvfs.delete(path + ".txt") ...
path = getUserDataPath(provider + "/" + all_user[index])
random_line_split
SSD1351.py
# Default to platform GPIO if not provided. self._gpio = gpio if self._gpio is None: self._gpio = GPIO.get_platform_gpio() # Setup reset pin. self._rst = rst self._gpio.setup(self._rst, GPIO.OUT) # Handle hardware SPI if spi is not None: self._log.debug('Using hardware SPI') self._spi = spi se...
_initialize
identifier_name
SSD1351.py
SSD1351_COMSCANDEC = 0xC8 SSD1351_SEGREMAP = 0xA0 SSD1351_CHARGEPUMP = 0x8D SSD1351_EXTERNALVCC = 0x1 SSD1351_SWITCHCAPVCC = 0x2 # Scrolling constants SSD1351_ACTIVATE_SCROLL = 0x2F SSD1351_DEACTIVATE_SCROLL = 0x2E SSD1351_SET_VERTICAL_SCROLL_AREA = 0xA3 SSD1351_RIGHT_HORIZONTAL_SCROLL = 0x26 SSD1351_LEFT_HORIZONTAL_...
control = 0x40 # Co = 0, DC = 0 self._i2c.write8(control, c) def begin(self, vccstate=SSD1351_SWITCHCAPVCC): """Initialize display.""" # Save vcc state. self._vccstate = vccstate # Reset and initialize display. self.reset() self._initialize() # Turn on the display. self.command(SSD1351_DISPLAY...
# SPI write. self._gpio.set_high(self._dc) self._spi.write([c]) else: # I2C write.
random_line_split
SSD1351.py
SSD1351_COMSCANDEC = 0xC8 SSD1351_SEGREMAP = 0xA0 SSD1351_CHARGEPUMP = 0x8D SSD1351_EXTERNALVCC = 0x1 SSD1351_SWITCHCAPVCC = 0x2 # Scrolling constants SSD1351_ACTIVATE_SCROLL = 0x2F SSD1351_DEACTIVATE_SCROLL = 0x2E SSD1351_SET_VERTICAL_SCROLL_AREA = 0xA3 SSD1351_RIGHT_HORIZONTAL_SCROLL = 0x26 SSD1351_LEFT_HORIZONTAL_...
def data(self, c): """Send byte of data to display.""" if self._spi is not None: # SPI write. self._gpio.set_high(self._dc) self._spi.write([c]) else: # I2C write. control = 0x40 # Co = 0, DC = 0 self._i2c.write8(control, c) def begin(self, vccstate=SSD1351_SWITCHCAPVCC): """Initialize ...
"""Send command byte to display.""" if self._spi is not None: # SPI write. self._gpio.set_low(self._dc) self._spi.write([c]) else: # I2C write. control = 0x00 # Co = 0, DC = 0 self._i2c.write8(control, c)
identifier_body
SSD1351.py
2F SSD1351_DEACTIVATE_SCROLL = 0x2E SSD1351_SET_VERTICAL_SCROLL_AREA = 0xA3 SSD1351_RIGHT_HORIZONTAL_SCROLL = 0x26 SSD1351_LEFT_HORIZONTAL_SCROLL = 0x27 SSD1351_VERTICAL_AND_RIGHT_HORIZONTAL_SCROLL = 0x29 SSD1351_VERTICAL_AND_LEFT_HORIZONTAL_SCROLL = 0x2A #? SSD1351_DELAYS_HWFILL (3) #? SSD1351_DELAYS_HWLINE ...
for x in range(self.width): # Set the bits for the column of pixels at the current position. bits = 0 # Don't use range here as it's a bit slow for bit in [0, 1, 2, 3, 4, 5, 6, 7]: bits = bits << 1 bits |= 0 if pix[(x, page*8+7-bit)] == 0 else 1 # Update buffer byte and increment to next b...
conditional_block
internetvideoarchive.py
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_parse_qs, compat_urlparse, ) from ..utils import ( determine_ext, int_or_none, xpath_text, ) class InternetVideoArchiveIE(InfoExtractor): _VALID_URL = r'https?://video\.internetvideoarchive...
return { 'id': video_id, 'title': title, 'formats': formats, 'thumbnail': thumbnail, 'description': description, }
configuration = self._download_xml(url, video_id) formats = [{ 'url': xpath_text(configuration, './file', 'file URL', fatal=True), }] thumbnail = xpath_text(configuration, './image', 'thumbnail') title = 'InternetVideoArchive video %s' % video_id ...
conditional_block
internetvideoarchive.py
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_parse_qs, compat_urlparse, ) from ..utils import ( determine_ext, int_or_none, xpath_text, ) class InternetVideoArchiveIE(InfoExtractor): _VALID_URL = r'https?://video\.internetvideoarchive...
(query): return 'http://video.internetvideoarchive.net/player/6/configuration.ashx?' + query @staticmethod def _build_xml_url(query): return 'http://video.internetvideoarchive.net/flash/players/flashconfiguration.aspx?' + query def _real_extract(self, url): query = compat_urlparse....
_build_json_url
identifier_name
internetvideoarchive.py
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_parse_qs, compat_urlparse, ) from ..utils import ( determine_ext, int_or_none, xpath_text, ) class InternetVideoArchiveIE(InfoExtractor): _VALID_URL = r'https?://video\.internetvideoarchive...
def _real_extract(self, url): query = compat_urlparse.urlparse(url).query query_dic = compat_parse_qs(query) video_id = query_dic['publishedid'][0] if '/player/' in url: configuration = self._download_json(url, video_id) # There are multiple videos in the ...
return 'http://video.internetvideoarchive.net/flash/players/flashconfiguration.aspx?' + query
identifier_body
internetvideoarchive.py
from __future__ import unicode_literals from .common import InfoExtractor from ..compat import ( compat_parse_qs, compat_urlparse, ) from ..utils import ( determine_ext, int_or_none, xpath_text, ) class InternetVideoArchiveIE(InfoExtractor): _VALID_URL = r'https?://video\.internetvideoarchive...
file_url = source['file'] if determine_ext(file_url) == 'm3u8': m3u8_formats = self._extract_m3u8_formats( file_url, video_id, 'mp4', 'm3u8_native', m3u8_id='hls', fatal=False) if m3u8_formats: format...
video_info = configuration['playlist'][0] title = video_info['title'] formats = [] for source in video_info['sources']:
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-08-19 19:46 from __future__ import unicode_literals from django.db import migrations, models import phonenumber_field.modelfields class Migration(migrations.Migration):
}, ), ]
initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CallbackRequest', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True,...
identifier_body
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-08-19 19:46 from __future__ import unicode_literals from django.db import migrations, models import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.Cr...
('extra_info', models.CharField(blank=True, max_length=1024, null=True, verbose_name='дополнительная информация')), ('date', models.DateTimeField(auto_now=True, verbose_name='время подачи')), ('promotion_context', models.CharField(blank=True, max_length=127, null=True, ve...
fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(blank=True, max_length=127, null=True, verbose_name='имя')), ('phone_number', phonenumber_field.modelfields.PhoneNumberField(m...
random_line_split
0001_initial.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-08-19 19:46 from __future__ import unicode_literals from django.db import migrations, models import phonenumber_field.modelfields class
(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='CallbackRequest', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name',...
Migration
identifier_name
reflection_capabilities.ts
'; import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; import {GetterFn, MethodFn, SetterFn} from './types'; /** * Attention: This regex has to hold even if the code is minified! */ export const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/; export cla...
} private _ownAnnotations(typeOrFunc: Type<any>, parentCtor: any): any[]|null { // Prefer the direct API. if ((<any>typeOrFunc).annotations && (<any>typeOrFunc).annotations !== parentCtor.annotations) { let annotations = (<any>typeOrFunc).annotations; if (typeof annotations === 'function' && an...
random_line_split
reflection_capabilities.ts
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; import {GetterFn, MethodFn, SetterFn} from './types'; /** * Attention: This regex has to hold even if the code is minified! */ export const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/; export class R...
decorators.push(...ownPropMetadata[propName]); propMetadata[propName] = decorators; }); } return propMetadata; } hasLifecycleHook(type: any, lcProperty: string): boolean { return type instanceof Type && lcProperty in type.prototype; } getter(name: string): GetterFn { return ...
{ decorators.push(...propMetadata[propName]); }
conditional_block
reflection_capabilities.ts
'; import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; import {GetterFn, MethodFn, SetterFn} from './types'; /** * Attention: This regex has to hold even if the code is minified! */ export const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/; export cla...
(typeOrFunc: any): {[key: string]: any[]} { if (!isType(typeOrFunc)) { return {}; } const parentCtor = getParentCtor(typeOrFunc); const propMetadata: {[key: string]: any[]} = {}; if (parentCtor !== Object) { const parentPropMetadata = this.propMetadata(parentCtor); Object.keys(pare...
propMetadata
identifier_name
reflection_capabilities.ts
import {PlatformReflectionCapabilities} from './platform_reflection_capabilities'; import {GetterFn, MethodFn, SetterFn} from './types'; /** * Attention: This regex has to hold even if the code is minified! */ export const DELEGATE_CTOR = /^function\s+\S+\(\)\s*{[\s\S]+\.apply\(this,\s*arguments\)/; export class R...
if (paramAnnotations && paramAnnotations[i] != null) { result[i] = result[i].concat(paramAnnotations[i]); } } return result; } private _ownParameters(type: Type<any>, parentCtor: any): any[][]|null { // If we have no decorators, we only have function.length as metadata. // In t...
{ let result: any[][]; if (typeof paramTypes === 'undefined') { result = new Array(paramAnnotations.length); } else { result = new Array(paramTypes.length); } for (let i = 0; i < result.length; i++) { // TS outputs Object for parameters without types, while Traceur omits //...
identifier_body
index.js
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, } from 'react-native'; import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view'; class wsapp extends Component {
() { return <ScrollableTabView style={{marginTop: 20, }} initialPage={2} scrollWithoutAnimation={false} renderTabBar={() => <ScrollableTabBar />} ref={(tabView) => { this.tabView = tabView; }}> <Text tabLabel='Tab #1'>My</Text> <Text tabLabel='Tab #2'>favori...
render
identifier_name
index.js
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableOpacity, } from 'react-native'; import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view';
return <ScrollableTabView style={{marginTop: 20, }} initialPage={2} scrollWithoutAnimation={false} renderTabBar={() => <ScrollableTabBar />} ref={(tabView) => { this.tabView = tabView; }}> <Text tabLabel='Tab #1'>My</Text> <Text tabLabel='Tab #2'>favorite</T...
class wsapp extends Component { render() {
random_line_split
tendr.js
var _ = require('underscore'), nconf = require('nconf'), fs = require('fs'), path = require('path'), utils = require('./lib/utility'); // Default nconf nconf.use('memory'); _.each({ debug: false }, function(v, k) { nconf.set(k, v); }); // New stuff! var Manager = require('./lib/manager'), main = new Manager()...
}); // Default storage engine main.register_storage("memory"); module.exports = function(options) { // Set up app-wide options if (_.isObject(options)) _.each(options, function(v, k) { nconf.set(k, v); }); // Return manager object return main; }
var res = require(path.join(load_folder, file))(); if (_.isArray(res)) main.register_load.apply(main, res) }
random_line_split
lib.rs
// Copyright 2015 Brendan Zabarauskas and the gl-rs developers // // 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 b...
let _: raw::c_uint = gl::CreateProgram(); gl::CompileShader(5); gl::GetActiveUniformBlockiv( 0, 0, gl::UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER, std::ptr::null_mut(), ); } } #[test] fn test_fallback_works() { fn loader(name: &st...
pub fn compile_test_symbols_exist() { unsafe { gl::Clear(gl::COLOR_BUFFER_BIT);
random_line_split
lib.rs
// Copyright 2015 Brendan Zabarauskas and the gl-rs developers // // 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 b...
{ fn loader(name: &str) -> *const raw::c_void { match name { "glGenFramebuffers" => 0 as *const raw::c_void, "glGenFramebuffersEXT" => 42 as *const raw::c_void, name => panic!("test tried to load {} unexpectedly!", name), } }; gl::GenFramebuffers::load_wi...
identifier_body
lib.rs
// Copyright 2015 Brendan Zabarauskas and the gl-rs developers // // 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 b...
(name: &str) -> *const raw::c_void { match name { "glGenFramebuffers" => 0 as *const raw::c_void, "glGenFramebuffersEXT" => 42 as *const raw::c_void, name => panic!("test tried to load {} unexpectedly!", name), } }; gl::GenFramebuffers::load_with(loader); ...
loader
identifier_name
scm.py
import os import re import subprocess from six.moves.urllib.parse import urlparse, quote_plus from subprocess import CalledProcessError, PIPE, STDOUT from conans.client.tools.env import no_op, environment_append from conans.client.tools.files import chdir from conans.errors import ConanException from conans.util.file...
(self, url, branch=None): url = self.get_url_with_credentials(url) if os.path.exists(url): url = url.replace("\\", "/") # Windows local directory if os.path.exists(self.folder) and os.listdir(self.folder): if not branch: raise ConanException("The destinat...
clone
identifier_name
scm.py
import os import re import subprocess from six.moves.urllib.parse import urlparse, quote_plus from subprocess import CalledProcessError, PIPE, STDOUT from conans.client.tools.env import no_op, environment_append from conans.client.tools.files import chdir from conans.errors import ConanException from conans.util.file...
output = self.run("init") output += self._configure_ssl_verify() output += self.run('remote add origin "%s"' % url) output += self.run("fetch ") output += self.run("checkout -t origin/%s" % branch) else: branch_cmd = "--branch %s" % branch...
raise ConanException("The destination folder '%s' is not empty, " "specify a branch to checkout (not a tag or commit) " "or specify a 'subfolder' " "attribute in the 'scm'" % self.folder)
conditional_block
scm.py
import os import re import subprocess from six.moves.urllib.parse import urlparse, quote_plus from subprocess import CalledProcessError, PIPE, STDOUT from conans.client.tools.env import no_op, environment_append from conans.client.tools.files import chdir from conans.errors import ConanException from conans.util.file...
def get_repo_root(self): return self.run("rev-parse --show-toplevel") def get_url_with_credentials(self, url): if not self._username or not self._password: return url if urlparse(url).password: return url user_enc = quote_plus(self._username) p...
command = "git %s" % command with chdir(self.folder) if self.folder else no_op(): with environment_append({"LC_ALL": "en_US.UTF-8"}) if self._force_eng else no_op(): if not self._runner: return subprocess.check_output(command, shell=True).decode().strip() ...
identifier_body
scm.py
import os import re import subprocess from six.moves.urllib.parse import urlparse, quote_plus from subprocess import CalledProcessError, PIPE, STDOUT from conans.client.tools.env import no_op, environment_append from conans.client.tools.files import chdir from conans.errors import ConanException from conans.util.file...
output = self.run("init") output += self._configure_ssl_verify() output += self.run('remote add origin "%s"' % url) output += self.run("fetch ") output += self.run("checkout -t origin/%s" % branch) else: branch_cmd = "--branch %s" % branch ...
if not branch: raise ConanException("The destination folder '%s' is not empty, " "specify a branch to checkout (not a tag or commit) " "or specify a 'subfolder' " "attribute in the ...
random_line_split
cb_language.js
var CB_NavTextPrv='zurück', // text of previous image CB_NavTextNxt='weiter', // text of next image CB_NavTextFull='volle grösse', // text of original size (only at pictures) CB_NavTextOpen='in neuem Browser-Fenster öffnen', // text of open in a new browser window CB_NavTextDL='herunterladen', // t...
// // ClearBox Language File (JavaScript) //
random_line_split
int_macros.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...
// calling the `Bounded::max_value` function. #[stable(feature = "rust1", since = "1.0.0")] pub const MAX: $T = !MIN; ) }
#[stable(feature = "rust1", since = "1.0.0")] pub const MIN: $T = (-1 as $T) << (BITS - 1); // FIXME(#9837): Compute MIN like this so the high bits that shouldn't exist are 0. // FIXME(#11621): Should be deprecated once CTFE is implemented in favour of
random_line_split
auto-launch.d.ts
// Type definitions for auto-launch 0.1.18 // Project: https://github.com/Teamwork/node-auto-launch // Definitions by: rhysd <https://github.com/rhysd> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface AutoLaunchOption { /** * Application name. */ name: string; /** * Hidden on launch or...
{ constructor(opts: AutoLaunchOption); /** * Enables to launch at start up */ enable(callback?: (err: Error) => void): void; /** * Disables to launch at start up */ disable(callback?: (err: Error) => void): void; /** * Returns if auto start up is enabled */ isEnabled(callback: (enabled: boolean) => ...
AutoLaunch
identifier_name
auto-launch.d.ts
// Type definitions for auto-launch 0.1.18 // Project: https://github.com/Teamwork/node-auto-launch // Definitions by: rhysd <https://github.com/rhysd> // Definitions: https://github.com/borisyankov/DefinitelyTyped interface AutoLaunchOption { /** * Application name. */ name: string; /** * Hidden on launch or...
export = al; }
random_line_split
safe.rs
// Copyright 2012-2015 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...
//! The `DepGraphSafe` trait use hir::BodyId; use hir::def_id::DefId; use syntax::ast::NodeId; use ty::TyCtxt; /// The `DepGraphSafe` trait is used to specify what kinds of values /// are safe to "leak" into a task. The idea is that this should be /// only be implemented for things like the tcx as well as various id ...
// option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
safe.rs
// Copyright 2012-2015 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...
<T>(pub T); impl<T> DepGraphSafe for AssertDepGraphSafe<T> { }
AssertDepGraphSafe
identifier_name
start.ts
'use strict'; import * as electron from "electron"; const app = electron.app; const BrowserWindow = electron.BrowserWindow; var electronConnect = require('electron-connect'); app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user...
}); app.on('ready', function () { var mainWindow = new BrowserWindow({ width: 700, height: 500, resizable: false, center: true, title: app.getName() }); var client = electronConnect.client.create(mainWindow); mainWindow.loadURL('file://' + __dirname + '/pag...
{ app.quit(); }
conditional_block
start.ts
'use strict'; import * as electron from "electron"; const app = electron.app; const BrowserWindow = electron.BrowserWindow; var electronConnect = require('electron-connect'); app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user...
});
random_line_split
command.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 { analytics, logging, strings, tags } from '@angular-devkit/core'; import { colors } from '../utilities/color'...
const argDisplay = args && args.length > 0 ? ' ' + args.map((a) => `<${a.name}>`).join(' ') : ''; const optionsDisplay = opts && opts.length > 0 ? ` [options]` : ``; this.logger.info(`usage: ng ${name}${argDisplay}${optionsDisplay}`); this.logger.info(''); } protected async printHelpOptions...
this.logger.info(this.description.description); const name = this.description.name; const args = this.description.options.filter((x) => x.positional !== undefined); const opts = this.description.options.filter((x) => x.positional === undefined);
random_line_split
command.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 { analytics, logging, strings, tags } from '@angular-devkit/core'; import { colors } from '../utilities/color'...
(options: Option[] = this.description.options) { const args = options.filter((opt) => opt.positional !== undefined); const opts = options.filter((opt) => opt.positional === undefined); const formatDescription = (description: string) => ` ${description.replace(/\n/g, '\n ')}`; if (args.leng...
printHelpOptions
identifier_name
command.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 { analytics, logging, strings, tags } from '@angular-devkit/core'; import { colors } from '../utilities/color'...
}); } if (options.length > 0) { if (args.length > 0) { this.logger.info(''); } this.logger.info(`options:`); opts .filter((o) => !o.hidden) .sort((a, b) => a.name.localeCompare(b.name)) .forEach((o) => { const aliases = o.alias...
{ this.logger.info(formatDescription(o.description)); }
conditional_block
command.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 { analytics, logging, strings, tags } from '@angular-devkit/core'; import { colors } from '../utilities/color'...
async initialize(options: T & Arguments): Promise<number | void> {} async printHelp(): Promise<number> { await this.printHelpUsage(); await this.printHelpOptions(); return 0; } async printJsonHelp(): Promise<number> { const replacer = (key: string, value: string) => key === 'name' ? s...
{ this.workspace = context.workspace; this.analytics = context.analytics || new analytics.NoopAnalytics(); }
identifier_body
requirement_vis.tsx
/* * Wazuh app - React component building the welcome screen of an agent. * version, OS, registration date, last keep alive. * * Copyright (C) 2015-2021 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * t...
{ const [requirement, setRequirement] = useState('pci_dss'); return ( <EuiFlexItem> <EuiPanel paddingSize="s"> <EuiFlexItem> <RequirementsHead requirement={requirement} setRequirement={setRequirement} /> <EuiSpacer size="m" /> <RequirementsBody requirement={requiremen...
identifier_body
requirement_vis.tsx
/* * Wazuh app - React component building the welcome screen of an agent. * version, OS, registration date, last keep alive. * * Copyright (C) 2015-2021 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * t...
import { RequirementsHead, RequirementsBody } from './components'; export function RequirementVis(props) { const [requirement, setRequirement] = useState('pci_dss'); return ( <EuiFlexItem> <EuiPanel paddingSize="s"> <EuiFlexItem> <RequirementsHead requirement={requirement} setRequiremen...
EuiSpacer, } from '@elastic/eui';
random_line_split
requirement_vis.tsx
/* * Wazuh app - React component building the welcome screen of an agent. * version, OS, registration date, last keep alive. * * Copyright (C) 2015-2021 Wazuh, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * t...
(props) { const [requirement, setRequirement] = useState('pci_dss'); return ( <EuiFlexItem> <EuiPanel paddingSize="s"> <EuiFlexItem> <RequirementsHead requirement={requirement} setRequirement={setRequirement} /> <EuiSpacer size="m" /> <RequirementsBody requirement={re...
RequirementVis
identifier_name
3c7fd5b4e2c2_add_two_new_columns_.py
"""Add two new columns for Person. Revision ID: 3c7fd5b4e2c2 Revises: 24282792d72a Create Date: 2013-06-26 14:46:28.361709 """ # revision identifiers, used by Alembic. revision = "3c7fd5b4e2c2" down_revision = "16943d9088cf" import tahrir_api from alembic import op import sqlalchemy as sa import datetime def upgr...
session.commit() def downgrade(): op.drop_column("persons", "opt_out") op.drop_column("persons", "created_on")
person.created_on = datetime.datetime.now() person.opt_out = False
conditional_block
3c7fd5b4e2c2_add_two_new_columns_.py
"""Add two new columns for Person. Revision ID: 3c7fd5b4e2c2 Revises: 24282792d72a Create Date: 2013-06-26 14:46:28.361709 """ # revision identifiers, used by Alembic. revision = "3c7fd5b4e2c2" down_revision = "16943d9088cf" import tahrir_api from alembic import op import sqlalchemy as sa import datetime def upgr...
op.drop_column("persons", "opt_out") op.drop_column("persons", "created_on")
identifier_body
3c7fd5b4e2c2_add_two_new_columns_.py
"""Add two new columns for Person. Revision ID: 3c7fd5b4e2c2 Revises: 24282792d72a Create Date: 2013-06-26 14:46:28.361709 """ # revision identifiers, used by Alembic. revision = "3c7fd5b4e2c2" down_revision = "16943d9088cf" import tahrir_api from alembic import op import sqlalchemy as sa import datetime def upgr...
persons = session.query(tahrir_api.model.Person).all() for person in persons: # Set our defaults person.created_on = datetime.datetime.now() person.opt_out = False session.commit() def downgrade(): op.drop_column("persons", "opt_out") op.drop_column("persons", "created_on")
# We have to do this manually because I can't figure out how to make # alembic apply defaults to sqlite. engine = op.get_bind().engine session_maker = sa.orm.sessionmaker(bind=engine) session = sa.orm.scoped_session(session_maker)
random_line_split
3c7fd5b4e2c2_add_two_new_columns_.py
"""Add two new columns for Person. Revision ID: 3c7fd5b4e2c2 Revises: 24282792d72a Create Date: 2013-06-26 14:46:28.361709 """ # revision identifiers, used by Alembic. revision = "3c7fd5b4e2c2" down_revision = "16943d9088cf" import tahrir_api from alembic import op import sqlalchemy as sa import datetime def upgr...
(): op.drop_column("persons", "opt_out") op.drop_column("persons", "created_on")
downgrade
identifier_name
setup.py
from ber_kit import __version__ setup(name='ber-kit', version= __version__, description='Toolkit to manage rolling upgrades on a Marathon cluster', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', ...
import multiprocessing from setuptools import setup, find_packages
random_line_split
compressor.rs
/* * Copyright 2021 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 agreed to i...
use snap::read::FrameDecoder; use snap::write::FrameEncoder; /// A trait that provides a compression and decompression strategy for this filter. /// Conversion takes place on a mutable Vec, to ensure the most performant compression or /// decompression operation can occur. pub(crate) trait Compressor { /// Compres...
* limitations under the License. */ use std::io;
random_line_split
compressor.rs
/* * Copyright 2021 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 agreed to i...
(&self, contents: &mut Vec<u8>) -> io::Result<()> { let input = std::mem::take(contents); let mut rdr = FrameDecoder::new(input.as_slice()); io::copy(&mut rdr, contents)?; Ok(()) } }
decode
identifier_name
insert_input.py
# -*- coding: utf8 -*- # Author: Adrien Bibal # Date: 2014 # Insert the student answer in the correction framework file. import sys
for line in oz_file: # "@@q1@@" is the arbitrary marker used to say "insert the student answer here". if "@@q1@@" in line : for input_line in input_file : if '\0' in input_line : input_line = input_line.strip('\0') new_file.write(input_line) # Copy each line from...
import codecs input_file = sys.stdin # input = file containing the student answer. oz_file = codecs.open("/task/task.oz", "r", "utf8") # Open the "correction framework file". new_file = codecs.open("new_file.oz", "w","utf8") # Open the final file.
random_line_split
insert_input.py
# -*- coding: utf8 -*- # Author: Adrien Bibal # Date: 2014 # Insert the student answer in the correction framework file. import sys import codecs input_file = sys.stdin # input = file containing the student answer. oz_file = codecs.open("/task/task.oz", "r", "utf8") # Open the "correction framework file". new_file =...
else : new_file.write(line) # Copy each line from the "correction framework file" to the final file. oz_file.close() new_file.close()
for input_line in input_file : if '\0' in input_line : input_line = input_line.strip('\0') new_file.write(input_line) # Copy each line from the student answer to the final file.
conditional_block
operation.rs
#[repr(u32)] #[derive(Debug, Clone, Copy)] pub enum
{ /** * The default storage mode. This constant was added in version 2.6.2 for * the sake of maintaining a default storage mode, eliminating the need * for simple storage operations to explicitly define operation. * Behaviorally it is identical to Set * in that it will make the server unco...
Operation
identifier_name
operation.rs
#[repr(u32)] #[derive(Debug, Clone, Copy)] pub enum Operation { /** * The default storage mode. This constant was added in version 2.6.2 for * the sake of maintaining a default storage mode, eliminating the need * for simple storage operations to explicitly define operation. * Behaviorally it is...
/** Unconditionally store the item in the cluster */ Set = 3, /** * Rather than setting the contents of the entire document, take the value * specified in value and _append_ it to the existing bytes in * the value. */ Append = 4, /** * Like Append, but prepends the new va...
* Will cause the operation to fail _unless_ the key already exists in the * cluster. */ Replace = 2,
random_line_split
windowToggle.d.ts
import { Observable } from '../Observable'; import { OperatorFunction } from '../types'; /** * Branch out the source Observable values as a nested Observable starting from * an emission from `openings` and ending when the output of `closingSelector` * emits. * * <span class="informal">It's like {@link bufferToggle...
* const result = clicks.pipe( * windowToggle(openings, i => i % 2 ? interval(500) : empty()), * mergeAll(), * ); * result.subscribe(x => console.log(x)); * ``` * * @see {@link window} * @see {@link windowCount} * @see {@link windowTime} * @see {@link windowWhen} * @see {@link bufferToggle} * * @param ...
* const clicks = fromEvent(document, 'click'); * const openings = interval(1000);
random_line_split
mod.rs
use self::api_request_processor::ApiReply; use crate::commands::CommandHelpers; use crate::entity::EntityRef; use crate::entity::Realm; use crate::player_output::PlayerOutput; use crate::sessions::SessionOutput; mod api_request_processor; mod entity_create_command; mod entity_delete_command; mod entity_list_command; m...
let reply = serde_json::to_value(reply).unwrap(); let mut output: Vec<PlayerOutput> = Vec::new(); push_session_output!(output, player_ref, SessionOutput::Json(reply)); output }) }
Ok(reply) => reply, Err(error) => error, }, _ => ApiReply::new_error("", 403, "Forbidden"), };
random_line_split
mod.rs
use self::api_request_processor::ApiReply; use crate::commands::CommandHelpers; use crate::entity::EntityRef; use crate::entity::Realm; use crate::player_output::PlayerOutput; use crate::sessions::SessionOutput; mod api_request_processor; mod entity_create_command; mod entity_delete_command; mod entity_list_command; m...
<F>( f: F, ) -> Box<dyn Fn(&mut Realm, EntityRef, CommandHelpers) -> Vec<PlayerOutput>> where F: Fn(&mut Realm, CommandHelpers) -> Result<ApiReply, ApiReply> + 'static, { Box::new(move |realm, player_ref, helpers| { let reply = match realm.player(player_ref) { Some(player) if player.is_a...
wrap_api_request
identifier_name
mod.rs
use self::api_request_processor::ApiReply; use crate::commands::CommandHelpers; use crate::entity::EntityRef; use crate::entity::Realm; use crate::player_output::PlayerOutput; use crate::sessions::SessionOutput; mod api_request_processor; mod entity_create_command; mod entity_delete_command; mod entity_list_command; m...
{ Box::new(move |realm, player_ref, helpers| { let reply = match realm.player(player_ref) { Some(player) if player.is_admin() => match f(realm, helpers) { Ok(reply) => reply, Err(error) => error, }, _ => ApiReply::new_error("", 403, "Forbid...
identifier_body
main.ts
/// <reference path="../../../../angular2/typings/node/node.d.ts" /> var {Cc, Ci, Cu} = require('chrome'); var os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService); var ParserUtil = require('./parser_util'); class Profiler { private _profiler; private _markerEvents: any[]; private _profi...
addStartEvent(name: string, timeStarted: number) { this._markerEvents.push({ph: 'b', ts: timeStarted - this._profilerStartTime, name: name}); } addEndEvent(name: string, timeEnded: number) { this._markerEvents.push({ph: 'e', ts: timeEnded - this._profilerStartTime, name: name}); } } function forceGC...
{ this._markerEvents.forEach(function(markerEvent) { perfEvents.push(markerEvent); }); return perfEvents; }
identifier_body
main.ts
/// <reference path="../../../../angular2/typings/node/node.d.ts" /> var {Cc, Ci, Cu} = require('chrome'); var os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
class Profiler { private _profiler; private _markerEvents: any[]; private _profilerStartTime: number; constructor() { this._profiler = Cc['@mozilla.org/tools/profiler;1'].getService(Ci.nsIProfiler); } start(entries, interval, features, timeStarted) { this._profiler.StartProfiler(entries, interval, feat...
var ParserUtil = require('./parser_util');
random_line_split
main.ts
/// <reference path="../../../../angular2/typings/node/node.d.ts" /> var {Cc, Ci, Cu} = require('chrome'); var os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService); var ParserUtil = require('./parser_util'); class
{ private _profiler; private _markerEvents: any[]; private _profilerStartTime: number; constructor() { this._profiler = Cc['@mozilla.org/tools/profiler;1'].getService(Ci.nsIProfiler); } start(entries, interval, features, timeStarted) { this._profiler.StartProfiler(entries, interval, features, features....
Profiler
identifier_name
middleware.py
from django.conf import settings from csp.utils import build_policy class CSPMiddleware(object): """ Implements the X-Content-Security-Policy response header, which conforming user-agents can use to restrict the permitted sources of various content. See https://wiki.mozilla.org/Security/CSP/Spec...
header = 'X-Content-Security-Policy' if getattr(settings, 'CSP_REPORT_ONLY', False): header = 'X-Content-Security-Policy-Report-Only' if header in response: # Don't overwrite existing headers. return response if getattr(settings, 'CSP_POLICY_URI', F...
# Check for ignored path prefix. for prefix in getattr(settings, 'CSP_EXCLUDE_URL_PREFIXES', []): if request.path_info.startswith(prefix): return response
random_line_split
middleware.py
from django.conf import settings from csp.utils import build_policy class CSPMiddleware(object): """ Implements the X-Content-Security-Policy response header, which conforming user-agents can use to restrict the permitted sources of various content. See https://wiki.mozilla.org/Security/CSP/Spec...
response[header] = policy return response
if getattr(response, '_csp_exempt', False): return response # Check for ignored path prefix. for prefix in getattr(settings, 'CSP_EXCLUDE_URL_PREFIXES', []): if request.path_info.startswith(prefix): return response header = 'X-Content-Security-Policy' ...
identifier_body
middleware.py
from django.conf import settings from csp.utils import build_policy class CSPMiddleware(object): """ Implements the X-Content-Security-Policy response header, which conforming user-agents can use to restrict the permitted sources of various content. See https://wiki.mozilla.org/Security/CSP/Spec...
(self, request, response): if getattr(response, '_csp_exempt', False): return response # Check for ignored path prefix. for prefix in getattr(settings, 'CSP_EXCLUDE_URL_PREFIXES', []): if request.path_info.startswith(prefix): return response head...
process_response
identifier_name
middleware.py
from django.conf import settings from csp.utils import build_policy class CSPMiddleware(object): """ Implements the X-Content-Security-Policy response header, which conforming user-agents can use to restrict the permitted sources of various content. See https://wiki.mozilla.org/Security/CSP/Spec...
response[header] = policy return response
policy = build_policy()
conditional_block
formatDate.test.ts
import { formatDistance, formatToLocaleString, defaultEnvironment, Environment } from './formatDate' import { subDays } from 'date-fns' import { ja, enUS } from 'date-fns/locale' // memo(otofune): This requires that process.env.TZ equals to 'UTC'. (;;) const jaEnvironment: Environment = { getLocale: () => ja } const ...
}) it('navigaror.language must be en', () => { expect(navigator.language).toBe('en') }) it('getLocale must return enUS locale', () => { expect(defaultEnvironment.getLocale()).toBe(enUS) }) }) describe('with "de-DE" locale (unsupported)', () => { beforeEach(() ...
languageSpy.mockReturnValue('en')
random_line_split
lock_button.rs
// This file is part of rgtk. // // rgtk 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, or // (at your option) any later version. // // rgtk is distributed in the hop...
pub fn get_permission(&self) -> Option<Permission> { let tmp_pointer = unsafe { ffi::gtk_lock_button_get_permission(GTK_LOCKBUTTON(self.pointer)) }; if tmp_pointer.is_null() { None } else { Some(GlibContainer::wrap(tmp_pointer)) } } pub fn set_permis...
let tmp_pointer = unsafe { ffi::gtk_lock_button_new(permission.unwrap()) }; check_pointer!(tmp_pointer, LockButton) }
identifier_body
lock_button.rs
// This file is part of rgtk. // // rgtk 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, or // (at your option) any later version. // // rgtk is distributed in the hop...
} pub fn set_permission(&self, permission: &Permission) { unsafe { ffi::gtk_lock_button_set_permission(GTK_LOCKBUTTON(self.pointer), permission.unwrap()) } } } impl_drop!(LockButton); impl_TraitWidget!(LockButton); impl gtk::ContainerTrait for LockButton {} impl gtk::ButtonTrait for LockButton {} ...
Some(GlibContainer::wrap(tmp_pointer)) }
conditional_block
lock_button.rs
// This file is part of rgtk. // // rgtk 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, or // (at your option) any later version. // // rgtk is distributed in the hop...
self) -> Option<Permission> { let tmp_pointer = unsafe { ffi::gtk_lock_button_get_permission(GTK_LOCKBUTTON(self.pointer)) }; if tmp_pointer.is_null() { None } else { Some(GlibContainer::wrap(tmp_pointer)) } } pub fn set_permission(&self, permission: &Pe...
t_permission(&
identifier_name
lock_button.rs
// This file is part of rgtk. // // rgtk 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, or // (at your option) any later version. // // rgtk is distributed in the hop...
//! A container for arranging buttons use gtk::cast::GTK_LOCKBUTTON; use gtk::{self, ffi}; use glib::Permission; use glib::GlibContainer; /// GtkLockButton — A widget to unlock or lock privileged operations struct_Widget!(LockButton); impl LockButton { pub fn new(permission: &Permission) -> Option<LockButton> { ...
// You should have received a copy of the GNU Lesser General Public License // along with rgtk. If not, see <http://www.gnu.org/licenses/>.
random_line_split
create-multimethod.ts
import {AsyncMultimethod, Decorators, Methods, Multimethod} from '../interface/multimethod'; import {Options} from '../interface/options'; import {analyse} from './analysis'; import {codegen} from './codegen'; // TODO: ... export function createMultimethod<P extends unknown[]>(options?: Options<P>): Multimethod<P>;...
let superIndex = additionVal.indexOf('super'); let pre = additionVal.slice(0, superIndex) as Function[]; let post = additionVal.slice(superIndex + 1) as Function[]; result[k] = pre.concat(existingVal, post); } return result; } // // TODO: temp testing... // declare co...
{ throw new Error(`Override must be an array with exactly one element containing the value 'super'`); }
conditional_block
create-multimethod.ts
import {AsyncMultimethod, Decorators, Methods, Multimethod} from '../interface/multimethod'; import {Options} from '../interface/options'; import {analyse} from './analysis'; import {codegen} from './codegen'; // TODO: ... export function createMultimethod<P extends unknown[]>(options?: Options<P>): Multimethod<P>;...
(options: Options<unknown[], any>) { let mm = codegen(analyse(options, {}, {})); let result = addMethods(mm, {}, {}); return result; function addMethods<T>(mm: T, existingMethods: Methods, existingDecorators: Decorators) { let extend = (methods: Methods<unknown[], unknown, 'super'>) => { ...
createMultimethod
identifier_name
create-multimethod.ts
import {AsyncMultimethod, Decorators, Methods, Multimethod} from '../interface/multimethod'; import {Options} from '../interface/options'; import {analyse} from './analysis'; import {codegen} from './codegen'; // TODO: ... export function createMultimethod<P extends unknown[]>(options?: Options<P>): Multimethod<P>;...
for (let k of keysInBoth) { let existingVal = existing[k]; let additionVal = additional[k]; if (!Array.isArray(additionVal) || additionVal.filter(m => m === 'super').length !== 1) { throw new Error(`Override must be an array with exactly one element containing the value 'super'`...
{ let existingKeys = Object.keys(existing); let additionalKeys = Object.keys(additional); let keysInBoth = existingKeys.filter(k => additionalKeys.indexOf(k) !== -1); let existingOnlyKeys = existingKeys.filter(k => keysInBoth.indexOf(k) === -1); let additionalOnlyKeys = additionalKeys.filter(k => ke...
identifier_body
create-multimethod.ts
import {AsyncMultimethod, Decorators, Methods, Multimethod} from '../interface/multimethod'; import {Options} from '../interface/options'; import {analyse} from './analysis'; import {codegen} from './codegen'; // TODO: ... export function createMultimethod<P extends unknown[]>(options?: Options<P>): Multimethod<P>;...
function addMethods<T>(mm: T, existingMethods: Methods, existingDecorators: Decorators) { let extend = (methods: Methods<unknown[], unknown, 'super'>) => { let combinedMethods = combine(existingMethods, methods); let mm2 = codegen(analyse(options, combinedMethods, existingDecorators...
let mm = codegen(analyse(options, {}, {})); let result = addMethods(mm, {}, {}); return result;
random_line_split
swagger-restify-mw-tests.ts
import * as SwaggerRestify from "swagger-restify-mw"; import * as restify from "restify"; const app = restify.createServer(); const config = { appRoot: __dirname // required config } as SwaggerRestify.Config; SwaggerRestify.create(config, (err, swaggerRestify) => { if (err)
swaggerRestify.register(app); const port = process.env.PORT || 10010; app.listen(port); }); const swaggerSecurityHandlerCb = (err: Error) => { // do nothing }; const configComplex: SwaggerRestify.Config = { appRoot: __dirname, configDir: "some/directory", controllersDirs: ["some/directory"], ...
{ throw err; }
conditional_block
swagger-restify-mw-tests.ts
import * as SwaggerRestify from "swagger-restify-mw";
const app = restify.createServer(); const config = { appRoot: __dirname // required config } as SwaggerRestify.Config; SwaggerRestify.create(config, (err, swaggerRestify) => { if (err) { throw err; } swaggerRestify.register(app); const port = process.env.PORT || 10010; app.listen(port); }); const swagger...
import * as restify from "restify";
random_line_split
ReaderComponent.tsx
import * as React from 'react'; import styled from 'styled-components' import { PostView } from './PostView';
const ReaderContainer = styled.div` display: grid; width: 100%; margin: 0; grid-template-columns: auto; grid-template-rows: auto; grid-template-areas: "f f f" "f f f"; `; interface IProps { } interface IState { } class PostComponent extends React.Component<IProps, IState> { publi...
random_line_split
ReaderComponent.tsx
import * as React from 'react'; import styled from 'styled-components' import { PostView } from './PostView'; const ReaderContainer = styled.div` display: grid; width: 100%; margin: 0; grid-template-columns: auto; grid-template-rows: auto; grid-template-areas: "f f f" "f f f"; `; inter...
public render() { return ( <ReaderContainer> <PostView query={{post_title: this.postTitle}} /> </ReaderContainer> ) } } module.exports = PostComponent;
{ const i = location.pathname.lastIndexOf('/'); const l = location.pathname.length; return location.pathname.substr(i + 1, l - 1) }
identifier_body
ReaderComponent.tsx
import * as React from 'react'; import styled from 'styled-components' import { PostView } from './PostView'; const ReaderContainer = styled.div` display: grid; width: 100%; margin: 0; grid-template-columns: auto; grid-template-rows: auto; grid-template-areas: "f f f" "f f f"; `; inter...
(): string { const i = location.pathname.lastIndexOf('/'); const l = location.pathname.length; return location.pathname.substr(i + 1, l - 1) } public render() { return ( <ReaderContainer> <PostView query={{post_title: this.postTitle}} /> <...
postTitle
identifier_name
common.py
import collections import mui4py.mui4py_mod as mui4py_mod from mui4py.config import get_default_config from mui4py.types import map_type, get_float_type_str, get_int_type_str, get_io_type_str import re import numpy as np class
(object): def __init__(self, config=None, args=(), kwargs={}): self._cpp_class_name = None self._cpp_point_class_name = None self.raw_point = None self.raw = None self.io_data_type = None # Convertir args en Args() self.args = tuple([Arg(a) if not issubclass(a...
CppClass
identifier_name
common.py
import collections import mui4py.mui4py_mod as mui4py_mod from mui4py.config import get_default_config from mui4py.types import map_type, get_float_type_str, get_int_type_str, get_io_type_str import re import numpy as np class CppClass(object): def __init__(self, config=None, args=(), kwargs={}): self._cpp...
if kwargs_str: sig += "_KWARGS_" + "_".join(kwargs_str) return sig def _split_class_name(self, title=True): tokens = re.findall('[A-Z][^A-Z]*', self.__class__.__name__) tokens = [t.lower() for t in tokens] if title: tokens[0] = tokens[0].title() ...
random_line_split
common.py
import collections import mui4py.mui4py_mod as mui4py_mod from mui4py.config import get_default_config from mui4py.types import map_type, get_float_type_str, get_int_type_str, get_io_type_str import re import numpy as np class CppClass(object): def __init__(self, config=None, args=(), kwargs={}): self._cpp...
def array2Point(arr, config, cpp_point): arr_aux = arr if not isinstance(arr, list) and\ not isinstance(arr, tuple) and\ not isinstance(arr, np.ndarray): arr_aux = [arr] # TODO:Maybe check for point type? if len(arr_aux) == config.dim: return cpp_point(arr_aux) else: ...
self.arg = array2Point(self.point_rep, config, cpp_point)
identifier_body
common.py
import collections import mui4py.mui4py_mod as mui4py_mod from mui4py.config import get_default_config from mui4py.types import map_type, get_float_type_str, get_int_type_str, get_io_type_str import re import numpy as np class CppClass(object): def __init__(self, config=None, args=(), kwargs={}): self._cpp...
else: self.config = config self.signature = self._signature() def _signature(self): sig = self._split_class_name() args_str = [str(a) for a in self.get_plain_args()] kwargs_str = ["{}={}".format(k,v) for k,v in self.kwargs.items()] if args_str: ...
self.config = get_default_config()
conditional_block
403.component.spec.ts
import { TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import {MockedTranslatePipe} from '../../../_mocks/translate.mock.spec'; import { Error403Component } from './403.component'; describe('Error403.Component', () => { beforeEach(() => { TestBed.configureTestingMo...
it('should create the component', () => { let fixture = TestBed.createComponent(Error403Component); expect(fixture.componentInstance instanceof Error403Component).toBe(true, 'should create Error403Component'); }); it('should have 404 text in heading', () => { let fixture = TestBed.c...
declarations: [ Error403Component, MockedTranslatePipe ] }); });
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule, ToastController } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; ...
{}
AppModule
identifier_name
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { ErrorHandler, NgModule } from '@angular/core'; import { IonicApp, IonicErrorHandler, IonicModule, ToastController } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; ...
HttpModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, LoginPage, HomePage, CoinsPage, SignupPage, ProfilePage, AddthreadPage, ViewthreadsPage, ThreadPage, AboutPage ], providers: [ StatusBar, ToastController, Spl...
imports: [ BrowserModule,
random_line_split
register-form.controller.js
(function() { 'use strict'; angular.module('cd.app.registerForm') .controller('RegisterFormController', RegisterFormController); /* @ngInject */ function RegisterFormController ($location, StepsService) { var $ctrl = this; $ctrl.selectedPlatform = JSON.parse(localStorage.g...
}; })();
{ $ctrl.registerForm = { nome: '', email: '', nascimento: '', cpf: '', telefone: '' }; $ctrl.submit = submit; function submit () { console.groupCollapsed('Formulá...
identifier_body
register-form.controller.js
(function() { 'use strict'; angular.module('cd.app.registerForm') .controller('RegisterFormController', RegisterFormController); /* @ngInject */ function RegisterFormController ($location, StepsService) { var $ctrl = this; $ctrl.selectedPlatform = JSON.parse(localStorage.g...
} function _init () { $ctrl.registerForm = { nome: '', email: '', nascimento: '', cpf: '', telefone: '' }; $ctrl.submit = submit; function submit () { ...
} else { _init();
random_line_split
register-form.controller.js
(function() { 'use strict'; angular.module('cd.app.registerForm') .controller('RegisterFormController', RegisterFormController); /* @ngInject */ function RegisterFormController ($location, StepsService) { var $ctrl = this; $ctrl.selectedPlatform = JSON.parse(localStorage.g...
function _init () { $ctrl.registerForm = { nome: '', email: '', nascimento: '', cpf: '', telefone: '' }; $ctrl.submit = submit; function submit () { con...
{ _init(); }
conditional_block
register-form.controller.js
(function() { 'use strict'; angular.module('cd.app.registerForm') .controller('RegisterFormController', RegisterFormController); /* @ngInject */ function RegisterFormController ($location, StepsService) { var $ctrl = this; $ctrl.selectedPlatform = JSON.parse(localStorage.g...
() { $ctrl.registerForm = { nome: '', email: '', nascimento: '', cpf: '', telefone: '' }; $ctrl.submit = submit; function submit () { console.groupCollapsed('For...
_init
identifier_name
main.rs
// Import Crate Module with shapes use traits_shapes::shapes; // use traits_shapes::shapes::HasArea; // Compile and link to the 'hello_world' Crate so its Modules may be used in main.rs extern crate traits_shapes; // Traits are defined similar to the 'impl' keyword that is used to call a function // with method synta...
}; let my_square = shapes::Square { x: 0.0f64, y: 0.0f64, side: 1.0f64, }; // print_area is now Generic and ensures only correct Types are passed in shapes::print_area(my_circle); // outputs 3.141593 shapes::print_area(my_square); // outputs 1 shapes::print_area(5); // outputs 5 }
fn main() { let my_circle = shapes::Circle { x: 0.0f64, y: 0.0f64, radius: 1.0f64,
random_line_split
main.rs
// Import Crate Module with shapes use traits_shapes::shapes; // use traits_shapes::shapes::HasArea; // Compile and link to the 'hello_world' Crate so its Modules may be used in main.rs extern crate traits_shapes; // Traits are defined similar to the 'impl' keyword that is used to call a function // with method synta...
() { let my_circle = shapes::Circle { x: 0.0f64, y: 0.0f64, radius: 1.0f64, }; let my_square = shapes::Square { x: 0.0f64, y: 0.0f64, side: 1.0f64, }; // print_area is now Generic and ensures only correct Types are passed in shapes::print_area(my_circle); // outputs 3...
main
identifier_name
main.rs
// Import Crate Module with shapes use traits_shapes::shapes; // use traits_shapes::shapes::HasArea; // Compile and link to the 'hello_world' Crate so its Modules may be used in main.rs extern crate traits_shapes; // Traits are defined similar to the 'impl' keyword that is used to call a function // with method synta...
{ let my_circle = shapes::Circle { x: 0.0f64, y: 0.0f64, radius: 1.0f64, }; let my_square = shapes::Square { x: 0.0f64, y: 0.0f64, side: 1.0f64, }; // print_area is now Generic and ensures only correct Types are passed in shapes::print_area(my_circle); // outputs 3.14...
identifier_body