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
hlp.py
""" Microsoft Windows Help (HLP) parser for Hachoir project. Documents: - Windows Help File Format / Annotation File Format / SHG and MRB File Format written by M. Winterhoff (100326.2776@compuserve.com) found on http://www.wotsit.org/ Author: Victor Stinner Creation date: 2007-09-03 """
from hachoir_py3.field import (FieldSet, Bits, Int32, UInt16, UInt32, NullBytes, RawBytes, PaddingBytes, String) from hachoir_py3.core.endian import LITTLE_ENDIAN from hachoir_py3.core.text_handler import (textHandler, hexadecimal, ...
from hachoir_py3.parser import Parser
random_line_split
hlp.py
""" Microsoft Windows Help (HLP) parser for Hachoir project. Documents: - Windows Help File Format / Annotation File Format / SHG and MRB File Format written by M. Winterhoff (100326.2776@compuserve.com) found on http://www.wotsit.org/ Author: Victor Stinner Creation date: 2007-09-03 """ from hachoir_py3.parser ...
size = (self.size - self.current_size) // 8 if size: yield PaddingBytes(self, "reserved_space", size) class HlpFile(Parser): PARSER_TAGS = { "id": "hlp", "category": "misc", "file_ext": ("hlp",), "min_size": 32, "description": "Microsoft Window...
def __init__(self, *args, **kw): FieldSet.__init__(self, *args, **kw) self._size = self["res_space"].value * 8 def createFields(self): yield displayHandler(UInt32(self, "res_space", "Reserved space"), humanFilesize) yield displayHandler(UInt32(self, "used_space", "Used space"), huma...
identifier_body
hlp.py
""" Microsoft Windows Help (HLP) parser for Hachoir project. Documents: - Windows Help File Format / Annotation File Format / SHG and MRB File Format written by M. Winterhoff (100326.2776@compuserve.com) found on http://www.wotsit.org/ Author: Victor Stinner Creation date: 2007-09-03 """ from hachoir_py3.parser ...
(self, *args, **kw): FieldSet.__init__(self, *args, **kw) self._size = self["res_space"].value * 8 def createFields(self): yield displayHandler(UInt32(self, "res_space", "Reserved space"), humanFilesize) yield displayHandler(UInt32(self, "used_space", "Used space"), humanFilesize) ...
__init__
identifier_name
hlp.py
""" Microsoft Windows Help (HLP) parser for Hachoir project. Documents: - Windows Help File Format / Annotation File Format / SHG and MRB File Format written by M. Winterhoff (100326.2776@compuserve.com) found on http://www.wotsit.org/ Author: Victor Stinner Creation date: 2007-09-03 """ from hachoir_py3.parser ...
class HlpFile(Parser): PARSER_TAGS = { "id": "hlp", "category": "misc", "file_ext": ("hlp",), "min_size": 32, "description": "Microsoft Windows Help (HLP)", } endian = LITTLE_ENDIAN def validate(self): if self["magic"].value != 0x00035F3F: ...
yield PaddingBytes(self, "reserved_space", size)
conditional_block
data-store-loader.js
var jsonfile = require('jsonfile'); var logger = require('../logger.js'); var middleware = require('swagger-express-middleware'); var recursive = require('recursive-readdir'); var DataStoreLoader = {}; module.exports = DataStoreLoader; DataStoreLoader.load = function(myDB, baseDir) { // Filter function ...
// Scan through the /db directory for all *.json files and add them into the custom data store recursive(baseDir, [ignoreFunc], function(err, files) { for (var i = 0; i < files.length; i++) { var file = files[i]; var path = file.slice(baseDir.length, file.length - 5).replace(...
random_line_split
data-store-loader.js
var jsonfile = require('jsonfile'); var logger = require('../logger.js'); var middleware = require('swagger-express-middleware'); var recursive = require('recursive-readdir'); var DataStoreLoader = {}; module.exports = DataStoreLoader; DataStoreLoader.load = function(myDB, baseDir) { // Filter function ...
}); }
{ var file = files[i]; var path = file.slice(baseDir.length, file.length - 5).replace(/\\/g, '/'); var data = jsonfile.readFileSync(file, 'utf8'); logger.debug(`Loading file: ${file}, and configured path to: ${path}`); myDB.save(new middleware.Resource(...
conditional_block
template.js
ast novietojumu. Noklikšķiniet, lai tās redzētu" }, "detailPanelBuilder": { "changeLocation": "Mainīt novietojumu", "setLocation": "Iestatīt novietojumu", "cancel": "Atcelt", "addImage": "Lai pievienotu attēlu, noklikšķiniet vai velciet un nometiet", "chooseImage": "IZVĒLĒTI...
"extentSensitive": "Cilnēs rādīt tikai vietas, kas redzamas kartē (tikai skatītājs)", "extentSensitiveTooltip": "Šī izvēlne ir spēkā tikai tad, kad jūsu atlases saraksts tiek skatīts. Shortlist veidotāja cilnēs vienmēr tiek rādītas visas vietas, arī tās, kuras nav redzamas kartē. Lai Shortlist lietotnes sk...
"settings": { "numberedPlaces": "Rādīt vietas ar skaitļiem",
random_line_split
__main__.py
#!/usr/bin/env python3 # Copyright 2021 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
sys.exit(0) if __name__ == '__main__': main()
components.project(args.manifest_filename, include=args.include, exclude=args.exclude, path_prefix=args.path_prefix)
conditional_block
__main__.py
#!/usr/bin/env python3 # Copyright 2021 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
if __name__ == '__main__': main()
"""Main command line function.""" args = _parse_args() if args.command == 'project': components.project(args.manifest_filename, include=args.include, exclude=args.exclude, path_prefix=args.path_prefix) sys.exit(0)
identifier_body
__main__.py
#!/usr/bin/env python3 # Copyright 2021 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
() -> argparse.Namespace: """Setup argparse and parse command line args.""" parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest='command', metavar='<command>', required=True) project_parser = subparser...
_parse_args
identifier_name
__main__.py
#!/usr/bin/env python3 # Copyright 2021 The Pigweed Authors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicab...
if args.command == 'project': components.project(args.manifest_filename, include=args.include, exclude=args.exclude, path_prefix=args.path_prefix) sys.exit(0) if __name__ == '__main__': main()
"""Main command line function.""" args = _parse_args()
random_line_split
setup.py
from setuptools import setup, find_packages import sys, os version = '1.3' long_description = """The raisin.restyler package is a part of Raisin, the web application used for publishing the summary statistics of Grape, a pipeline used for processing and analyzing RNA-Seq data.""" setup(name='raisin.restyler', v...
classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Natural Language :: En...
random_line_split
endpoint-service-replace.py
#!/usr/bin/env python from optparse import OptionParser import getpass import os import sys import yaml possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_t...
from anvil import log as logging from anvil import importer from anvil import passwords from anvil.components.helpers import keystone from anvil import utils def get_token(): pw_storage = passwords.KeyringProxy(path='/etc/anvil/passwords.cfg') lookup_name = "service_token" prompt = "Please enter the pa...
sys.path.insert(0, possible_topdir)
conditional_block
endpoint-service-replace.py
#!/usr/bin/env python
from optparse import OptionParser import getpass import os import sys import yaml possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_topdir, ...
random_line_split
endpoint-service-replace.py
#!/usr/bin/env python from optparse import OptionParser import getpass import os import sys import yaml possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_t...
for e in current_endpoints: print("Deleting endpoint: ") print(utils.prettify_yaml(filter_resource(e))) client.endpoints.delete(e.id) for s in current_services: print("Deleting service: ") print(utils.prettify_yaml(filter_resource(s))) client.services.delete(s....
raw = dict(r.__dict__) # Can't access the raw attrs, arg... raw_cleaned = {} for k, v in raw.items(): if k == 'manager' or k.startswith('_'): continue raw_cleaned[k] = v return raw_cleaned
identifier_body
endpoint-service-replace.py
#!/usr/bin/env python from optparse import OptionParser import getpass import os import sys import yaml possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os.path.exists(os.path.join(possible_t...
(): pw_storage = passwords.KeyringProxy(path='/etc/anvil/passwords.cfg') lookup_name = "service_token" prompt = "Please enter the password for %s: " % ('/etc/anvil/passwords.cfg') (exists, token) = pw_storage.read(lookup_name, prompt) if not exists: pw_storage.save(lookup_name, token) re...
get_token
identifier_name
server-started-notification.component.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import { TranslateService } from '@ngx-translate/core' import { ChallengeService } from '../Services/challenge.service' import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core' import { CookieService } from 'ngx-coo...
@Component({ selector: 'app-server-started-notification', templateUrl: './server-started-notification.component.html', styleUrls: ['./server-started-notification.component.scss'] }) export class ServerStartedNotificationComponent implements OnInit { public hackingProgress: HackingProgress = {} as HackingProgre...
interface HackingProgress { autoRestoreMessage: string | null cleared: boolean }
random_line_split
server-started-notification.component.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import { TranslateService } from '@ngx-translate/core' import { ChallengeService } from '../Services/challenge.service' import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core' import { CookieService } from 'ngx-coo...
if (continueCodeFixIt) { this.challengeService.restoreProgressFixIt(encodeURIComponent(continueCodeFixIt)).subscribe(() => { }, (error) => { console.log(error) }) } this.ref.detectChanges() }) }) } closeNotification () { this.hackingP...
{ this.challengeService.restoreProgressFindIt(encodeURIComponent(continueCodeFindIt)).subscribe(() => { }, (error) => { console.log(error) }) }
conditional_block
server-started-notification.component.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import { TranslateService } from '@ngx-translate/core' import { ChallengeService } from '../Services/challenge.service' import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core' import { CookieService } from 'ngx-coo...
() { this.hackingProgress.autoRestoreMessage = null } clearProgress () { this.cookieService.remove('continueCode') this.cookieService.remove('continueCodeFixIt') this.cookieService.remove('continueCodeFindIt') this.cookieService.remove('token') sessionStorage.removeItem('bid') sessionS...
closeNotification
identifier_name
server-started-notification.component.ts
/* * Copyright (c) 2014-2021 Bjoern Kimminich. * SPDX-License-Identifier: MIT */ import { TranslateService } from '@ngx-translate/core' import { ChallengeService } from '../Services/challenge.service' import { ChangeDetectorRef, Component, NgZone, OnInit } from '@angular/core' import { CookieService } from 'ngx-coo...
}
{ this.cookieService.remove('continueCode') this.cookieService.remove('continueCodeFixIt') this.cookieService.remove('continueCodeFindIt') this.cookieService.remove('token') sessionStorage.removeItem('bid') sessionStorage.removeItem('itemTotal') localStorage.removeItem('token') localStor...
identifier_body
bootstrap-popover.js
//Wrapped in an outer function to preserve global this (function (root) { var amdExports; define(['bootstrap/bootstrap-transition','bootstrap/bootstrap-tooltip'], function () { (function () { /* =========================================================== * bootstrap-popover.js v2.3.1 * http://twitter.github.com/boot...
placement: 'right' , trigger: 'click' , content: '' , template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) /* POPOVER NO CONFLICT * =================== */ $.fn.popover.noConflict = function () { $.fn.popover = old ...
$.fn.popover.Constructor = Popover $.fn.popover.defaults = $.extend({} , $.fn.tooltip.defaults, {
random_line_split
binomial_prob.py
#!/usr/bin/env python """ Let's say we play a game where I keep flipping a coin until I get heads. If the first time I get heads is on the nth coin, then I pay you 2n-1 dollars. How much would you pay me to play this game? You should end up with a sequence that you need to find the closed form of. If you don't know ho...
(): tails, num_flips = True, 0 while tails: num_flips += 1 if np.random.binomial(1,0.5): tails = False return num_flips if __name__ == '__main__': ## simulate flips = [coin() for k in xrange(10000)] ## get the distribution of counts condition on the number of flip...
coin
identifier_name
binomial_prob.py
#!/usr/bin/env python """ Let's say we play a game where I keep flipping a coin until I get heads. If the first time I get heads is on the nth coin, then I pay you 2n-1 dollars. How much would you pay me to play this game? You should end up with a sequence that you need to find the closed form of. If you don't know ho...
if __name__ == '__main__': ## simulate flips = [coin() for k in xrange(10000)] ## get the distribution of counts condition on the number of flips range_flips = range(1, max(flips) + 1) counts = np.array([flips.count(k)*1. for k in range_flips]) fig = plt.figure() ax = fig.add_subplot(1...
tails, num_flips = True, 0 while tails: num_flips += 1 if np.random.binomial(1,0.5): tails = False return num_flips
identifier_body
binomial_prob.py
#!/usr/bin/env python """ Let's say we play a game where I keep flipping a coin until I get heads. If the first time I get heads is on the nth coin, then I pay you 2n-1 dollars. How much would you pay me to play this game? You should end up with a sequence that you need to find the closed form of. If you don't know ho...
return num_flips if __name__ == '__main__': ## simulate flips = [coin() for k in xrange(10000)] ## get the distribution of counts condition on the number of flips range_flips = range(1, max(flips) + 1) counts = np.array([flips.count(k)*1. for k in range_flips]) fig = plt.figure() a...
tails = False
conditional_block
binomial_prob.py
#!/usr/bin/env python """ Let's say we play a game where I keep flipping a coin until I get heads. If the first time I get heads is on the nth coin, then I pay you 2n-1 dollars. How much would you pay me to play this game? You should end up with a sequence that you need to find the closed form of. If you don't know ho...
## simulate the number of flips before heads def coin(): tails, num_flips = True, 0 while tails: num_flips += 1 if np.random.binomial(1,0.5): tails = False return num_flips if __name__ == '__main__': ## simulate flips = [coin() for k in xrange(10000)] ## get the ...
random_line_split
ordering.py
# -*- coding: utf-8 -*- '''auto ordering call chain test mixins''' from inspect import ismodule from twoq.support import port class ARandomQMixin(object): def test_choice(self): self.assertEqual(len(list(self.qclass(1, 2, 3, 4, 5, 6).choice())), 1) def test_sample(self): self.assertEqual(l...
def test_reversed(self): self.assertEqual( self.qclass(5, 4, 3, 2, 1).reverse().end(), [1, 2, 3, 4, 5], ) def test_sort(self): from math import sin self.assertEqual( self.qclass(1, 2, 3, 4, 5, 6).tap( lambda x: sin(x) ).sort(...
self.assertEqual( self.qclass( 'moe', 'larry', 'curly', 30, 40, 50, True ).grouper(2, 'x').end(), [('moe', 'larry'), ('curly', 30), (40, 50), (True, 'x')] )
identifier_body
ordering.py
# -*- coding: utf-8 -*- '''auto ordering call chain test mixins''' from inspect import ismodule from twoq.support import port class ARandomQMixin(object): def test_choice(self): self.assertEqual(len(list(self.qclass(1, 2, 3, 4, 5, 6).choice())), 1) def test_sample(self): self.assertEqual(l...
(self): self.assertEqual( self.qclass(5, 4, 3, 2, 1).reverse().end(), [1, 2, 3, 4, 5], ) def test_sort(self): from math import sin self.assertEqual( self.qclass(1, 2, 3, 4, 5, 6).tap( lambda x: sin(x) ).sort().end(), [5...
test_reversed
identifier_name
ordering.py
# -*- coding: utf-8 -*- '''auto ordering call chain test mixins''' from inspect import ismodule from twoq.support import port class ARandomQMixin(object): def test_choice(self): self.assertEqual(len(list(self.qclass(1, 2, 3, 4, 5, 6).choice())), 1) def test_sample(self): self.assertEqual(l...
# # def test_permutations(self): # foo = self.qclass('ABCD').permutations(2).value() # self.assertEqual( # foo[0], # [('A', 'B'), ('A', 'C'), ('A', 'D'), ('B', 'A'), ('B', 'C'), # ('B', 'D'), ('C', 'A'), ('C', 'B'), ('C', 'D'), ('D', 'A'), # ('D', 'B'), ('D',...
random_line_split
cursor.py
long value or None. """ return self._last_insert_id class MySQLCursor(CursorBase): """Default cursor for interacting with MySQL This cursor will execute statements and handle the result. It will not automatically fetch all rows. MySQLCursor should be inherited whenever other ...
stmt = operation % self._process_params(params) except TypeError: raise errors.ProgrammingError( "Wrong number of arguments during string formatting") else: stmt = operation if multi: self._executed = stmt ...
random_line_split
cursor.py
def fetchmany(self, size=1): pass def fetchall(self): pass def nextset(self): pass def setinputsizes(self, sizes): pass def setoutputsize(self, size, column=None): pass def reset(self): pass @property def des...
pass
identifier_body
cursor.py
_iter (result of MySQLConnection.cmd_query_iter()) and the list of statements that were executed. Yields a MySQLCursor instance. """ if not self._executed_list: self._executed_list = RE_SQL_SPLIT_STMTS.split(self._executed) for result, stmt in iterto...
res.append(row)
conditional_block
cursor.py
(self): """Returns the value generated for an AUTO_INCREMENT column Returns the value generated for an AUTO_INCREMENT column by the previous INSERT or UPDATE statement or None when there is no such value available. Returns a long value or None. """ ...
lastrowid
identifier_name
LanguageDistribution-test.tsx
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, o...
shallow( <LanguageDistribution distribution="java=1734;js=845;cpp=73;<null>=15" languages={{ java: { key: 'java', name: 'Java' }, js: { key: 'js', name: 'JavaScript' } }} /> ) ).toMatchSnapshot(); });
expect(
random_line_split
preview.test.ts
import { createPreview } from '@dicebear/core'; import * as style from '../dist'; import * as fs from 'fs'; import * as path from 'path'; const data = [ [style, { seed: 'test' }, 'eyes'], [style, { seed: 'test' }, 'eyebrows'], [style, { seed: 'test' }, 'mouth'], [style, { seed: 'test' }, 'glasses'], [style, ...
fs.writeFileSync(svgComponent, createPreview(...params), { encoding: 'utf-8', }); } const svg = fs.readFileSync(svgComponent, { encoding: 'utf-8' }); expect(createPreview(...params)).toEqual(svg); }); });
{ fs.mkdirSync(path.dirname(svgComponent), { recursive: true }); }
conditional_block
preview.test.ts
import { createPreview } from '@dicebear/core'; import * as style from '../dist'; import * as fs from 'fs'; import * as path from 'path'; const data = [ [style, { seed: 'test' }, 'eyes'], [style, { seed: 'test' }, 'eyebrows'], [style, { seed: 'test' }, 'mouth'], [style, { seed: 'test' }, 'glasses'], [style, ...
if (false === fs.existsSync(svgComponent)) { if (false === fs.existsSync(path.dirname(svgComponent))) { fs.mkdirSync(path.dirname(svgComponent), { recursive: true }); } fs.writeFileSync(svgComponent, createPreview(...params), { encoding: 'utf-8', }); } const svg = ...
test(`Create avatar #${key}`, async () => { const svgComponent = path.resolve(__dirname, 'svg/preview', `${key}.svg`);
random_line_split
values.js
var express = require( 'express' ); var router = express.Router( ); var http = require( 'http' ); var options = { host: 'jettestarmpaas.cloudapp.net', port: 80, path: '/api/simple', method: 'GET', headers: { connection: 'keep-alive' } }; function ca
options, callback ) { return http.request( options, function ( res ) { console.log( 'STATUS: ' + res.statusCode ); console.log( 'HEADERS: ' + JSON.stringify( res.headers ) ); res.setEncoding( 'utf8' ); var body = ''; res.on( 'data', function ( chunk ) { c...
llApi(
identifier_name
values.js
var express = require( 'express' ); var router = express.Router( ); var http = require( 'http' ); var options = { host: 'jettestarmpaas.cloudapp.net', port: 80, path: '/api/simple', method: 'GET', headers: { connection: 'keep-alive' } }; function callApi( options, callback ) {
} } ); } ).on( 'error', function ( e ) { callback( true, "error" ); } ).on( 'timeout', function ( e ) { res.abort( ); callback( true, "timeout" ); } ); } /* GET values page. */ router.get( '/', function ( req, res ) { var stuff, rawData; cal...
return http.request( options, function ( res ) { console.log( 'STATUS: ' + res.statusCode ); console.log( 'HEADERS: ' + JSON.stringify( res.headers ) ); res.setEncoding( 'utf8' ); var body = ''; res.on( 'data', function ( chunk ) { console.log( 'BODY: ' +...
identifier_body
values.js
var express = require( 'express' ); var router = express.Router( ); var http = require( 'http' ); var options = { host: 'jettestarmpaas.cloudapp.net', port: 80, path: '/api/simple', method: 'GET', headers: { connection: 'keep-alive' } }; function callApi( options, callback ) { re...
var st = res.status; if ( res.statusCode == 200 ) callback( null, parsed ); else { callback( res.statusCode, parsed ); } } ); } ).on( 'error', function ( e ) { callback( true, "error" ); } ).on( 'time...
// Data reception is done, do whatever with it! var parsed = JSON.parse( body );
random_line_split
values.js
var express = require( 'express' ); var router = express.Router( ); var http = require( 'http' ); var options = { host: 'jettestarmpaas.cloudapp.net', port: 80, path: '/api/simple', method: 'GET', headers: { connection: 'keep-alive' } }; function callApi( options, callback ) { re...
} ); } ).on( 'error', function ( e ) { callback( true, "error" ); } ).on( 'timeout', function ( e ) { res.abort( ); callback( true, "timeout" ); } ); } /* GET values page. */ router.get( '/', function ( req, res ) { var stuff, rawData; callApi( options, ...
callback( res.statusCode, parsed ); }
conditional_block
data_loader.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/. */ use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use mime_classifier::MIMEClassifier; use net_traits::Pro...
} // ";base64" must come at the end of the content type, per RFC 2397. // rust-http will fail to parse it because there's no =value part. let mut is_base64 = false; let mut ct_str = parts[0].to_owned(); if ct_str.ends_with(";base64") { is_base64 = true; let end_index = ct_str.le...
{ let url = load_data.url; assert!(&*url.scheme == "data"); // Split out content type and data. let mut scheme_data = match url.scheme_data { SchemeData::NonRelative(ref scheme_data) => scheme_data.clone(), _ => panic!("Expected a non-relative scheme URL.") }; match url.query { ...
identifier_body
data_loader.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/. */ use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use mime_classifier::MIMEClassifier; use net_traits::Pro...
} // Parse the content type using rust-http. // FIXME: this can go into an infinite loop! (rust-http #25) let mut content_type: Option<Mime> = ct_str.parse().ok(); if content_type == None { content_type = Some(Mime(TopLevel::Text, SubLevel::Plain, vec!((Attr...
ct_str = format!("text/plain{}", ct_str);
random_line_split
data_loader.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/. */ use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value}; use mime_classifier::MIMEClassifier; use net_traits::Pro...
(load_data: LoadData, senders: LoadConsumer, classifier: Arc<MIMEClassifier>) { // NB: we don't spawn a new task. // Hypothesis: data URLs are too small for parallel base64 etc. to be worth it. // Should be tested at some point. // Left in separate function to allow easy moving to a task, if desired. ...
factory
identifier_name
gettags.py
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
## MODULE CONSTANTS VFFSL=valueFromFrameOrSearchList VFSL=valueFromSearchList VFN=valueForName currentTime=time.time __CHEETAH_version__ = '2.4.4' __CHEETAH_versionTuple__ = (2, 4, 4, 'development', 0) __CHEETAH_genTime__ = 1406885498.501688 __CHEETAH_genTimestamp__ = 'Fri Aug 1 18:31:38 2014' __CHEETAH_src__ = '/home...
from Cheetah.CacheRegion import CacheRegion import Cheetah.Filters as Filters import Cheetah.ErrorCatchers as ErrorCatchers ##################################################
random_line_split
gettags.py
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
else: _dummyTrans = False write = trans.response().write SL = self._CHEETAH__searchList _filter = self._CHEETAH__currentFilter ######################################## ## START - generated method body _orig_filter_91099948 = _filter filt...
trans = DummyTransaction() _dummyTrans = True
conditional_block
gettags.py
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
(self, *args, **KWs): super(gettags, self).__init__(*args, **KWs) if not self._CHEETAH__instanceInitialized: cheetahKWArgs = {} allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split() for k,v in KWs.items(): if k in allowedKWs: che...
__init__
identifier_name
gettags.py
#!/usr/bin/env python ################################################## ## DEPENDENCIES import sys import os import os.path try: import builtins as builtin except ImportError: import __builtin__ as builtin from os.path import getmtime, exists import time import types from Cheetah.Version import MinCompatib...
_dummyTrans = True else: _dummyTrans = False write = trans.response().write SL = self._CHEETAH__searchList _filter = self._CHEETAH__currentFilter ######################################## ## START - generated method body _orig_filter_9...
def __init__(self, *args, **KWs): super(gettags, self).__init__(*args, **KWs) if not self._CHEETAH__instanceInitialized: cheetahKWArgs = {} allowedKWs = 'searchList namespaces filter filtersLib errorCatcher'.split() for k,v in KWs.items(): if k in all...
identifier_body
rpc_blockchain.py
math assert_equal(round(chaintxstats['txrate'] * 600, 10), Decimal(1)) b1_hash = self.nodes[0].getblockhash(1) b1 = self.nodes[0].getblock(b1_hash) b200_hash = self.nodes[0].getblockhash(200) b200 = self.nodes[0].getblock(b200_hash) time_diff = b200['mediantime'] - b1['...
BlockchainTest().main()
conditional_block
rpc_blockchain.py
000000000000000000000000') blockhash = self.nodes[0].getblockhash(200) self.nodes[0].invalidateblock(blockhash) assert_raises_rpc_error(-8, "Block is not in main chain", self.nodes[0].getchaintxstats, blockhash=blockhash) self.nodes[0].reconsiderblock(blockhash) chaintxstats = s...
self.log.info("Test waitforblockheight") node = self.nodes[0] node.add_p2p_connection(P2PInterface()) current_height = node.getblock(node.getbestblockhash())['height'] # Create a fork somewhere below our current height, invalidate the tip # of that fork, and then ensure that wa...
identifier_body
rpc_blockchain.py
(self): self.mine_chain() self.restart_node(0, extra_args=['-stopatheight=207', '-prune=1']) # Set extra args with pruning after rescan is complete self._test_getblockchaininfo() self._test_getchaintxstats() self._test_gettxoutsetinfo() self._test_getblockheader() ...
run_test
identifier_name
rpc_blockchain.py
0].reconsiderblock(blockhash) chaintxstats = self.nodes[0].getchaintxstats(nblocks=1) # 200 txs plus genesis tx assert_equal(chaintxstats['txcount'], 201) # tx rate should be 1 per 10 minutes, or 1/600 # we have to round because of binary math assert_equal(round(chaintxs...
node.invalidateblock(b22f.hash)
random_line_split
profile.service.ts
import { Injectable } from "@angular/core"; import { Http, Response, URLSearchParams } from "@angular/http"; @Injectable() export class ProfileService { constructor(public http: Http) {} insert(doc) : any { return this.http.post("/profiles", JSON.stringify(doc)) .map((res: Response) => res...
} }
params.set(key, String(options[key])); } return base + "?" + params.toString();
random_line_split
profile.service.ts
import { Injectable } from "@angular/core"; import { Http, Response, URLSearchParams } from "@angular/http"; @Injectable() export class ProfileService {
(public http: Http) {} insert(doc) : any { return this.http.post("/profiles", JSON.stringify(doc)) .map((res: Response) => res.json()); } get(id: string) : any { return this.http.get("/profiles/" + id) .map((res: Response) => res.json()); } all(options?: Ob...
constructor
identifier_name
profile.service.ts
import { Injectable } from "@angular/core"; import { Http, Response, URLSearchParams } from "@angular/http"; @Injectable() export class ProfileService { constructor(public http: Http) {} insert(doc) : any { return this.http.post("/profiles", JSON.stringify(doc)) .map((res: Response) => res...
activate(id: string) : any { return this.http.post("/profiles/activate", id) .map((res: Response) => res.json()) } query(base: string, options?: Object) : string { if (!options) return base; var params = new URLSearchParams(); for (var key in options) { ...
{ var url = this.query("/profiles/" + id, {rev: rev}); return this.http.delete(url); }
identifier_body
spsc_queue.rs
ail addition: Addition, } unsafe impl<T: Send, P: Send + Sync, C: Send + Sync> Send for Queue<T, P, C> { } unsafe impl<T: Send, P: Send + Sync, C: Send + Sync> Sync for Queue<T, P, C> { } impl<T> Node<T> { fn new() -> *mut Node<T> { Box::into_raw(box Node { value: None, cached...
{ unsafe { let q: Queue<Box<_>> = Queue::with_additions(0, (), ()); q.push(box 1); q.push(box 2); } }
identifier_body
spsc_queue.rs
this could be an uninitialized T if we're careful enough, and // that would reduce memory usage (and be a bit faster). // is it worth it? value: Option<T>, // nullable for re-use of nodes cached: bool, // This node goes into the node cache next: AtomicPtr<Node<T>>,...
unsafe { // The `tail` node is not actually a used node, but rather a // sentinel from where we should start popping from. Hence, look at // tail's next field and see if we can use it. If we do a pop, then // the current tail node is a candidate for going into the...
} /// Attempts to pop a value from this queue. Remember that to use this type /// safely you must ensure that there is only one popper at a time. pub fn pop(&self) -> Option<T> {
random_line_split
spsc_queue.rs
this could be an uninitialized T if we're careful enough, and // that would reduce memory usage (and be a bit faster). // is it worth it? value: Option<T>, // nullable for re-use of nodes cached: bool, // This node goes into the node cache next: AtomicPtr<Node<T>>,...
(&self) -> &ProducerAddition { &self.producer.addition } pub fn consumer_addition(&self) -> &ConsumerAddition { &self.consumer.addition } } impl<T, ProducerAddition, ConsumerAddition> Drop for Queue<T, ProducerAddition, ConsumerAddition> { fn drop(&mut self) { unsafe { ...
producer_addition
identifier_name
abstracts.py
# This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import argparse import viper.common.out as out from viper.core.config import console_output class ArgumentErrorCallback(Exception): def __init__(self, message, level=''): self.message ...
(argparse.ArgumentParser): def print_usage(self): raise ArgumentErrorCallback(self.format_usage()) def print_help(self): raise ArgumentErrorCallback(self.format_help()) def error(self, message): raise ArgumentErrorCallback(message, 'error') def exit(self, status, message=None)...
ArgumentParser
identifier_name
abstracts.py
# This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import argparse import viper.common.out as out from viper.core.config import console_output class ArgumentErrorCallback(Exception): def __init__(self, message, level=''): self.message ...
self.log(*e.get())
random_line_split
abstracts.py
# This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import argparse import viper.common.out as out from viper.core.config import console_output class ArgumentErrorCallback(Exception): def __init__(self, message, level=''): self.message ...
def help(self): self.log('', self.parser.format_help()) def run(self): try: self.args = self.parser.parse_args(self.command_line) except ArgumentErrorCallback as e: self.log(*e.get())
self.log('', self.parser.format_usage())
identifier_body
abstracts.py
# This file is part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import argparse import viper.common.out as out from viper.core.config import console_output class ArgumentErrorCallback(Exception): def __init__(self, message, level=''): self.message ...
class Module(object): cmd = '' description = '' command_line = [] args = None authors = [] output = [] def __init__(self): self.parser = ArgumentParser(prog=self.cmd, description=self.description) def set_commandline(self, command): self.command_line = command de...
raise ArgumentErrorCallback(message)
conditional_block
dashboard.js
/*! * Piwik - Web Analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ function initDashboard(dashboardId, dashboardLayout)
$('#removeDashboardLink').hide(); } else { $('#removeDashboardLink').show(); } // fix position $('#dashboardSettings .widgetpreview-widgetlist').css('paddingTop', $('#dashboardSettings .widgetpreview-categorylist').parent('li').position().top); }); $('body...
{ // Standard dashboard if($('#periodString').length) { $('#periodString').after($('#dashboardSettings')); $('#dashboardSettings').css({left:$('#periodString')[0].offsetWidth}); } // Embed dashboard if(!$('#topBars').length) { $('#dashboardSettings').css({left:0}); ...
identifier_body
dashboard.js
/*! * Piwik - Web Analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ function initDashboard(dashboardId, dashboardLayout) { // Standard dashboard if($('#periodString').length) { $('#periodString').after($('#dashboardSettings')); ...
var type = ($('#dashboard_type_empty:checked').length > 0) ? 'empty' : 'default'; piwikHelper.showAjaxLoading(); var ajaxRequest = { type: 'GET', url: 'index.php?module=Dashboard&action=createNewDashboard', dataType: 'json', async: true, ...
function createDashboard() { $('#createDashboardName').attr('value', ''); piwikHelper.modalConfirm('#createDashboardConfirm', {yes: function(){ var dashboardName = $('#createDashboardName').attr('value');
random_line_split
dashboard.js
/*! * Piwik - Web Analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ function initDashboard(dashboardId, dashboardLayout) { // Standard dashboard if($('#periodString').length) { $('#periodString').after($('#dashboardSettings')); ...
// fix position $('#dashboardSettings .widgetpreview-widgetlist').css('paddingTop', $('#dashboardSettings .widgetpreview-categorylist').parent('li').position().top); }); $('body').on('mouseup', function(e) { if(!$(e.target).parents('#dashboardSettings').length && !$(e.target).is('#dashb...
{ $('#removeDashboardLink').show(); }
conditional_block
dashboard.js
/*! * Piwik - Web Analytics * * @link http://piwik.org * @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later */ function initDashboard(dashboardId, dashboardLayout) { // Standard dashboard if($('#periodString').length) { $('#periodString').after($('#dashboardSettings')); ...
() { piwikHelper.modalConfirm('#dashboardEmptyNotification', { resetDashboard: function() { $('#dashboardWidgetsArea').dashboard('resetLayout'); }, addWidget: function(){ $('#dashboardSettings').trigger('click'); } }); } function setAsDefaultWidgets() { piwikHelper.modalConfirm('#setAsDefau...
showEmptyDashboardNotification
identifier_name
ipc_lista2.16.py
#EQUIPE 2 #Nahan Trindade Passos - 1615310021 #Ana Beatriz Frota - 1615310027 # # # # # # import math print("Digite os termos da equacao ax2+bx+c")
b = float(input("Valor de B:\n")) c = float(input("Valor de C:\n")) delta = (math.pow(b,2) - (4*a*c)) if(delta<0): print("A equacao nao possui raizes reais") elif(delta == 0): raiz = ((-1)*b + math.sqrt(delta))/(2*a) print("A equacao possui apenas uma raiz",raiz) ...
a = float(input("Digite o valor de A:\n")) if(a==0): print("Nao e uma equacao de segundo grau") else:
random_line_split
ipc_lista2.16.py
#EQUIPE 2 #Nahan Trindade Passos - 1615310021 #Ana Beatriz Frota - 1615310027 # # # # # # import math print("Digite os termos da equacao ax2+bx+c") a = float(input("Digite o valor de A:\n")) if(a==0): print("Nao e uma equacao de segundo grau") else:
b = float(input("Valor de B:\n")) c = float(input("Valor de C:\n")) delta = (math.pow(b,2) - (4*a*c)) if(delta<0): print("A equacao nao possui raizes reais") elif(delta == 0): raiz = ((-1)*b + math.sqrt(delta))/(2*a) print("A equacao possui apenas uma raiz",raiz) el...
conditional_block
slope.py
# -*- coding: utf-8 -*- """ *************************************************************************** slope.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *******************...
return ['gdaldem', GdalUtils.escapeAndJoin(arguments)]
arguments.append('ZevenbergenThorne') if self.getParameterValue(self.AS_PERCENT): arguments.append('-p')
random_line_split
slope.py
# -*- coding: utf-8 -*- """ *************************************************************************** slope.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *******************...
def displayName(self): return self.tr('Slope') def defineCharacteristics(self): self.addParameter(ParameterRaster(self.INPUT, self.tr('Input layer'))) self.addParameter(ParameterNumber(self.BAND, self.tr('Band number'), 1, 99, 1)) self...
return 'slope'
identifier_body
slope.py
# -*- coding: utf-8 -*- """ *************************************************************************** slope.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *******************...
(GdalAlgorithm): INPUT = 'INPUT' BAND = 'BAND' COMPUTE_EDGES = 'COMPUTE_EDGES' ZEVENBERGEN = 'ZEVENBERGEN' AS_PERCENT = 'AS_PERCENT' SCALE = 'SCALE' OUTPUT = 'OUTPUT' def group(self): return self.tr('Raster analysis') def name(self): return 'slope' def display...
slope
identifier_name
slope.py
# -*- coding: utf-8 -*- """ *************************************************************************** slope.py --------------------- Date : October 2013 Copyright : (C) 2013 by Alexander Bruy Email : alexander dot bruy at gmail dot com *******************...
if self.getParameterValue(self.AS_PERCENT): arguments.append('-p') return ['gdaldem', GdalUtils.escapeAndJoin(arguments)]
arguments.append('-alg') arguments.append('ZevenbergenThorne')
conditional_block
Tab.d.ts
import * as React from "react"; import ReactToolbox from "../index"; export interface TabTheme { /** * Added to the navigation tab element in case it's active. */ active?: string; /** * Added to the navigation tab element in case it's disabled. */ disabled?: string; /** * Added to the navigati...
/** * Additional properties passed to Tab root container. */ [key: string]: any; } export class Tab extends React.Component<TabProps, {}> { } export default Tab;
* Classnames object defining the component style. */ theme?: TabTheme;
random_line_split
Tab.d.ts
import * as React from "react"; import ReactToolbox from "../index"; export interface TabTheme { /** * Added to the navigation tab element in case it's active. */ active?: string; /** * Added to the navigation tab element in case it's disabled. */ disabled?: string; /** * Added to the navigati...
extends React.Component<TabProps, {}> { } export default Tab;
Tab
identifier_name
index.js
/** * @param {string} s * @return {boolean} */ const checkValidString = function (s) { let leftCount = 0, rightCount = 0, starCount = 0; let idx = 0; while (idx < s.length)
idx = s.length - 1; leftCount = rightCount = starCount = 0; while (idx >= 0) { let ch = s[idx--]; if (ch === ')') { ++rightCount; } else if (ch === '*') { ++starCount; } else { // ch === '(' ++leftCount; if (leftCount > righ...
{ let ch = s[idx++]; if (ch === '(') { ++leftCount; } else if (ch === '*') { ++starCount; } else { // ch === ')' ++rightCount; if (rightCount > leftCount + starCount) { return false; } } }
conditional_block
index.js
/** * @param {string} s * @return {boolean} */ const checkValidString = function (s) { let leftCount = 0, rightCount = 0, starCount = 0; let idx = 0; while (idx < s.length) { let ch = s[idx++]; if (ch === '(') {
if (rightCount > leftCount + starCount) { return false; } } } idx = s.length - 1; leftCount = rightCount = starCount = 0; while (idx >= 0) { let ch = s[idx--]; if (ch === ')') { ++rightCount; } else if (ch === '*') { ...
++leftCount; } else if (ch === '*') { ++starCount; } else { // ch === ')' ++rightCount;
random_line_split
HelpDialog.js
/* * ../../../..//localization/fr/HelpDialog.js * * Copyright (c) 2009-2018 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org...
MathJax.Ajax.loadComplete("[MathJax]/localization/fr/HelpDialog.js");
} });
random_line_split
airline-seat-recline-normal.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMi...
var NotificationAirlineSeatReclineNormal = _react2.default.createClass({ displayName: 'NotificationAirlineSeatReclineNormal', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement( _svgIcon2.default, this.props, _react2.default.c...
{ return obj && obj.__esModule ? obj : { default: obj }; }
identifier_body
airline-seat-recline-normal.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMi...
this.props, _react2.default.createElement('path', { d: 'M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1....
random_line_split
airline-seat-recline-normal.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMi...
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var NotificationAirlineSeatReclineNormal = _react2.default.createClass({ displayName: 'NotificationAirlineSeatReclineNormal', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement( ...
_interopRequireDefault
identifier_name
WebpackRunner.ts
import MemoryFS = require('memory-fs'); import path = require('path'); import webpack = require('webpack'); import logger from './logger'; export type WebpackBundle = { [key: string]: Buffer }; export type Options = { config?: webpack.Configuration; packages?: string[]; includes?: string[]; basedir?: string; }...
(): object { return { config: Object.freeze(Object.assign({}, this.config)), node_modules: this.nodeModulesInContext().sort() }; } public toString(): string { return JSON.stringify(this.toJSON(), null, 2); } private runAsync(source: string | Buffer, onComplete: OnComplete): void { ...
toJSON
identifier_name
WebpackRunner.ts
import MemoryFS = require('memory-fs'); import path = require('path'); import webpack = require('webpack'); import logger from './logger'; export type WebpackBundle = { [key: string]: Buffer }; export type Options = { config?: webpack.Configuration; packages?: string[]; includes?: string[]; basedir?: string; }...
return new Promise((resolve, reject) => { log.debug('Executing script...'); this.runAsync(source, (error, bundle, stats) => { if (error) { log.error('Failed to execute script.'); reject(error); } else if (stats && stats.hasErrors()) { log.error('Script finis...
public run(source: string | Buffer): Promise<[WebpackBundle, webpack.Stats]> {
random_line_split
WebpackRunner.ts
import MemoryFS = require('memory-fs'); import path = require('path'); import webpack = require('webpack'); import logger from './logger'; export type WebpackBundle = { [key: string]: Buffer }; export type Options = { config?: webpack.Configuration; packages?: string[]; includes?: string[]; basedir?: string; }...
}
{ return this.memfs.readdirSync(path.join(this.config.context, 'node_modules')); }
identifier_body
uStripDesign.py
# -*- coding: utf-8 -*- # @Author: Marco Benzi <marco.benzi@alumnos.usm.cl> # @Date: 2015-06-07 19:44:12 # @Last Modified 2015-06-09 # @Last Modified time: 2015-06-09 16:07:05 # ========================================================================== # This program is free software: you can redistribute it and/or...
""" Returns the dielectric loss in [dB/cm]. Paramenters: - `er` : Relative permitivity of the dielectric - `ef` : Effective permitivity - `tanD` : tan \delta - `f` : Operating frequency """ lam = c/math.sqrt(ef)/f return 27.3*(er*(ef-1)*tanD)/(lam*math.sqrt(er)*(er-1))
identifier_body
uStripDesign.py
# -*- coding: utf-8 -*- # @Author: Marco Benzi <marco.benzi@alumnos.usm.cl> # @Date: 2015-06-07 19:44:12 # @Last Modified 2015-06-09 # @Last Modified time: 2015-06-09 16:07:05 # ========================================================================== # This program is free software: you can redistribute it and/or...
else: return W + (1 + math.log(4*math.pi*H/t))*(t/math.pi) else: print "The conductor is too thick!!" def getConductorLoss(W,H,t,sigma,f,Zo): """ Returns the conductor loss in [Np/m]. Parameters: - `W` : Width - `H` : Height - `t` : Conductor thickness - `sigma` : Conductance of medium - `f` : Operat...
if t < H and t < W/2: if W/H <= math.pi/2: return W + (1 + math.log(2*H/t))*(t/math.pi)
random_line_split
uStripDesign.py
# -*- coding: utf-8 -*- # @Author: Marco Benzi <marco.benzi@alumnos.usm.cl> # @Date: 2015-06-07 19:44:12 # @Last Modified 2015-06-09 # @Last Modified time: 2015-06-09 16:07:05 # ========================================================================== # This program is free software: you can redistribute it and/or...
def getCorrectedWidth(W,H,t): """ For significant conductor thickness, this returns the corrected width. Paramenters: - `W` : Width - `H` : Height - `t` : Conductor thickness """ if t < H and t < W/2: if W/H <= math.pi/2: return W + (1 + math.log(2*H/t))*(t/math.pi) else: return W + (1 + math.log(4...
rA = getWHRatioA(Zoa,efa) rB = getWHRatioB(Zob,efb) if rA < 2: return rA if rB > 2: return rB Zoa = math.sqrt(efa)*Zoa Zob = math.sqrt(efb)*Zob
conditional_block
uStripDesign.py
# -*- coding: utf-8 -*- # @Author: Marco Benzi <marco.benzi@alumnos.usm.cl> # @Date: 2015-06-07 19:44:12 # @Last Modified 2015-06-09 # @Last Modified time: 2015-06-09 16:07:05 # ========================================================================== # This program is free software: you can redistribute it and/or...
(W,H,t): """ For significant conductor thickness, this returns the corrected width. Paramenters: - `W` : Width - `H` : Height - `t` : Conductor thickness """ if t < H and t < W/2: if W/H <= math.pi/2: return W + (1 + math.log(2*H/t))*(t/math.pi) else: return W + (1 + math.log(4*math.pi*H/t))*(t/math...
getCorrectedWidth
identifier_name
tflow.py
import uuid from typing import Optional, Union from mitmproxy import connection from mitmproxy import flow from mitmproxy import http from mitmproxy import tcp from mitmproxy import websocket from mitmproxy.test.tutils import treq, tresp from wsproto.frame_protocol import Opcode def ttcpflow(client_conn=True, server...
if messages is True: messages = [ tcp.TCPMessage(True, b"hello", 946681204.2), tcp.TCPMessage(False, b"it's me", 946681204.5), ] if err is True: err = terr() f = tcp.TCPFlow(client_conn, server_conn) f.messages = messages f.error = err f.live = T...
server_conn = tserver_conn()
conditional_block
tflow.py
import uuid from typing import Optional, Union from mitmproxy import connection from mitmproxy import flow from mitmproxy import http from mitmproxy import tcp from mitmproxy import websocket from mitmproxy.test.tutils import treq, tresp from wsproto.frame_protocol import Opcode def ttcpflow(client_conn=True, server...
) flow.response = http.Response( b"HTTP/1.1", 101, reason=b"Switching Protocols", headers=http.Headers( connection='upgrade', upgrade='websocket', sec_websocket_accept=b'', ), content=b'', trailers=None, timestam...
flow = http.HTTPFlow(tclient_conn(), tserver_conn()) flow.request = http.Request( "example.com", 80, b"GET", b"http", b"example.com", b"/ws", b"HTTP/1.1", headers=http.Headers( connection="upgrade", upgrade="websocket", ...
identifier_body
tflow.py
import uuid from typing import Optional, Union from mitmproxy import connection from mitmproxy import flow from mitmproxy import http from mitmproxy import tcp from mitmproxy import websocket from mitmproxy.test.tutils import treq, tresp from wsproto.frame_protocol import Opcode def ttcpflow(client_conn=True, server...
(messages=True, err=None, close_code=None, close_reason='') -> http.HTTPFlow: flow = http.HTTPFlow(tclient_conn(), tserver_conn()) flow.request = http.Request( "example.com", 80, b"GET", b"http", b"example.com", b"/ws", b"HTTP/1.1", headers=http.He...
twebsocketflow
identifier_name
tflow.py
import uuid from typing import Optional, Union from mitmproxy import connection from mitmproxy import flow from mitmproxy import http from mitmproxy import tcp from mitmproxy import websocket from mitmproxy.test.tutils import treq, tresp from wsproto.frame_protocol import Opcode def ttcpflow(client_conn=True, server...
b"http", b"example.com", b"/ws", b"HTTP/1.1", headers=http.Headers( connection="upgrade", upgrade="websocket", sec_websocket_version="13", sec_websocket_key="1234", ), content=b'', trailers=None, time...
random_line_split
num.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/. */ //! The `Finite<T>` struct. use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use num_traits::Float; use std::...
impl<T: Float> Finite<T> { /// Create a new `Finite<T: Float>` safely. pub fn new(value: T) -> Option<Finite<T>> { if value.is_finite() { Some(Finite(value)) } else { None } } /// Create a new `Finite<T: Float>`. #[inline] pub fn wrap(value: T) ->...
random_line_split
num.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/. */ //! The `Finite<T>` struct. use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use num_traits::Float; use std::...
<T: Float>(T); impl<T: Float> Finite<T> { /// Create a new `Finite<T: Float>` safely. pub fn new(value: T) -> Option<Finite<T>> { if value.is_finite() { Some(Finite(value)) } else { None } } /// Create a new `Finite<T: Float>`. #[inline] pub fn w...
Finite
identifier_name
num.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/. */ //! The `Finite<T>` struct. use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use num_traits::Float; use std::...
} impl<T: Float> Deref for Finite<T> { type Target = T; fn deref(&self) -> &T { let &Finite(ref value) = self; value } } impl<T: Float + MallocSizeOf> MallocSizeOf for Finite<T> { fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { (**self).size_of(ops) } } impl<T: F...
{ assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestricted value."); Finite(value) }
identifier_body
num.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/. */ //! The `Finite<T>` struct. use malloc_size_of::{MallocSizeOf, MallocSizeOfOps}; use num_traits::Float; use std::...
} /// Create a new `Finite<T: Float>`. #[inline] pub fn wrap(value: T) -> Finite<T> { assert!(value.is_finite(), "Finite<T> doesn't encapsulate unrestricted value."); Finite(value) } } impl<T: Float> Deref for Finite<T> { type Target = T; fn deref(&self) -...
{ None }
conditional_block
cartoonmad.py
"""The www.cartoonmad.com analyzer. [Entry examples] - http://www.cartoonmad.com/comic/5640.html - https://www.cartoonmad.com/comic/5640.html """ import re from urllib.parse import parse_qsl from cmdlr.analyzer import BaseAnalyzer from cmdlr.autil import fetch class Analyzer(BaseAnalyzer): """The www....
one volume.""" soup, absurl = await fetch(url, request, encoding='big5') get_img_url = self.__get_imgurl_func(soup, absurl) page_count = len(soup.find_all('option', value=True)) for page_num in range(1, page_count + 1): save_image( page_num, ...
identifier_body
cartoonmad.py
"""The www.cartoonmad.com analyzer. [Entry examples] - http://www.cartoonmad.com/comic/5640.html - https://www.cartoonmad.com/comic/5640.html """ import re from urllib.parse import parse_qsl from cmdlr.analyzer import BaseAnalyzer from cmdlr.autil import fetch class Analyzer(BaseAnalyzer): """The www....
page_num, url=get_img_url(page_num), headers={'Referer': url}, )
conditional_block
cartoonmad.py
"""The www.cartoonmad.com analyzer. [Entry examples] - http://www.cartoonmad.com/comic/5640.html - https://www.cartoonmad.com/comic/5640.html """ import re from urllib.parse import parse_qsl from cmdlr.analyzer import BaseAnalyzer from cmdlr.autil import fetch class Analyzer(BaseAnalyzer): """The www....
[Entry examples] - http://www.cartoonmad.com/comic/5640.html - https://www.cartoonmad.com/comic/5640.html """ entry_patterns = [ re.compile( r'^https?://(?:www.)?cartoonmad.com/comic/(\d+)(?:\.html)?$' ), ] def entry_normalizer(self, url): """Normalize ...
random_line_split
cartoonmad.py
"""The www.cartoonmad.com analyzer. [Entry examples] - http://www.cartoonmad.com/comic/5640.html - https://www.cartoonmad.com/comic/5640.html """ import re from urllib.parse import parse_qsl from cmdlr.analyzer import BaseAnalyzer from cmdlr.autil import fetch class Analyzer(BaseAnalyzer): """The www....
**unused): """Get comic info.""" fetch_result = await fetch(url, request, encoding='big5') return { 'name': self.__extract_name(fetch_result), 'volumes': self.__extract_volumes(fetch_result), 'description': self.__extract_description(fetch_result), ...
url, request,
identifier_name
alloc_support.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 in ...
<'frame>( self, storage: DroppingSlot<'frame, Self::Storage>, ) -> MoveRef<'frame, Self::Target> where Self: 'frame, { let cast = unsafe { Box::from_raw(Box::into_raw(self).cast::<MaybeUninit<T>>()) }; let (storage, drop_flag) = storage.put(cast); unsafe { MoveRef::new_unchecked(sto...
deref_move
identifier_name
alloc_support.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 in ...
}
{ let uninit = Arc::new(MaybeUninit::<T>::uninit()); unsafe { let pinned = Pin::new_unchecked(&mut *(Arc::as_ptr(&uninit) as *mut _)); n.try_new(pinned)?; Ok(Pin::new_unchecked(Arc::from_raw( Arc::into_raw(uninit).cast::<T>(), ))) } }
identifier_body
alloc_support.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 in ...
unsafe { Box::from_raw(Box::into_raw(self).cast::<MaybeUninit<T>>()) }; let (storage, drop_flag) = storage.put(cast); unsafe { MoveRef::new_unchecked(storage.assume_init_mut(), drop_flag) } } } impl<T> EmplaceUnpinned<T> for Pin<Box<T>> { fn try_emplace<N: TryNew<Output = T>>(n: N) -> Result<Self, N...
Self: 'frame, { let cast =
random_line_split