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
admin.py
grr_response_core.lib.rdfvalues import client as rdf_client from grr_response_core.lib.rdfvalues import client_action as rdf_client_action from grr_response_core.lib.rdfvalues import client_stats as rdf_client_stats from grr_response_core.lib.rdfvalues import flows as rdf_flows from grr_response_core.lib.rdfvalues imp...
class GetHostname(actions.ActionPlugin): """Retrieves the host name of the client.""" out_rdfvalues = [rdf_protodict.DataBlob] def Run(self, args): for res in GetHostnameFromClient(args): self.SendReply(res) class GetPlatformInfo(actions.ActionPlugin): """Retrieves platform information.""" out_r...
random_line_split
admin.py
grr_response_core.lib.rdfvalues import client as rdf_client from grr_response_core.lib.rdfvalues import client_action as rdf_client_action from grr_response_core.lib.rdfvalues import client_stats as rdf_client_stats from grr_response_core.lib.rdfvalues import flows as rdf_flows from grr_response_core.lib.rdfvalues imp...
(actions.ActionPlugin): """Updates configuration parameters on the client.""" in_rdfvalue = rdf_protodict.Dict UPDATABLE_FIELDS = {"Client.foreman_check_frequency", "Client.server_urls", "Client.max_post_size", "Client.max_out_queue", ...
UpdateConfiguration
identifier_name
admin.py
grr_response_core.lib.rdfvalues import client as rdf_client from grr_response_core.lib.rdfvalues import client_action as rdf_client_action from grr_response_core.lib.rdfvalues import client_stats as rdf_client_stats from grr_response_core.lib.rdfvalues import flows as rdf_flows from grr_response_core.lib.rdfvalues imp...
try: config_obj.Write() except (IOError, OSError): pass def Run(self, arg): """Does the actual work.""" try: if self.grr_worker.client.FleetspeakEnabled(): raise ValueError("Not supported on Fleetspeak enabled clients.") except AttributeError: pass smart_arg...
config_obj.Set(field, value)
conditional_block
admin.py
from grr_response_core.lib.rdfvalues import client as rdf_client from grr_response_core.lib.rdfvalues import client_action as rdf_client_action from grr_response_core.lib.rdfvalues import client_stats as rdf_client_stats from grr_response_core.lib.rdfvalues import flows as rdf_flows from grr_response_core.lib.rdfvalues...
return pytsk3.get_version() def GetYaraVersion(self): return yara.YARA_VERSION library_map = { "pytsk": GetPyTSKVersion, "TSK": GetTSKVersion, "cryptography": GetCryptographyVersion, "SSL": GetSSLVersion, "psutil": GetPSUtilVersion, "yara": GetYaraVersion, } error_...
"""Retrieves version information for installed libraries.""" in_rdfvalue = None out_rdfvalues = [rdf_protodict.Dict] def GetSSLVersion(self): return openssl.backend.openssl_version_text() def GetCryptographyVersion(self): return cryptography.__version__ def GetPSUtilVersion(self): return ".".jo...
identifier_body
cycloidal_curves.py
from turtle import * from math import * from os import system def save(): getcanvas().postscript(file=name+".ps") system("ps2pdf "+name+".ps "+name+".pdf") def quit(): Screen().bye() def hypotrochoid(R, r, d, iteration): x, y, up = 0, 0, 1 penup(); fillcolor("green") while iteration: theta = iteration/...
(): tp = textinput("Hypotrochoid or Epitrochoid","provide no input for an Epitrochoid, and any input for a Hypotrochoid") if tp: tp = "Hypotrochoid" else: tp = "Epitrochoid" R = numinput("Fixed circle", "Radius R between 10 and 290") r = numinput("Rolling circle", "Radius r between 10 and 290") d = numinput("Poin...
main
identifier_name
cycloidal_curves.py
from turtle import * from math import * from os import system def save(): getcanvas().postscript(file=name+".ps") system("ps2pdf "+name+".ps "+name+".pdf") def quit(): Screen().bye() def hypotrochoid(R, r, d, iteration): x, y, up = 0, 0, 1 penup(); fillcolor("green") while iteration: theta = iteration/...
iteration -= 5 end_fill() def epitrochoid(R, r, d, iteration): x, y, up = 0, 0, 1 penup(); fillcolor("green") while iteration: theta = iteration/180*pi x = (R+r) * cos(theta) - d * cos((R+r)/r*theta) y = (R+r) * sin(theta) - d * sin((R+r)/r*theta) goto(x,y) if up: pendown(); begin_fill(); up = 0 ...
pendown(); begin_fill(); up = 0
conditional_block
cycloidal_curves.py
from turtle import * from math import * from os import system def save(): getcanvas().postscript(file=name+".ps") system("ps2pdf "+name+".ps "+name+".pdf") def quit(): Screen().bye() def hypotrochoid(R, r, d, iteration): x, y, up = 0, 0, 1 penup(); fillcolor("green") while iteration: theta = iteration/...
if __name__ == '__main__': main(); done()
random_line_split
cycloidal_curves.py
from turtle import * from math import * from os import system def save():
def quit(): Screen().bye() def hypotrochoid(R, r, d, iteration): x, y, up = 0, 0, 1 penup(); fillcolor("green") while iteration: theta = iteration/180*pi x = (R-r) * cos(theta) + d * cos((R-r)/r*theta) y = (R-r) * sin(theta) - d * sin((R-r)/r*theta) goto(x,y) if up: pendown(); begin_fill(); up = 0...
getcanvas().postscript(file=name+".ps") system("ps2pdf "+name+".ps "+name+".pdf")
identifier_body
context-menu.js
.execCommand("paste"); }, null, config.btnList["paste"][1] ]); var currentTarget = target; var elmenus = []; var link = null; var table = null; var tr = null; var td = null; var img = null; function tableOperation(opcode) { tbo.buttonPress(editor, opcode); }; for (; target; target = target.parentNode) {...
; function documentClick(ev) { ev || (ev = window.event); if (!self.currentMenu) { alert(i18n["How did you get here? (Please report!)"]); return false; } var el = HTMLArea.is_ie ? ev.srcElement : ev.target; for (; el != null && el != self.currentMenu; el = el.parentNode); if (el == null) self.clos...
{ var r = { x: el.offsetLeft, y: el.offsetTop }; if (el.offsetParent) { var tmp = getPos(el.offsetParent); r.x += tmp.x; r.y += tmp.y; } return r; }
identifier_body
context-menu.js
config.btnList["TO-col-insert-before"][1] ], [ i18n["Insert Column After"], function() { tableOperation("TO-col-insert-after"); }, i18n["Insert a new column after the current one"], config.btnList["TO-col-insert-after"][1] ], [ i18n["Delete Column"], ...
if (dy > 0) y -= dy; div.style.left = x + "px";
random_line_split
context-menu.js
editor.execCommand("paste"); }, null, config.btnList["paste"][1] ]); var currentTarget = target; var elmenus = []; var link = null; var table = null; var tr = null; var td = null; var img = null; function tableOperation(opcode) { tbo.buttonPress(editor, opcode); }; for (; target; target = target.parent...
(ev) { ev || (ev = window.event); HTMLArea._stopEvent(ev); if (ev.keyCode == 27) { self.closeMenu(); return false; } var key = String.fromCharCode(HTMLArea.is_ie ? ev.keyCode : ev.charCode).toLowerCase(); for (var i = keys.length; --i >= 0;) { var k = keys[i]; if (k[0].toLowerCase() == key) ...
keyPress
identifier_name
d_modal.js
/* ======================================================================== * Bootstrap: modal.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#modals * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Versio...
$.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) ...
if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) }
random_line_split
d_modal.js
/* ======================================================================== * Bootstrap: modal.js v3.0.0 * http://twbs.github.com/bootstrap/javascript.html#modals * ======================================================================== * Copyright 2012 Twitter, Inc. * * Licensed under the Apache License, Versio...
that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.d_modal-dialog') // wait for modal to slide in .one($.support.transition.end...
{ that.$element[0].offsetWidth // force reflow }
conditional_block
test_v1beta1_pod_security_policy_list.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git
from __future__ import absolute_import import os import sys import unittest import kubernetes.client from kubernetes.client.rest import ApiException from kubernetes.client.models.v1beta1_pod_security_policy_list import V1beta1PodSecurityPolicyList class TestV1beta1PodSecurityPolicyList(unittest.TestCase): """...
"""
random_line_split
test_v1beta1_pod_security_policy_list.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
unittest.main()
conditional_block
test_v1beta1_pod_security_policy_list.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
if __name__ == '__main__': unittest.main()
""" Test V1beta1PodSecurityPolicyList """ model = kubernetes.client.models.v1beta1_pod_security_policy_list.V1beta1PodSecurityPolicyList()
identifier_body
test_v1beta1_pod_security_policy_list.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.7.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import os import sys im...
(self): """ Test V1beta1PodSecurityPolicyList """ model = kubernetes.client.models.v1beta1_pod_security_policy_list.V1beta1PodSecurityPolicyList() if __name__ == '__main__': unittest.main()
testV1beta1PodSecurityPolicyList
identifier_name
router.config.js
export default function($stateProvider) { 'ngInject'; return $stateProvider.state('root', { abstract: true, views: { '@': { template: `<ion-side-menus enable-menu-with-back-views="true"> <ion-side-menu-content> <ion-nav-bar ...
<ion-side-menu side="left" ui-view="menu"></ion-side-menu> </ion-side-menus>` } } }); }
</button> </ion-nav-buttons> </ion-nav-bar> <ion-nav-view name="content"></ion-nav-view> </ion-side-menu-content>
random_line_split
OfflineSearchCtrl.ts
module OfflineSearch { export interface IOfflineSearchScope extends ng.IScope { vm: OfflineSearchCtrl; } export interface ILookupResult { title?: string; score: number; key: string; entries: Entry[]; } export class OfflineSearchResultViewModel { firs...
(public title: string, public layerTitle: string, public groupTitle: string, public entry: Entry) { } toString() { return this.title; } get fullTitle(): string { return this.groupTitle + ' >> ' + this.layerTitle + ' >> ' + this.title; } } export class O...
constructor
identifier_name
OfflineSearchCtrl.ts
module OfflineSearch { export interface IOfflineSearchScope extends ng.IScope { vm: OfflineSearchCtrl; } export interface ILookupResult { title?: string; score: number; key: string; entries: Entry[]; } export class OfflineSearchResultViewModel { firs...
results = results.sort((a, b) => { return b.score - a.score; }); return results; } /** * When an item is selected, optionally open the layer and jump to the selected feature. */ public onSelect(selectedItem: OfflineSearchResultViewModel) { /...
if (!keywordIndex.hasOwnProperty(key)) continue; var score = key.score(text); if (score < 0.5) continue; results.push({ score: score, key: key, entries: keywordIndex[key] }) }
random_line_split
form.ts
import MessageBox from "../components/messagebox"; export default class Form { public $form: JQuery; public form: HTMLFormElement; constructor(form: string) { this.$form = $(form); // eventual just use new FormData instead... this.form = <HTMLFormElement>document.getElementById(form.slice(1, form.length...
}); } }
success.close(5); overlay.close(); })
random_line_split
form.ts
import MessageBox from "../components/messagebox"; export default class
{ public $form: JQuery; public form: HTMLFormElement; constructor(form: string) { this.$form = $(form); // eventual just use new FormData instead... this.form = <HTMLFormElement>document.getElementById(form.slice(1, form.length)); } submit(url: string, overlay: any) : void { this.$form.on("subm...
Form
identifier_name
form.ts
import MessageBox from "../components/messagebox"; export default class Form { public $form: JQuery; public form: HTMLFormElement; constructor(form: string)
submit(url: string, overlay: any) : void { this.$form.on("submit", (event: Event) => { event.preventDefault(); //loader.style.visibility = "visible"; // get the form data right when it is sent let formData: string = JSON.stringify($(this.$form).serializeArray()); $.post(url, formDa...
{ this.$form = $(form); // eventual just use new FormData instead... this.form = <HTMLFormElement>document.getElementById(form.slice(1, form.length)); }
identifier_body
model.js
* Creates a new instance of the Model class * @constructor */ Models.Model = function(id, name, status, type, normalValue, wierdValue) { /** @type {string} */ this._id = id || ''; /** @type {string} */ this.name = name || ''; /** @type {string} */ this.status = status || 'disable'; /** @type {...
var Models = {}; module.exports = Models; /**
random_line_split
extHostNotebookEditor.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(): INotebookEditData { this._finalized = true; return { documentVersionId: this._documentVersionId, cellEdits: this._collectedEdits }; } private _throwIfFinalized() { if (this._finalized) { throw new Error('Edit is only valid while callback runs'); } } replaceMetadata(value: vscode.NotebookDoc...
finalize
identifier_name
extHostNotebookEditor.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} export class ExtHostNotebookEditor { private _selections: vscode.NotebookRange[] = []; private _visibleRanges: vscode.NotebookRange[] = []; private _viewColumn?: vscode.ViewColumn; private _visible: boolean = false; private readonly _hasDecorationsForKey = new Set<string>(); private _editor?: vscode.Notebo...
{ this._throwIfFinalized(); if (from === to && cells.length === 0) { return; } this._collectedEdits.push({ editType: CellEditType.Replace, index: from, count: to - from, cells: cells.map(extHostConverter.NotebookCellData.from) }); }
identifier_body
extHostNotebookEditor.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
_acceptSelections(selections: vscode.NotebookRange[]): void { this._selections = selections; } _acceptViewColumn(value: vscode.ViewColumn | undefined) { this._viewColumn = value; } private _applyEdit(editData: INotebookEditData): Promise<boolean> { // return when there is nothing to do if (editData.cell...
random_line_split
extHostNotebookEditor.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} compressedEdits.push(editData.cellEdits[i]); compressedEditsIndex++; } return this._proxy.$tryApplyEdits(this.id, editData.documentVersionId, compressedEdits); } setDecorations(decorationType: vscode.NotebookEditorDecorationType, range: vscode.NotebookRange): void { if (range.isEmpty && !this._ha...
{ prev.cells.push(...(editData.cellEdits[i] as ICellReplaceEdit).cells); prev.count += (editData.cellEdits[i] as ICellReplaceEdit).count; continue; }
conditional_block
mockGraphql.ts
// Ideia tirada do vídeo abaixo: // How Level Up Tests Apollo Queries - Level Up Code Blog // https://youtu.be/OCBWsscJFEQ // https://gist.github.com/stolinski/7cea67d470b4299828b1293aa8cbde0c // An example with 'apollo-link-state': // https://gist.github.com/kristianmandrup/1f7e4a550e6c32b99881aa1b78a4a440
import { schema } from './FakeDataProvider'; // Takes a query and args and returns mocked data const mockGraphql = async (query, args = {}) => { try { const res = await graphql(schema, query.loc.source.body, null, null, args); return res.data; } catch (e) { console.log(e.message); return { errors: e }; } };...
import { graphql } from 'graphql';
random_line_split
cryptojs-enc-base64.js
/* CryptoJS v3.1.2 enc-base64.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strat...
// Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} b...
{ var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var...
conditional_block
cryptojs-enc-base64.js
/* CryptoJS v3.1.2 enc-base64.js code.google.com/p/crypto-js (c) 2009-2013 by Jeff Mott. All rights reserved. code.google.com/p/crypto-js/wiki/License */ (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strat...
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(p...
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
random_line_split
runtime.js
// ECMAScript 5 strict mode "use strict"; assert2(cr, "cr namespace not created"); assert2(cr.behaviors, "cr.behaviors not created"); ///////////////////////////////////// // Behavior class cr.behaviors.Rex_layouter_text = function(runtime) { this.runtime = runtime; }; (function () { var behaviorProto = cr.behavi...
{}; behaviorProto.acts = new Acts(); Acts.prototype.SetCharacterObject = function (objtype) { if (!objtype) return; assert2(cr.plugins_.Sprite, "Layouter text: you should assign a sprite objct for character."); this._sprite_objtype = objtype; this.character_object_s...
ts()
identifier_name
runtime.js
// ECMAScript 5 strict mode "use strict"; assert2(cr, "cr namespace not created"); assert2(cr.behaviors, "cr.behaviors not created"); ///////////////////////////////////// // Behavior class cr.behaviors.Rex_layouter_text = function(runtime) { this.runtime = runtime; }; (function () { var behaviorProto = cr.behavi...
{ this.content = o["t"]; this.character_object_sid = o["csid"]; this.char2frameindex = o["c2fi"]; }; ////////////////////////////////////// // Conditions function Cnds() {}; behaviorProto.cnds = new Cnds(); ////////////////////////////////////// // Actions function ...
behinstProto.loadFromJSON = function (o)
random_line_split
runtime.js
// ECMAScript 5 strict mode "use strict"; assert2(cr, "cr namespace not created"); assert2(cr.behaviors, "cr.behaviors not created"); ///////////////////////////////////// // Behavior class cr.behaviors.Rex_layouter_text = function(runtime) { this.runtime = runtime; }; (function () { var behaviorProto = cr.behavi...
behaviorProto.cnds = new Cnds(); ////////////////////////////////////// // Actions function Acts() {}; behaviorProto.acts = new Acts(); Acts.prototype.SetCharacterObject = function (objtype) { if (!objtype) return; assert2(cr.plugins_.Sprite, "Layouter text: you should assign a sprite o...
;
identifier_body
alias-uninit-value.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 ...
() { mk_raw_ty(ty_nil, None::<~str>); }
main
identifier_name
alias-uninit-value.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 ...
return RawT {struct_: st, cname: cname, hash: 0u}; } pub fn main() { mk_raw_ty(ty_nil, None::<~str>); }
fn mk_raw_ty(st: sty, cname: Option<~str>) -> RawT {
random_line_split
utils.rs
use std::collections::{HashSet, HashMap}; use std::iter::FromIterator; use std::cmp::min; use std::error::Error; use rand::{thread_rng, Rng}; use image::{GenericImage, DynamicImage, ImageBuffer, Luma, FilterType}; use image::imageops::rotate270; use image::imageops::colorops::grayscale; pub fn slice(count: u32, limit:...
fn convert(im: &DynamicImage, size: u32) -> Result<(f32, ImageBuffer<Luma<u8>, Vec<u8>>), Box<Error>> { let mut conv = im.clone(); let (w, h) = conv.dimensions(); let mul = match size > 0 && (w > size || h > size) { true => { conv = conv.resize(size, size, Filter...
{ let mut indexes: Vec<u32> = (0..count).collect(); if limit > 0 && limit < count { let mut rng = thread_rng(); rng.shuffle(&mut indexes); let len = indexes.len(); indexes.truncate(min(len, limit as usize)); } Ok(HashSet::from_iter(indexes.iter().cloned())) }
identifier_body
utils.rs
use std::collections::{HashSet, HashMap}; use std::iter::FromIterator; use std::cmp::min; use std::error::Error; use rand::{thread_rng, Rng}; use image::{GenericImage, DynamicImage, ImageBuffer, Luma, FilterType}; use image::imageops::rotate270; use image::imageops::colorops::grayscale; pub fn slice(count: u32, limit:...
(strip: &mut ImageBuffer<Luma<u8>, Vec<u8>>, x: u32, y: u32, width: u32, height: u32) -> Result<f32, Box<Error>> { let sub = strip.sub_image(x, y, width, height); let (w, h) = sub.dimensions(); let len = (w * h) as f32; let hm = sub.pixels().fold(H...
entropy
identifier_name
utils.rs
use std::collections::{HashSet, HashMap}; use std::iter::FromIterator; use std::cmp::min; use std::error::Error; use rand::{thread_rng, Rng}; use image::{GenericImage, DynamicImage, ImageBuffer, Luma, FilterType}; use image::imageops::rotate270; use image::imageops::colorops::grayscale; pub fn slice(count: u32, limit:...
sub = center; } } if sub == 0 || border == sub { break; } border = sub; if !deep { break; } } borders.push((border as f32 * mul) as u32); if side != 3 { ...
false => delta, }; if diff < delta && diff < threshold { delta = diff;
random_line_split
radio8x2.py
_TIME) interrupt = True else: DisplayExitMessage(lcd) elif switch == left_switch: log.message("LEFT switch" ,log.DEBUG) if display_mode != radio.MODE_SLEEP: if display_mode == radio.MODE_OPTIONS: toggle_option(radio,lcd,DOWN) interrupt = True elif display_mode == radio.MODE_SEARCH and inpu...
line = "" p = os.popen("/usr/bin/mpc " + cmd) while True: line = p.readline().strip('\n')
random_line_split
radio8x2.py
GPIO.RISING, callback=switch_event, bouncetime=200) GPIO.add_event_detect(down_switch, GPIO.RISING, callback=switch_event, bouncetime=200) # Main processing loop count = 0 while True: switch = radio.getSwitch() if switch > 0: get_switch_states(lcd,radio,rss) display_mode = radio.getDisplayMode(...
if radio.muted(): msg = "Sound muted" if radio.getStreaming(): msg = msg + ' *' lcd.line2(msg) else: display_current(lcd,radio) elif display_mode == radio.MODE_SEARCH: display_search(lcd,radio) elif display_mode == radio.MODE_SOURCE: display_source_select(lcd,radio) ...
displayTime(lcd,radio)
conditional_block
radio8x2.py
if count < 0: log.message("Shutdown", log.DEBUG) MenuSwitch = False radio.setDisplayMode(radio.MODE_SHUTDOWN) if radio.getUpdateLibrary(): update_library(lcd,radio) radio.setDisplayMode(radio.MODE_TIME) elif radio.getReload(): source = radio.getSource() log.message("Reload " + str(sour...
reload
identifier_name
radio8x2.py
= GPIO.input(right_switch) else: radio.decrementTimer(1) lcd.line2("Timer " + radio.getTimerString()) TimerChange = GPIO.input(left_switch) time.sleep(0.1) else: radio.timerOn() elif option == radio.ALARM: radio.alarmCycle(direction) elif option == radio.ALARMSETHOURS or option...
dateFormat = "%H:%M" todaysdate = strftime(dateFormat) timenow = strftime("%H:%M") message = todaysdate if radio.getTimer(): message = timenow + " " + radio.getTimerString() if radio.alarmActive(): message = message + " " + radio.getAlarmTime() lcd.line1(message) return
identifier_body
light_controller.py
import dmx import socket
wash = dmx.EuroliteMovingHeadWash(base=1, color=(1, 1, 1), intensity=1) controller = dmx.DMXController(debug=True, fixtures=[wash], port='/dev/tty.usbmodem1421') controller.enabled = True server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(('localhost', 9000)) while True: message = server.recv(...
random_line_split
light_controller.py
import dmx import socket wash = dmx.EuroliteMovingHeadWash(base=1, color=(1, 1, 1), intensity=1) controller = dmx.DMXController(debug=True, fixtures=[wash], port='/dev/tty.usbmodem1421') controller.enabled = True server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind(('localhost', 9000)) while True:...
message = server.recv(1000) command, argument = message.strip().split(' ', 1) if command == 'color': rgb = int(argument, 16) wash.color = (rgb >> 16) / 255., ((rgb >> 8) & 0xff) / 255., (rgb & 0xff) / 255. elif command == 'tilt': wash.tilt = int(argument) elif command == 'pan': ...
conditional_block
test.js
let deserialize = require('./src/deserialize'); let serialize = require('./src/serialize'); let prettyHrtime = require('pretty-hrtime'); let Instruction = require('./src/Instruction'); let start = process.hrtime(), data; let tree = [ new Instruction('test', { a: 1, b: 2, c: 3 }) ]; let sMethods = { 'test': ({ a, ...
end = process.hrtime(start); let dtime = prettyHrtime(end, {precise:true}); setTimeout(() => console.log('result is', result)); setTimeout(() => console.log(`deserialization 10000x took ${dtime}`));
{ result = deserialize(data, dsMethods); }
conditional_block
test.js
let Instruction = require('./src/Instruction'); let start = process.hrtime(), data; let tree = [ new Instruction('test', { a: 1, b: 2, c: 3 }) ]; let sMethods = { 'test': ({ a, b, c }) => [a, b, c] }; let dsMethods = { 'test': ([a, b, c]) => ({ a, b, c }) }; for (let i = 0; i < 10000; i++) { data = serialize(...
let deserialize = require('./src/deserialize'); let serialize = require('./src/serialize'); let prettyHrtime = require('pretty-hrtime');
random_line_split
functions_63.js
['cinit',['cInit',['../group___game_object.html#gab6ed5a737f27fa166a782a2b8141df7d',1,'GameObject']]], ['clearassimps',['clearAssimps',['../_lua_binder_8dox.html#ae54b1056949421de790925afdd89b3e7',1,'LuaBinder.dox']]], ['clearlocallights',['clearLocalLights',['../group___graphics3_d.html#gaa5dd02573dd44e82671c796...
var searchData= [ ['cdeactivate',['cDeactivate',['../group___game_object.html#gab3a5c1145d984bfffc6542a1c5326623',1,'GameObject']]],
random_line_split
mallory.py
#promote products or services of Licensee, or any third party. # #8. By accessing, copying, installing or otherwise using the Software, #Licensee agrees to be bound by the terms and conditions of this License #Agreement. #! /usr/bin/env python """ Usage: %s [ database_filename ] """ import config import copy import o...
def cleanup_proto(self): #self.log.info("Mallory.cleanup_proto()") # List of proto instances that are done done_list = [] for proto in self.protoinstances: if proto.is_done(): done_list.append(proto) ...
self.configure_protocols()
conditional_block
mallory.py
#promote products or services of Licensee, or any third party. # #8. By accessing, copying, installing or otherwise using the Software, #Licensee agrees to be bound by the terms and conditions of this License #Agreement. #! /usr/bin/env python """ Usage: %s [ database_filename ] """ import config import copy import o...
(self, protocol, action): """ Configure a protocol. Use this method to configure Mallory protocols. @param protocol: The Mallory protocol, from the protocol module, to be configured. @param action: when the value is "add" the protocol will be added to the protocol class...
configure_protocol
identifier_name
mallory.py
#promote products or services of Licensee, or any third party. #
#! /usr/bin/env python """ Usage: %s [ database_filename ] """ import config import copy import os import os.path import re import socket import sqlite3 import ssl import sys import thread import time import Queue import select import xmlrpclib import logging import traceback import struct import rpc ### MALLORY IMPO...
#8. By accessing, copying, installing or otherwise using the Software, #Licensee agrees to be bound by the terms and conditions of this License #Agreement.
random_line_split
mallory.py
#promote products or services of Licensee, or any third party. # #8. By accessing, copying, installing or otherwise using the Software, #Licensee agrees to be bound by the terms and conditions of this License #Agreement. #! /usr/bin/env python """ Usage: %s [ database_filename ] """ import config import copy import o...
def __str__(self): return "clientip:%s, clientport:%d, serverip:%s, serverport:%d " \ "conncount:%d, direction:%s" % (self.clientip, self.clientport, \ self.serverip, self.serverport, self.conncount, self.direction) class Mallory(Subject): """ The main Mal...
""" Initialize the connection data. @param data: This is the data associated with the connection. clientip: the client's (victim's) ip address). clientport: the victim's source port. serverip: the destination IP address. serverport: the destination port. conncoun...
identifier_body
nontransitive_dice.py
# Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com # # 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 ...
(m=3, n=6, minimize_val=0): # Create the solver. solver = pywrapcp.Solver("Nontransitive dice") # # data # print "number of dice:", m print "number of sides:", n # # declare variables # dice = {} for i in range(m): for j in range(n): dice[(i, j)] = solver.IntVar(1, n * 2, "dice(%i,...
main
identifier_name
nontransitive_dice.py
# Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com # # 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 ...
# probability gap [solver.Add(gap[i] == comp[i, 0] - comp[i, 1]) for i in range(m)] [solver.Add(gap[i] > 0) for i in range(m)] solver.Add(gap_sum == solver.Sum(gap)) # and now we roll... # Number of wins for [A vs B, B vs A] for d in range(m): b1 = [solver.IsGreaterVar(dice[d % m, r1], dice[(d + 1)...
random_line_split
nontransitive_dice.py
# Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com # # 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 ...
else: solver.NewSearch(db) num_solutions = 0 while solver.NextSolution(): print "gap_sum:", gap_sum.Value() print "gap:", [gap[i].Value() for i in range(m)] print "max_val:", max_val.Value() print "max_win:", max_win.Value() print "dice:" for i in range(m): for j in range(n): ...
solver.NewSearch(db, [objective])
conditional_block
nontransitive_dice.py
# Copyright 2010 Hakan Kjellerstrand hakank@bonetmail.com # # 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 ...
for j in range(2): comp[(i, j)] = solver.IntVar(0, n * n, "comp(%i,%i)" % (i, j)) comp_flat = [comp[(i, j)] for i in range(m) for j in range(2)] # The following variables are for summaries or objectives gap = [solver.IntVar(0, n * n, "gap(%i)" % i) for i in range(m)] gap_sum = solver.IntVar(0, m * n ...
solver = pywrapcp.Solver("Nontransitive dice") # # data # print "number of dice:", m print "number of sides:", n # # declare variables # dice = {} for i in range(m): for j in range(n): dice[(i, j)] = solver.IntVar(1, n * 2, "dice(%i,%i)" % (i, j)) dice_flat = [dice[(i, j)] for i in ra...
identifier_body
partial.py
from polybori import BooleSet, interpolate_smallest_lex class PartialFunction(object): """docstring for PartialFunction""" def __init__(self, zeros, ones): super(PartialFunction, self).__init__() self.zeros = zeros.set() self.ones = ones.set() def interpolate_smallest_lex(self): ...
domain = self.definedOn().intersect(other.definedOn()) zeros = self.zeros.intersect(other.zeros).union(self.ones.intersect( other.ones)) ones = self.zeros.intersect(other.ones).union(self.ones.intersect( other.zeros)) assert zeros.diff(domain).empty() asse...
def definedOn(self): return self.zeros.union(self.ones) def __add__(self, other):
random_line_split
partial.py
from polybori import BooleSet, interpolate_smallest_lex class PartialFunction(object): """docstring for PartialFunction""" def __init__(self, zeros, ones): super(PartialFunction, self).__init__() self.zeros = zeros.set() self.ones = ones.set() def interpolate_smallest_lex(self): ...
def __add__(self, other): domain = self.definedOn().intersect(other.definedOn()) zeros = self.zeros.intersect(other.zeros).union(self.ones.intersect( other.ones)) ones = self.zeros.intersect(other.ones).union(self.ones.intersect( other.zeros)) assert zeros.d...
return self.zeros.union(self.ones)
identifier_body
partial.py
from polybori import BooleSet, interpolate_smallest_lex class PartialFunction(object): """docstring for PartialFunction""" def __init__(self, zeros, ones): super(PartialFunction, self).__init__() self.zeros = zeros.set() self.ones = ones.set() def
(self): return interpolate_smallest_lex(self.zeros, self.ones) def __str__(self): return "PartialFunction(zeros=" + str(self.zeros) + ", ones=" + str( self.ones) + ")" def definedOn(self): return self.zeros.union(self.ones) def __add__(self, other): domain = se...
interpolate_smallest_lex
identifier_name
mod.rs
: Span, msg: &str, suggestion: String) { self.diagnostic().span_suggestion(sp, msg, suggestion) } pub fn span_help(&self, sp: Span, msg: &str) { self.diagnostic().span_help(sp, msg) } pub fn fileline_note(&self, sp: Span, msg: &str) { self.diagnostic().fileline_note(sp, msg) ...
.last()
random_line_split
mod.rs
str) -> ! { if self.opts.treat_err_as_bug { self.span_bug(sp, msg); } panic!(self.diagnostic().span_fatal(sp, msg)) } pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! { if self.opts.treat_err_as_bug { self.span_bug(sp, msg); ...
(&self, sp: Span, msg: &str) { self.diagnostic().fileline_note(sp, msg) } pub fn fileline_help(&self, sp: Span, msg: &str) { self.diagnostic().fileline_help(sp, msg) } pub fn note(&self, msg: &str) { self.diagnostic().handler().note(msg) } pub fn help(&self, msg: &str) { ...
fileline_note
identifier_name
mod.rs
str) -> ! { if self.opts.treat_err_as_bug { self.span_bug(sp, msg); } panic!(self.diagnostic().span_fatal(sp, msg)) } pub fn span_fatal_with_code(&self, sp: Span, msg: &str, code: &str) -> ! { if self.opts.treat_err_as_bug { self.span_bug(sp, msg); ...
pub fn span_unimpl(&self, sp: Span, msg: &str) -> ! { self.diagnostic().span_unimpl(sp, msg) } pub fn unimpl(&self, msg: &str) -> ! { self.diagnostic().handler().unimpl(msg) } pub fn add_lint(&self, lint: &'static lint::Lint, id: ast::NodeId, ...
{ self.diagnostic().handler().bug(msg) }
identifier_body
control_get_firmware.py
#! /usr/bin/env python """ # control_get_firmware.py: get firmware version of Gemalto readers # Copyright (C) 2009-2012 Ludovic Rousseau """ # 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 Foun...
else: print " Not a Gemalto reader" try: res = properties['PCSCv2_PART10_PROPERTY_sFirmwareID'] print " Firmware:", frimware except KeyError: print " PCSCv2_PART10_PROPERTY_sFirmwareID not supported"
get_firmware = [0x02] IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE = SCARD_CTL_CODE(1) res = cardConnection.control(IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE, get_firmware) print " Firmware:", "".join([chr(x) for x in res])
conditional_block
control_get_firmware.py
#! /usr/bin/env python """ # control_get_firmware.py: get firmware version of Gemalto readers # Copyright (C) 2009-2012 Ludovic Rousseau """ # 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 Foun...
properties = getTlvProperties(cardConnection) # Gemalto devices supports a control code to get firmware if properties['PCSCv2_PART10_PROPERTY_wIdVendor'] == 0x08E6: get_firmware = [0x02] IOCTL_SMARTCARD_VENDOR_IFD_EXCHANGE = SCARD_CTL_CODE(1) res = cardConnection.control(IOCTL_SMART...
# properties returned by IOCTL_FEATURE_GET_TLV_PROPERTIES
random_line_split
flask_app.py
# Copyright 2019 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
client = ndb.Client() def ndb_wsgi_middleware(wsgi_app): def middleware(environ, start_response): with client.context(): return wsgi_app(environ, start_response) return middleware app = Flask(__name__) app.wsgi_app = ndb_wsgi_middleware(app.wsgi_app) # Wrap the app in middleware. cl...
from flask import Flask from google.cloud import ndb
random_line_split
flask_app.py
# Copyright 2019 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
app = Flask(__name__) app.wsgi_app = ndb_wsgi_middleware(app.wsgi_app) # Wrap the app in middleware. class Book(ndb.Model): title = ndb.StringProperty() @app.route('/') def list_books(): books = Book.query() return str([book.to_dict() for book in books]) # [END ndb_flask]
def middleware(environ, start_response): with client.context(): return wsgi_app(environ, start_response) return middleware
identifier_body
flask_app.py
# Copyright 2019 Google LLC All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ag...
(environ, start_response): with client.context(): return wsgi_app(environ, start_response) return middleware app = Flask(__name__) app.wsgi_app = ndb_wsgi_middleware(app.wsgi_app) # Wrap the app in middleware. class Book(ndb.Model): title = ndb.StringProperty() @app.route('/') def li...
middleware
identifier_name
processinginstruction.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ProcessingInstructionBinding; use crate::dom::bindings::codegen::Bin...
( target: DOMString, data: DOMString, document: &Document, ) -> ProcessingInstruction { ProcessingInstruction { characterdata: CharacterData::new_inherited(data, document), target: target, } } pub fn new( target: DOMString, dat...
new_inherited
identifier_name
processinginstruction.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ProcessingInstructionBinding;
use crate::dom::bindings::codegen::Bindings::ProcessingInstructionBinding::ProcessingInstructionMethods; use crate::dom::bindings::root::DomRoot; use crate::dom::bindings::str::DOMString; use crate::dom::characterdata::CharacterData; use crate::dom::document::Document; use crate::dom::node::Node; use dom_struct::dom_st...
random_line_split
processinginstruction.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::codegen::Bindings::ProcessingInstructionBinding; use crate::dom::bindings::codegen::Bin...
}
{ self.target.clone() }
identifier_body
prosemirror-view-tests.ts
import * as model from 'prosemirror-model'; import * as schema from 'prosemirror-schema-basic'; import * as state from 'prosemirror-state'; import * as view from 'prosemirror-view'; const { Decoration } = view; const decoration = new Decoration(); const plainDecoration = new Decoration<{ a: number }>(); plainDecorati...
(text, plain) { const isPlain: boolean = plain; return text; }, clipboardTextParser(text, $context, plain) { const isPlain: boolean = plain; return model.Slice.empty; }, }, }); const view1 = new state.Plugin({ props: { handleDOMEv...
transformPastedText
identifier_name
prosemirror-view-tests.ts
import * as model from 'prosemirror-model'; import * as schema from 'prosemirror-schema-basic'; import * as state from 'prosemirror-state'; import * as view from 'prosemirror-view'; const { Decoration } = view; const decoration = new Decoration(); const plainDecoration = new Decoration<{ a: number }>(); plainDecorati...
, blur(view, event) { event; // $ExpectType FocusEvent return true; }, customxyz: (view, event) => { event; // $ExpectType any return true; }, }, }, });
{ event; // $ExpectType MouseEvent return true; }
identifier_body
prosemirror-view-tests.ts
import * as model from 'prosemirror-model'; import * as schema from 'prosemirror-schema-basic'; import * as state from 'prosemirror-state'; import * as view from 'prosemirror-view'; const { Decoration } = view; const decoration = new Decoration(); const plainDecoration = new Decoration<{ a: number }>(); plainDecorati...
const res1_1 = new view.EditorView({} as any, {} as any); const res1_2: { pos: number; inside: number } = res1_1.posAtCoords({ left: 0, top: 0 })!; const res1_3: boolean = res1_1.editable; const res1_4 = res1_1.coordsAtPos(1); const res1_5 = res1_1.coordsAtPos(1, 1); const res1_6 = res1_1.domAtPos(1); const res1_7 = re...
random_line_split
contact.py
""" pyfire.contact ~~~~~~~~~~ Handles Contact ("roster item") interpretation as per RFC-6121 :copyright: 2011 by the pyfire Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import xml.etree.ElementTree as ET from sqlalchemy import Table, Column, Boolean, Integ...
class Contact(Base): """Jabber Contact, aka roster item. It has some really strict attribute setting mechanism as it leads to all kinds of fantastic crashes with clients which should be avoided in any case. """ __tablename__ = 'contacts' id = Column(Integer, primary_key=True) appr...
"""Simple group, only providing a name for now""" __tablename__ = 'groups' id = Column(Integer, primary_key=True) name = Column(String(255))
identifier_body
contact.py
""" pyfire.contact ~~~~~~~~~~ Handles Contact ("roster item") interpretation as per RFC-6121 :copyright: 2011 by the pyfire Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import xml.etree.ElementTree as ET from sqlalchemy import Table, Column, Boolean, Integ...
elif isinstance(jid, JID): self.jid = jid self.jid.validate(raise_error=True) else: raise AttributeError("Needs valid jid either as string or JID instance") # optional self.approved = False self.ask = None self.name = None sel...
self.jid = JID(jid)
conditional_block
contact.py
""" pyfire.contact ~~~~~~~~~~ Handles Contact ("roster item") interpretation as per RFC-6121 :copyright: 2011 by the pyfire Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import xml.etree.ElementTree as ET from sqlalchemy import Table, Column, Boolean, Integ...
subscription = Column(Enum("none", "from", "to", "remove", "both")) groups = relationship(Group, secondary=contacts_groups) roster = relationship(Roster, backref=backref('contacts')) roster_id = Column(Integer, ForeignKey('rosters.id'), nullable=False) def __init__(self, jid, **kwds): super...
approved = Column(Boolean) ask = Column(Enum('subscribe')) jid = Column(JIDString, nullable=False) name = Column(String(255))
random_line_split
contact.py
""" pyfire.contact ~~~~~~~~~~ Handles Contact ("roster item") interpretation as per RFC-6121 :copyright: 2011 by the pyfire Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import xml.etree.ElementTree as ET from sqlalchemy import Table, Column, Boolean, Integ...
(self): """Formats contact as `class`:ET.Element object""" element = ET.Element("item") if self.approved is not None: element.set("approved", 'true' if self.approved else 'false') if self.ask is not None: element.set("ask", self.ask) element.set("jid", st...
to_element
identifier_name
FilesRemoteAddResponse.ts
/* tslint:disable */ import { WebAPICallResult } from '../WebClient'; export type FilesRemoteAddResponse = WebAPICallResult & { ok?: boolean; file?: File; error?: string; needed?: string; provided?: string; }; export interface File { id?: string; created?: number; ...
pretty_type?: string; user?: string; editable?: boolean; size?: number; mode?: string; is_external?: boolean; external_type?: string; is_public?: boolean; public_url_shared?: boolean; display_as_bot?: boolean; username?: ...
title?: string; mimetype?: string; filetype?: string;
random_line_split
mod.rs
// Copyright 2016 LambdaStack All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law...
(buf: &[u8]) -> StreamIdentifier { StreamIdentifier( byteorder::BigEndian::read_u32(buf) & ((1 << 31) - 1) ) } pub fn encode(&self, buf: &mut [u8]) -> usize { encode_u32(buf, self.0) } } #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct ErrorCode(pub u32); ...
parse
identifier_name
mod.rs
// Copyright 2016 LambdaStack All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law...
pub enum HttpError { Protocol, Internal, FlowControlError, SettingsTimeout, } impl ErrorCode { pub fn parse(buf: &[u8]) -> ErrorCode { ErrorCode(byteorder::BigEndian::read_u32(buf)) } pub fn encode(&self, buf: &mut [u8]) -> usize { encode_u32(buf, self.0) } } #[derive(...
pub struct ErrorCode(pub u32);
random_line_split
LixIn.py
# -*- coding: utf-8 -*- import re from module.plugins.Crypter import Crypter class LixIn(Crypter): __name__ = "LixIn" __type__ = "crypter" __version__ = "0.22" __pattern__ = r'http://(?:www\.)?lix\.in/(?P<ID>.+)' __config__ = [("use_subfolder", "bool", "Save package to subfolder", True),...
id = m.group("ID") self.logDebug("File id is %s" % id) self.html = self.load(url, decode=True) m = re.search(self.SUBMIT_PATTERN, self.html) if m is None: self.error(_("Link doesn't seem valid")) m = re.search(self.CAPTCHA_PATTERN, self.html) if m...
self.error(_("Unable to identify file ID"))
conditional_block
LixIn.py
# -*- coding: utf-8 -*- import re from module.plugins.Crypter import Crypter class LixIn(Crypter):
m = re.match(self.__pattern__, url) if m is None: self.error(_("Unable to identify file ID")) id = m.group("ID") self.logDebug("File id is %s" % id) self.html = self.load(url, decode=True) m = re.search(self.SUBMIT_PATTERN, self.html) if m is None:...
__name__ = "LixIn" __type__ = "crypter" __version__ = "0.22" __pattern__ = r'http://(?:www\.)?lix\.in/(?P<ID>.+)' __config__ = [("use_subfolder", "bool", "Save package to subfolder", True), ("subfolder_per_package", "bool", "Create a subfolder for each package", True)] __...
identifier_body
LixIn.py
# -*- coding: utf-8 -*- import re from module.plugins.Crypter import Crypter class LixIn(Crypter): __name__ = "LixIn" __type__ = "crypter" __version__ = "0.22" __pattern__ = r'http://(?:www\.)?lix\.in/(?P<ID>.+)' __config__ = [("use_subfolder", "bool", "Save package to subfolder", True),...
(self, pyfile): url = pyfile.url m = re.match(self.__pattern__, url) if m is None: self.error(_("Unable to identify file ID")) id = m.group("ID") self.logDebug("File id is %s" % id) self.html = self.load(url, decode=True) m = re.search(self.SUBMIT_...
decrypt
identifier_name
LixIn.py
# -*- coding: utf-8 -*- import re from module.plugins.Crypter import Crypter class LixIn(Crypter): __name__ = "LixIn" __type__ = "crypter" __version__ = "0.22" __pattern__ = r'http://(?:www\.)?lix\.in/(?P<ID>.+)' __config__ = [("use_subfolder", "bool", "Save package to subfolder", True),...
self.error(_("Unable to find destination url")) else: self.urls = [m.group("link")] self.logDebug("Found link %s, adding to package" % self.urls[0])
m = re.search(self.LINK_PATTERN, self.html) if m is None:
random_line_split
utils.py
"""Common utility for testing third party oauth2 features.""" import json from base64 import b64encode import httpretty from onelogin.saml2.utils import OneLogin_Saml2_Utils from oauth2_provider.models import Application from social_core.backends.facebook import API_VERSION as FACEBOOK_API_VERSION from social_core.b...
(file_name): """ Read XML file with the name specified in the argument and pre process the xml so that it can be parsed. Pre Processing removes line retune characters (i.e. "\n"). Arguments: file_name (str): Name of the XML file. Returns: (str): Pre Processed contents of the file...
read_and_pre_process_xml
identifier_name
utils.py
"""Common utility for testing third party oauth2 features.""" import json from base64 import b64encode import httpretty from onelogin.saml2.utils import OneLogin_Saml2_Utils from oauth2_provider.models import Application from social_core.backends.facebook import API_VERSION as FACEBOOK_API_VERSION from social_core.b...
def tearDown(self): super(ThirdPartyOAuthTestMixin, self).tearDown() Partial.objects.all().delete() def _create_client(self): """ Create an OAuth2 client application """ return Application.objects.create( client_id=self.client_id, client...
super(ThirdPartyOAuthTestMixin, self).setUp() if self.CREATE_USER: self.user = UserFactory() UserSocialAuth.objects.create(user=self.user, provider=self.BACKEND, uid=self.social_uid) self.oauth_client = self._create_client() if self.BACKEND == 'google-oauth2': ...
identifier_body
utils.py
"""Common utility for testing third party oauth2 features.""" import json from base64 import b64encode import httpretty from onelogin.saml2.utils import OneLogin_Saml2_Utils from oauth2_provider.models import Application from social_core.backends.facebook import API_VERSION as FACEBOOK_API_VERSION from social_core.b...
elif self.BACKEND == 'facebook': self.configure_facebook_provider(enabled=True, visible=True) def tearDown(self): super(ThirdPartyOAuthTestMixin, self).tearDown() Partial.objects.all().delete() def _create_client(self): """ Create an OAuth2 client applicati...
self.configure_google_provider(enabled=True, visible=True)
conditional_block
utils.py
"""Common utility for testing third party oauth2 features.""" import json from base64 import b64encode import httpretty from onelogin.saml2.utils import OneLogin_Saml2_Utils from oauth2_provider.models import Application from social_core.backends.facebook import API_VERSION as FACEBOOK_API_VERSION from social_core.b...
Pre Process XML so that it can be used as a SAML Response coming from SAML IdP. This method will perform the following operations on the XML in given order 1. base64 encode XML. 2. URL encode the base64 encoded data. Arguments: xml (string): XML data relay_state (string): Relay St...
def prepare_saml_response_from_xml(xml, relay_state='testshib'): """
random_line_split
font_template.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::fs::File; use std::io::Read; use string_cache::Atom; /// Platform specific font representation for Linux...
} impl FontTemplateData { pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData { let bytes = match font_data { Some(bytes) => { bytes }, None => { // TODO: Handle file load failure! let mut file = Fi...
/// freetype and azure directly. #[derive(Deserialize, Serialize)] pub struct FontTemplateData { pub bytes: Vec<u8>, pub identifier: Atom,
random_line_split
font_template.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::fs::File; use std::io::Read; use string_cache::Atom; /// Platform specific font representation for Linux...
{ pub bytes: Vec<u8>, pub identifier: Atom, } impl FontTemplateData { pub fn new(identifier: Atom, font_data: Option<Vec<u8>>) -> FontTemplateData { let bytes = match font_data { Some(bytes) => { bytes }, None => { // TODO: Handle...
FontTemplateData
identifier_name
font_template.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::fs::File; use std::io::Read; use string_cache::Atom; /// Platform specific font representation for Linux...
}
{ let bytes = match font_data { Some(bytes) => { bytes }, None => { // TODO: Handle file load failure! let mut file = File::open(&*identifier).unwrap(); let mut buffer = vec![]; file.read_to_end(&...
identifier_body
font_template.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use std::fs::File; use std::io::Read; use string_cache::Atom; /// Platform specific font representation for Linux...
, }; FontTemplateData { bytes: bytes, identifier: identifier, } } }
{ // TODO: Handle file load failure! let mut file = File::open(&*identifier).unwrap(); let mut buffer = vec![]; file.read_to_end(&mut buffer).unwrap(); buffer }
conditional_block
views.py
# # Copyright (C) 2003-2022 Sébastien Helleu <flashcode@flashtux.org> # # This file is part of WeeChat.org. # # WeeChat.org 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 #...
""View for a plain text file.""" def render_to_response(self, context, **response_kwargs): response_kwargs['content_type'] = 'text/plain' return super().render_to_response(context, **response_kwargs)
identifier_body
views.py
#
# This file is part of WeeChat.org. # # WeeChat.org 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 later version. # # WeeChat.org is distributed in t...
# Copyright (C) 2003-2022 Sébastien Helleu <flashcode@flashtux.org> #
random_line_split
views.py
# # Copyright (C) 2003-2022 Sébastien Helleu <flashcode@flashtux.org> # # This file is part of WeeChat.org. # # WeeChat.org 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 #...
TemplateView): """View for a plain text file.""" def render_to_response(self, context, **response_kwargs): response_kwargs['content_type'] = 'text/plain' return super().render_to_response(context, **response_kwargs)
extTemplateView(
identifier_name
main.rs
extern crate env_logger; extern crate glutin; extern crate gfx; extern crate gfx_window_glutin; extern crate claymore_game as game; pub fn
() { use gfx::traits::*; env_logger::init().unwrap(); println!("Initializing the window..."); let window = glutin::WindowBuilder::new() .with_title("Claymore".to_string()) .with_vsync() .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (3, 2))) .with_srgb(Some(t...
main
identifier_name
main.rs
extern crate env_logger; extern crate glutin; extern crate gfx; extern crate gfx_window_glutin; extern crate claymore_game as game; pub fn main() { use gfx::traits::*; env_logger::init().unwrap(); println!("Initializing the window..."); let window = glutin::WindowBuilder::new() .with_title("C...
} } app.render(&mut stream); stream.present(&mut device); } println!("Done."); }
let (sx, sy) = stream.out.get_size(); app.mouse_click(mouse_x as f32 / sx as f32, mouse_y as f32 / sy as f32); }, _ => (),
random_line_split
main.rs
extern crate env_logger; extern crate glutin; extern crate gfx; extern crate gfx_window_glutin; extern crate claymore_game as game; pub fn main()
'main: loop { // quit when Esc is pressed. for event in stream.out.window.poll_events() { use glutin::{ElementState, Event, MouseButton, VirtualKeyCode}; match event { Event::Closed => break 'main, Event::KeyboardInput(ElementState::Pressed, _,...
{ use gfx::traits::*; env_logger::init().unwrap(); println!("Initializing the window..."); let window = glutin::WindowBuilder::new() .with_title("Claymore".to_string()) .with_vsync() .with_gl(glutin::GlRequest::Specific(glutin::Api::OpenGl, (3, 2))) .with_srgb(Some(true...
identifier_body
__init__.py
# Copyright 2019 TWO SIGMA OPEN SOURCE, 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...
(): return [{ 'section': 'notebook', 'src': 'static', 'dest': 'beakerx_tabledisplay', 'require': 'beakerx_tabledisplay/index' } ] def _jupyter_server_extension_paths(): return [dict(module="beakerx_tabledisplay")] def run(): try: parse() except Keyboard...
_jupyter_nbextension_paths
identifier_name
__init__.py
# Copyright 2019 TWO SIGMA OPEN SOURCE, 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...
from .tabledisplay import * from ._version import version_info, __version__ from .handlers import load_jupyter_server_extension from .commands import parse def _jupyter_nbextension_paths(): return [{ 'section': 'notebook', 'src': 'static', 'dest': 'beakerx_tabledisplay', 'require': ...
random_line_split