file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
lib.rs
struct Lexer<'a> { src: &'a [u8], pos: usize } impl<'a> Lexer<'a> { fn new(src: &'a [u8]) -> Lexer
} impl<'a> Lexer<'a> { fn ch(&self) -> u8 { self.src[self.pos] } fn eof(&self) -> bool { self.pos >= self.src.len() } fn skip_ws(&mut self) -> usize { let prev_pos = self.pos; while self.valid_ws() { self.pos += 1; } self.pos - prev_pos } fn string(&mut self) -> Option<String> { let mut tok...
{ Lexer { src: src, pos: 0 } }
identifier_body
lib.rs
struct Lexer<'a> { src: &'a [u8], pos: usize } impl<'a> Lexer<'a> { fn new(src: &'a [u8]) -> Lexer { Lexer { src: src, pos: 0 } } } impl<'a> Lexer<'a> { fn ch(&self) -> u8 { self.src[self.pos] } fn eof(&self) -> bool { self.pos >= self.src.len() } fn skip_ws(&mut self) -> usize { let prev_pos = sel...
match self.ch() { b' ' => break, b'\t' => break, b'\r' => break, b'\n' => break, b'"' => break, _ => () } tok.push(self.ch()); self.pos += 1; } match tok.len() { 0 => None, _ => Some(String::from_utf8(tok).unwrap()) } } fn quoted_string(&mut self) -> Option<Stri...
let mut tok = Vec::<u8>::new(); loop { if self.eof() { break }
random_line_split
FontLineShapeRenderer.js
Clazz.declarePackage ("org.jmol.render"); Clazz.load (["org.jmol.render.ShapeRenderer", "org.jmol.util.Point3f", "$.Point3i", "$.Vector3f"], "org.jmol.render.FontLineShapeRenderer", ["java.lang.Float", "org.jmol.constant.EnumAxesMode", "org.jmol.util.TextFormat"], function () { c$ = Clazz.decorateAsClass (function () {...
this.pointT3 = null; this.vectorT = null; this.vectorT2 = null; this.vectorT3 = null; this.tickInfo = null; this.draw000 = true; this.endcap = 3; Clazz.instantialize (this, arguments); }, org.jmol.render, "FontLineShapeRenderer", org.jmol.render.ShapeRenderer); Clazz.prepareFields (c$, function () { this.pt0 = new org...
this.pointT2 = null;
random_line_split
webpack.prod.config.js
const assign = require('object-assign'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const baseConfig = require('./webpack.base.config.js'); const config = Object.assign(baseConfig, {}); Object.assign = assign; // No hot reload, just straight compiling. // Keep this in sync with webpack.config....
test: /(\.scss|\.css)$/, use: ExtractTextPlugin.extract({ fallback: 'style-loader', use: [ 'css-loader', 'sass-loader', ], }), }); module.exports = config;
}); // Extract all the sass and scss into a separate file. config.plugins.push(new ExtractTextPlugin('styles.css')); config.module.rules.push({
random_line_split
Eventhandler.ts
/** * kreXX: Krumo eXXtended * * kreXX is a debugging tool, which displays structured information * about any PHP object. It is a nice replacement for print_r() or var_dump() * which are used by a lot of PHP developers. * * kreXX is a fork of Krumo, which was originally written by: * Kaloyan K. Tsvetkov <kaloya...
el.dispatchEvent(event); } }
let event:Event = new Event(eventName, {bubbles: true,cancelable: false});
random_line_split
Eventhandler.ts
/** * kreXX: Krumo eXXtended * * kreXX is a debugging tool, which displays structured information * about any PHP object. It is a nice replacement for print_r() or var_dump() * which are used by a lot of PHP developers. * * kreXX is a fork of Krumo, which was originally written by: * Kaloyan K. Tsvetkov <kaloya...
/** * Whenever a click is bubbled on a kreXX instance, we try to find * the according callback, and simply call it. * * @param {Event} event * @event click */ protected handle = (event:Event): void => { // We stop the event in its tracks. event.stopPropagation...
{ if (!(selector in this.storage)) { this.storage[selector] = []; } this.storage[selector].push(callback); }
identifier_body
Eventhandler.ts
/** * kreXX: Krumo eXXtended * * kreXX is a debugging tool, which displays structured information * about any PHP object. It is a nice replacement for print_r() or var_dump() * which are used by a lot of PHP developers. * * kreXX is a fork of Krumo, which was originally written by: * Kaloyan K. Tsvetkov <kaloya...
(selector:string) { this.kdt = new Kdt(); // Register the event handler. let elements:NodeList = document.querySelectorAll(selector); for (let i = 0; i < elements.length; i++) { elements[i].addEventListener('click', this.handle); } } /** * Adds an e...
constructor
identifier_name
Eventhandler.ts
/** * kreXX: Krumo eXXtended * * kreXX is a debugging tool, which displays structured information * about any PHP object. It is a nice replacement for print_r() or var_dump() * which are used by a lot of PHP developers. * * kreXX is a fork of Krumo, which was originally written by: * Kaloyan K. Tsvetkov <kaloya...
} while (element !== null && typeof (element as Element).matches === 'function'); }; /** * Triggers an event on an element. * * @param {Element} el * @param {string} eventName */ public triggerEvent(el:Element, eventName:string): void { /** @type {Event} */ ...
{ element = null; }
conditional_block
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}",...
(source:&str)->Vec<u8>{ DecodeBytes(source.as_bytes()) } // Convert byte to base64 rep fn BaseIndex(index:u8) -> u8 { match index { 62 => {b'+'} 63 => {b'/'} 0..25 => { b'A' + index } 26..51 => { b'a' + index - 26 } _ => { b'0'...
DecodeStr
identifier_name
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}",...
} } // Some tests fn main() { let mut encoded = ::Base64::EncodeStr("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"); ::Base64::Debug::PrintBytes(encoded); let mut decoded = ::Base64::DecodeStr("TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVy...
b'a'..b'z' => { 26 + source - b'a'} b'0'..b'9' => { 52 + source - b'0'} _ => { 0 } }
random_line_split
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}",...
// Convert base64 rep to byte fn BaseIndexToByte(source:u8)->u8{ match source { b'+' => { 62 } b'/' => { 63 } b'A'..b'Z' => { source - b'A'} b'a'..b'z' => { 26 + source - b'a'} b'0'..b'9' => { 52 + source - b'0'} _ => { 0 } ...
{ match index { 62 => {b'+'} 63 => {b'/'} 0..25 => { b'A' + index } 26..51 => { b'a' + index - 26 } _ => { b'0' + index - 52 } } }
identifier_body
base64.rs
#[allow(non_snake_case_functions)] #[allow(unnecessary_parens)] // Author - Vikram // Contact - @TheVikO_o // License - MIT mod Base64 { // Debug Module pub mod Debug { use std::str; // Print bytes as UTF-8 string pub fn PrintBytes(data: Vec<u8>) { println!("{}",...
i += 3; } output } // Encode str pub fn EncodeStr(source: &str) -> Vec<u8> { EncodeBytes(source.as_bytes()) } // Decode array of u8 bytes pub fn DecodeBytes(source:&[u8]) -> Vec<u8> { let bytes = source; ...
{ output.push(BaseIndex(((bytes[i] & 0b11) << 4))); output.push(b'='); output.push(b'='); }
conditional_block
objectClassificationDataExportGui.py
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # mod...
@property def gui_applet(self): return self.parentApplet def get_raw_shape(self): return self.get_exporting_operator().RawImages.meta.shape def get_feature_names(self): return self.get_exporting_operator().ComputedFeatureNames([]).wait() def _initAppletDrawerUic(self): ...
return "Export Object Information"
identifier_body
objectClassificationDataExportGui.py
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # mod...
elif selection == "Object Probabilities": exportedLayers = self._initPredictionLayers(opLane.ImageOnDisk) for layer in exportedLayers: layer.visible = True layer.name = layer.name + "- Exported" layers += exportedLayers ...
fromDiskSlot = self.topLevelOperatorView.ImageOnDisk if fromDiskSlot.ready(): exportLayer = ColortableLayer( LazyflowSource(fromDiskSlot), colorTable=self._colorTable16 ) exportLayer.name = "Prediction - Exported" exportLayer.visible = True lay...
conditional_block
objectClassificationDataExportGui.py
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # mod...
@property def gui_applet(self): return self.parentApplet def get_raw_shape(self): return self.get_exporting_operator().RawImages.meta.shape def get_feature_names(self): return self.get_exporting_operator().ComputedFeatureNames([]).wait() def _initAppletDrawerUic(self): ...
def get_export_dialog_title(self): return "Export Object Information"
random_line_split
objectClassificationDataExportGui.py
############################################################################### # ilastik: interactive learning and segmentation toolkit # # Copyright (C) 2011-2014, the ilastik developers # <team@ilastik.org> # # This program is free software; you can redistribute it and/or # mod...
(self, opLane): return ObjectClassificationResultsViewer(self.parentApplet, opLane) def get_export_dialog_title(self): return "Export Object Information" @property def gui_applet(self): return self.parentApplet def get_raw_shape(self): return self.get_exporting_operato...
createLayerViewer
identifier_name
programList.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AppService } from '../services/app.service'; import { IProgram } from '../interfaces/program.interface'; @Component({ selector: 'ProgramList', template: ` <form> <div class="form-group"> <label for="pass">日付</label> <s...
new Date(); this.date = today.getFullYear() + '-' + ('00' + (today.getMonth() + 1)).slice(-2) + '-' + ('00' + today.getDate()).slice(-2) this.onChangeDate(); } private onChangeDate = () =>{ this.loading = true; this.appService.getPrograms(this.stationId, this.date).then((...
eList.push(tmp.getFullYear() + '-' + ('00' + (tmp.getMonth() + 1)).slice(-2) + '-' + ('00' + tmp.getDate()).slice(-2)); } let today =
conditional_block
programList.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AppService } from '../services/app.service'; import { IProgram } from '../interfaces/program.interface'; @Component({ selector: 'ProgramList', template: `
</select> </div> </form> <p *ngIf="loading">読み込み中です</p> <table class="table" *ngIf="!loading"> <tr *ngFor="let program of programs"> <th style="width:80px">{{program.start|date:'HH:mm'}} <td>{{program.title}}</td> <td class="text-right"> <button type...
<form> <div class="form-group"> <label for="pass">日付</label> <select name="date" [(ngModel)]="date" (change)="onChangeDate()"> <option *ngFor="let date of dateList" (value)="date">{{date}}</option>
random_line_split
programList.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AppService } from '../services/app.service'; import { IProgram } from '../interfaces/program.interface'; @Component({ selector: 'ProgramList', template: ` <form> <div class="form-group"> <label for="pass">日付</label> <s...
t = new Date(); start.setDate(start.getDate() -7); start.setHours(5); start.setMinutes(0); start.setSeconds(0); let end = new Date(); end.setDate(end.getDate() + 6 ); end.setHours(5); end.setMinutes(0); end.setSeconds(0); for(let tmp = start; tmp <= end ; tm...
let star
identifier_name
programList.component.ts
import { Component, Input, OnInit } from '@angular/core'; import { AppService } from '../services/app.service'; import { IProgram } from '../interfaces/program.interface'; @Component({ selector: 'ProgramList', template: ` <form> <div class="form-group"> <label for="pass">日付</label> <s...
angeDate = () =>{ this.loading = true; this.appService.getPrograms(this.stationId, this.date).then((programs:IProgram[])=>{ this.loading = false; programs.forEach((p)=>{ p.canRecording = new Date(p.end) < new Date(); }); this.programs = programs; }); } ...
= new Date(); start.setDate(start.getDate() -7); start.setHours(5); start.setMinutes(0); start.setSeconds(0); let end = new Date(); end.setDate(end.getDate() + 6 ); end.setHours(5); end.setMinutes(0); end.setSeconds(0); for(let tmp = start; tmp <= end ; tmp....
identifier_body
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0,
1 << 3, 1 << 29, 1 << 23, 1 << 17, 1 << 10, 1 << 4, 1 << 30, 1 << 24, 1 << 11, 1 << 05, 1 << 31, 1 << 25]; pub const BP_INIT: Bitboard = S[0] | S[1] | S[2] | S[3] | S[4] | S[5] | S[6] | S[7] | S[8] | S[9] | S[10] | S[11]; pub const WP_INIT: Bitboard =...
1 << 19, 1 << 13, 1 << 7, 1 << 1, 1 << 26, 1 << 20, 1 << 14, 1 << 8, 1 << 27, 1 << 21, 1 << 15, 1 << 9, 1 << 2, 1 << 28, 1 << 22, 1 << 16,
random_line_split
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0, ...
} // Maps from Bitboard indicating a position to the number // of that position itself pub fn bbumap(b: Bitboard) -> Bitboard { S.iter().position(|&x| x == b).unwrap() as u32 } #[inline] pub fn high_bit(mut board: Bitboard) -> Bitboard { board |= board >> 1; board |= board >> 2; board |= board >> 4; ...
{ *self != 0 }
identifier_body
bitboard.rs
// use std::num::Int; pub type Bitboard = u32; pub trait BitMove { fn up_left(&self) -> Self; fn up_right(&self) -> Self; fn down_left(&self) -> Self; fn down_right(&self) -> Self; fn is(&self) -> bool; } pub const S: [Bitboard; 32] = [ 1 << 18, 1 << 12, 1 << 6, 1 << 0, ...
(src: u16, dst: u16, jump: bool) -> Move { assert!(src < 32); assert!(dst < 32); Move { src: src, dst: dst, jump: jump, __dummy: () } } pub fn calc_direction(&self) -> Option<Direction> { let (src, dst) = (S[self.src as usize], S[self.dst as usize]); ...
new
identifier_name
common.py
from django.utils.encoding import force_text import re from django.utils import six from ginger import serializer from jinja2 import Markup __all__ = ['html_json', 'html_attrs', "Element", "CssClassList", "CssStyle", 'add_css_class', 'empty'] def html_json(values): content = serializer.encode(values) try: ...
def copy(self): el = self.__class__(self.tag) el.attrib = self.attrib.copy() el.children = self.children[:] return el def mutate(self, tag): el = tag.copy() el.attrib.update(self.attrib.copy()) el.children = self.children[:] return el def a...
el = self.copy() if not isinstance(item, (list, tuple)): item = [item] for c in item: el.append(c) return el
identifier_body
common.py
from django.utils.encoding import force_text import re from django.utils import six from ginger import serializer from jinja2 import Markup __all__ = ['html_json', 'html_attrs', "Element", "CssClassList", "CssStyle", 'add_css_class', 'empty'] def html_json(values): content = serializer.encode(values) try: ...
def render(self): return ";".join("%s:%s" % (key.replace("_", "-"), value) for (key, value) in six.iteritems(self)) def __str__(self): return self.render() def copy(self): return CssStyle(super(CssStyle, self).copy()) def _normalize(key): if key.endswith("_"): key = ...
return " ".join(str(c) for c in self.classes if c) class CssStyle(dict):
random_line_split
common.py
from django.utils.encoding import force_text import re from django.utils import six from ginger import serializer from jinja2 import Markup __all__ = ['html_json', 'html_attrs', "Element", "CssClassList", "CssStyle", 'add_css_class', 'empty'] def html_json(values): content = serializer.encode(values) try: ...
(self): value = CssClassList() value.classes.extend(self.classes) return value def append(self, value): if isinstance(value, six.text_type): value = re.sub(r'\s+', ' ', value.strip()) if len(value) == 1: value = value[0] if isinstance(...
copy
identifier_name
common.py
from django.utils.encoding import force_text import re from django.utils import six from ginger import serializer from jinja2 import Markup __all__ = ['html_json', 'html_attrs', "Element", "CssClassList", "CssStyle", 'add_css_class', 'empty'] def html_json(values): content = serializer.encode(values) try: ...
else: self.attrs[key] = value def update(self, *args, **attrs): values = {} values.update(*args, **attrs) for k, v in values.items(): self.set(k, v) def __iter__(self): for k, v in six.iteritems(self.attrs): yield k, v if sel...
self.styles.update(value)
conditional_block
Forwarding.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ver...
(self): while 1: self.send(str(self.value), "outbox") time.sleep(self.sleep) Backplane("broadcast").activate() Pipeline( Source(), SubscribeTo("broadcast"), ConsoleEchoer(), ).activate() Pipeline( ConsoleReader(), PublishTo("broadcast", forwarder=True), Console...
main
identifier_name
Forwarding.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ver...
from Kamaelia.Util.Backplane import * from Kamaelia.Util.Console import * from Kamaelia.Chassis.Pipeline import Pipeline class Source(Axon.ThreadedComponent.threadedcomponent): value = 1 sleep = 1 def main(self): while 1: self.send(str(self.value), "outbox") time.sleep(self....
import time import Axon
random_line_split
Forwarding.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ver...
Backplane("broadcast").activate() Pipeline( Source(), SubscribeTo("broadcast"), ConsoleEchoer(), ).activate() Pipeline( ConsoleReader(), PublishTo("broadcast", forwarder=True), ConsoleEchoer(), ).run()
value = 1 sleep = 1 def main(self): while 1: self.send(str(self.value), "outbox") time.sleep(self.sleep)
identifier_body
Forwarding.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1) # # (1) Kamaelia Contributors are listed in the AUTHORS file and at # http://www.kamaelia.org/AUTHORS - please extend this file, # not this notice. # # Licensed under the Apache License, Ver...
Backplane("broadcast").activate() Pipeline( Source(), SubscribeTo("broadcast"), ConsoleEchoer(), ).activate() Pipeline( ConsoleReader(), PublishTo("broadcast", forwarder=True), ConsoleEchoer(), ).run()
self.send(str(self.value), "outbox") time.sleep(self.sleep)
conditional_block
SeqCal.js
function SeqCal()
SeqCal.prototype = Object.create(Plugin.prototype); SeqCal.prototype.constructor = SeqCal; function Day(obj) { Drawable.call(this); this.evts = obj; this.marked = false; this.fontSize = 10; this.h = 30; this.lvl = obj.length; this.label = this.evts.map(function(dt) { var dd = new Date(dt.date), h = dd.g...
{ Plugin.apply(this, arguments); Canvas.apply(this, Array.prototype.slice.call(arguments, 1)); var layout = new Layout(this.width, this.height); layout.padding = 10; this.addView(); var inpSize = 4; this.draw = function(param) { inpSize = arguments.length > 0 && "inpSize" in param ? Number(param.inpSize) : i...
identifier_body
SeqCal.js
function SeqCal() { Plugin.apply(this, arguments); Canvas.apply(this, Array.prototype.slice.call(arguments, 1)); var layout = new Layout(this.width, this.height); layout.padding = 10; this.addView(); var inpSize = 4; this.draw = function(param) { inpSize = arguments.length > 0 && "inpSize" in param ? Number(...
this.clear(); layout.clear(); var days = this.data.reduce(function(r, a) { var dt = new Date(a.date), date = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()); r[date.getTime()] = r[date.getTime()] || []; r[date.getTime()].push(a); return r; }, Object.create(null)); for (var i in days)...
{ return false; }
conditional_block
SeqCal.js
function
() { Plugin.apply(this, arguments); Canvas.apply(this, Array.prototype.slice.call(arguments, 1)); var layout = new Layout(this.width, this.height); layout.padding = 10; this.addView(); var inpSize = 4; this.draw = function(param) { inpSize = arguments.length > 0 && "inpSize" in param ? Number(param.inpSize) ...
SeqCal
identifier_name
SeqCal.js
function SeqCal() { Plugin.apply(this, arguments); Canvas.apply(this, Array.prototype.slice.call(arguments, 1)); var layout = new Layout(this.width, this.height); layout.padding = 10; this.addView(); var inpSize = 4; this.draw = function(param) { inpSize = arguments.length > 0 && "inpSize" in param ? Number(...
SeqCal.prototype.constructor = SeqCal; function Day(obj) { Drawable.call(this); this.evts = obj; this.marked = false; this.fontSize = 10; this.h = 30; this.lvl = obj.length; this.label = this.evts.map(function(dt) { var dd = new Date(dt.date), h = dd.getHours(); return h % 12; }).join(','); this.dra...
} } SeqCal.prototype = Object.create(Plugin.prototype);
random_line_split
screenshot.py
from lib.common import helpers class Module:
def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns the output as a .PNG.'), 'Background' ...
identifier_body
screenshot.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns ...
(self): script = """ function Get-Screenshot { param ( [Parameter(Mandatory = $False)] [string] $Ratio ) Add-Type -Assembly System.Windows.Forms; $ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen; $ScreenshotObject = New-Object Drawing.Bit...
generate
identifier_name
screenshot.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns ...
return script
script += " -" + str(option) + " " + str(values['Value'])
conditional_block
screenshot.py
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-Screenshot', 'Author': ['@obscuresec', '@harmj0y'], 'Description': ('Takes a screenshot of the current desktop and ' 'returns ...
'Description' : 'Agent to run module on.', 'Required' : True, 'Value' : '' }, 'Ratio' : { 'Description' : "JPEG Compression ratio: 1 to 100.", 'Required' : False, 'Valu...
random_line_split
sitemap-helpers.js
const libxmljs2 = require('libxmljs2'); const fetch = require('node-fetch'); const E2eHelpers = require('../../../testing/e2e/helpers'); const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap.xml`; const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'; const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//; const pag...
() { return fetch(SITEMAP_URL) .then(res => res.text()) .then(body => libxmljs2.parseXml(body)) .then(doc => doc .find('//xmlns:loc', SITEMAP_LOC_NS) .map(n => n.text().replace(DOMAIN_REGEX, `${E2eHelpers.baseUrl}/`)) .filter(shouldIgnore), ) .then(urls => { con...
sitemapURLs
identifier_name
sitemap-helpers.js
const libxmljs2 = require('libxmljs2'); const fetch = require('node-fetch'); const E2eHelpers = require('../../../testing/e2e/helpers'); const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap.xml`; const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'; const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//; const pag...
module.exports = { sitemapURLs };
{ return fetch(SITEMAP_URL) .then(res => res.text()) .then(body => libxmljs2.parseXml(body)) .then(doc => doc .find('//xmlns:loc', SITEMAP_LOC_NS) .map(n => n.text().replace(DOMAIN_REGEX, `${E2eHelpers.baseUrl}/`)) .filter(shouldIgnore), ) .then(urls => { const ...
identifier_body
sitemap-helpers.js
const libxmljs2 = require('libxmljs2'); const fetch = require('node-fetch'); const E2eHelpers = require('../../../testing/e2e/helpers'); const SITEMAP_URL = `${E2eHelpers.baseUrl}/sitemap.xml`; const SITEMAP_LOC_NS = 'http://www.sitemaps.org/schemas/sitemap/0.9'; const DOMAIN_REGEX = /http[s]?:\/\/(.*?)\//; const pag...
// 404 page contains 2 search auto-suggest elements with the same element ID, // which violates WCAG 2.0 standards. This element id is referenced by // https://search.usa.gov/assets/sayt_loader_libs.js, so if we change the ID // of one of the elements, search won't work. '/404.ht...
.then(urls => { const onlyTest508Rules = [
random_line_split
evaluation_parameters.py
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, ...
except ParseException as e: logger.debug( f"Parse exception while parsing evaluation parameter: {str(e)}" ) raise EvaluationParameterError(f"No value found for $PARAMETER {str(L[0])}") except AttributeError: logger.warning("Unable to get s...
logger.error( "Unrecognized urn_type in ge_urn: must be 'stores' to use a metric store." ) raise EvaluationParameterError( f"No value found for $PARAMETER {str(L[0])}" )
conditional_block
evaluation_parameters.py
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, ...
def clear_stack(self): del self.exprStack[:] def get_parser(self): self.clear_stack() if not self._parser: # use CaselessKeyword for e and pi, to avoid accidentally matching # functions that start with 'e' or 'pi' (such as 'exp'); Keyword # and Case...
for t in toks: if t == "-": self.exprStack.append("unary -") else: break
identifier_body
evaluation_parameters.py
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, ...
exception_traceback = traceback.format_exc() exception_message = ( f'{type(e).__name__}: "{str(e)}". Traceback: "{exception_traceback}".' ) logger.debug(exception_message, e, exc_info=True) raise EvaluationParameterError( f"Error while evaluating evaluati...
result = convert_to_json_serializable(result) except Exception as e:
random_line_split
evaluation_parameters.py
import copy import datetime import logging import math import operator import traceback from collections import namedtuple from typing import Any, Dict, Optional, Tuple from pyparsing import ( CaselessKeyword, Combine, Forward, Group, Literal, ParseException, Regex, Suppress, Word, ...
(self): self.clear_stack() if not self._parser: # use CaselessKeyword for e and pi, to avoid accidentally matching # functions that start with 'e' or 'pi' (such as 'exp'); Keyword # and CaselessKeyword only match whole words e = CaselessKeyword("E") ...
get_parser
identifier_name
sysPage.js
angular.module('classeur.optional.sysPage', []) .config( function ($routeProvider) { $routeProvider .when('/sys', { template: '<cl-sys-page></cl-sys-page>', controller: function (clAnalytics) { clAnalytics.trackPage('/sys') } }) }) .directive('...
() { $http.get('/api/v1/config/app', { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function (res) { scope.properties = Object.keys(res).sort().cl_map(function (key) { return { key: key, value: r...
retrieveConfig
identifier_name
sysPage.js
angular.module('classeur.optional.sysPage', []) .config( function ($routeProvider) { $routeProvider .when('/sys', { template: '<cl-sys-page></cl-sys-page>', controller: function (clAnalytics) { clAnalytics.trackPage('/sys') } }) }) .directive('...
properties[property.key] = property.value }) ) { return } $http.post('/api/v1/config/app', properties, { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function () { clToast('App config updat...
{ clToast('Duplicate property: ' + property.key + '.') return true }
conditional_block
sysPage.js
angular.module('classeur.optional.sysPage', []) .config( function ($routeProvider) { $routeProvider .when('/sys', { template: '<cl-sys-page></cl-sys-page>', controller: function (clAnalytics) { clAnalytics.trackPage('/sys') } }) }) .directive('...
clToast('Error: ' + (err && err.message) || 'unknown') }) } function retrieveConfig () { $http.get('/api/v1/config/app', { headers: clSocketSvc.makeAuthorizationHeader() }) .success(function (res) { scope.properties = O...
}) .error(function (err) {
random_line_split
sysPage.js
angular.module('classeur.optional.sysPage', []) .config( function ($routeProvider) { $routeProvider .when('/sys', { template: '<cl-sys-page></cl-sys-page>', controller: function (clAnalytics) { clAnalytics.trackPage('/sys') } }) }) .directive('...
})
{ scope.properties = [] scope.deleteRow = function (propertyToDelete) { scope.properties = scope.properties.cl_filter(function (property) { return property !== propertyToDelete }) } scope.addRow = function () { scope.properties.push({}) }...
identifier_body
TravelRecommendation_faster.py
#!/usr/bin/python """ Copyright 2015 Ericsson AB 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 writi...
(MAX_COORDINATE - MIN_COORDINATE)) return new_value /2 def lat_normalizer(value): new_value = float((float(value) - MIN_LATITUDE) / (MAX_LATITUDE - MIN_LATITUDE)) return new_value def lon_normalizer(value): new_value = float((float(value) - MIN_LONGITUDE) / ...
new_value = float((float(value) - MIN_COORDINATE) /
random_line_split
TravelRecommendation_faster.py
#!/usr/bin/python """ Copyright 2015 Ericsson AB 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 writi...
(): route = get_today_timetable() waypoints = [] for res in route: for res1 in res['timetable']: for res2 in db2.BusTrip.find({'_id': res1}): for res3 in res2['trajectory']: for res4 in db2.BusStop.find({'_id':res3['busStop']}): ...
populate_timetable
identifier_name
TravelRecommendation_faster.py
#!/usr/bin/python """ Copyright 2015 Ericsson AB 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 writi...
def empty_past_recommendations(): db3.TravelRecommendation.drop() if __name__ == "__main__": user_ids = [] users = [] routes = [] user_ids = [] sc = SparkContext() populate_timetable() my_routes = sc.parallelize(routes, 8) my_routes = my_routes.map(lambda (x,y): (x, iterator(y)...
o_id = ObjectId() line = item[0] bus_id = item[1] start_place = item[2] end_place = item[3] start_time = item[5] end_time = item[6] bus_trip_id = item[7] request_time = "null" feedback = -1 request_id = "null" next_trip = "null" ...
conditional_block
TravelRecommendation_faster.py
#!/usr/bin/python """ Copyright 2015 Ericsson AB 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 writi...
def get_today_timetable(): TimeTable = db2.TimeTable first = datetime.datetime.today() first = first.replace(hour = 0, minute = 0, second = 0, microsecond = 0) route = TimeTable.find({'date': {'$gte': first}}) return route def populate_timetable(): route = get_today_timetable() waypoints ...
results = db2.TravelRequest.find() for res in results: dist = time_approximation(res['startPositionLatitude'], res['startPositionLongitude'], res['endPositionLatitude'], res['endPositionLongitude']) if...
identifier_body
nedb.repository.ts
import IModelRepository from '../engine/IModelRepository'; import Model from '../entities/model.entity'; import { IWhereFilter } from "../engine/filter/WhereFilter"; var DataStore = require('NeDb'); /** * This class is a simple implementation of the NeDB data storage. * @see https://github.com/louischatriot/nedb *...
; /** * Update multiple instances that match the where clause. * * @param: models Object * Object containing data to replace matching instances, if any. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ...} * see Where filter....
{}
identifier_body
nedb.repository.ts
import IModelRepository from '../engine/IModelRepository'; import Model from '../entities/model.entity'; import { IWhereFilter } from "../engine/filter/WhereFilter"; var DataStore = require('NeDb'); /** * This class is a simple implementation of the NeDB data storage. * @see https://github.com/louischatriot/nedb *...
(id, where?: IWhereFilter) {}; /** * Update multiple instances that match the where clause. * * @param: models Object * Object containing data to replace matching instances, if any. * @param: [where] IWhereFilter * Optional where filter, like { key: val, key2: {gt: 'val2'}, ......
updateById
identifier_name
nedb.repository.ts
import IModelRepository from '../engine/IModelRepository'; import Model from '../entities/model.entity'; import { IWhereFilter } from "../engine/filter/WhereFilter"; var DataStore = require('NeDb'); /** * This class is a simple implementation of the NeDB data storage. * @see https://github.com/louischatriot/nedb *...
let err = new Error('Please provide an id!'); // TODO: turn this into promise //callback(err, null); }; /** * Check whether a model instance exists in database. * * @param: id * Identifier of object (primary key value). * @param: modelName string *...
{ this.db.remove({ _id: id }, {}, (err, numRemoved) => { // TODO: turn this into promise //callback(err, numRemoved); }); }
conditional_block
nedb.repository.ts
import IModelRepository from '../engine/IModelRepository'; import Model from '../entities/model.entity'; import { IWhereFilter } from "../engine/filter/WhereFilter"; var DataStore = require('NeDb'); /** * This class is a simple implementation of the NeDB data storage. * @see https://github.com/louischatriot/nedb *...
// TODO: turn this into promise //callback(err, null); } }; /** * Update single model instance that match the where clause. * * @param: id * Primary key value * @param: [where] IWhereFilter * Optional where filter, like {} */ updat...
//callback(err, model); }); } else { let err = new Error('Please provide an id!');
random_line_split
lmcons.rs
// Copyright © 2015, Peter Atashian // Licensed under the MIT License <LICENSE.md> //! This file contains constants used throughout the LAN Manager API header files. pub const CNLEN: ::DWORD = 15; pub const LM20_CNLEN: ::DWORD = 15; pub const DNLEN: ::DWORD = CNLEN; pub const LM20_DNLEN: ::DWORD = LM20_CNLEN; pub const...
pub const PLATFORM_ID_NT: ::DWORD = 500; pub const PLATFORM_ID_OSF: ::DWORD = 600; pub const PLATFORM_ID_VMS: ::DWORD = 700;
pub type API_RET_TYPE = NET_API_STATUS; pub const PLATFORM_ID_DOS: ::DWORD = 300; pub const PLATFORM_ID_OS2: ::DWORD = 400;
random_line_split
termsetops.py
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("sel...
Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tsetdiff(a,b) from table1") tsetdiff(a,b) ------------- t1 t1 t2 """ if len(args) < 2: ...
def tsetdiff(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset
random_line_split
termsetops.py
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("sel...
(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tsetdiff(a,b) from table1") tsetdiff...
tsetdiff
identifier_name
termsetops.py
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("sel...
tsetdiff.registered = True def tsetcombinations(*args): """ .. function:: tsetcombinations(termset, r) -> termset Returns all the termset combinations of length r. It is a multiset operator that returns one column but many rows. .. seealso:: * :ref:`tutmultiset` functions >>> s...
""" .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("select tsetdiff(a,b) from table1") tsetdiff(a,b) ---...
identifier_body
termsetops.py
# coding: utf-8 import itertools def tset(*args): """ .. function:: termsetdiff(termset1, termset2) -> termset Returns the termset that is the difference of sets of termset1 - termset2. Examples: >>> table1(''' ... 't1 t2 t3' 't2 t3' ... 't3 t2 t1' 't3 t4' ... ''') >>> sql("sel...
""" This is needed to be able to test the function, put it at the end of every new function you create """ import sys from functions import * testfunction() if __name__ == "__main__": reload(sys) sys.setdefaultencoding('utf-8') import doctest doctest.testmod...
conditional_block
home.ts
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { ServiceProvider} from "../../providers/service/service"; import { ControlUserApp } from '../../control/ControlUserApp'; import { UserApp } from '../../model/UserApp'; @Component({ selector: 'page-home', templateUrl: ...
console.log('RETORNO DO SERVIDOR : ' +objeto_retorno); }, error=>{ console.log('Erro executado : '+error); }) } }
console.log('RETORNO DO SERVIDOR : ' +response); console.log('RETORNO DO SERVIDOR : ' +response._body); const objeto_retorno = JSON.parse(response._body);
random_line_split
home.ts
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { ServiceProvider} from "../../providers/service/service"; import { ControlUserApp } from '../../control/ControlUserApp'; import { UserApp } from '../../model/UserApp'; @Component({ selector: 'page-home', templateUrl: ...
{ constructor( public navCtrl: NavController, public movProvides: ServiceProvider, public controlUser: ControlUserApp, public userApp : UserApp ) {} gravarTeste(){ console.log('GRAVANDO DADOS'); //this.userApp = new UserApp(); //this.userApp.dsLogin = "OLA MUNDO"; //this...
HomePage
identifier_name
translate_smt.py
#! /usr/bin/env python import os import sys from barf.barf import BARF if __name__ == "__main__": # # Open file # try: filename = os.path.abspath("../../samples/toy/arm/branch4") barf = BARF(filename) except Exception as err: print err print "[-] Error opening fil...
# Some instructions cannot be translate to SMT, i.e, # UNKN, UNDEF, JCC. In those cases, an exception is # raised. smt_exprs = barf.smt_translator.translate(reil_instr) for smt_expr in smt_exprs: print("{0:16}{1}".forma...
try:
random_line_split
translate_smt.py
#! /usr/bin/env python import os import sys from barf.barf import BARF if __name__ == "__main__": # # Open file # try: filename = os.path.abspath("../../samples/toy/arm/branch4") barf = BARF(filename) except Exception as err: print err print "[-] Error opening fil...
except: pass
print("{0:16}{1}".format("", smt_expr))
conditional_block
lint-unused-imports.rs
// Copyright 2012 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 ...
(p: Point) -> int { return 2 * (p.x + p.y); } } #[allow(unused_imports)] mod foo { use std::cmp::Eq; } } fn main() { cal(foo::Point{x:3, y:9}); let mut a = 3; let mut b = 4; swap(&mut a, &mut b); test::C.b(); let _a = from_elem(0, 0); }
cc
identifier_name
lint-unused-imports.rs
// Copyright 2012 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 ...
// Make sure this import is warned about when at least one of its imported names // is unused use std::slice::{from_fn, from_elem}; //~ ERROR unused import mod test { pub trait A { fn a(&self) {} } pub trait B { fn b(&self) {} } pub struct C; impl A for C {} impl B for C {} } mod foo { pub s...
// counted as being used. use test::B;
random_line_split
omaps.py
from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os im...
class ModuleNotFound(Exception): def __init__(self, m): self.message = m def __str__(self): return self.message def setup(bot): global geotiler global Color, Drawing, display, Image, Color, Image, COMPOSITE_OPERATORS global BeautifulSoup check_folders() check_...
f not os.path.isfile(POINTER): print("pointer.png is missing!")
identifier_body
omaps.py
from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os im...
self): return self.message def setup(bot): global geotiler global Color, Drawing, display, Image, Color, Image, COMPOSITE_OPERATORS global BeautifulSoup check_folders() check_files() try: import geotiler except: raise ModuleNotFound("geotiler is not inst...
_str__(
identifier_name
omaps.py
from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os im...
from wand.color import Color except: raise ModuleNotFound("Wand is not installed. Do 'pip3 install Wand --upgrade' and make sure you have ImageMagick installed http://docs.wand-py.org/en/0.4.2/guide/install.html") bot.add_cog(OpenStreetMaps(bot))
random_line_split
omaps.py
from .utils.dataIO import fileIO from .utils import checks from __main__ import send_cmd_help from __main__ import settings as bot_settings # Sys. from operator import itemgetter, attrgetter import discord from discord.ext import commands #from copy import deepcopy import aiohttp import asyncio import json import os im...
# line 0 if len(str(line0)) > 2: draw.text(x=15, y=60, body=line0) draw(w) # line 1 if len(str(line1)) > 2: draw.text(x=15, y=80, body=line1) draw(w) # Copyright Open Street Map ...
if len(str(line0)) > 30: line1 = line1 + i + "," else: line0 = line0 + i + ","
conditional_block
itusozluk.py
# -*- coding: utf-8 -*- __author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi class ItusozlukBaslikSpider(GenericSozlukSpider): ...
def parse(self, response): self.log("PARSING: %s" % response.request.url, level=log.INFO) items_to_scrape = response.xpath('//*[@id="entry-list"]/li/article') if len(items_to_scrape) == 0: self.log("!!! No item to parse found. It may indicate a problem with HTML !!!", ...
super(ItusozlukBaslikSpider, self).__init__(**kwargs) self.allowed_domains = ['itusozluk.com']
identifier_body
itusozluk.py
# -*- coding: utf-8 -*- __author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi class ItusozlukBaslikSpider(GenericSozlukSpider): ...
(self, **kwargs): super(ItusozlukBaslikSpider, self).__init__(**kwargs) self.allowed_domains = ['itusozluk.com'] def parse(self, response): self.log("PARSING: %s" % response.request.url, level=log.INFO) items_to_scrape = response.xpath('//*[@id="entry-list"]/li/article') i...
__init__
identifier_name
itusozluk.py
# -*- coding: utf-8 -*- __author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi
class ItusozlukBaslikSpider(GenericSozlukSpider): name = 'itusozluk' def __init__(self, **kwargs): super(ItusozlukBaslikSpider, self).__init__(**kwargs) self.allowed_domains = ['itusozluk.com'] def parse(self, response): self.log("PARSING: %s" % response.request.url, level=log.I...
random_line_split
itusozluk.py
# -*- coding: utf-8 -*- __author__ = 'Eren Turkay <turkay.eren@gmail.com>' from scrapy import log from scrapy.http import Request from scrapy.exceptions import CloseSpider from datetime import datetime from . import GenericSozlukSpider from ..items import Girdi class ItusozlukBaslikSpider(GenericSozlukSpider): ...
current_url = response.request.url.split('/sayfa')[0] title_re = response.xpath('//title').re(r'sayfa (\d*)') current_page = int(title_re[0]) if title_re else 1 page_count = int(response.xpath('//a[@rel="last"]')[0].xpath('text()').extract()[0]) next_page = current_page + 1 ...
girdi_id = sel.xpath('./footer/div[@class="entrymenu"]/@data-info').extract()[0].split(',')[0] baslik_id = response.xpath('//*[@id="canonical_url"]/@value').re(r'--(\d*)')[0] baslik = response.xpath('//*[@id="title"]/a/text()').extract()[0] date = sel.xpath('./footer/div[2]/time/a/te...
conditional_block
test_errors.py
#! /usr/bin/env python # # test_errors.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the License, or ...
self.fail('wrong error message') # another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def suite(): suite = unittest.makeSuite(ErrorTestCase,'test') return suite if __name__ == "__main__": runner = uni...
nest.Create(-1) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownModelName" in info.__str__():
random_line_split
test_errors.py
#! /usr/bin/env python # # test_errors.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the License, or ...
# another error has been thrown, this is wrong except: self.fail('wrong error has been thrown') def test_UnknownNode(self): """Unknown node""" nest.ResetKernel() try: nest.Connect([99],[99]) self.fail('an error should hav...
self.fail('wrong error message')
conditional_block
test_errors.py
#! /usr/bin/env python # # test_errors.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the License, or ...
def test_DivisionByZero(self): """Division by zero""" nest.ResetKernel() try: nest.sr('1 0 div') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "DivisionByZ...
"""Stack underflow""" nest.ResetKernel() try: nest.sr('clear ;') self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "StackUnderflow" in info.__str__(): self.fail(...
identifier_body
test_errors.py
#! /usr/bin/env python # # test_errors.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST 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 2 of the License, or ...
(self): """Unknown model name""" nest.ResetKernel() try: nest.Create(-1) self.fail('an error should have risen!') # should not be reached except nest.NESTError: info = sys.exc_info()[1] if not "UnknownModelName" in info.__str__(): ...
test_UnknownModel
identifier_name
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use st...
ToComputedValue, ToCss, ToResolvedValue, ToShmem, )] #[repr(C, u8)] pub enum GenericSVGOpacity<OpacityType> { /// `<opacity-value>` Opacity(OpacityType), /// `context-fill-opacity` #[animation(error)] ContextFillOpacity, /// `context-stroke-opacity` #[animation(error)] Co...
PartialEq, Parse, SpecifiedValueInfo, ToAnimatedZero,
random_line_split
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use st...
() -> Self { Self { kind: SVGPaintKind::None, fallback: SVGPaintFallback::Unset, } } } /// An SVG paint value without the fallback. /// /// Whereas the spec only allows PaintServer to have a fallback, Gecko lets the /// context properties have a fallback as well. #[animation...
default
identifier_name
svg.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Generic types for CSS values in SVG use crate::parser::{Parse, ParserContext}; use cssparser::Parser; use st...
let fallback = input .try(|i| SVGPaintFallback::parse(context, i)) .unwrap_or(SVGPaintFallback::Unset); Ok(SVGPaint { kind, fallback }) } } /// An SVG length value supports `context-value` in addition to length. #[derive( Animate, Clone, ComputeSquaredDistance, ...
{ return Ok(SVGPaint { kind, fallback: SVGPaintFallback::Unset, }); }
conditional_block
rnn_char_windowing.py
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # -...
fontsize=20, y=1.5) plt.ylabel('Character List', fontsize=20) plot = plt.imshow(pred_act.T, cmap=plt.get_cmap('plasma')) fig.colorbar(plot, fraction=0.015, pad=0.04) plt.xticks(np.arange(len(char_data)-1), list(char_raw)[:-1], fontsize=15) plt.yticks(np.arange(len(char_list)), [idx_to_char[i] for i in range(...
fig, ax = plt.subplots() fig.set_size_inches(15,20) plt.title('Input Sequence', y=1.08, fontsize=20) plt.xlabel('Probability of Next Character(y) Given Current One(x)'+ '\n[window_size={}, accuracy={:.1f}]'.format(n_window, accuracy),
random_line_split
rnn_char_windowing.py
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # ...
# (total_batch) x (batch_size) x (window_size) x (dim) # total_batch is set to 1 (no mini-batch) x_new = x_batch.reshape((n_examples, window_size, x_batch.shape[2])) y_new = y_batch.reshape((n_examples, window_size, y_batch.shape[2])) return x_new, y_new, n_examples # In[4]: def RNN(x, weights, bia...
ch, y_batch = zip(*z) x_batch = np.array(x_batch) y_batch = np.array(y_batch)
conditional_block
rnn_char_windowing.py
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # ...
e((x.shape[0],1)) return x / sum_x pred = RNN(x_data, weights, biases) cost = tf.reduce_mean(tf.squared_difference(pred, y_data)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # In[5]: # Learning with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for ...
.nn.dynamic_rnn** - 'x' can have shape (batch)x(time)x(input_dim), if time_major=False or (time)x(batch)x(input_dim), if time_major=True - 'outputs' can have the same shape as 'x' (batch)x(time)x(input_dim), if time_major=False or (ti...
identifier_body
rnn_char_windowing.py
# coding: utf-8 # # Simple Character-level Language Model using vanilla RNN # 2017-04-21 jkang # Python3.5 # TensorFlow1.0.1 # # - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window) # - input: &nbsp;&nbsp;'hello_world_good_morning_see_you_hello_grea' # ...
,1)) return x / sum_x pred = RNN(x_data, weights, biases) cost = tf.reduce_mean(tf.squared_difference(pred, y_data)) optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # In[5]: # Learning with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(ma...
hape[0]
identifier_name
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); ...
() { let mut repl = REPL::new(); repl.test("if True then 1 else 0", Some("1")); repl.test("if False then 1 else 0", Some("0")); } #[test] fn records() { let mut repl = REPL::new(); repl.test("let record = { pi = 3.14, add1 = (+) 1.0 }", None); repl.test("record.pi", Some("3.14")); repl.t...
if_expressions
identifier_name
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); ...
#[test] fn assert() { let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); repl.test("assert False", None); }
{ let mut repl = REPL::new(); repl.test("let { assert } = import! std.test", None); }
identifier_body
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); ...
self.session.exp_string(self.prompt)?; Ok(()) } fn quit(&mut self) { self.quit_().unwrap_or_else(|err| panic!("{}", err)); } fn quit_(&mut self) -> Result<()> { let line: &'static str = ":q"; self.session.send_line(line)?; self.session.exp_string(line)?...
self.session.exp_string(string)?; }
random_line_split
rexpect.rs
#![cfg(unix)] extern crate rexpect; use std::process::Command; use rexpect::errors::*; use rexpect::session::{spawn_command, PtySession}; struct REPL { session: PtySession, prompt: &'static str, } impl REPL { fn new() -> REPL { let repl = REPL::new_().unwrap_or_else(|err| panic!("{}", err)); ...
self.session.exp_string(self.prompt)?; Ok(()) } fn quit(&mut self) { self.quit_().unwrap_or_else(|err| panic!("{}", err)); } fn quit_(&mut self) -> Result<()> { let line: &'static str = ":q"; self.session.send_line(line)?; self.session.exp_string(line)...
{ self.session.exp_string(string)?; }
conditional_block
variables_a.js
var searchData= [ ['page_5flinks',['PAGE_LINKS',['../classtemplates_1_1_settings_temp.html#a813be5a9356d17a9165b65f97b40aadc',1,'templates::SettingsTemp']]], ['page_5fprofile',['PAGE_PROFILE',['../classtemplates_1_1_settings_temp.html#a6dd91f0c75e530b35b11f4e6f7da5b89',1,'templates::SettingsTemp']]], ['page_5fsen...
['preview',['PREVIEW',['../classtemplates_1_1_get_badge_temp.html#a99aa8032b2d02e1841d39b0854e68053',1,'templates::GetBadgeTemp']]] ];
['post_5ftype_5fclass_5fjl',['POST_TYPE_CLASS_JL',['../class_inc_1_1_pages_1_1_admin.html#a6ac1dded84bc08a46965aad4dbf21b12',1,'Inc::Pages::Admin']]],
random_line_split
aspect_frame.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...
use glib::translate::ToGlibPtr; use gtk::cast::GTK_ASPECTFRAME; use gtk::{self, ffi}; use glib::to_gboolean; /// AspectFrame — A frame that constrains its child to a particular aspect ratio struct_Widget!(AspectFrame); impl AspectFrame { pub fn new(label: Option<&str>, x_align: f32, y_align: f32, ratio: f32, obe...
use libc::c_float;
random_line_split
aspect_frame.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...
mut self, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> () { unsafe { ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)); } ...
t(&
identifier_name
aspect_frame.rs
// This file is part of rgtk. // // rgtk is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // rgtk is distributed in the hop...
pub fn set(&mut self, x_align: f32, y_align: f32, ratio: f32, obey_child: bool) -> () { unsafe { ffi::gtk_aspect_frame_set(GTK_ASPECTFRAME(self.pointer), x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)...
let tmp_pointer = unsafe { ffi::gtk_aspect_frame_new(label.borrow_to_glib().0, x_align as c_float, y_align as c_float, ratio as c_float, to_gboolean(obey_child)) }; check_pointer!(tmp_pointer, AspectFrame) ...
identifier_body
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSp...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!( f, "{}", match self { MethodType::Unary => "MethodType::Unary", MethodType::ClientStreaming => "MethodType::ClientStreaming", MethodType::ServerStreaming => "MethodType::S...
fmt
identifier_name
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSp...
else if c == b'_' { pos = i; break; } else { meet_lower = true; if upper_len > 1 { // So it should be AAa pos = i - 1; break; } } } let s =...
{ if meet_lower { // So it should be AaA or aaA pos = i; break; } upper_len += 1; }
conditional_block
util.rs
// Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0. use std::fmt; use std::str; // A struct that divide a name into serveral parts that meets rust's guidelines. struct NameSpliter<'a> { name: &'a [u8], pos: usize, } impl<'a> NameSpliter<'a> { fn new(s: &str) -> NameSpliter { NameSp...
("async_request", "async_request"), ("createID", "create_id"), ("AsyncRClient", "async_r_client"), ("CreateIDForReq", "create_id_for_req"), ("Create_ID_For_Req", "create_id_for_req"), ("Create_ID_For__Req", "create_id_for_req"), ("ID", ...
#[test] fn test_snake_name() { let cases = vec![ ("AsyncRequest", "async_request"), ("asyncRequest", "async_request"),
random_line_split
setup.py
#!/usr/bin/python import os import sys extra_opts = {'test_suite': 'tests'} extra_deps = [] extra_test_deps = [] if sys.version_info[:2] == (2, 6):
try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages try: with open('README.rst', 'r') as fd: extra_opts['long_description'] = fd.read() except IOError: pass # Insta...
extra_deps.append('argparse') extra_deps.append('simplejson') extra_test_deps.append('unittest2') extra_opts['test_suite'] = 'unittest2.collector'
conditional_block