file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
cpu.js
// https://en.wikipedia.org/wiki/CHIP-8 // http://www.codeslinger.co.uk/pages/projects/chip8/hardware.html // BYTE = 1 byte // WORD = 2 bytes MIDNIGHT = { fg: "#d387ff", bg: "#380c52", } CHIP8 = { r: { // 8-bit registers // Doubles as special FLAG V: new Uint8Array(new ArrayBuffer...
switch (firstDigit) { case 0x0: // handle 0x0.. return CHIP8.handleOp0(op & 0xfff); case 0x1: // JUMP opcode (0x1NNN) if ((op & 0x0fff) == CHIP8.r.PC - 0x2) { CHIP8.r.PC = op & 0x0fff; ...
random_line_split
cpu.js
// https://en.wikipedia.org/wiki/CHIP-8 // http://www.codeslinger.co.uk/pages/projects/chip8/hardware.html // BYTE = 1 byte // WORD = 2 bytes MIDNIGHT = { fg: "#d387ff", bg: "#380c52", } CHIP8 = { r: { // 8-bit registers // Doubles as special FLAG V: new Uint8Array(new ArrayBuffer...
return CODES.eqReg; } case 0x6: // LOAD TO REG (0x6XNN) // Sets VX to NN. CHIP8.r.V[secondDigit] = op & 0xff; return CODES.loadToReg; case 0x7: // ADD TO REG (0x7XNN) ...
{ CHIP8.r.PC += 2; }
conditional_block
cpu.js
// https://en.wikipedia.org/wiki/CHIP-8 // http://www.codeslinger.co.uk/pages/projects/chip8/hardware.html // BYTE = 1 byte // WORD = 2 bytes MIDNIGHT = { fg: "#d387ff", bg: "#380c52", } CHIP8 = { r: { // 8-bit registers // Doubles as special FLAG V: new Uint8Array(new ArrayBuffer...
(prgmBuffer) { console.log("Loading program buffer into memory.") CHIP8.r.I = 0; CHIP8.r.PC = 0x200; CHIP8.r.V = new Uint8Array(new ArrayBuffer(16)); prgm = new Uint8Array(prgmBuffer); for (let i = 0; i < prgm.length; i++) { CHIP8_MEM[i + 0x200] = prgm[i]; ...
memLoad
identifier_name
cpu.js
// https://en.wikipedia.org/wiki/CHIP-8 // http://www.codeslinger.co.uk/pages/projects/chip8/hardware.html // BYTE = 1 byte // WORD = 2 bytes MIDNIGHT = { fg: "#d387ff", bg: "#380c52", } CHIP8 = { r: { // 8-bit registers // Doubles as special FLAG V: new Uint8Array(new ArrayBuffer...
function loop() { CHIP8.read(); drawDebugger(); } function init() { CHIP8_GRAPHICS.clear(); CHIP8_GRAPHICS.draw(); drawDebugger(); } function clearLoop() { if (clockInterval) { clearInterval(clockInterval); DEBUGGER.slowMode = false; clockInterval = 0; } }
{ clearLoop(); DEBUGGER.slowMode = true; FPS_INTERVAL = 200; clockInterval = setInterval(loop, FPS_INTERVAL); }
identifier_body
buffer_geometry.rs
extern crate uuid; extern crate heck; extern crate specs; use self::uuid::Uuid; use self::heck::ShoutySnakeCase; use std::vec::Vec; use std::fmt; use std::sync::{Arc,Mutex, LockResult, MutexGuard}; use std::mem; use std::error::Error; use self::specs::{Component, VecStorage}; use math::{ Vector, Vector2, Vector3...
(&self) -> usize { let l = self.len(); l / self.item_size() } pub fn item_size(&self) -> usize { self.data.item_size() } pub fn len(&self) -> usize { self.data.len() } pub fn set_normalized(&mut self, normalized: bool) -> &mut Self { self.normalized = normalized; self } pub fn set_dynamic(&mut s...
count
identifier_name
buffer_geometry.rs
extern crate uuid; extern crate heck; extern crate specs; use self::uuid::Uuid; use self::heck::ShoutySnakeCase; use std::vec::Vec; use std::fmt; use std::sync::{Arc,Mutex, LockResult, MutexGuard}; use std::mem; use std::error::Error; use self::specs::{Component, VecStorage}; use math::{ Vector, Vector2, Vector3...
} #[allow(dead_code)] #[derive(Hash, Eq, PartialEq, Debug, Clone)] pub struct BufferGroup { pub start: usize, pub material_index: usize, pub count: usize, pub name: Option<String>, } #[allow(dead_code)] #[derive(Clone)] pub struct BufferGeometry { pub uuid: Uuid, pub name: String, pub groups: Vec<BufferGroup>...
{ format!("VERTEX_{}_{}", self.buffer_type.definition(), self.data.definition()) }
identifier_body
buffer_geometry.rs
extern crate uuid; extern crate heck; extern crate specs; use self::uuid::Uuid; use self::heck::ShoutySnakeCase; use std::vec::Vec; use std::fmt; use std::sync::{Arc,Mutex, LockResult, MutexGuard}; use std::mem; use std::error::Error; use self::specs::{Component, VecStorage}; use math::{ Vector, Vector2, Vector3...
#[derive(Clone, Debug, Eq, PartialEq)] pub enum BufferType { Position, Normal, Tangent, UV(usize), Color(usize), Joint(usize), Weight(usize), Other(String), } impl BufferType { pub fn definition(&self) -> String { match self { BufferType::Position => "POSITION".to_string(), BufferType::Normal => "NO...
} }
random_line_split
span.rs
use crate::{ buffer::{ cell_buffer::{Contacts, Endorse}, fragment_buffer::FragmentSpan, FragmentBuffer, Property, PropertyBuffer, StringBuffer, }, fragment, fragment::Circle, map::{circle_map, UNICODE_FRAGMENTS}, Cell, Fragment, Merge, Point, Settings, }; use itertools::I...
/// merge as is without checking it it can pub fn merge_no_check(&self, other: &Self) -> Self { let mut cells = self.0.clone(); cells.extend(&other.0); Span(cells) } } impl Merge for Span { fn merge(&self, other: &Self) -> Option<Self> { if self.can_merge(other) { ...
{ self.iter().any(|(cell, ch)| *cell == needle) }
identifier_body
span.rs
use crate::{ buffer::{ cell_buffer::{Contacts, Endorse}, fragment_buffer::FragmentSpan, FragmentBuffer, Property, PropertyBuffer, StringBuffer, }, fragment, fragment::Circle, map::{circle_map, UNICODE_FRAGMENTS}, Cell, Fragment, Merge, Point, Settings, }; use itertools::I...
} } impl Bounds { pub fn new(cell1: Cell, cell2: Cell) -> Self { let (top_left, bottom_right) = Cell::rearrange_bound(cell1, cell2); Self { top_left, bottom_right, } } pub fn top_left(&self) -> Cell { self.top_left } pub fn bottom_right...
{ None }
conditional_block
span.rs
use crate::{ buffer::{ cell_buffer::{Contacts, Endorse}, fragment_buffer::FragmentSpan, FragmentBuffer, Property, PropertyBuffer, StringBuffer, }, fragment, fragment::Circle, map::{circle_map, UNICODE_FRAGMENTS}, Cell, Fragment, Merge, Point, Settings, }; use itertools::I...
(&self) -> Cell { Cell::new(self.top_left.x, self.bottom_right.y) } } /// create a property buffer for all the cells of this span impl<'p> From<Span> for PropertyBuffer<'p> { fn from(span: Span) -> Self { let mut pb = PropertyBuffer::new(); for (cell, ch) in span.iter() { if...
bottom_left
identifier_name
span.rs
use crate::{ buffer::{ cell_buffer::{Contacts, Endorse}, fragment_buffer::FragmentSpan, FragmentBuffer, Property, PropertyBuffer, StringBuffer, }, fragment, fragment::Circle, map::{circle_map, UNICODE_FRAGMENTS}, Cell, Fragment, Merge, Point, Settings, }; use itertools::I...
accepted, rejects: vec![], }; endorsed.extend(re_endorsed); endorsed } /// re try endorsing the contacts into arc and circles by converting it to span first fn re_endorse(rect_rejects: Vec<Contacts>) -> Endorse<FragmentSpan, Span> { // convert back to...
let re_endorsed = Self::re_endorse(rect_endorsed.rejects); let mut endorsed = Endorse {
random_line_split
SoloToolkit.js
const ipcRenderer = require('electron').ipcRenderer; const Device = require('./app/js/Device'); const Mousetrap = require('mousetrap'); const {remote} = require("electron"); //Solo + controller device let solo = new Device(successConnecting, successDisconnecting, failureConnecting); // Create Device instance for cont...
// Templates and views $(document).ready(function load_templates(){ //Renders all templates on initialization and drops them into their divs $('#system-view').html(system_info_template(solo.versions)); $('#logs-view').html(logs_template()); $('#settings-view').html(settings_template()); //switches the view...
//Takes an input html and then requests a dialog chooser //When response received from main thread with path, this drops a value in the input Logger.log('info',"getDirectory()"); let selected_dir = ''; ipcRenderer.send('open-dir-dialog'); //Listen for one return event to get the path back from the main thre...
identifier_body
SoloToolkit.js
const ipcRenderer = require('electron').ipcRenderer; const Device = require('./app/js/Device'); const Mousetrap = require('mousetrap'); const {remote} = require("electron"); //Solo + controller device let solo = new Device(successConnecting, successDisconnecting, failureConnecting); // Create Device instance for cont...
Logger.log('info',"Successfully disconnected from " + device); $("#" + device + "-connection-status").html(" disconnected"); $("." + device + "-connection").removeClass("active"); if (device === "controller"){ //If we're not connected to controller, good chance we're not going to be connected to Solo connec...
// Called if we successfully disconnect from a device (like when Disconnect button pressed) // Will not display a message to the user
random_line_split
SoloToolkit.js
const ipcRenderer = require('electron').ipcRenderer; const Device = require('./app/js/Device'); const Mousetrap = require('mousetrap'); const {remote} = require("electron"); //Solo + controller device let solo = new Device(successConnecting, successDisconnecting, failureConnecting); // Create Device instance for cont...
if (message){ display_overlay("connection", `Disconnected from ${message}`, `Check connections.`); } } function connectButtonDisabled(){ connect_button.addClass('disabled'); connect_button.prop("disabled", true); }; function connectButtonEnabled(){ connect_button.html('CONNECT'); connect_button.remove...
{ solo.soloConnected = false; }
conditional_block
SoloToolkit.js
const ipcRenderer = require('electron').ipcRenderer; const Device = require('./app/js/Device'); const Mousetrap = require('mousetrap'); const {remote} = require("electron"); //Solo + controller device let solo = new Device(successConnecting, successDisconnecting, failureConnecting); // Create Device instance for cont...
(){ //If we successfully conneced, switch the state of the connect button to enable disconnecting connectButtonEnabled(); connect_button.html("Disconnect"); } function connection_error_message(device_name){ if (device_name === "controller") { display_overlay("connection","Could not connect to controller"...
connectButtonConnected
identifier_name
FilterBar.js
//>>built require({cache:{"url:gridx/templates/FilterBar.html":"<input type=\"button\" data-dojo-type=\"dijit.form.Button\" data-dojo-props=\"\n\ticonClass: 'gridxFilterBarBtnIcon',\n\tlabel: '...',\n\ttitle: '${defineFilter}'\" aria-label='${defineFilter}'\n/><div class=\"gridxFilterBarStatus\"\n\t><span>${noFilterApp...
var d=new Date(); d.setFullYear(parseInt(RegExp.$1)); d.setMonth(parseInt(RegExp.$2)-1); return d; },_stringToTime:function(s,_38){ _38=_38||/(\d\d?):(\d\d?):(\d\d?)/; _38.test(s); var d=new Date(); d.setHours(parseInt(RegExp.$1)); d.setMinutes(parseInt(RegExp.$2)); d.setSeconds(parseInt(RegExp.$3)); return d; },_forma...
return exp; },_stringToDate:function(s,_37){ _37=_37||/(\d{4})\/(\d\d?)\/(\d\d?)/; _37.test(s);
random_line_split
FilterBar.js
//>>built require({cache:{"url:gridx/templates/FilterBar.html":"<input type=\"button\" data-dojo-type=\"dijit.form.Button\" data-dojo-props=\"\n\ticonClass: 'gridxFilterBarBtnIcon',\n\tlabel: '...',\n\ttitle: '${defineFilter}'\" aria-label='${defineFilter}'\n/><div class=\"gridxFilterBarStatus\"\n\t><span>${noFilterApp...
},uninitialize:function(){ this._filterDialog&&this._filterDialog.destroyRecursive(); this.inherited(arguments); _6.destroy(this.domNode); },_getColumnConditions:function(_1f){ var _20,_21; if(!_1f){ _20=[]; _21="string"; }else{ _20=this.grid._columnsById[_1f].disabledConditions||[]; _21=(this.grid._columnsById[_1f].d...
{ dlg.setData(this.filterData); }
conditional_block
sliding-puzzle.py
# 1 kyu # Sliding Puzzle Solver # https://www.codewars.com/kata/sliding-puzzle-solver/python import numpy as np import queue def compare(a, b): if a == b: return 0 if a > b: return 1 if a < b: return -1 class Puzzle: def __init__(self, puzzle): self.puzzle = np.array...
if not possible_paths: # Error check, shouldn't happen on solvable puzzles print(f'Could not find any good adjacent cases for {self.y}, {self.x}') for path in self.paths: print(f'({path.y}, {path.x}), solved = {path.solved}') print(puzzle.puzzle) ...
possible_paths.append((relative_to.distance_to(path), path))
random_line_split
sliding-puzzle.py
# 1 kyu # Sliding Puzzle Solver # https://www.codewars.com/kata/sliding-puzzle-solver/python import numpy as np import queue def compare(a, b): if a == b: return 0 if a > b: return 1 if a < b: return -1 class Puzzle: def __init__(self, puzzle): self.puzzle = np.array...
def best_adjacent(self, puzzle, relative_to): # y1, x1 = relative_to.y, relative_to.x possible_paths = [] for path in self.paths: if not path.solved: # Changed to distance_to # OLD: possible_paths.append((abs(y1-path.y)+abs(x1-path.x), path)) ...
height, width = puzzle.shape if self.y > 0: self.paths.append(puzzle[self.y-1, self.x]) if self.y < height-1: self.paths.append(puzzle[self.y+1, self.x]) if self.x > 0: self.paths.append(puzzle[self.y, self.x-1]) if self.x < width-1: self.p...
identifier_body
sliding-puzzle.py
# 1 kyu # Sliding Puzzle Solver # https://www.codewars.com/kata/sliding-puzzle-solver/python import numpy as np import queue def compare(a, b): if a == b: return 0 if a > b: return 1 if a < b: return -1 class Puzzle: def __init__(self, puzzle): self.puzzle = np.array...
self.solve_number(line[-2], solutions[-2]) self.solve_number(line[-1], solutions[-1]) return True def smol_solve(self): # First solves top row & column, etc, until 2x3 block left # helper_case[0] is below the last case of the row (row+1, -1) # helper_case[1] is to...
self.solve_number(helper_cases[1], line[-2].value, ignore=[helper_cases[0], line[-1]], solve=False)
conditional_block
sliding-puzzle.py
# 1 kyu # Sliding Puzzle Solver # https://www.codewars.com/kata/sliding-puzzle-solver/python import numpy as np import queue def compare(a, b): if a == b: return 0 if a > b: return 1 if a < b: return -1 class Puzzle: def __init__(self, puzzle): self.puzzle = np.array...
(self, puzzle, relative_to): # y1, x1 = relative_to.y, relative_to.x possible_paths = [] for path in self.paths: if not path.solved: # Changed to distance_to # OLD: possible_paths.append((abs(y1-path.y)+abs(x1-path.x), path)) possible_...
best_adjacent
identifier_name
types.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: alameda_api/v1alpha1/datahub/schemas/types.proto package schemas import ( fmt "fmt" common "github.com/containers-ai/api/alameda_api/v1alpha1/datahub/common" common1 "github.com/containers-ai/api/common" proto "github.com/golang/protobuf/proto" math "ma...
1: "TABLE_APPLICATION", 2: "TABLE_METRIC", 3: "TABLE_PLANNING", 4: "TABLE_PREDICTION", 5: "TABLE_RESOURCE", 6: "TABLE_RECOMMENDATION", } var Table_value = map[string]int32{ "TABLE_UNDEFINED": 0, "TABLE_APPLICATION": 1, "TABLE_METRIC": 2, "TABLE_PLANNING": 3, "TABLE_PREDICTION": 4, ...
Table_TABLE_RECOMMENDATION Table = 6 ) var Table_name = map[int32]string{ 0: "TABLE_UNDEFINED",
random_line_split
types.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: alameda_api/v1alpha1/datahub/schemas/types.proto package schemas import ( fmt "fmt" common "github.com/containers-ai/api/alameda_api/v1alpha1/datahub/common" common1 "github.com/containers-ai/api/common" proto "github.com/golang/protobuf/proto" math "ma...
(b []byte) error { return xxx_messageInfo_Mesaurement.Unmarshal(m, b) } func (m *Mesaurement) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Mesaurement.Marshal(b, m, deterministic) } func (m *Mesaurement) XXX_Merge(src proto.Message) { xxx_messageInfo_Mesaurement.Merge(m, src) } ...
XXX_Unmarshal
identifier_name
types.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: alameda_api/v1alpha1/datahub/schemas/types.proto package schemas import ( fmt "fmt" common "github.com/containers-ai/api/alameda_api/v1alpha1/datahub/common" common1 "github.com/containers-ai/api/common" proto "github.com/golang/protobuf/proto" math "ma...
return "" } type Mesaurement struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` MetricType common.MetricType `protobuf:"varint,2,opt,name=metric_type,json=metricType,proto3,enum=containersai.alameda.v1alpha1.datahub.common.MetricType" json:"met...
{ return m.Type }
conditional_block
types.pb.go
// Code generated by protoc-gen-go. DO NOT EDIT. // source: alameda_api/v1alpha1/datahub/schemas/types.proto package schemas import ( fmt "fmt" common "github.com/containers-ai/api/alameda_api/v1alpha1/datahub/common" common1 "github.com/containers-ai/api/common" proto "github.com/golang/protobuf/proto" math "ma...
func (m *SchemaMeta) GetType() string { if m != nil { return m.Type } return "" } type Mesaurement struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` MetricType common.MetricType `protobuf:"varint,2,opt,name=metric_type,json=metricType,pro...
{ if m != nil { return m.Category } return "" }
identifier_body
Hyphenation.qunit.js
/*global QUnit, sinon */ sap.ui.define("sap/ui/core/qunit/Hyphenation.qunit", [ "sap/ui/core/hyphenation/Hyphenation", "sap/ui/core/hyphenation/HyphenationTestingWords", "sap/ui/dom/includeScript", "sap/base/Log", "sap/ui/Device", "sap/ui/qunit/utils/createAndAppendDiv", "sap/ui/core/Configuration" ], function(...
e().getLanguage().toLowerCase(); // adjustment of the language to correspond to Hyphenopoly pattern files (.hpb files) switch (sMappedLanguage) { case "en": sMappedLanguage = "en-us"; break; case "nb": sMappedLanguage = "nb-no"; break; case "no": sMappedLanguage = "nb-no"; break; ...
ation.getLocal
identifier_name
Hyphenation.qunit.js
/*global QUnit, sinon */ sap.ui.define("sap/ui/core/qunit/Hyphenation.qunit", [ "sap/ui/core/hyphenation/Hyphenation", "sap/ui/core/hyphenation/HyphenationTestingWords", "sap/ui/dom/includeScript", "sap/base/Log", "sap/ui/Device", "sap/ui/qunit/utils/createAndAppendDiv", "sap/ui/core/Configuration" ], function(...
sDefaultLang = getDefaultLang(); assert.strictEqual(this.oHyphenation.isLanguageInitialized(sDefaultLang), true, "default lang '" + sDefaultLang + "' was initialized"); done(); }.bind(this)); }); QUnit.test("initialize only single language - " + sSingleLangTest, function(assert) { assert.expect(2); va...
test for this language if (!HyphenationTestingWords[sMappedLanguage]) { return false; } oTestDiv.lang = sLanguageOnThePage; oTestDiv.innerText = HyphenationTestingWords[sMappedLanguage]; // Chrome on macOS partially supported native hyphenation. It didn't hyphenate one word more than once. if (Device....
identifier_body
Hyphenation.qunit.js
/*global QUnit, sinon */ sap.ui.define("sap/ui/core/qunit/Hyphenation.qunit", [ "sap/ui/core/hyphenation/Hyphenation", "sap/ui/core/hyphenation/HyphenationTestingWords", "sap/ui/dom/includeScript", "sap/base/Log", "sap/ui/Device", "sap/ui/qunit/utils/createAndAppendDiv", "sap/ui/core/Configuration" ], function(...
if (!HyphenationTestingWords[sMappedLanguage]) { return false; } oTestDiv.lang = sLanguageOnThePage; oTestDiv.innerText = HyphenationTestingWords[sMappedLanguage]; // Chrome on macOS partially supported native hyphenation. It didn't hyphenate one word more than once. if (Device.os.macintosh && Device.b...
// we don't have a word to test for this language
random_line_split
Hyphenation.qunit.js
/*global QUnit, sinon */ sap.ui.define("sap/ui/core/qunit/Hyphenation.qunit", [ "sap/ui/core/hyphenation/Hyphenation", "sap/ui/core/hyphenation/HyphenationTestingWords", "sap/ui/dom/includeScript", "sap/base/Log", "sap/ui/Device", "sap/ui/qunit/utils/createAndAppendDiv", "sap/ui/core/Configuration" ], function(...
test("can use native hyphenation", function(assert) { assert.strictEqual(canUseNativeHyphenationRaw(), this.oHyphenation.canUseNativeHyphenation(), "The Hyphenation instance should give the same result as the raw check."); }); QUnit.test("hyphenate example words", function(assert) { var done = assert.async(), ...
}); }); QUnit.
conditional_block
MuseScraper.py
#!/usr/bin/env python3 from typing import Union, Optional, Any, List, Dict import os import sys from pkgutil import get_data from abc import ABC import pyppeteer import asyncio import requests import io from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF from PyPDF2 import PdfFileMerger from...
quiet: bool = False, proxy_server: Optional[str] = None, ): locs: Dict[str, Any] = locals() super().__init__(**{ k : v for k, v in locs.items() if not re.match(r"_|self$", k) }) if proxy_server: task: asyncio.Task = asyncio.create_task( ...
def __init__( self, *, debug_log: Union[None, str, Path] = None, timeout: float = 120,
random_line_split
MuseScraper.py
#!/usr/bin/env python3 from typing import Union, Optional, Any, List, Dict import os import sys from pkgutil import get_data from abc import ABC import pyppeteer import asyncio import requests import io from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF from PyPDF2 import PdfFileMerger from...
async def __aenter__(self): return self async def __aexit__(self, exc_type, exc_value, exc_traceback) -> None: await self.close() async def to_pdf( self, url: str, output: Union[None, str, Path] = None, ) -> Path: """ Extracts the i...
""" Closes browser. Should be called only once after all uses. :rtype: ``None`` """ await self._check_browser() await super()._close()
identifier_body
MuseScraper.py
#!/usr/bin/env python3 from typing import Union, Optional, Any, List, Dict import os import sys from pkgutil import get_data from abc import ABC import pyppeteer import asyncio import requests import io from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF from PyPDF2 import PdfFileMerger from...
score_name: str = ( await (await ( await page.querySelector("h1")).getProperty("innerText")).jsonValue()) score_creator: str = await (await ( await page.querySelector("h2")).getProperty("innerText")).jsonValue() a...
raise ConnectionError(f"Received <{response.status}> response.")
conditional_block
MuseScraper.py
#!/usr/bin/env python3 from typing import Union, Optional, Any, List, Dict import os import sys from pkgutil import get_data from abc import ABC import pyppeteer import asyncio import requests import io from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF from PyPDF2 import PdfFileMerger from...
(self): return self def close(self) -> None: """ Closes browser. Should be called only once after all uses. :rtype: ``None`` """ asyncio.get_event_loop().run_until_complete(super()._close()) def __exit__(self, exc_type, exc_value, exc_traceback) -> None: ...
__enter__
identifier_name
Orders.js
import React, { useEffect, useLayoutEffect, useState } from 'react'; import moment from 'moment'; import { connect } from 'react-redux'; import { t } from 'ttag'; import { OrderStatus, TPDI, TPDProvider } from '@sentinel-hub/sentinelhub-js'; import { extractErrorMessage, fetchOrders, fetchUserBYOCLayers, getBes...
}); break; default: } }; return ( <div className="commercial-data-orders"> {isLoading ? ( <div className="loader"> <i className="fa fa-spinner fa-spin fa-fw" /> </div> ) : ( orderStatus.map((item) => ( <OrdersByStatus ...
message: t`Are you sure you want to delete this order?`, action: () => deleteOrderAction(order), showCancel: true,
random_line_split
snippet.py
#!/usr/bin/env python3 # # Exploit for "assignment" of GoogleCTF 2017 # # CTF-quality exploit... # # Slightly simplified and shortened explanation: # # The bug is a UAF of one or both values during add_assign() if a GC is # triggered during allocate_value(). The exploit first abuses this to leak a # pointer into the he...
self): """Interact with the remote end: connect stdout and stdin to the socket.""" # TODO maybe use this at some point: https://docs.python.org/3/library/selectors.html self._verbose = False try: while True: available, _, _ = select.select([sys.stdin, self._s]...
nteract(
identifier_name
snippet.py
#!/usr/bin/env python3 # # Exploit for "assignment" of GoogleCTF 2017 # # CTF-quality exploit... # # Slightly simplified and shortened explanation: # # The bug is a UAF of one or both values during add_assign() if a GC is # triggered during allocate_value(). The exploit first abuses this to leak a # pointer into the he...
elif length <= len(self.alphabet) ** 4: self._seq = self._generate(4)[:length] else: raise Exception("Pattern length is way to large") def _generate(self, n): """Generate a De Bruijn sequence.""" # See https://en.wikipedia.org/wiki/De_Bruijn_sequence ...
elf._seq = self._generate(3)[:length]
conditional_block
snippet.py
#!/usr/bin/env python3 # # Exploit for "assignment" of GoogleCTF 2017 # # CTF-quality exploit... # # Slightly simplified and shortened explanation: # # The bug is a UAF of one or both values during add_assign() if a GC is # triggered during allocate_value(). The exploit first abuses this to leak a # pointer into the he...
if t > n: if n % p == 0: sequence.extend(a[1:p + 1]) else: a[t] = a[t - p] db(t + 1, p) for j in range(a[t - p] + 1, k): a[t] = j db(t + 1, t) db(1, 1) retu...
def db(t, p):
random_line_split
snippet.py
#!/usr/bin/env python3 # # Exploit for "assignment" of GoogleCTF 2017 # # CTF-quality exploit... # # Slightly simplified and shortened explanation: # # The bug is a UAF of one or both values during add_assign() if a GC is # triggered during allocate_value(). The exploit first abuses this to leak a # pointer into the he...
def sendnum(n): c.sendnum(n) def recv(n): return c.recv(n) def recvtil(delim): return c.recvtil(delim) def recvn(n): return c.recvn(n) def recvline(): return c.recvline() def recvregex(r): return c.recvregex(r) def interact(): c.interact() # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ...
.sendline(l)
identifier_body
stream.py
import re import subprocess from sys import platform from time import time from functools import partial from shutil import which from pylsl import StreamInfo, StreamOutlet import pygatt from . import backends from . import helper from .muse import Muse from .constants import MUSE_SCAN_TIMEOUT, AUTO_DISCONNECT_DELAY,...
if not eeg_disabled: eeg_info = StreamInfo('Muse', 'EEG', MUSE_NB_EEG_CHANNELS, MUSE_SAMPLING_EEG_RATE, 'float32', 'Muse%s' % address) eeg_info.desc().append_child_value("manufacturer", "Muse") eeg_channels = eeg_info.desc().append_child("cha...
address = found_muse['address'] name = found_muse['name']
conditional_block
stream.py
import re import subprocess from sys import platform from time import time from functools import partial from shutil import which from pylsl import StreamInfo, StreamOutlet import pygatt from . import backends from . import helper from .muse import Muse from .constants import MUSE_SCAN_TIMEOUT, AUTO_DISCONNECT_DELAY,...
(timeout, verbose=False): """Identify Muse BLE devices using bluetoothctl. When using backend='gatt' on Linux, pygatt relies on the command line tool `hcitool` to scan for BLE devices. `hcitool` is however deprecated, and seems to fail on Bluetooth 5 devices. This function roughly replicates the fu...
_list_muses_bluetoothctl
identifier_name
stream.py
import re import subprocess from sys import platform from time import time from functools import partial from shutil import which from pylsl import StreamInfo, StreamOutlet import pygatt from . import backends from . import helper from .muse import Muse from .constants import MUSE_SCAN_TIMEOUT, AUTO_DISCONNECT_DELAY,...
if eeg_disabled and not ppg_enabled and not acc_enabled and not gyro_enabled: print('Stream initiation failed: At least one data source must be enabled.') return # For any backend except bluemuse, we will start LSL streams hooked up to the muse callbacks. if backend != 'bluemuse': if no...
identifier_body
stream.py
import re import subprocess from sys import platform from time import time from functools import partial from shutil import which from pylsl import StreamInfo, StreamOutlet import pygatt from . import backends from . import helper from .muse import Muse from .constants import MUSE_SCAN_TIMEOUT, AUTO_DISCONNECT_DELAY,...
muses = [{ 'name': re.findall('Muse.*', string=d)[0], 'address': re.findall(r'..:..:..:..:..:..', string=d)[0] } for d in devices if 'Muse' in d] _print_muse_list(muses) return muses # Returns the address of the Muse with the name provided, otherwise returns address of fir...
list_devices_cmd = ['bluetoothctl', 'devices'] devices = subprocess.run( list_devices_cmd, stdout=subprocess.PIPE).stdout.decode( 'utf-8').split('\n')
random_line_split
mpc_range_proof.go
package mbp import ( "crypto/rand" "crypto/sha256" "fmt" "math/big" ) // MPCRangeProof is a struct of secure multi-party computation range proof type MPCRangeProof struct { Comms []ECPoint A ECPoint S ECPoint T1 ECPoint T2 ECPoint Tau *big.Int Th *big.Int Mu *big.In...
// given the t_i values, we can generate commitments to them tau1, err := rand.Int(rand.Reader, EC.N) check(err) tau2, err := rand.Int(rand.Reader, EC.N) check(err) prip.Tau1 = tau1 prip.Tau2 = tau2 T1 := EC.G.Mult(t1, EC).Add(EC.H.Mult(tau1, EC), EC) //commitment to t1 T2 := EC.G.Mult(t2, EC).Add(...
random_line_split
mpc_range_proof.go
package mbp import ( "crypto/rand" "crypto/sha256" "fmt" "math/big" ) // MPCRangeProof is a struct of secure multi-party computation range proof type MPCRangeProof struct { Comms []ECPoint A ECPoint S ECPoint T1 ECPoint T2 ECPoint Tau *big.Int Th *big.Int Mu *big.In...
tsPerValue : (id+1)*bitsPerValue] z2j2n := zPowersTimesTwoVec[id*bitsPerValue : (id+1)*bitsPerValue] left := CalculateLMRP(aL, sL, cz, cx, EC) right := CalculateRMRP(aR, sR, yn, z2j2n, cz, cx, EC) share.Left = left share.Right = right // t0 t1 t2 t0 := prip.Tt0 t1 := prip.Tt1 t2 := prip.Tt2 th...
sPerValue+i] = new(big.Int).Mod(new(big.Int).Mul(PowerOfTwos[i], zp), EC.N) } } yn := PowerOfCY[id*bi
conditional_block
mpc_range_proof.go
package mbp import ( "crypto/rand" "crypto/sha256" "fmt" "math/big" ) // MPCRangeProof is a struct of secure multi-party computation range proof type MPCRangeProof struct { Comms []ECPoint A ECPoint S ECPoint T1 ECPoint T2 ECPoint Tau *big.Int Th *big.Int Mu *big.In...
*big.Int, prip *PrivateParams, EC CryptoParams) T1T2Commitment { t1t2 := T1T2Commitment{} // aL aR sL sR aL := prip.AL aR := prip.AR sL := prip.SL sR := prip.SR bitsPerValue := EC.V / m // PowerOfTwos PowerOfTwos := PowerVector(bitsPerValue, big.NewInt(2), EC) PowerOfCY := PowerVector(EC.V, ...
cy, cz
identifier_name
mpc_range_proof.go
package mbp import ( "crypto/rand" "crypto/sha256" "fmt" "math/big" ) // MPCRangeProof is a struct of secure multi-party computation range proof type MPCRangeProof struct { Comms []ECPoint A ECPoint S ECPoint T1 ECPoint T2 ECPoint Tau *big.Int Th *big.Int Mu *big.In...
PerValue := EC.V / m //changes: // check 1 changes since it includes all commitments // check 2 commitment generation is also different // verify the challenges chal1s256 := sha256.Sum256([]byte(mrp.A.X.String() + mrp.A.Y.String())) cy := new(big.Int).SetBytes(chal1s256[:]) if cy.Cmp(mrp.Cy) != 0 { ...
identifier_body
recovery_workflow.go
package main import ( "context" "errors" "time" "github.com/pborman/uuid" "go.uber.org/cadence" "go.uber.org/cadence/.gen/go/shared" "go.uber.org/cadence/activity" "go.uber.org/cadence/client" "go.uber.org/cadence/workflow" "go.uber.org/zap" "github.com/uber-common/cadence-samples/cmd/samples/common" "gi...
(events []*shared.HistoryEvent) ([]*SignalParams, error) { var signals []*SignalParams for _, event := range events { if event.GetEventType() == shared.EventTypeWorkflowExecutionSignaled { attr := event.WorkflowExecutionSignaledEventAttributes if attr.GetSignalName() == TripSignalName && attr.Input != nil && ...
extractSignals
identifier_name
recovery_workflow.go
package main import ( "context" "errors" "time" "github.com/pborman/uuid" "go.uber.org/cadence" "go.uber.org/cadence/.gen/go/shared" "go.uber.org/cadence/activity" "go.uber.org/cadence/client" "go.uber.org/cadence/workflow" "go.uber.org/zap" "github.com/uber-common/cadence-samples/cmd/samples/common" "gi...
} // Start new execution run newRun, err := cadenceClient.StartWorkflow(ctx, params.Options, "TripWorkflow", params.State) if err != nil { return err } // re-inject all signals to new run for _, s := range signals { cadenceClient.SignalWorkflow(ctx, execution.GetWorkflowId(), newRun.RunID, s.Name, s.Data)...
{ return err }
conditional_block
recovery_workflow.go
package main import ( "context" "errors" "time" "github.com/pborman/uuid" "go.uber.org/cadence" "go.uber.org/cadence/.gen/go/shared" "go.uber.org/cadence/activity" "go.uber.org/cadence/client" "go.uber.org/cadence/workflow" "go.uber.org/zap" "github.com/uber-common/cadence-samples/cmd/samples/common" "gi...
func extractSignals(events []*shared.HistoryEvent) ([]*SignalParams, error) { var signals []*SignalParams for _, event := range events { if event.GetEventType() == shared.EventTypeWorkflowExecutionSignaled { attr := event.WorkflowExecutionSignaledEventAttributes if attr.GetSignalName() == TripSignalName && ...
{ switch event.GetEventType() { case shared.EventTypeWorkflowExecutionStarted: attr := event.WorkflowExecutionStartedEventAttributes state, err := deserializeUserState(attr.Input) if err != nil { // Corrupted Workflow Execution State return nil, err } return &RestartParams{ Options: client.StartWor...
identifier_body
recovery_workflow.go
package main import ( "context" "errors" "time" "github.com/pborman/uuid" "go.uber.org/cadence" "go.uber.org/cadence/.gen/go/shared" "go.uber.org/cadence/activity" "go.uber.org/cadence/client" "go.uber.org/cadence/workflow" "go.uber.org/zap" "github.com/uber-common/cadence-samples/cmd/samples/common" "gi...
} func recoverSingleExecution(ctx context.Context, workflowID string) error { logger := activity.GetLogger(ctx) cadenceClient, err := getCadenceClientFromContext(ctx) if err != nil { return err } execution := &shared.WorkflowExecution{ WorkflowId: common.StringPtr(workflowID), } history, err := getHistory(...
return nil
random_line_split
tx_pool.go
package mainchain import ( "fmt" "sort" "sync" "time" "github.com/sixexorg/magnetic-ring/bactor" "github.com/sixexorg/magnetic-ring/config" "github.com/sixexorg/magnetic-ring/log" "github.com/ontio/ontology-eventbus/actor" "github.com/sixexorg/magnetic-ring/common" "github.com/sixexorg/magnetic-ring/core/...
func (pool *TxPool) refreshWaitPool() { if pool.waitPool.Len() > 0 { for k, _ := range pool.waitPool { pool.TxEnqueue(pool.waitPool[k]) } } pool.waitPool = make(types.Transactions, 0, 10000) pool.waitTxNum = make(map[common.Hash]uint8, 10000) } func (pool *TxPool) RefreshValidator() { if pool != nil && po...
{ pool := NewTxPool() poolActor := NewTxActor(pool) pid, err := startActor(poolActor, "txpoolAcotor") if err != nil { return nil, err } bactor.RegistActorPid(bactor.TXPOOLACTOR, pid) pool.txpoolPid = pid return pool, nil }
identifier_body
tx_pool.go
package mainchain import ( "fmt" "sort" "sync" "time" "github.com/sixexorg/magnetic-ring/bactor" "github.com/sixexorg/magnetic-ring/config" "github.com/sixexorg/magnetic-ring/log" "github.com/ontio/ontology-eventbus/actor" "github.com/sixexorg/magnetic-ring/common" "github.com/sixexorg/magnetic-ring/core/...
} pool.refreshWaitPool() //log.Info("func txpool RefreshValidator 02", "newTargetHeight", pool.stateValidator.TargetHeight, "txlen", pool.stateValidator.GetTxLen()) fmt.Println("func txpool RefreshValidator 02 ", "newTargetHeight=", pool.stateValidator.TargetHeight, " txlen=", pool.stateValidator.GetTxLen()) } fu...
{ pool.TxEnqueue(ch) }
conditional_block
tx_pool.go
package mainchain import ( "fmt" "sort" "sync" "time" "github.com/sixexorg/magnetic-ring/bactor" "github.com/sixexorg/magnetic-ring/config" "github.com/sixexorg/magnetic-ring/log" "github.com/ontio/ontology-eventbus/actor" "github.com/sixexorg/magnetic-ring/common" "github.com/sixexorg/magnetic-ring/core/...
() { if pool.waitPool.Len() > 0 { for k, _ := range pool.waitPool { pool.TxEnqueue(pool.waitPool[k]) } } pool.waitPool = make(types.Transactions, 0, 10000) pool.waitTxNum = make(map[common.Hash]uint8, 10000) } func (pool *TxPool) RefreshValidator() { if pool != nil && pool.stateValidator != nil { //log.In...
refreshWaitPool
identifier_name
tx_pool.go
package mainchain import ( "fmt" "sort" "sync" "time" "github.com/sixexorg/magnetic-ring/bactor" "github.com/sixexorg/magnetic-ring/config" "github.com/sixexorg/magnetic-ring/log" "github.com/ontio/ontology-eventbus/actor" "github.com/sixexorg/magnetic-ring/common" "github.com/sixexorg/magnetic-ring/core/...
ret, err := pool.stateValidator.VerifyTx(tx) if err != nil { log.Error("range pool.mustPackTxs verifyTx error", "ret", ret, "error", err) } }*/ objectiveTxs, err := pool.mainRadar.GenerateMainTxs() if err != nil { log.Error("GenerateMainTxs failed", "error", err) } for _, tx := range objectiveTxs { i...
/*for _, tx := range pool.mustPackTxs {
random_line_split
titanic5.py
# # read Titanic data # import numpy as np from sklearn import cross_validation from sklearn import tree from sklearn import ensemble import pandas as pd print("+++ Start of pandas' datahandling +++\n") # df here is a "dataframe": df = pd.read_csv('titanic5.csv', header=0) # read the file w/header row #0 # drop co...
if testing_avgScore > BestScore: BestScore = testing_avgScore best_n = n resultList += [[n, trainng_avgScore, testing_avgScore]] print ('The best average score and the corresponding n_estimator is: ') return BestScore, best_n # Run multiple trials and determine n value #...
random_line_split
titanic5.py
# # read Titanic data # import numpy as np from sklearn import cross_validation from sklearn import tree from sklearn import ensemble import pandas as pd print("+++ Start of pandas' datahandling +++\n") # df here is a "dataframe": df = pd.read_csv('titanic5.csv', header=0) # read the file w/header row #0 # drop co...
# Compute the average score for both traning and testing data trainng_avgScore = 1.0 * sum(trainng_score)/len(trainng_score) testing_avgScore = 1.0 * sum(testing_score)/len(testing_score) # find the best score if testing_avgScore > BestScore: BestScore = testing_avgSco...
ata_train, cv_data_test, cv_target_train, cv_target_test = \ cross_validation.train_test_split(X_train, y_train, test_size=0.1) # fit the model using the cross-validation data # and tune parameter, such as max_depth here rforest = rforest.fit(cv_data_train, cv_target...
conditional_block
titanic5.py
# # read Titanic data # import numpy as np from sklearn import cross_validation from sklearn import tree from sklearn import ensemble import pandas as pd print("+++ Start of pandas' datahandling +++\n") # df here is a "dataframe": df = pd.read_csv('titanic5.csv', header=0) # read the file w/header row #0 # drop co...
""" findRFBestDepth iterates through the model parameter, max_depth between 1 and 20 to determine which one performs best by returning the maximum testing_avgScore and the corresponding max_depth value when n_estimators is 100. """ resultList = [] BestScore = 0 # iterate thro...
RFBestDepth():
identifier_name
titanic5.py
# # read Titanic data # import numpy as np from sklearn import cross_validation from sklearn import tree from sklearn import ensemble import pandas as pd print("+++ Start of pandas' datahandling +++\n") # df here is a "dataframe": df = pd.read_csv('titanic5.csv', header=0) # read the file w/header row #0 # drop co...
Run multiple trials and determine max_depth value # for i in range(20): # print (findRFBestDepth()) def findRFBestN(): """ findRFBestN iterates through the model parameter, n_estimators between 1 and 200 that is the mutiple of 10 to determine which one performs best by returning the maximum tes...
findRFBestDepth iterates through the model parameter, max_depth between 1 and 20 to determine which one performs best by returning the maximum testing_avgScore and the corresponding max_depth value when n_estimators is 100. """ resultList = [] BestScore = 0 # iterate through diff...
identifier_body
apiserver.go
package nqas import ( native_context "context" "encoding/json" "fmt" "github.com/kataras/iris/v12" iris_logger "github.com/kataras/iris/v12/middleware/logger" iris_recover "github.com/kataras/iris/v12/middleware/recover" "local.lc/log" "net" "os" "os/signal" "runtime/debug" "strings" "sync" "syscall" "t...
Time = time.Now() startTime = endTime.Add(-30 * time.Second) } else { endTime = time.Unix(t.EndTime, 0) startTime = time.Unix(t.StartTime, 0) } //最大查询时间不超过1天,如果开始时间和结束事件相同,查询最近30s内的数据 if endTime.Sub(startTime) > 24*time.Hour { endTime = startTime.Add(24 * time.Hour) } data, err := queryNetQualityDataBySo...
<= 0 || t.EndTime <= 0 { end
identifier_name
apiserver.go
package nqas import ( native_context "context" "encoding/json" "fmt" "github.com/kataras/iris/v12" iris_logger "github.com/kataras/iris/v12/middleware/logger" iris_recover "github.com/kataras/iris/v12/middleware/recover" "local.lc/log" "net" "os" "os/signal" "runtime/debug" "strings" "sync" "syscall" "t...
ostQualityDataResponse struct { Code int `json:"code"` Message string `json:"message"` Data []*HostQuality `json:"data"` } /* 查询最近时刻时刻或者指定时刻的全量数据 */ func (a *APIServer) queryQualityDataTotalHandler(ctx iris.Context) { var t TimeStampFilterPayload if err := ctx.ReadJSON(&t); err != nil { ...
`json:"code"` Message string `json:"message"` Data []*InternetNetQuality `json:"data"` } type H
identifier_body
apiserver.go
package nqas import ( native_context "context" "encoding/json" "fmt" "github.com/kataras/iris/v12" iris_logger "github.com/kataras/iris/v12/middleware/logger" iris_recover "github.com/kataras/iris/v12/middleware/recover" "local.lc/log" "net" "os" "os/signal" "runtime/debug" "strings" "sync" "syscall" "t...
go func() { ch := make(chan os.Signal, 1) signal.Notify(ch, // kill -SIGINT XXXX 或 Ctrl+c os.Interrupt, syscall.SIGINT, // register that too, it should be ok // os.Kill等同于syscall.Kill os.Kill, syscall.SIGKILL, // register that too, it should be ok // kill -SIGTERM XXXX syscall.SIGTERM, ) ...
random_line_split
apiserver.go
package nqas import ( native_context "context" "encoding/json" "fmt" "github.com/kataras/iris/v12" iris_logger "github.com/kataras/iris/v12/middleware/logger" iris_recover "github.com/kataras/iris/v12/middleware/recover" "local.lc/log" "net" "os" "os/signal" "runtime/debug" "strings" "sync" "syscall" "t...
a} } d, err := json.Marshal(respBody) if err != nil { a.log.Error(err) } l := sync.Mutex{} l.Lock() a.qualityDataCache = d a.qualityDataRaw = data l.Unlock() } /* 周期性查询全量监控数据,然后分析告警。这里相当于把api接口和告警分析结合了起来 主要是避免数据多次查询,也是为了报警和和前端查询的结果一致。 */ func (a *APIServer) retrieveQualityDataAndAnalysisAuto(config *Con...
DataResponse{200, "", dat
conditional_block
packages.py
""" restriction classes designed for package level matching """ from snakeoil import klass from snakeoil.compatibility import IGNORED_EXCEPTIONS from snakeoil.klass import generic_equality, static_attrgetter from ..log import logger from . import boolean, restriction class PackageRestriction(restriction.base, metac...
elif not self.restriction.match(enabled): return if self.payload: boolean.AndRestriction(*self.payload).evaluate_conditionals( parent_cls, parent_seq, enabled, tristate_locked ) # "Invalid name" (pylint uses the module const regexp, not the class r...
return
conditional_block
packages.py
""" restriction classes designed for package level matching """ from snakeoil import klass from snakeoil.compatibility import IGNORED_EXCEPTIONS from snakeoil.klass import generic_equality, static_attrgetter from ..log import logger from . import boolean, restriction class PackageRestriction(restriction.base, metac...
str(exc), ) eargs = [x for x in exc.args if isinstance(x, str)] if any(x in attr_split for x in eargs): return False elif any("'%s'" % x in y for x in attr_split for y in eargs): # this is fairly horrible; probably ...
random_line_split
packages.py
""" restriction classes designed for package level matching """ from snakeoil import klass from snakeoil.compatibility import IGNORED_EXCEPTIONS from snakeoil.klass import generic_equality, static_attrgetter from ..log import logger from . import boolean, restriction class PackageRestriction(restriction.base, metac...
(PackageRestriction): __slots__ = () __inst_caching__ = True attr = None def force_False(self, pkg): attrs = self._pull_attr(pkg) if attrs is klass.sentinel: return not self.negate if self.negate: return self.restriction.force_True(pkg, self.attrs, attrs)...
PackageRestrictionMulti
identifier_name
packages.py
""" restriction classes designed for package level matching """ from snakeoil import klass from snakeoil.compatibility import IGNORED_EXCEPTIONS from snakeoil.klass import generic_equality, static_attrgetter from ..log import logger from . import boolean, restriction class PackageRestriction(restriction.base, metac...
@property def attrs(self): return tuple(".".join(x) for x in self._attr_split) def _parse_attr(self, attrs): object.__setattr__( self, "_pull_attr_func", tuple(map(static_attrgetter, attrs)) ) object.__setattr__(self, "_attr_split", tuple(x.split(".") for x in ...
attrs = self._pull_attr(pkg) if attrs is klass.sentinel: return self.negate if self.negate: return self.restriction.force_False(pkg, self.attrs, attrs) return self.restriction.force_True(pkg, self.attrs, attrs)
identifier_body
plasma.py
import os import random import socket import subprocess import time import libplasma PLASMA_ID_SIZE = 20 PLASMA_WAIT_TIMEOUT = 2 ** 30 class PlasmaBuffer(object): """This is the type of objects returned by calls to get with a PlasmaClient. We define our own class instead of directly returning a buffer object so ...
elif use_profiler: pid = subprocess.Popen(["valgrind", "--tool=callgrind"] + command) time.sleep(1.0) else: pid = subprocess.Popen(command) time.sleep(0.1) return plasma_store_name, pid def start_plasma_manager(store_name, redis_address, num_retries=20, use_valgrind=False, run_profiler=False): ...
pid = subprocess.Popen(["valgrind", "--track-origins=yes", "--leak-check=full", "--show-leak-kinds=all", "--error-exitcode=1"] + command) time.sleep(1.0)
conditional_block
plasma.py
import os import random import socket import subprocess import time import libplasma PLASMA_ID_SIZE = 20 PLASMA_WAIT_TIMEOUT = 2 ** 30 class PlasmaBuffer(object): """This is the type of objects returned by calls to get with a PlasmaClient. We define our own class instead of directly returning a buffer object so ...
(self, object_id): """Create a buffer from the PlasmaStore based on object ID. If the object has not been sealed yet, this call will block. The retrieved buffer is immutable. Args: object_id (str): A string used to identify an object. """ buff = libplasma.get(self.conn, object_id)[0] ...
get
identifier_name
plasma.py
import os import random import socket import subprocess import time import libplasma PLASMA_ID_SIZE = 20 PLASMA_WAIT_TIMEOUT = 2 ** 30 class PlasmaBuffer(object): """This is the type of objects returned by calls to get with a PlasmaClient. We define our own class instead of directly returning a buffer object so ...
def start_plasma_manager(store_name, redis_address, num_retries=20, use_valgrind=False, run_profiler=False): """Start a plasma manager and return the ports it listens on. Args: store_name (str): The name of the plasma store socket. redis_address (str): The address of the Redis server. use_valgrind (b...
"""Start a plasma store process. Args: use_valgrind (bool): True if the plasma store should be started inside of valgrind. If this is True, use_profiler must be False. use_profiler (bool): True if the plasma store should be started inside a profiler. If this is True, use_valgrind must be False. ...
identifier_body
plasma.py
import os import random import socket import subprocess import time import libplasma PLASMA_ID_SIZE = 20 PLASMA_WAIT_TIMEOUT = 2 ** 30 class PlasmaBuffer(object): """This is the type of objects returned by calls to get with a PlasmaClient. We define our own class instead of directly returning a buffer object so ...
def transfer(self, addr, port, object_id): """Transfer local object with id object_id to another plasma instance Args: addr (str): IPv4 address of the plasma instance the object is sent to. port (int): Port number of the plasma instance the object is sent to. object_id (str): A string used ...
""" return libplasma.evict(self.conn, num_bytes)
random_line_split
observing.rs
use std::ffi::CStr; use std::mem; use libc::c_void; use crate::bw; use crate::bw_1161::{self, vars}; pub unsafe fn process_commands_hook( data: *const u8, len: u32, replay: u32, orig: unsafe extern fn(*const u8, u32, u32), ) { if replay == 0 && *vars::current_command_player >= 8 { // Repl...
// To make observers appear in network timeout dialog, we temporarily write their info to // ingame player structure, and revert the change after this function has been called. let bw_players: &mut [bw::Player] = &mut vars::players[..8]; let actual_players: [bw::Player; 8] = { let mut players:...
{ if (*vars::timeout_bin).is_null() { return None; } let mut label = find_dialog_child(*vars::timeout_bin, -10)?; let mut label_count = 0; while !label.is_null() && label_count < 8 { // Flag 0x8 == Shown if (*label).flags & 0x8 != 0 && (*label)...
identifier_body
observing.rs
use std::ffi::CStr; use std::mem; use libc::c_void; use crate::bw; use crate::bw_1161::{self, vars}; pub unsafe fn process_commands_hook( data: *const u8, len: u32, replay: u32, orig: unsafe extern fn(*const u8, u32, u32), ) { if replay == 0 && *vars::current_command_player >= 8 { // Repl...
( storm_player: u32, message: *const u8, length: u32, orig: unsafe extern fn(u32, *const u8, u32) -> u32, ) -> u32 { use std::io::Write; if vars::storm_id_to_human_id[storm_player as usize] >= 8 { // Observer message, we'll have to manually print text and add to replay recording. ...
chat_message_hook
identifier_name
observing.rs
use std::ffi::CStr; use std::mem; use libc::c_void; use crate::bw; use crate::bw_1161::{self, vars}; pub unsafe fn process_commands_hook( data: *const u8, len: u32, replay: u32, orig: unsafe extern fn(*const u8, u32, u32), ) { if replay == 0 && *vars::current_command_player >= 8 { // Repl...
unsafe fn is_local_player_observer() -> bool { // Should probs use shieldbattery's data instead of checking BW variables, // but we don't have anything that's readily accessible by game thread. *vars::local_nation_id == !0 } pub unsafe fn with_replay_flag_if_obs<F: FnOnce() -> R, R>(func: F) -> R { let...
} None }
random_line_split
observing.rs
use std::ffi::CStr; use std::mem; use libc::c_void; use crate::bw; use crate::bw_1161::{self, vars}; pub unsafe fn process_commands_hook( data: *const u8, len: u32, replay: u32, orig: unsafe extern fn(*const u8, u32, u32), ) { if replay == 0 && *vars::current_command_player >= 8 { // Repl...
} } for (i, player) in actual_players.iter().enumerate() { vars::players[i] = player.clone(); } } pub unsafe fn update_command_card_hook(orig: unsafe extern fn()) { if is_local_player_observer() && !(*vars::primary_selected).is_null() { *vars::local_nation_id = (**vars::primary...
{ // We need to redirect the name string to the storm player string, and replace the // player value to unused player 10, whose color will be set to neutral resource // color. (The neutral player 11 actually can have a different color for neutral // buildi...
conditional_block
parser.go
package queryme import ( "fmt" "errors" "net/url" "strconv" "strings" "time" "unicode/utf8" ) /* predicates = predicate *("," predicate) predicate = (not / and / or / eq / lt / le / gt / ge) not = "not" "(" predicate ")" and = "and" "(" predicates ")" or = "or" "(" predica...
(s string) (p Predicate, n string) { if len(s) == 0 { panic(OperatorExpected) } var op string op, n = parseIdentifier(s) n = parseLiteral(n, "(") var f string var ps []Predicate var vs []Value var v Value switch op { case "not": var operand Predicate operand, n = parsePredicate(n) p = Not{ope...
parsePredicate
identifier_name
parser.go
package queryme import ( "fmt" "errors" "net/url" "strconv" "strings" "time" "unicode/utf8" ) /* predicates = predicate *("," predicate) predicate = (not / and / or / eq / lt / le / gt / ge) not = "not" "(" predicate ")" and = "and" "(" predicates ")" or = "or" "(" predica...
for { var o *SortOrder o, s = parseSortOrder(s) os = append(os, o) if len(s) == 0 { break } if r, l := utf8.DecodeRuneInString(s); r != ',' { panic(SortOrderSeparatorExpected) } else { s = s[l:] } } } n = s return } func parseSortOrder(s string) (o *SortOrder, n string) { ...
func parseSortOrders(s string) (os []*SortOrder, n string) { os = make([]*SortOrder, 0, 4) if len(s) > 0 {
random_line_split
parser.go
package queryme import ( "fmt" "errors" "net/url" "strconv" "strings" "time" "unicode/utf8" ) /* predicates = predicate *("," predicate) predicate = (not / and / or / eq / lt / le / gt / ge) not = "not" "(" predicate ")" and = "and" "(" predicates ")" or = "or" "(" predica...
func parseSortOrder(s string) (o *SortOrder, n string) { o = new(SortOrder) if r, _ := utf8.DecodeRuneInString(s); r == '!' { s = s[1:] } else { o.Ascending = true } f, n := parseIdentifier(s) o.Field = Field(f) return } func ParseIdentifier(s string) (Value, error) { v, n := parseIdentifier(s) if n !...
{ os = make([]*SortOrder, 0, 4) if len(s) > 0 { for { var o *SortOrder o, s = parseSortOrder(s) os = append(os, o) if len(s) == 0 { break } if r, l := utf8.DecodeRuneInString(s); r != ',' { panic(SortOrderSeparatorExpected) } else { s = s[l:] } } } n = s return }
identifier_body
parser.go
package queryme import ( "fmt" "errors" "net/url" "strconv" "strings" "time" "unicode/utf8" ) /* predicates = predicate *("," predicate) predicate = (not / and / or / eq / lt / le / gt / ge) not = "not" "(" predicate ")" and = "and" "(" predicates ")" or = "or" "(" predica...
for i := int('a'); i <= int('z'); i++ { characters[i] = 5 } for i := int('A'); i <= int('Z'); i++ { characters[i] = 5 } } func firstCharClass(s string) byte { r, _ := utf8.DecodeRuneInString(s) if r > 127 { return 0 } else { return characters[r] } } func charClassDetector(min byte, max byte) func(r...
{ characters[i] = 5 }
conditional_block
uint.rs
use alloc::vec::Vec; use common::ceil_div; use core::cmp::Ord; use core::cmp::Ordering; use core::marker::PhantomData; use core::ops; use core::ops::Div; use core::ops::Index; use core::ops::IndexMut; use generic_array::{arr::AddLength, ArrayLength, GenericArray}; use typenum::Quot; use typenum::{Prod, U32}; use crat...
out } } impl PartialEq for SecureBigUint { fn eq(&self, other: &Self) -> bool { self.cmp(other) == Ordering::Equal } } impl Eq for SecureBigUint {} impl PartialOrd for SecureBigUint { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } imp...
{ out = Ordering::Equal; }
conditional_block
uint.rs
use alloc::vec::Vec; use common::ceil_div; use core::cmp::Ord; use core::cmp::Ordering; use core::marker::PhantomData; use core::ops; use core::ops::Div; use core::ops::Index; use core::ops::IndexMut; use generic_array::{arr::AddLength, ArrayLength, GenericArray}; use typenum::Quot; use typenum::{Prod, U32}; use crat...
/// In-place increases the size pub fn extend(&mut self, bit_width: usize) { let new_len = ceil_div(bit_width, BASE_BITS); assert!(new_len >= self.value.len()); self.value.resize(new_len, 0); } pub fn from_str(s: &str, bit_width: usize) -> common::errors::Result<Self> { ...
{ for v in self.value.iter_mut() { *v = 0; } }
identifier_body
uint.rs
use alloc::vec::Vec; use common::ceil_div; use core::cmp::Ord; use core::cmp::Ordering; use core::marker::PhantomData; use core::ops; use core::ops::Div; use core::ops::Index; use core::ops::IndexMut; use generic_array::{arr::AddLength, ArrayLength, GenericArray}; use typenum::Quot; use typenum::{Prod, U32}; use crat...
reduced.copy_if(!overflow, self); self.truncate(modulus.bit_width()); } #[must_use] pub fn shl(&mut self) -> BaseType { let mut carry = 0; for v in self.value.iter_mut() { let (new_v, _) = v.overflowing_shl(1); let new_carry = *v >> 31; *v...
/// /// Will panic if 'self' was >= 2*modulus pub fn reduce_once(&mut self, modulus: &Self) { let mut reduced = Self::from_usize(0, self.bit_width()); let overflow = self.overflowing_sub_to(modulus, &mut reduced);
random_line_split
uint.rs
use alloc::vec::Vec; use common::ceil_div; use core::cmp::Ord; use core::cmp::Ordering; use core::marker::PhantomData; use core::ops; use core::ops::Div; use core::ops::Index; use core::ops::IndexMut; use generic_array::{arr::AddLength, ArrayLength, GenericArray}; use typenum::Quot; use typenum::{Prod, U32}; use crat...
(&mut self, n: usize) { let byte_shift = n / BASE_BITS; let carry_size = n % BASE_BITS; let carry_mask = ((1 as BaseType) << carry_size).wrapping_sub(1); for i in 0..self.value.len() { let v = self.value[i]; self.value[i] = 0; if i < byte_shift { ...
shr_n
identifier_name
Parameter.py
# -*- coding: utf-8 -*- import unittest from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException from random import Random from datetime import datetime import unittest, time, re, os import json import requests import csv ran...
about_us_expect = '关于创富' #登入帳戶 main_user_id = '81134740' main_user_demo_id = '11092003' main_user_password = 'abc123' #包為CF3 else: # 指定apk路徑 apk_url = dir_path + 'release-cf3-1.8.5-release_185_jiagu_sign_zp-update&utm_medium=bycfd.apk' # 應用名稱&版本號(用於關於我們檢查) app_name_version_expect = '白银交易平台 V_1.8.5' # 關於創富(用於...
富(用於關於創富檢查) about_us_expect = '关于神龙科技' #登入帳戶 main_user_id = '81018322' main_user_demo_id = '11002074' main_user_password = 'abc123' #包為CF2 elif(package_name == 'com.gwtsz.gts2.cf2'): #指定apk路徑 apk_url = dir_path + '/20201120-prd-cf2-1.8.3-release.apk' #應用名稱&版本號(用於關於我們檢查) app_name_version_expect = '柯洛夫黃金平台 V_1.8...
conditional_block
Parameter.py
# -*- coding: utf-8 -*- import unittest from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException from random import Random from datetime import datetime import unittest, time, re, os import json import requests import csv ran...
'noReset':True } #每次開啟重置app desired_caps_reset = { 'platformName':desired_caps['platformName'], 'platformVersion':desired_caps['platformVersion'], 'deviceName':desired_caps['deviceName'], 'appPackage':desired_caps['appPackage'], 'appActivity':desired_caps['appActivity'], 'newCommandTimeout':...
'deviceName':'Mi 9t', 'appPackage': package_name, 'appActivity':'gw.com.android.ui.WelcomeActivity', 'newCommandTimeout':6000,
random_line_split
Parameter.py
# -*- coding: utf-8 -*- import unittest from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException from random import Random from datetime import datetime import unittest, time, re, os import json import requests import csv ran...
nt_type,'',current_time,package_name] writed_csv.append(account_information) #寫入CSV writer.writerows(writed_csv)
identifier_body
Parameter.py
# -*- coding: utf-8 -*- import unittest from appium import webdriver from appium.webdriver.common.touch_action import TouchAction from selenium.common.exceptions import NoSuchElementException from random import Random from datetime import datetime import unittest, time, re, os import json import requests import csv ran...
id.widget.RelativeLayout/android.widget.RelativeLayout/android.widget.RelativeLayout/android.widget.RelativeLayout/androidx.recyclerview.widget.RecyclerView/android.widget.RelativeLayout[2]/android.widget.LinearLayout/android.widget.ImageView") element.click() #交易tab def click_transaction(self): element = self.driver...
idget.FrameLayout/andro
identifier_name
app.ts
import { d, o, MaybeObservable, Observable, ObserverFunction, VirtualHolder, NodeCreatorFn } from 'domic' export type Instantiator<T> = new (...a: any[]) => T /** * */ export class ServiceConfig { service: Instantiator<Service> params: any[] = [] constructor(service: Instantiator<Service>, .....
// free the old resolver so it can be garbage collected. this.old_resolver = null } /** * Call all the init() of the services. * * @returns: A promise of when the initiation will be done. */ init(): Promise<any> { let promises: Promise<any>[] = [] this.services.forEach(serv => { ...
{ this.old_resolver.services.forEach((serv, type) => { if (this.services.get(type) !== serv) { serv.destroy() } }) }
conditional_block
app.ts
import { d, o, MaybeObservable, Observable, ObserverFunction, VirtualHolder, NodeCreatorFn } from 'domic' export type Instantiator<T> = new (...a: any[]) => T /** * */ export class ServiceConfig { service: Instantiator<Service> params: any[] = [] constructor(service: Instantiator<Service>, .....
(block: Block): Node { var comment = document.createComment(' DisplayBlock ') var displayer = new BlockDisplayer(block) displayer.addToNode(comment) return comment }
DisplayBlock
identifier_name
app.ts
import { d, o, MaybeObservable, Observable, ObserverFunction, VirtualHolder, NodeCreatorFn } from 'domic' export type Instantiator<T> = new (...a: any[]) => T /** * */ export class ServiceConfig { service: Instantiator<Service> params: any[] = [] constructor(service: Instantiator<Service>, ......
ondestroy: (() => any)[] = [] _dependencies: Array<Service> = [] protected _initPromise: Promise<any> constructor(app: App) { this.app = app } // static with<Z, A, B, C, D, E, F>(this: new (app: App, a: A, b: B, c: C, d: D, e: E, f: F) => Z, a: A, b: B, c: C, d: D, e: E, f: F): ServiceConfig; // st...
*/ export class Service { app: App
random_line_split
image-clip.component.ts
import { ViewChild, Component, ElementRef, ChangeDetectorRef, SimpleChanges, AfterViewInit, OnInit, OnChanges, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; import { HttpEventType } from '@angular/common/http'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import * as Rx ...
getInset(): string{ return 'inset(' + this.clipPath.value[0].y + '% ' + (100 - this.clipPath.value[1].x) + '% ' + (100 - this.clipPath.value[2].y) + '% ' + this.clipPath.value[3].x + '%)'; } getClipPath() { if (!this.clipPath) return ''; switch(this.clipPath.type) { case 'polygon': return t...
{ return 'ellipse(' + Math.abs(50-this.clipPath.value[0].x) + '% ' + Math.abs(50-this.clipPath.value[1].y) + '% at ' + this.clipPath.value[2].x + '% ' + this.clipPath.value[2].y + '%)'; }
identifier_body
image-clip.component.ts
import { ViewChild, Component, ElementRef, ChangeDetectorRef, SimpleChanges, AfterViewInit, OnInit, OnChanges, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; import { HttpEventType } from '@angular/common/http'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import * as Rx ...
() { if (!this.clipPath) return ''; switch(this.clipPath.type) { case 'polygon': return this.sanitizer.bypassSecurityTrustStyle(this.getPolygon()); case 'ellipse': return this.sanitizer.bypassSecurityTrustStyle(this.getEllipse()); case 'circle': return this.sanitizer.bypassSecurityTrust...
getClipPath
identifier_name
image-clip.component.ts
import { ViewChild, Component, ElementRef, ChangeDetectorRef, SimpleChanges, AfterViewInit, OnInit, OnChanges, OnDestroy, Input, Output, EventEmitter } from '@angular/core'; import { HttpEventType } from '@angular/common/http'; import { DomSanitizer, SafeStyle } from '@angular/platform-browser'; import * as Rx ...
ngOnDestroy() { if (this.subs) { this.subs.forEach(s => s.unsubscribe()); } } }
random_line_split
data_providers.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package testbed // import "github.com/open-telemetry/opentelemetry-collector-contrib/testbed/testbed" import ( "log" "strconv" "sync/atomic" "time" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/pdata/pcommo...
(dataItemsGenerated *atomic.Uint64) { dp.dataItemsGenerated = dataItemsGenerated } func (dp *perfTestDataProvider) GenerateTraces() (ptrace.Traces, bool) { traceData := ptrace.NewTraces() spans := traceData.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans() spans.EnsureCapacity(dp.options.ItemsPerBat...
SetLoadGeneratorCounters
identifier_name
data_providers.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package testbed // import "github.com/open-telemetry/opentelemetry-collector-contrib/testbed/testbed" import ( "log" "strconv" "sync/atomic" "time" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/pdata/pcommo...
func (dp *FileDataProvider) GenerateTraces() (ptrace.Traces, bool) { dp.dataItemsGenerated.Add(uint64(dp.ItemsPerBatch)) return dp.traces, false } func (dp *FileDataProvider) GenerateMetrics() (pmetric.Metrics, bool) { dp.dataItemsGenerated.Add(uint64(dp.ItemsPerBatch)) return dp.metrics, false } func (dp *File...
{ dp.dataItemsGenerated = dataItemsGenerated }
identifier_body
data_providers.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package testbed // import "github.com/open-telemetry/opentelemetry-collector-contrib/testbed/testbed" import ( "log" "strconv" "sync/atomic" "time" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/pdata/pcommo...
} metrics := rm.ScopeMetrics().AppendEmpty().Metrics() metrics.EnsureCapacity(dp.options.ItemsPerBatch) for i := 0; i < dp.options.ItemsPerBatch; i++ { metric := metrics.AppendEmpty() metric.SetDescription("Load Generator Counter #" + strconv.Itoa(i)) metric.SetUnit("1") dps := metric.SetEmptyGauge().Data...
{ attrs.PutStr(k, v) }
conditional_block
data_providers.go
// Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 package testbed // import "github.com/open-telemetry/opentelemetry-collector-contrib/testbed/testbed" import ( "log" "strconv" "sync/atomic" "time" "go.opentelemetry.io/collector/component" "go.opentelemetry.io/collector/pdata/pcommo...
type perfTestDataProvider struct { options LoadOptions traceIDSequence atomic.Uint64 dataItemsGenerated *atomic.Uint64 } // NewPerfTestDataProvider creates an instance of perfTestDataProvider which generates test data based on the sizes // specified in the supplied LoadOptions. func NewPerfTestDataPro...
random_line_split
AES.py
#! /usr/bin/env python from BitVector import BitVector RCON = [ 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0...
fout.close() enctxtout.close() def sub_word(word, sbox): newword = '' for i in xrange(0, 32, 8): [row, col] = word[i:i+8].divide_into_two() row = row.int_val() col = col.int_val() newword += str(BitVector(intVal=sbox[row][col])) return BitVector(bitstring=newword) ...
random_line_split
AES.py
#! /usr/bin/env python from BitVector import BitVector RCON = [ 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0...
def mix_cols(state): mod = BitVector(bitstring='100011011') bv2 = BitVector(hexstring='2') bv3 = BitVector(hexstring='3') for j in xrange(0, 4): # to select col s0 = state[0][j] s1 = state[1][j] s2 = state[2][j] s3 = state[3][j] sp0 = bv2.gf_multiply_modular(s0...
for i in xrange(1, 4): # to select row state[i] = state[i][i:4] + state[i][0:i]
identifier_body
AES.py
#! /usr/bin/env python from BitVector import BitVector RCON = [ 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0...
(state): mod = BitVector(bitstring='100011011') brw0 = [BitVector(hexstring='0e'), BitVector(hexstring='0b'), BitVector(hexstring='0d'), BitVector(hexstring='09')] brw1 = [brw0[3]] + brw0[1:4] brw2 = [brw1[3]] + brw1[1:4] brw3 = [brw2[3]] + brw2[1:4] for...
invmix_cols
identifier_name
AES.py
#! /usr/bin/env python from BitVector import BitVector RCON = [ 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0...
fout.close() enctxtout.close() def sub_word(word, sbox): newword = '' for i in xrange(0, 32, 8): [row, col] = word[i:i+8].divide_into_two() row = row.int_val() col = col.int_val() newword += str(BitVector(intVal=sbox[row][col])) return BitVector(bitstring=newword)...
for j in xrange(0, 4): enctxtout.write(rstate[i][j].get_hex_string_from_bitvector()) rstate[i][j].write_to_file(fout)
conditional_block