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
coding.rs
/* Copyright 2015 Tyler Neely 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 wri...
(buf: [u8; 8]) -> u64 { ((buf[0] & 0xff).to_u64().unwrap() << 56) | ((buf[1] & 0xff).to_u64().unwrap() << 48) | ((buf[2] & 0xff).to_u64().unwrap() << 40) | ((buf[3] & 0xff).to_u64().unwrap() << 32) | ((buf[4] & 0xff).to_u64().unwrap() << 24) | ((buf[5] & 0xff).to_u64().unwrap() << 16) | ((bu...
decode_u64
identifier_name
grid.py
import bisect import string from abc import ABC, abstractmethod from typing import Optional from django.conf import settings class AbstractGrid(ABC): enabled = False @abstractmethod def get_square_for_point(self, x, y) -> Optional[str]: pass @abstractmethod def get_squares_for_bounds(se...
grid = DummyGrid()
random_line_split
grid.py
import bisect import string from abc import ABC, abstractmethod from typing import Optional from django.conf import settings class AbstractGrid(ABC): enabled = False @abstractmethod def get_square_for_point(self, x, y) -> Optional[str]: pass @abstractmethod def get_squares_for_bounds(se...
y = bisect.bisect(self.rows, y) if y <= 0 or y >= len(self.rows): return None if self.invert_x: x = len(self.cols) - x if self.invert_y: y = len(self.rows) - y return '%s%d' % (string.ascii_uppercase[x-1], y) def get_squares_for_bounds...
return None
conditional_block
grid.py
import bisect import string from abc import ABC, abstractmethod from typing import Optional from django.conf import settings class AbstractGrid(ABC): enabled = False @abstractmethod def get_square_for_point(self, x, y) -> Optional[str]:
@abstractmethod def get_squares_for_bounds(self, bounds) -> Optional[str]: pass class Grid(AbstractGrid): enabled = True def __init__(self, rows, cols): rows = tuple(float(y) for y in rows) cols = tuple(float(x) for x in cols) self.rows = tuple(sorted(rows)) ...
pass
identifier_body
grid.py
import bisect import string from abc import ABC, abstractmethod from typing import Optional from django.conf import settings class AbstractGrid(ABC): enabled = False @abstractmethod def get_square_for_point(self, x, y) -> Optional[str]: pass @abstractmethod def get_squares_for_bounds(se...
(self, bounds): minx, miny, maxx, maxy = bounds if self.invert_x: minx, maxx = maxx, minx if self.invert_y: miny, maxy = maxy, miny min_square = self.get_square_for_point(minx, miny) max_square = self.get_square_for_point(maxx, maxy) if not min_...
get_squares_for_bounds
identifier_name
polyfills.ts
/** * This file includes polyfills needed by Angular and is loaded before the app. * You can add your own extra polyfills to this file. * * This file is divided into 2 sections: * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. * 2. Application imports. Files imported...
/*************************************************************************************************** * APPLICATION IMPORTS */ /** * Date, currency, decimal and percent pipes. * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 */ // import 'intl'; // Run `npm install --save intl`.
*/ import 'zone.js/dist/zone'; // Included with Angular CLI.
random_line_split
bookmark.py
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Timothy Legge <timlegge@gmail.com> and Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from contextlib import closing class Bookmark(): # {{{
def get_bookmark_data(self): ''' Return the timestamp and last_read_location ''' import sqlite3 as sqlite user_notes = {} self.timestamp = os.path.getmtime(self.path) with closing(sqlite.connect(self.db_path)) as connection: # return bytestrings if the content can...
''' A simple class fetching bookmark data kobo-specific ''' def __init__(self, db_path, contentid, path, id, book_format, bookmark_extension): self.book_format = book_format self.bookmark_extension = bookmark_extension self.book_length = 0 # Not Used self.id = ...
identifier_body
bookmark.py
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Timothy Legge <timlegge@gmail.com> and Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from contextlib import closing class Bookmark(): # {{{ ''' A simple class fetching boo...
elif text and annotation: e_type = 'Annotation' else: e_type = 'Unknown annotation type' note_id = row[10] + bm_count chapter_title = row[9] # book_title = row[8] chapter_progress = ...
e_type = 'Highlight'
conditional_block
bookmark.py
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Timothy Legge <timlegge@gmail.com> and Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from contextlib import closing class Bookmark(): # {{{ ''' A simple class fetching boo...
(self): ''' Return the timestamp and last_read_location ''' import sqlite3 as sqlite user_notes = {} self.timestamp = os.path.getmtime(self.path) with closing(sqlite.connect(self.db_path)) as connection: # return bytestrings if the content cannot the decoded as unicod...
get_bookmark_data
identifier_name
bookmark.py
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai __license__ = 'GPL v3' __copyright__ = '2011, Timothy Legge <timlegge@gmail.com> and Kovid Goyal <kovid@kovidgoyal.net>' __docformat__ = 'restructuredtext en' import os from contextlib import closing class Bookmark(): # {{{ ''' A simple class fetching boo...
note_id = row[10] + bm_count chapter_title = row[9] # book_title = row[8] chapter_progress = min(round(float(100*row[5]),2),100) user_notes[note_id] = dict(id=self.id, displayed_location=note_id, ...
e_type = 'Annotation' else: e_type = 'Unknown annotation type'
random_line_split
noise.rs
use num_traits; use num_traits::NumCast; #[cfg(feature = "noise")] use noise::{NoiseModule, Perlin, Seedable}; fn cast<T: NumCast, R: NumCast>(val: T) -> R { num_traits::cast(val).unwrap() } #[cfg(feature = "noise")] pub struct Noise { perlin: Perlin, } #[cfg(feature = "noise")] impl Noise { pub fn new...
(&mut self, seed: u32) { } }
set_seed
identifier_name
noise.rs
use num_traits; use num_traits::NumCast; #[cfg(feature = "noise")] use noise::{NoiseModule, Perlin, Seedable}; fn cast<T: NumCast, R: NumCast>(val: T) -> R { num_traits::cast(val).unwrap() } #[cfg(feature = "noise")] pub struct Noise { perlin: Perlin, } #[cfg(feature = "noise")] impl Noise { pub fn new...
pub fn set_seed(&mut self, seed: u32) { } }
{ 0. }
identifier_body
noise.rs
use num_traits; use num_traits::NumCast; #[cfg(feature = "noise")] use noise::{NoiseModule, Perlin, Seedable}; fn cast<T: NumCast, R: NumCast>(val: T) -> R { num_traits::cast(val).unwrap() } #[cfg(feature = "noise")] pub struct Noise { perlin: Perlin,
info!("[Unicorn][Noise] new"); Noise { perlin: Perlin::new() } } pub fn get(&mut self, x: f64, y: f64, z: f64) -> f64 { let r: f64 = cast(self.perlin.get([x, y, z])); r } pub fn set_seed(&mut self, seed: u32) { debug!("Change seed to {:?}", seed); self.p...
} #[cfg(feature = "noise")] impl Noise { pub fn new() -> Noise {
random_line_split
local.rs
} fn spawn<O: Into<Stdio>, E: Into<Stdio>>( &mut self, stdout: O, stderr: E, ) -> std::io::Result<Child>
} // TODO: A Stream that ends with `Exit` is error prone: we should consider creating a Child struct // similar to nails::server::Child (which is itself shaped like `std::process::Child`). // See https://github.com/stuhood/nails/issues/1 for more info. #[derive(Debug, PartialEq, Eq)] pub enum ChildOutput { Stdout(B...
{ self .inner .stdin(Stdio::null()) .stdout(stdout) .stderr(stderr) .spawn() }
identifier_body
local.rs
} fn
<O: Into<Stdio>, E: Into<Stdio>>( &mut self, stdout: O, stderr: E, ) -> std::io::Result<Child> { self .inner .stdin(Stdio::null()) .stdout(stdout) .stderr(stderr) .spawn() } } // TODO: A Stream that ends with `Exit` is error prone: we should consider creating a Child s...
spawn
identifier_name
local.rs
.cleanup_local_dirs { // Hold on to the workdir so that we can drop it explicitly after we've finished using it. (workdir.path().to_owned(), Some(workdir)) } else { // This consumes the `TempDir` without deleting directory on the filesystem, meaning // that the ...
{ workdir_path.join(working_directory) }
conditional_block
local.rs
// https://github.com/pantsbuild/pants/issues/6089 let child_results_result = { let child_results_future = ChildResults::collect_from( self .run_in_workdir(&workdir_path, workdir_token, req.clone(), exclusive_spawn) .await?, ); if let Some(req_timeout) = req.timeout ...
let res: Result<_, String> = Ok(exe_was_materialized); res })
random_line_split
GA_8Queens.py
''' Solution for Eight Queens Problem Using the Genetic Algorithms This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any la...
def run(self): self.create_initial_chromosomes() while not self.success(): self.next_gen() self.generation_info(self.chromosomes) print "Result", self.optimum.queens, self.optimum.fitness def success(self): re...
self.population = 10 self.chromosomes = [] self.prob_crossover = 0.9 # crossover possibility self.prob_mutation = 0.1 # mutation possibility self.fitness = 28 # successor value self.generation = 0 self.max_generation = 50 self.optimum = Chromosome() ...
identifier_body
GA_8Queens.py
''' Solution for Eight Queens Problem Using the Genetic Algorithms This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any la...
def mutation(self, chromosome, next_generation): for i in range(0,8): if random.random() < self.prob_mutation: chromosome.queens[i] = random.randint(0, 7) chromosome.fitness = self.calc_fitness(chromosome.queens) print "Mutati...
return success
random_line_split
GA_8Queens.py
''' Solution for Eight Queens Problem Using the Genetic Algorithms This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any la...
(self): return self.generation >= self.max_generation or \ self.fitness == self.optimum.fitness def next_gen(self): next_generation = [] self.generation += 1 success = False next_generation.append(self.optimum) while len(next_genera...
success
identifier_name
GA_8Queens.py
''' Solution for Eight Queens Problem Using the Genetic Algorithms This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any la...
next_generation.append(chromosome) if chromosome.fitness == self.fitness: return True else: return False def choose_chromosome(self, chromosomes): total_fitness = 0 for chrom in chromosomes: total_fitne...
chromosome.queens[i] = random.randint(0, 7) chromosome.fitness = self.calc_fitness(chromosome.queens) print "Mutation result:", chromosome.queens, "fitness:", chromosome.fitness
conditional_block
copyright.py
"""Plugin which add a copyright to the image. Settings: - ``copyright``: the copyright text. - ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.ttf file. If no font is specified, or specified font is not found, the default font is used. - ``copyright_text_f...
(5, img.size[1] - text_height)) draw.text((left, top), text, fill=color, font=font) return img def register(settings): if settings.get('copyright'): signals.img_resized.connect(add_copyright) else: logger.warning('Copyright text is not set')
logger.debug('Adding copyright to %r', img) draw = ImageDraw.Draw(img) text = settings['copyright'] font = settings.get('copyright_text_font', None) font_size = settings.get('copyright_text_font_size', 10) assert font_size >= 0 color = settings.get('copyright_text_color', (0, 0, 0)) bottom_m...
identifier_body
copyright.py
"""Plugin which add a copyright to the image. Settings: - ``copyright``: the copyright text. - ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.ttf file. If no font is specified, or specified font is not found, the default font is used. - ``copyright_text_f...
(img, settings=None): logger.debug('Adding copyright to %r', img) draw = ImageDraw.Draw(img) text = settings['copyright'] font = settings.get('copyright_text_font', None) font_size = settings.get('copyright_text_font_size', 10) assert font_size >= 0 color = settings.get('copyright_text_color...
add_copyright
identifier_name
copyright.py
"""Plugin which add a copyright to the image. Settings: - ``copyright``: the copyright text. - ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.ttf file. If no font is specified, or specified font is not found, the default font is used. - ``copyright_text_f...
import logging from PIL import ImageDraw, ImageFont from sigal import signals logger = logging.getLogger(__name__) def add_copyright(img, settings=None): logger.debug('Adding copyright to %r', img) draw = ImageDraw.Draw(img) text = settings['copyright'] font = settings.get('copyright_text_font', No...
random_line_split
copyright.py
"""Plugin which add a copyright to the image. Settings: - ``copyright``: the copyright text. - ``copyright_text_font``: the copyright text font - either system/user font-name or absolute path to font.ttf file. If no font is specified, or specified font is not found, the default font is used. - ``copyright_text_f...
else: font = ImageFont.load_default() left, top = settings.get('copyright_text_position', (5, img.size[1] - text_height)) draw.text((left, top), text, fill=color, font=font) return img def register(settings): if settings.get('copyright'): signals.img_r...
try: font = ImageFont.truetype(font, font_size) text_height = font.getsize(text)[1] + bottom_margin except Exception: # load default font in case of any exception logger.debug("Exception: Couldn't locate font %s, using " "default font", font) ...
conditional_block
extHostDebugService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
public onTerminalClosed(terminal: vscode.Terminal) { this._terminalInstances.delete(terminal); } }
{ const info = this._terminalInstances.get(terminal); if (info) { info.lastUsedAt = -1; } }
identifier_body
extHostDebugService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
if (termInfo.config !== config) { return null; } termInfo.lastUsedAt = now; return terminal; })); return await firstParallel(promises, (t): t is vscode.Terminal => !!t); } public insert(terminal: vscode.Terminal, termConfig: string) { this._terminalInstances.set(terminal, { lastUsedAt: Date...
{ return null; }
conditional_block
extHostDebugService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
( @IExtHostRpcService extHostRpcService: IExtHostRpcService, @IExtHostWorkspace workspaceService: IExtHostWorkspace, @IExtHostExtensionService extensionService: IExtHostExtensionService, @IExtHostDocumentsAndEditors editorsService: IExtHostDocumentsAndEditors, @IExtHostConfiguration configurationService: IExt...
constructor
identifier_name
extHostDebugService.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} } class DebugTerminalCollection { /** * Delay before a new terminal is a candidate for reuse. See #71850 */ private static minUseDelay = 1000; private _terminalInstances = new Map<vscode.Terminal, { lastUsedAt: number, config: string }>(); public async checkout(config: string) { const entries = [...this...
protected createVariableResolver(folders: vscode.WorkspaceFolder[], editorService: ExtHostDocumentsAndEditors, configurationService: ExtHostConfigProvider): AbstractVariableResolverService { return new ExtHostVariableResolverService(folders, editorService, configurationService, this._editorTabs, this._workspaceServi...
random_line_split
cdn_assets.py
from django import template from django.utils.safestring import mark_safe from django.template.base import Node register = template.Library() from tag_parser import template_tag from tag_parser.basetags import BaseNode @template_tag(register, 'asset') class JsCssAssetNode(BaseNode): """ Implement asset filte...
def __repr__(self): return "<CDNNode>" def render(self, context): output = self.nodelist.render(context) return mark_safe(output) @register.tag('cdn') def do_cdn(parser, token): """ Implement cdn filter Usage: {% cdn bootcss %} {% asset jquery 3.0.0-beta1 jq...
node.host = host
conditional_block
cdn_assets.py
from django import template from django.utils.safestring import mark_safe from django.template.base import Node register = template.Library() from tag_parser import template_tag from tag_parser.basetags import BaseNode @template_tag(register, 'asset') class JsCssAssetNode(BaseNode): """ Implement asset filte...
output = '' return mark_safe(output) @register.tag def js(parser, token): bits = token.split_contents() nodelist = parser.parse(('endjs',)) token = parser.next_token() return JsCssFontNode('js', bits) @register.tag def css(parser, token): bits = token.split_contents() nodelist ...
return "<JsCssNode>" def render(self, context):
random_line_split
cdn_assets.py
from django import template from django.utils.safestring import mark_safe from django.template.base import Node register = template.Library() from tag_parser import template_tag from tag_parser.basetags import BaseNode @template_tag(register, 'asset') class JsCssAssetNode(BaseNode): """ Implement asset filte...
(self): return "<JsCssNode>" def render(self, context): output = '' return mark_safe(output) @register.tag def js(parser, token): bits = token.split_contents() nodelist = parser.parse(('endjs',)) token = parser.next_token() return JsCssFontNode('js', bits) @register.tag de...
__repr__
identifier_name
cdn_assets.py
from django import template from django.utils.safestring import mark_safe from django.template.base import Node register = template.Library() from tag_parser import template_tag from tag_parser.basetags import BaseNode @template_tag(register, 'asset') class JsCssAssetNode(BaseNode): """ Implement asset filte...
def render(self, context): output = self.nodelist.render(context) return mark_safe(output) @register.tag('cdn') def do_cdn(parser, token): """ Implement cdn filter Usage: {% cdn bootcss %} {% asset jquery 3.0.0-beta1 jquery.min js %} {% asset bootstrap 3.3.6 css ...
return "<CDNNode>"
identifier_body
cleanexe.py
#!/usr/bin/python # -*- coding: utf-8 -*- # # --- BEGIN_HEADER --- # # cleanexe - [insert a few words of module description on this line] # Copyright (C) 2003-2009 The MiG Project lead by Brian Vinter # # This file is part of MiG. # # MiG is free software: you can redistribute it and/or modify # it under the terms of ...
from shared.functionality.cleanexe import main from shared.cgiscriptstub import run_cgi_script run_cgi_script(main)
cgitb.enable()
random_line_split
login.component.spec.ts
/** * Copyright 2020-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 agre...
import { LoginComponent } from './login.component'; import { RouterTestingModule } from '@angular/router/testing'; import { AngularFireModule } from '@angular/fire/compat'; import { AngularFireAuthModule } from '@angular/fire/compat/auth'; import { firebaseConfig } from '../../environments/firebaseConfig'; import { Ma...
random_line_split
table-body-cell.component.ts
* it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * ...
public confirmUnlink() { this.notificationService.confirm( 'Unlinking a row will permanently delete the link between the data records.', 'Delete this link?', [ {text: 'Yes', action: () => this.onUnlinkRow(), bold: false}, {text: 'No'} ] ); } public confirmRemove(...
{ const newRow = this.tableManagerService.addLinkedRow(this.row); setTimeout(() => this.selectedCell = {row: newRow, attribute: newRow.part.shownAttributes[0]}); }
identifier_body
table-body-cell.component.ts
modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty...
import {HtmlModifier} from '../../../../shared/utils/html-modifier'; import {KeyCodeHelper} from '../../../../shared/utils/key-code.helper'; import {Direction} from '../../post-it/document-data/direction'; import {DataChangeEvent, LinkInstanceEvent, TableCursorEvent} from '../event'; import {TableRow} from '../model/t...
import {Component, ElementRef, EventEmitter, Input, OnChanges, Output, SimpleChanges, ViewChild} from '@angular/core'; import {Attribute, Document} from '../../../../core/dto'; import {NotificationService} from '../../../../core/notifications/notification.service'; import {DocumentConverter} from '../../../../core/stor...
random_line_split
table-body-cell.component.ts
* it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * ...
() { if (this.isSinglePart() && this.isLastAttribute()) { this.tableManagerService.addColumn(this.row.part, this.attribute); } } private isSinglePart() { return this.row.part.index === 0 && !this.row.part.nextPart; } private isLastAttribute() { return this.row.part.shownAttributes.indexO...
initNextColumn
identifier_name
table-body-cell.component.ts
* it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * ...
if (changes.hasOwnProperty('editedCell')) { this.highlighted = this.editedCell && this.editedCell.attribute === this.attribute && this.row.documents.includes(this.editedCell.row.documents[0]); } if (changes.hasOwnProperty('row') && this.row.documents.length === 0) { const doc = ...
{ this.dataCell.nativeElement.focus(); }
conditional_block
dsound.rs
DEFINE_GUID!{DSDEVID_DefaultVoiceCapture, 0xdef00003, 0x9c6d, 0x47ed, 0xaa, 0xf1, 0x4d, 0xda, 0x8f, 0x2b, 0x5c, 0x03} STRUCT!{struct DSCAPS { dwSize: DWORD, dwFlags: DWORD, dwMinSecondarySampleRate: DWORD, dwMaxSecondarySampleRate: DWORD, dwPrimaryBuffers: DWORD, dwMaxHwMixingAllBuffers: DWO...
0xdef00002, 0x9c6d, 0x47ed, 0xaa, 0xf1, 0x4d, 0xda, 0x8f, 0x2b, 0x5c, 0x03}
random_line_split
store.ts
import { PersistenceEngine, ModelDefinition, Types, Generator } from '@akala/storage'; export interface Store { DevicesInit: db.DbSet<{ name: string, body: string, type: string, room: string }>; // Devices: db.DbSet<devices.IDevice>; } export interface LiveStore { Devices: db.DbSet<devices.IDevi...
import * as akala from '@akala/core' import * as db from '@akala/storage' import * as devices from '../devices';
random_line_split
visxBidAdapter.js
fererInfo && bidderRequest.refererInfo.referer) { payload.u = bidderRequest.refererInfo.referer; } if (bidderRequest.gdprConsent) { if (bidderRequest.gdprConsent.consentString) { payload.gdpr_consent = bidderRequest.gdprConsent.consentString; } payload.gdpr_applies ...
_isValidVideoBid
identifier_name
visxBidAdapter.js
hasNoArrayOfBids: 'Seatbid from response has no array of bid objects - ', notAllowedCurrency: 'Currency is not supported - ', currencyMismatch: 'Currency from the request is not match currency from the response - ', onlyVideoInstream: `Only video ${VIDEO_INSTREAM} supported`, videoMissing: 'Bid request videoT...
if (syncOptions.iframeEnabled) { return [{ type: 'iframe', url: buildUrl(ADAPTER_SYNC_PATH) + '?iframe=1' + (query.length ? '&' + query.join('&') : '') }]; } else if (syncOptions.pixelEnabled) { return [{ type: 'image', url: buildUrl(ADAPTER_SYNC_PATH) + (query...
{ if (gdprConsent.consentString) { query.push('gdpr_consent=' + encodeURIComponent(gdprConsent.consentString)); } query.push('gdpr_applies=' + encodeURIComponent( (typeof gdprConsent.gdprApplies === 'boolean') ? Number(gdprConsent.gdprApplies) : 1)); }
conditional_block
visxBidAdapter.js
(bidderRequest.refererInfo && bidderRequest.refererInfo.referer) { payload.u = bidderRequest.refererInfo.referer; } if (bidderRequest.gdprConsent) { if (bidderRequest.gdprConsent.consentString) { payload.gdpr_consent = bidderRequest.gdprConsent.consentString; } pay...
{ return bid.mediaType === BANNER || deepAccess(bid, 'mediaTypes.banner'); }
identifier_body
visxBidAdapter.js
', hasNoArrayOfBids: 'Seatbid from response has no array of bid objects - ', notAllowedCurrency: 'Currency is not supported - ', currencyMismatch: 'Currency from the request is not match currency from the response - ', onlyVideoInstream: `Only video ${VIDEO_INSTREAM} supported`, videoMissing: 'Bid request vid...
return !!bid.params.uid && !isNaN(parseInt(bid.params.uid)); }, buildRequests: function(validBidRequests, bidderRequest) { const auids = []; const bidsMap = {}; const bids = validBidRequests || []; const currency = config.getConfig(`currency.bidderCurrencyDefault.${BIDDER_CODE}`) || ...
} }
random_line_split
suntsu.py
# Natural Language Toolkit: Sun Tsu-Bot # # Copyright (C) 2001-2011 NLTK Project # Author: Sam Huston 2007 # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT from util import * """ Tsu bot responds to all queries with a Sun Tsu sayings Quoted from Sun Tsu's The Art of War Translated by LIONEL ...
(): print "Talk to the program by typing in plain English, using normal upper-" print 'and lower-case letters and punctuation. Enter "quit" when done.' print '='*72 print "You seek enlightenment?" suntsu_chatbot.converse() def demo(): suntsu_chat() if __name__ == "__main__": demo()
suntsu_chat
identifier_name
suntsu.py
# Natural Language Toolkit: Sun Tsu-Bot # # Copyright (C) 2001-2011 NLTK Project # Author: Sam Huston 2007 # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT from util import * """ Tsu bot responds to all queries with a Sun Tsu sayings Quoted from Sun Tsu's The Art of War Translated by LIONEL ...
if __name__ == "__main__": demo()
suntsu_chat()
identifier_body
suntsu.py
# Natural Language Toolkit: Sun Tsu-Bot # # Copyright (C) 2001-2011 NLTK Project # Author: Sam Huston 2007 # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT from util import * """ Tsu bot responds to all queries with a Sun Tsu sayings Quoted from Sun Tsu's The Art of War Translated by LIONEL ...
demo()
conditional_block
suntsu.py
# Natural Language Toolkit: Sun Tsu-Bot # # Copyright (C) 2001-2011 NLTK Project # Author: Sam Huston 2007 # URL: <http://www.nltk.org/> # For license information, see LICENSE.TXT from util import * """ Tsu bot responds to all queries with a Sun Tsu sayings Quoted from Sun Tsu's The Art of War Translated by LIONEL ...
(r'[V-Zv-z](.*)', ("It is a matter of life and death, a road either to safety or to ruin.", "Hold out baits to entice the enemy. Feign disorder, and crush him.", "All men can see the tactics whereby I conquer, but what none can see is the strategy out of which victory is evolved.", "Do not repeat the tactics...
"There are not more than five musical notes, yet the combinations of these five give rise to more melodies than can ever be heard.", "Appear at points which the enemy must hasten to defend; march swiftly to places where you are not expected.")),
random_line_split
processArgs-spec.js
const processArgs = require('../../../lib/update-markdown-from-config/processArgs') describe('processArgs', () => { it('is ok if --config-file and --markdown-file are present', (done) => { const processArgv = [ '/path/to/bin', '/path/of/node/script', '--markdown-file', 'config.json.md', '...
}) }) it('it is not ok if --markdown-file is not present', (done) => { const processArgv = [ '/path/to/bin', '/path/of/node/script', '--config-file', 'config.json' ] processArgs(processArgv).catch((err) => { const usageIndex = err.indexOf('update-markdown-from-config --config...
expect(usageIndex !== -1).toBe(true) done()
random_line_split
index.js
import { randomInt32 } from '@provably-fair/core'; /** * Shuffles an array based on the given seeds, using the given HMAC algorithm. * @param {[]} arr Array to be shuffled. * @param {string} hmacAlgorithm Algorithm used for computing the HMAC of the given seed pair. * @param {string|Buffer} secretSeed Secret seed ...
i + 1, hmacBufferUIntParser, fallbackProvider, ); // Exchange `result[i]` and `result[j]` [result[i], result[j]] = [result[j], result[i]]; } return result; }; export default shuffle;
random_line_split
index.js
import { randomInt32 } from '@provably-fair/core'; /** * Shuffles an array based on the given seeds, using the given HMAC algorithm. * @param {[]} arr Array to be shuffled. * @param {string} hmacAlgorithm Algorithm used for computing the HMAC of the given seed pair. * @param {string|Buffer} secretSeed Secret seed ...
return result; }; export default shuffle;
{ // Generate a random integer within [0, i] const j = randomInt32( hmacAlgorithm, secretSeed, `${publicSeed}-${i}`, 0, i + 1, hmacBufferUIntParser, fallbackProvider, ); // Exchange `result[i]` and `result[j]` [result[i], result[j]] = [result[j], result[i]]...
conditional_block
service.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
let io = IoContext::new(self.io_service.channel(), 0); let host = self.host.read(); host.as_ref().map(|ref host| host.with_context_eval(protocol, &io, action)) } } impl MayPanic for NetworkService { fn on_panic<F>(&self, closure: F) where F: OnPanicListener { self.panic_handler.on_panic(closure); } }
random_line_split
service.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
<F>(&self, closure: F) where F: OnPanicListener { self.panic_handler.on_panic(closure); } }
on_panic
identifier_name
service.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
/// Returns host identifier string as advertised to other peers pub fn host_info(&self) -> String { self.host_info.clone() } /// Returns underlying io service. pub fn io(&self) -> &IoService<NetworkIoMessage> { &self.io_service } /// Returns network statistics. pub fn stats(&self) -> &NetworkStats { &...
{ self.io_service.send_message(NetworkIoMessage::AddHandler { handler: handler, protocol: protocol, versions: versions.to_vec(), packet_count: packet_count, })?; Ok(()) }
identifier_body
service.rs
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any la...
else { Ok(()) } } /// Try to remove a reserved peer. pub fn remove_reserved_peer(&self, peer: &str) -> Result<(), NetworkError> { let host = self.host.read(); if let Some(ref host) = *host { host.remove_reserved_node(peer) } else { Ok(()) } } /// Set the non-reserved peer mode. pub fn set_no...
{ host.add_reserved_node(peer) }
conditional_block
cursor.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...
isplay: &gdk::Display, cursor_type: gdk::CursorType) -> Option<Cursor> { let tmp = unsafe { ffi::gdk_cursor_new_for_display(display.unwrap_pointer(), cursor_type) }; if tmp.is_null() { None } else { Some(Cursor { pointer: tmp }) } ...
w_for_display(d
identifier_name
cursor.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...
lse { Some(Cursor { pointer: tmp }) } } pub fn get_display(&self) -> Option<gdk::Display> { let tmp = unsafe { ffi::gdk_cursor_get_display(self.pointer) }; if tmp.is_null() { None } else { Some(gdk::Display::wrap_p...
None } e
conditional_block
cursor.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_image(&self) -> Option<gdk::Pixbuf> { let tmp = unsafe { ffi::gdk_cursor_get_image(self.pointer) }; if tmp.is_null() { None } else { Some(gdk::Pixbuf::wrap_pointer(tmp)) } }*/ pub fn get_cursor_type(&self) -> gdk::CursorType { un...
let tmp = unsafe { ffi::gdk_cursor_get_display(self.pointer) }; if tmp.is_null() { None } else { Some(gdk::Display::wrap_pointer(tmp)) } }
identifier_body
cursor.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...
if tmp.is_null() { None } else { Some(Cursor { pointer: tmp }) } } /*pub fn new_from_pixbuf(display: &gdk::Display, pixbuf: &gdk::Pixbuf, x: i32, y: i32) -> Option<Cursor> { let tmp = unsafe { ffi::gdk_cursor_new_from_pixbuf(d...
let tmp = unsafe { ffi::gdk_cursor_new(cursor_type) };
random_line_split
usePopper.test.js
// @flow strict import { renderHook, act } from '@testing-library/react-hooks'; import * as PopperJs from '@popperjs/core'; // Public API import { usePopper } from '.'; const referenceElement = document.createElement('div'); const popperElement = document.createElement('div'); describe('userPopper', () => { afterE...
usePopper(referenceElement, popperElement) ); await waitForNextUpdate(); const popperInstance = spy.mock.results[0].value; const destroy = jest.spyOn(popperInstance, 'destroy'); await unmount(); expect(destroy).toHaveBeenCalled(); }); it('Initializes the arrow positioning', async (...
}); it('destroys Popper on instance on unmount', async () => { const spy = jest.spyOn(PopperJs, 'createPopper'); const { waitForNextUpdate, unmount } = renderHook(() =>
random_line_split
quote-tokens.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
// ignore-android // ignore-pretty: does not work well with `--test` #![feature(quote)] extern crate syntax; use syntax::ext::base::ExtCtxt; use syntax::ptr::P; fn syntax_extension(cx: &ExtCtxt) { let e_toks : Vec<syntax::ast::TokenTree> = quote_tokens!(cx, 1 + 2); let p_toks : Vec<syntax::ast::TokenTree> ...
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms.
random_line_split
quote-tokens.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...
fn main() { }
{ let e_toks : Vec<syntax::ast::TokenTree> = quote_tokens!(cx, 1 + 2); let p_toks : Vec<syntax::ast::TokenTree> = quote_tokens!(cx, (x, 1 .. 4, *)); let a: P<syntax::ast::Expr> = quote_expr!(cx, 1 + 2); let _b: Option<P<syntax::ast::Item>> = quote_item!(cx, static foo : int = $e_toks; ); let _c: P<...
identifier_body
quote-tokens.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...
(cx: &ExtCtxt) { let e_toks : Vec<syntax::ast::TokenTree> = quote_tokens!(cx, 1 + 2); let p_toks : Vec<syntax::ast::TokenTree> = quote_tokens!(cx, (x, 1 .. 4, *)); let a: P<syntax::ast::Expr> = quote_expr!(cx, 1 + 2); let _b: Option<P<syntax::ast::Item>> = quote_item!(cx, static foo : int = $e_toks; );...
syntax_extension
identifier_name
MercurialHasRevisionRule.py
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify...
(AnsibleLintRule): id = 'hg-latest' shortdesc = 'Mercurial checkouts must contain explicit revision' description = ( 'All version control checkouts must point to ' 'an explicit commit or tag, not just ``latest``' ) severity = 'MEDIUM' tags = ['idempotency'] version_added = 'h...
MercurialHasRevisionRule
identifier_name
MercurialHasRevisionRule.py
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify...
id = 'hg-latest' shortdesc = 'Mercurial checkouts must contain explicit revision' description = ( 'All version control checkouts must point to ' 'an explicit commit or tag, not just ``latest``' ) severity = 'MEDIUM' tags = ['idempotency'] version_added = 'historic' def match...
identifier_body
MercurialHasRevisionRule.py
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify...
def matchtask( self, task: Dict[str, Any], file: 'Optional[Lintable]' = None ) -> Union[bool, str]: return bool( task['action']['__ansible_module__'] == 'hg' and task['action'].get('revision', 'default') == 'default' )
version_added = 'historic'
random_line_split
MercurialHasRevisionRule.py
# Copyright (c) 2013-2014 Will Thames <will@thames.id.au> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify...
class MercurialHasRevisionRule(AnsibleLintRule): id = 'hg-latest' shortdesc = 'Mercurial checkouts must contain explicit revision' description = ( 'All version control checkouts must point to ' 'an explicit commit or tag, not just ``latest``' ) severity = 'MEDIUM' tags = ['ide...
from typing import Optional from ansiblelint.file_utils import Lintable
conditional_block
test_optional_dependency.py
import sys import types import pytest from pandas.compat._optional import VERSIONS, import_optional_dependency import pandas._testing as tm def test_import_optional(): match = "Missing .*notapackage.* pip .* conda .* notapackage" with pytest.raises(ImportError, match=match): import_optional_depende...
def test_no_version_raises(monkeypatch): name = "fakemodule" module = types.ModuleType(name) sys.modules[name] = module monkeypatch.setitem(VERSIONS, name, "1.0.0") with pytest.raises(ImportError, match="Can't determine .* fakemodule"): import_optional_dependency(name)
name = "fakemodule" module = types.ModuleType(name) module.__version__ = "0.9.0" sys.modules[name] = module monkeypatch.setitem(VERSIONS, name, "1.0.0") match = "Pandas requires .*1.0.0.* of .fakemodule.*'0.9.0'" with pytest.raises(ImportError, match=match): import_optional_dependency("...
identifier_body
test_optional_dependency.py
import sys import types import pytest from pandas.compat._optional import VERSIONS, import_optional_dependency import pandas._testing as tm def test_import_optional(): match = "Missing .*notapackage.* pip .* conda .* notapackage" with pytest.raises(ImportError, match=match): import_optional_depende...
with tm.assert_produces_warning(UserWarning): result = import_optional_dependency("fakemodule", on_version="warn") assert result is None module.__version__ = "1.0.0" # exact match is OK result = import_optional_dependency("fakemodule") assert result is module def test_no_version_raises(m...
with pytest.raises(ImportError, match=match): import_optional_dependency("fakemodule")
random_line_split
test_optional_dependency.py
import sys import types import pytest from pandas.compat._optional import VERSIONS, import_optional_dependency import pandas._testing as tm def test_import_optional(): match = "Missing .*notapackage.* pip .* conda .* notapackage" with pytest.raises(ImportError, match=match): import_optional_depende...
(monkeypatch): name = "fakemodule" module = types.ModuleType(name) sys.modules[name] = module monkeypatch.setitem(VERSIONS, name, "1.0.0") with pytest.raises(ImportError, match="Can't determine .* fakemodule"): import_optional_dependency(name)
test_no_version_raises
identifier_name
freshen.rs
// Copyright 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-MIT or ...
fn fold_region(&mut self, r: ty::Region) -> ty::Region { match r { ty::ReEarlyBound(..) | ty::ReLateBound(..) => { // leave bound regions alone r } ty::ReStatic | ty::ReFree(_) | ty::ReScope(_) | ...
{ self.infcx.tcx }
identifier_body
freshen.rs
// Copyright 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-MIT or ...
(&mut self, t: Ty<'tcx>) -> Ty<'tcx> { if !ty::type_needs_infer(t) && !ty::type_has_erasable_regions(t) { return t; } let tcx = self.infcx.tcx; match t.sty { ty::TyInfer(ty::TyVar(v)) => { self.freshen( self.infcx.type_variabl...
fold_ty
identifier_name
freshen.rs
// Copyright 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-MIT or ...
//! Note that you should be careful not to allow the output of freshening to leak to the user in //! error messages or in any other form. Freshening is only really useful as an internal detail. //! //! __An important detail concerning regions.__ The freshener also replaces *all* regions with //! 'static. The reason beh...
random_line_split
0030_populate_postresult_post_election.py
from collections import defaultdict from django.db import migrations def set_post_election_from_post(apps, schema_editor): """ This is far from ideal. Try to guess the PostExtraElection that this PostResult relates to. This will have to be done by looking and the related memberships and assuming they...
if len(set(result_sets_by_election.keys())) == 1: election = result_sets_by_election.keys()[0] pee = PostExtraElection.objects.get( election=election, postextra=post_result.post.extra ) post_result.post_election = pee ...
is_election = candidate_result.membership.extra.election result_sets_by_election[this_election].append(result_set)
conditional_block
0030_populate_postresult_post_election.py
from collections import defaultdict from django.db import migrations def set_post_election_from_post(apps, schema_editor): """ This is far from ideal. Try to guess the PostExtraElection that this PostResult relates to. This will have to be done by looking and the related memberships and assuming they...
igrations.Migration): dependencies = [("uk_results", "0029_add_postresult_post_election")] operations = [migrations.RunPython(set_post_election_from_post)]
gration(m
identifier_name
0030_populate_postresult_post_election.py
from collections import defaultdict from django.db import migrations def set_post_election_from_post(apps, schema_editor): """ This is far from ideal. Try to guess the PostExtraElection that this PostResult relates to. This will have to be done by looking and the related memberships and assuming they...
if len(set(result_sets_by_election.keys())) == 1: election = result_sets_by_election.keys()[0] pee = PostExtraElection.objects.get( election=election, postextra=post_result.post.extra ) post_result.post_election = pee ...
for candidate_result in result_set.candidate_results.all(): this_election = candidate_result.membership.extra.election result_sets_by_election[this_election].append(result_set)
random_line_split
0030_populate_postresult_post_election.py
from collections import defaultdict from django.db import migrations def set_post_election_from_post(apps, schema_editor): """ This is far from ideal. Try to guess the PostExtraElection that this PostResult relates to. This will have to be done by looking and the related memberships and assuming they...
pendencies = [("uk_results", "0029_add_postresult_post_election")] operations = [migrations.RunPython(set_post_election_from_post)]
identifier_body
date_picker.js
document.on('click', 'div.date_picker', function(e, element) { var field = element.down('input') var label = element.down('span') var parentDiv = element.up('div') var date_picker = DatePicker.initialize(field, label, parentDiv); if (element.hasClassName("show_urgent")) { DatePicker.add_urgent_box(date_pi...
date_picker.close(); } else { date_picker.calendar_div.select("> div").each(function(div) { if (!div.hasClassName("cds_top")) { div[input_urgent.checked ? "hide" : "show"](); } }); } date_picker.positionCalendarDiv(); } v...
date_picker.callback("onchange"); label.update(I18n.translations.date_picker.no_date_assigned); } if (user_action && input_urgent.checked) {
random_line_split
bcm_host.py
# vim: set et sw=4 sts=4 fileencoding=utf-8: # # Python header conversion # Copyright (c) 2013,2014 Dave Hughes <dave@waveform.org.uk> # # Original headers # Copyright (c) 2012, Broadcom Europe Ltd # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitte...
# # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FO...
random_line_split
connection.py
import socket try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: from select import select except ImportError: # `select` doesn't exist on AppEngine. select = False def is_connection_dropped(conn): # Platform-...
if options is None: return for opt in options: sock.setsockopt(*opt)
identifier_body
connection.py
import socket try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: from select import select except ImportError: # `select` doesn't exist on AppEngine. select = False def is_connection_dropped(conn): # Platform-...
raise socket.error("getaddrinfo returns an empty list") def _set_socket_options(sock, options): if options is None: return for opt in options: sock.setsockopt(*opt)
raise err
conditional_block
connection.py
import socket try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: from select import select except ImportError: # `select` doesn't exist on AppEngine. select = False def is_connection_dropped(conn): # Platform-...
if options is None: return for opt in options: sock.setsockopt(*opt)
def _set_socket_options(sock, options):
random_line_split
connection.py
import socket try: from select import poll, POLLIN except ImportError: # `poll` doesn't exist on OSX and other platforms poll = False try: from select import select except ImportError: # `select` doesn't exist on AppEngine. select = False def is_connection_dropped(conn): # Platform-...
(sock, options): if options is None: return for opt in options: sock.setsockopt(*opt)
_set_socket_options
identifier_name
dateformat.py
(?<!\\)([aAbBcdDfFgGhHiIjlLmMnNOPrsStTUuwWyYzZ])') re_escaped = re.compile(r'\\(.)') class Formatter(object): def format(self, formatstr): pieces = [] for i, piece in enumerate(re_formatchars.split(force_unicode(formatstr))): if i % 2: pieces.append(force_unicode(getattr...
(self): "Minutes; i.e. '00' to '59'" return u'%02d' % self.data.minute def P(self): """ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'mi...
i
identifier_name
dateformat.py
TUuwWyYzZ])') re_escaped = re.compile(r'\\(.)') class Formatter(object): def format(self, formatstr): pieces = [] for i, piece in enumerate(re_formatchars.split(force_unicode(formatstr))): if i % 2: pieces.append(force_unicode(getattr(self, piece)())) elif pi...
random_line_split
dateformat.py
"'a.m.' or 'p.m.'" if self.data.hour > 11: return _('p.m.') return _('a.m.') def A(self): "'AM' or 'PM'" if self.data.hour > 11: return _('PM') return _('AM') def B(self): "Swatch Internet time" raise NotImplementedError ...
doy += 1
conditional_block
dateformat.py
(?<!\\)([aAbBcdDfFgGhHiIjlLmMnNOPrsStTUuwWyYzZ])') re_escaped = re.compile(r'\\(.)') class Formatter(object): def format(self, formatstr): pieces = [] for i, piece in enumerate(re_formatchars.split(force_unicode(formatstr))): if i % 2: pieces.append(force_unicode(getattr...
def d(self): "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'" return u'%02d' % self.data.day def D(self): "Day of the week, textual, 3 letters; e.g. 'Fri'" return WEEKDAYS_ABBR[self.data.weekday()] def F(self): "Month, textual, long; e.g. 'Januar...
""" ISO 8601 Format Example : '2008-01-02T10:30:00.000123' """ return self.data.isoformat()
identifier_body
app.component.ts
import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from 'angular2/router'; import {DashboardComponent} from './dashboard.component'; import {BoardContentComponent} from './board-content.component'; import {ListContentComponent} from './list-content.component'; import {Bo...
{ title = 'Task Management System'; }
AppComponent
identifier_name
app.component.ts
import {Component} from 'angular2/core'; import {RouteConfig, ROUTER_DIRECTIVES, ROUTER_PROVIDERS} from 'angular2/router'; import {DashboardComponent} from './dashboard.component'; import {BoardContentComponent} from './board-content.component'; import {ListContentComponent} from './list-content.component'; import {Bo...
}, { path: '/board/:boardTitle/list/:listTitle', name: 'ListContent', component: ListContentComponent } ]) export class AppComponent { title = 'Task Management System'; }
name: 'BoardContent', component: BoardContentComponent
random_line_split
test-returns.ts
import * as _ from 'lodash'; import * as assert from 'assert'; import * as request from 'request'; import * as web from '../dist/index'; import { app, baseUrl } from './test-base'; var localBaseUrl = baseUrl + 'returns/'; @web.Controller('returns') @web.Public() class ReturnsTestController extends web.AdvancedCont...
} describe('ReturnsTestController', () => { let mainController: ReturnsTestController; let generalAssert = (err, res) => { assert(!err); assert.equal(res.statusCode, 200); }; before(() => { mainController = new ReturnsTestController(); mainController.register(app, { implicitAccess: true }); }); it('...
{ await new Promise((resolve, reject) => setTimeout(() => reject(new Error('Catch me async!')), 100) ); }
identifier_body
test-returns.ts
import * as _ from 'lodash'; import * as assert from 'assert'; import * as request from 'request'; import * as web from '../dist/index'; import { app, baseUrl } from './test-base'; var localBaseUrl = baseUrl + 'returns/'; @web.Controller('returns') @web.Public() class ReturnsTestController extends web.AdvancedCont...
(@web.Res() res: web.Response) { await new Promise((resolve, reject) => setTimeout(() => reject(new Error('Catch me async!')), 100) ); } } describe('ReturnsTestController', () => { let mainController: ReturnsTestController; let generalAssert = (err, res) => { assert(!err); assert.equal(res.statusCode, ...
getFailingAutoClosedAsnyc
identifier_name
test-returns.ts
import * as _ from 'lodash'; import * as assert from 'assert'; import * as request from 'request'; import * as web from '../dist/index'; import { app, baseUrl } from './test-base'; var localBaseUrl = baseUrl + 'returns/'; @web.Controller('returns') @web.Public() class ReturnsTestController extends web.AdvancedCont...
} @web.Get('get-promise-rejected') getPromiseRejected( @web.Query('code', Number) code: number ) { return new Promise((resolve, reject) => { setTimeout(() => { reject({ statusCode: code}); }, 20); }); } @web.Get('failing-autoclosed') getFailingAutoClosed(@web.Res() res: web.Response) { throw ...
}, 20); });
random_line_split
QueryLogic.py
# -*- coding: UTF-8 -*- import re def mgo_text_split(query_text): ''' split text to support mongodb $text match on a phrase ''' sep = r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]' word_lst = re.split(sep, query_text) text_query = ' '.join('\"{}\"'.format(w) for w in word_lst) return text_query # 搜...
query = {} if len(list) > 1 or len(list[0].split(':')) > 1: for _ in list: if _.find(':') > -1: q_key, q_value = _.split(':', 1) if q_key == 'port': query['port'] = int(q_value) elif q_key == 'banner': zh...
ic(list):
identifier_name
QueryLogic.py
# -*- coding: UTF-8 -*- import re def mgo_text_split(query_text): ''' split text to support mongodb $text match on a phrase ''' sep = r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]' word_lst = re.split(sep, query_text) text_query = ' '.join('\"{}\"'.format(w) for w in word_lst) return text_query # 搜...
query['server'] = q_value.lower() elif q_key == 'title': query['webinfo.title'] = {"$regex": q_value, '$options': 'i'} elif q_key == 'tag': query['webinfo.tag'] = q_value.lower() elif q_key == 'hostname': ...
{} if len(list) > 1 or len(list[0].split(':')) > 1: for _ in list: if _.find(':') > -1: q_key, q_value = _.split(':', 1) if q_key == 'port': query['port'] = int(q_value) elif q_key == 'banner': zhPattern = re...
identifier_body
QueryLogic.py
# -*- coding: UTF-8 -*- import re def mgo_text_split(query_text): ''' split text to support mongodb $text match on a phrase ''' sep = r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]' word_lst = re.split(sep, query_text) text_query = ' '.join('\"{}\"'.format(w) for w in word_lst) return text_query # 搜...
if q_key == 'port': query['port'] = int(q_value) elif q_key == 'banner': zhPattern = re.compile(u'[\u4e00-\u9fa5]+') contents = q_value match = zhPattern.search(contents) # 如果没有中文用全文索引 ...
if len(list) > 1 or len(list[0].split(':')) > 1: for _ in list: if _.find(':') > -1: q_key, q_value = _.split(':', 1)
random_line_split
QueryLogic.py
# -*- coding: UTF-8 -*- import re def mgo_text_split(query_text): ''' split text to support mongodb $text match on a phrase ''' sep = r'[`\-=~!@#$%^&*()_+\[\]{};\'\\:"|<,./<>?]' word_lst = re.split(sep, query_text) text_query = ' '.join('\"{}\"'.format(w) for w in word_lst) return text_query # 搜...
'title': query['webinfo.title'] = {"$regex": q_value, '$options': 'i'} elif q_key == 'tag': query['webinfo.tag'] = q_value.lower() elif q_key == 'hostname': query['hostname'] = {"$regex": q_value, '$options': 'i'} ...
r() elif q_key ==
conditional_block
tooltip.d.ts
/// <reference path="./common.d.ts" /> declare namespace M { class
extends Component<TooltipOptions> implements Openable { /** * Get Instance */ static getInstance(elem: Element): Tooltip; /** * Init Tooltip */ static init(els: Element, options?: Partial<TooltipOptions>): Tooltip; /** * Init Toolti...
Tooltip
identifier_name
tooltip.d.ts
/// <reference path="./common.d.ts" /> declare namespace M { class Tooltip extends Component<TooltipOptions> implements Openable { /** * Get Instance */ static getInstance(elem: Element): Tooltip; /** * Init Tooltip */ static init(els: Element, o...
* Can take regular text or HTML strings. * @default null */ html: string; /** * Set distance tooltip appears away from its activator excluding transitionMovement. * @default 5 */ margin: number; /** * Enter transition durat...
* @default 200 */ enterDelay: number; /**
random_line_split
lib.rs
//! Huffman //! //! A library for huffman coding written in Rust. //! extern crate bit_vec; mod encode; mod decode; use bit_vec::BitVec; use std::collections::HashMap; pub use encode::*; pub use decode::*; /// Alias for the type of frequency. pub type Frequency = usize; /// Alias for the hashmap pub type BinMap = H...
() { // "Hello" should yield: {'H': 1, 'e': 1, 'l': 2, 'o': 3} let message = b"Hello"; let freq_map = freq_analysis(message); assert_eq!(freq_map.len(), 4); assert_eq!(freq_map[&b'H'], 1); assert_eq!(freq_map[&b'e'], 1); assert_eq!(freq_map[&b'l'], 2); a...
test_freq_analysis
identifier_name