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 |
|---|---|---|---|---|
cpu.js | CHIP8.r.PC];
nextOp <<= 8;
nextOp |= CHIP8_MEM[CHIP8.r.PC + 1];
CHIP8.r.PC += 2;
CHIP8.handleTimers();
DEBUGGER.report(nextOp, CHIP8.do(nextOp));
},
// Performs an opcode operation
// Needs to handle all 35 opcodes!
do: function(op) {
firstDigit = (op & ... |
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 | (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 | handleOpF: function(reg, mode) {
switch (mode) {
case 0x07:
// SET VX to DELAY TIMER
CHIP8.r.V[reg] = CHIP8.r.TD;
return CODES.getDelay;
case 0x0A:
// WAIT FOR KEY
CHIP8.KH = reg + 0x1;
retur... | {
clearLoop();
DEBUGGER.slowMode = true;
FPS_INTERVAL = 200;
clockInterval = setInterval(loop, FPS_INTERVAL);
} | identifier_body | |
buffer_geometry.rs | 1,
BufferData::I16(_) => 1,
BufferData::U16(_) => 1,
BufferData::I8(_) => 1,
BufferData::U8(_) => 1,
}
}
pub fn len(&self) -> usize {
match self {
BufferData::Matrix2(a) => a.len(),
BufferData::Matrix3(a) => a.len(),
BufferData::Matrix4(a) => a.len(),
BufferData::Vector2(a) => a.len(),
... | (&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 | 1,
BufferData::I16(_) => 1,
BufferData::U16(_) => 1,
BufferData::I8(_) => 1,
BufferData::U8(_) => 1,
}
}
pub fn len(&self) -> usize {
match self {
BufferData::Matrix2(a) => a.len(),
BufferData::Matrix3(a) => a.len(),
BufferData::Matrix4(a) => a.len(),
BufferData::Vector2(a) => a.len(),
... |
}
#[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 | 1,
BufferData::I16(_) => 1,
BufferData::U16(_) => 1,
BufferData::I8(_) => 1,
BufferData::U8(_) => 1,
}
}
pub fn len(&self) -> usize {
match self {
BufferData::Matrix2(a) => a.len(),
BufferData::Matrix3(a) => a.len(),
BufferData::Matrix4(a) => a.len(),
BufferData::Vector2(a) => a.len(),
... |
#[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 | -> &mut Self::Target {
&mut self.0
}
}
impl From<Vec<(Cell, char)>> for Span {
fn from(cell_chars: Vec<(Cell, char)>) -> Self {
Span(cell_chars)
}
}
impl Span {
pub(crate) fn new(cell: Cell, ch: char) -> Self {
Span(vec![(cell, ch)])
}
pub(super) fn is_adjacent(&self,... |
/// 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 | -> &mut Self::Target {
&mut self.0
}
}
impl From<Vec<(Cell, char)>> for Span {
fn from(cell_chars: Vec<(Cell, char)>) -> Self {
Span(cell_chars)
}
}
impl Span {
pub(crate) fn new(cell: Cell, ch: char) -> Self {
Span(vec![(cell, ch)])
}
pub(super) fn is_adjacent(&self,... |
}
}
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 | -> &mut Self::Target {
&mut self.0
}
}
impl From<Vec<(Cell, char)>> for Span {
fn from(cell_chars: Vec<(Cell, char)>) -> Self {
Span(cell_chars)
}
}
impl Span {
pub(crate) fn new(cell: Cell, ch: char) -> Self {
Span(vec![(cell, ch)])
}
pub(super) fn is_adjacent(&self,... | (&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 | ) -> &mut Self::Target {
&mut self.0
}
}
impl From<Vec<(Cell, char)>> for Span {
fn from(cell_chars: Vec<(Cell, char)>) -> Self {
Span(cell_chars)
}
}
impl Span {
pub(crate) fn new(cell: Cell, ch: char) -> Self {
Span(vec![(cell, ch)])
}
pub(super) fn is_adjacent(&self... | 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 | Solo + controller device
let solo = new Device(successConnecting, successDisconnecting, failureConnecting);
// Create Device instance for controller and device
solo.on('updated_versions', ()=>{
//Re-load the system info page when we get updated version info
if($('#system_info_button').hasClass('active')){ //if the... |
// 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 | //Solo + controller device
let solo = new Device(successConnecting, successDisconnecting, failureConnecting);
// Create Device instance for controller and device
solo.on('updated_versions', ()=>{
//Re-load the system info page when we get updated version info
if($('#system_info_button').hasClass('active')){ //if t... | 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 | Solo + controller device
let solo = new Device(successConnecting, successDisconnecting, failureConnecting);
// Create Device instance for controller and device
solo.on('updated_versions', ()=>{
//Re-load the system info page when we get updated version info
if($('#system_info_button').hasClass('active')){ //if the... |
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 | Solo + controller device
let solo = new Device(successConnecting, successDisconnecting, failureConnecting);
// Create Device instance for controller and device
solo.on('updated_versions', ()=>{
//Re-load the system info page when we get updated version info
if($('#system_info_button').hasClass('active')){ //if the... | (){
//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 | ,"onmousemove","onDomMouseMove");
this.connect(this.domNode,"onmouseout","onDomMouseOut");
this.loaded.callback();
},onDomClick:function(e){
if(!e.target||!e.target.tagName){
return;
}
if(_7.get(e.target,"action")==="clear"){
this.clearFilter();
}else{
if(_8.contains(e.target,"gridxFilterBarCloseBtn")||_8.contains(e.ta... | return exp;
},_stringToDate:function(s,_37){
_37=_37||/(\d{4})\/(\d\d?)\/(\d\d?)/;
_37.test(s); | random_line_split | |
FilterBar.js | },closeFilterBarButton:true,defineFilterButton:true,tooltipDelay:300,maxRuleCount:0,ruleCountToConfirmClearFilter:2,conditions:{string:["equal","contain","startWith","endWith","notEqual","notContain","notStartWith","notEndWith","isEmpty"],number:["equal","greater","less","greaterEqual","lessEqual","notEqual","isEmpty"]... |
},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 | # Build puzzle & solution to compare against:
for i, row in enumerate(self.puzzle):
for j, value in enumerate(row):
self.puzzle[i, j] = Case(value)
self.puzzle[i, j].y, self.puzzle[i, j].x = i, j
self.solved[i, j] = 1 + j + self.width*i
self.s... | 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 | # Build puzzle & solution to compare against:
for i, row in enumerate(self.puzzle):
for j, value in enumerate(row):
self.puzzle[i, j] = Case(value)
self.puzzle[i, j].y, self.puzzle[i, j].x = i, j
self.solved[i, j] = 1 + j + self.width*i
self.s... |
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 | # Build puzzle & solution to compare against:
for i, row in enumerate(self.puzzle):
for j, value in enumerate(row):
self.puzzle[i, j] = Case(value)
self.puzzle[i, j].y, self.puzzle[i, j].x = i, j
self.solved[i, j] = 1 + j + self.width*i
self.s... |
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 | # Build puzzle & solution to compare against:
for i, row in enumerate(self.puzzle):
for j, value in enumerate(row):
self.puzzle[i, j] = Case(value)
self.puzzle[i, j].y, self.puzzle[i, j].x = i, j
self.solved[i, j] = 1 + j + self.width*i
self.s... | (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 | 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 | , error) {
return xxx_messageInfo_SchemaMeta.Marshal(b, m, deterministic)
}
func (m *SchemaMeta) XXX_Merge(src proto.Message) {
xxx_messageInfo_SchemaMeta.Merge(m, src)
}
func (m *SchemaMeta) XXX_Size() int {
return xxx_messageInfo_SchemaMeta.Size(m)
}
func (m *SchemaMeta) XXX_DiscardUnknown() {
xxx_messageInfo_Sch... | (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 | , error) {
return xxx_messageInfo_SchemaMeta.Marshal(b, m, deterministic)
}
func (m *SchemaMeta) XXX_Merge(src proto.Message) {
xxx_messageInfo_SchemaMeta.Merge(m, src)
}
func (m *SchemaMeta) XXX_Size() int {
return xxx_messageInfo_SchemaMeta.Size(m)
}
func (m *SchemaMeta) XXX_DiscardUnknown() {
xxx_messageInfo_Sch... |
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 | , error) {
return xxx_messageInfo_SchemaMeta.Marshal(b, m, deterministic)
}
func (m *SchemaMeta) XXX_Merge(src proto.Message) {
xxx_messageInfo_SchemaMeta.Merge(m, src)
}
func (m *SchemaMeta) XXX_Size() int {
return xxx_messageInfo_SchemaMeta.Size(m)
}
func (m *SchemaMeta) XXX_DiscardUnknown() {
xxx_messageInfo_Sch... |
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 | 00ADrast\u00ADlõu\u00ADna\u00ADvä\u00ADsi\u00ADmus"],
"fi": ["kolmivaihekilowattituntimittari", "kolmivaihekilowattituntimittari"],
"fr": ["hippopotomonstrosesquippedaliophobie", "hip\u00ADpo\u00ADpo\u00ADto\u00ADmons\u00ADtro\u00ADses\u00ADquip\u00ADpe\u00ADda\u00ADlio\u00ADpho\u00ADbie"],
"de": ["Kindercarnaval... | ation.getLocal | identifier_name | |
Hyphenation.qunit.js | -at": ["Kindercarnavalsoptochtvoorbereidingswerkzaamheden", "Kin\u00ADder\u00ADcar\u00ADna\u00ADvals\u00ADop\u00ADtocht\u00ADvo\u00ADor\u00ADberei\u00ADdings\u00ADwerk\u00ADzaam\u00ADhe\u00ADden"],
"el": ["ηλεκτροεγκεφαλογράφημα", "ηλε\u00ADκτρο\u00ADε\u00ADγκε\u00ADφα\u00ADλο\u00ADγρά\u00ADφημα"],
"hi": ["किंकर्तव... | 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 | \u00ADpe\u00ADda\u00ADlio\u00ADpho\u00ADbie"],
"de": ["Kindercarnavalsoptochtvoorbereidingswerkzaamheden", "Kin\u00ADder\u00ADcar\u00ADna\u00ADvals\u00ADop\u00ADtocht\u00ADvo\u00ADor\u00ADberei\u00ADdings\u00ADwerk\u00ADzaam\u00ADhe\u00ADden"], // original word was Kindercarnavalsoptochtvoorbereidingswerkzaamhedenpla... | // we don't have a word to test for this language | random_line_split | |
Hyphenation.qunit.js | ADда\u00ADде\u00ADнін\u00ADди\u00ADну\u00ADкле\u00ADо\u00ADтид\u00ADфо\u00ADсфат"]
},
mCompoundWords = {
"en": ["factory-made", "fac\u00ADtory-\u200bmade"],
"de": ["Geheimzahl-Aufschreiber", "Geheim\u00ADzahl-\u200bAuf\u00ADschrei\u00ADber"]
},
mTexts = {
// lang: [not hyphenated, hyphenated]
"en": [
"A ... |
});
});
QUnit. | conditional_block | |
MuseScraper.py | logging_kwargs: Dict[str, Any] = {}
log_level: int = (logging.DEBUG if debug_log else
logging.INFO if not quiet else
logging.WARNING
)
logging_kwargs["level"] = log_level
if debug_log:
logg... | 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 | logging_kwargs: Dict[str, Any] = {}
log_level: int = (logging.DEBUG if debug_log else
logging.INFO if not quiet else
logging.WARNING
)
logging_kwargs["level"] = log_level
if debug_log:
logging_kwa... |
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 | logging_kwargs: Dict[str, Any] = {}
log_level: int = (logging.DEBUG if debug_log else
logging.INFO if not quiet else
logging.WARNING
)
logging_kwargs["level"] = log_level
if debug_log:
logging_kwa... |
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 | .Page = await self._browser.newPage()
try:
page.setDefaultNavigationTimeout(0)
await page.setViewport({ "width" : 1000, "height" : 1000 } )
response: pyppeteer.network_manager.Response = await page.goto(url, timeout=0)
if not response.ok:
raise Con... | __enter__ | identifier_name | |
Orders.js | input parameters`,
},
id: {
label: () => t`Order ID`,
},
collectionId: {
label: () => t`Collection ID`,
},
};
const JSONProperty = (order, property) => {
const [isExpanded, setIsExpanded] = useState(false);
const value = order[property];
if (!value) {
return null;
}
return (
<>
... | message: t`Are you sure you want to delete this order?`,
action: () => deleteOrderAction(order),
showCancel: true, | random_line_split | |
snippet.py | '0'
UNDERLINE = '4'
BOLD = '1'
ESCAPE_START = '\033['
ESCAPE_END = 'm'
# TODO rename to style and append Term.Clear ?
def ansi(*args):
"""Construct an ANSI terminal escape code."""
code = Term.ESCAPE_START
code += ';'.join(args)
code += Term.ESCAPE_END
return code
class Disconne... | nteract( | identifier_name | |
snippet.py | = ' '.join(hexblock[:8]), ' '.join(hexblock[8:])
asciiblock = ''.join(chr(b) if is_hexdump_printable(b) else '.' for b in chunk)
lines.append('{:08x} {:23} {:23} |{}|'.format(i*16, left, right, asciiblock))
return '\n'.join(lines)
class Term:
COLOR_BLACK = '30'
COLOR_RED = '31'
COL... | 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 | right = ' '.join(hexblock[:8]), ' '.join(hexblock[8:])
asciiblock = ''.join(chr(b) if is_hexdump_printable(b) else '.' for b in chunk)
lines.append('{:08x} {:23} {:23} |{}|'.format(i*16, left, right, asciiblock))
return '\n'.join(lines)
class Term:
COLOR_BLACK = '30'
COLOR_RED = '31'
... | 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 | = p32(needle)
else:
needle = p64(needle)
needle = d(needle)
idx = self._seq.index(needle)
if self._seq[idx+len(needle):].find(needle) != -1:
raise ValueError("Multiple occurances found!")
return idx
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ... | .sendline(l)
| identifier_body | |
stream.py | def _print_muse_list(muses):
for m in muses:
print(f'Found device {m["name"]}, MAC Address {m["address"]}')
if not muses:
print('No Muses found.')
# Returns a list of available Muse devices.
def list_muses(backend='auto', interface=None):
if backend == 'auto' and which('bluetoothctl') is n... |
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 | def _print_muse_list(muses):
for m in muses:
print(f'Found device {m["name"]}, MAC Address {m["address"]}')
if not muses:
print('No Muses found.')
# Returns a list of available Muse devices.
def list_muses(backend='auto', interface=None):
if backend == 'auto' and which('bluetoothctl') is n... | (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 | def _print_muse_list(muses):
for m in muses:
print(f'Found device {m["name"]}, MAC Address {m["address"]}')
if not muses:
print('No Muses found.')
# Returns a list of available Muse devices.
def list_muses(backend='auto', interface=None):
if backend == 'auto' and which('bluetoothctl') is n... | for c in ['TP9', 'AF7', 'AF8', 'TP10', 'Right AUX']:
eeg_channels.append_child("channel") \
.append_child_value("label", c) \
.append_child_value("unit", "microvolts") \
.append_child_value("type", "EEG")
eeg_outlet = S... | 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 | def _print_muse_list(muses):
for m in muses:
print(f'Found device {m["name"]}, MAC Address {m["address"]}')
if not muses:
print('No Muses found.')
# Returns a list of available Muse devices.
def list_muses(backend='auto', interface=None):
if backend == 'auto' and which('bluetoothctl') is n... | 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 | .SR = sR
rho, err := rand.Int(rand.Reader, EC.N)
check(err)
prip.Rho = rho
S := TwoVectorPCommitWithGens(BPG, BPH, sL, sR, EC).Add(EC.H.Mult(rho, EC), EC)
AS.S = S
return AS
}
func Fait_y_z(A, S []ECPoint, mpcrp *MPCRangeProof, EC CryptoParams) (*big.Int, *big.Int) {
countA := EC.Zero()
countS... |
// 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 | .SR = sR
rho, err := rand.Int(rand.Reader, EC.N)
check(err)
prip.Rho = rho
S := TwoVectorPCommitWithGens(BPG, BPH, sL, sR, EC).Add(EC.H.Mult(rho, EC), EC)
AS.S = S
return AS
}
func Fait_y_z(A, S []ECPoint, mpcrp *MPCRangeProof, EC CryptoParams) (*big.Int, *big.Int) {
countA := EC.Zero()
countS... | 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 | .SR = sR
rho, err := rand.Int(rand.Reader, EC.N)
check(err)
prip.Rho = rho
S := TwoVectorPCommitWithGens(BPG, BPH, sL, sR, EC).Add(EC.H.Mult(rho, EC), EC)
AS.S = S
return AS
}
func Fait_y_z(A, S []ECPoint, mpcrp *MPCRangeProof, EC CryptoParams) (*big.Int, *big.Int) {
countA := EC.Zero()
countS... | *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 | (big.Int).Neg(cz), EC)
l1 := sL
r0 := VectorAdd(
VectorHadamard(
yn,
VectorAddScalar(aR, cz, EC), EC),
z2j2n, EC)
r1 := VectorHadamard(sR, yn, EC)
//calculate t0
z2 := new(big.Int).Mod(new(big.Int).Mul(cz, cz), EC.N)
PowerOfCZ := PowerVector(m, cz, EC)
vz2 := new(big.Int).Mul(PowerOfCZ[i... | 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 | key for lookup
type ClientKey int
const (
// DomainName used for this sample
DomainName = "samples-domain"
// CadenceClientKey for retrieving cadence client from context
CadenceClientKey ClientKey = iota
// WorkflowExecutionCacheKey for retrieving executions cache from context
WorkflowExecutionCacheKey
)
// H... | (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 | key for lookup
type ClientKey int
const (
// DomainName used for this sample
DomainName = "samples-domain"
// CadenceClientKey for retrieving cadence client from context
CadenceClientKey ClientKey = iota
// WorkflowExecutionCacheKey for retrieving executions cache from context
WorkflowExecutionCacheKey
)
// H... |
}
// 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 | the key for lookup
type ClientKey int
const (
// DomainName used for this sample
DomainName = "samples-domain"
// CadenceClientKey for retrieving cadence client from context
CadenceClientKey ClientKey = iota
// WorkflowExecutionCacheKey for retrieving executions cache from context
WorkflowExecutionCacheKey
)
... | default:
return nil, errors.New("Unknown event type")
}
}
func extractSignals(events []*shared.HistoryEvent) ([]*SignalParams, error) {
var signals []*SignalParams
for _, event := range events {
if event.GetEventType() == shared.EventTypeWorkflowExecutionSignaled {
attr := event.WorkflowExecutionSignaledEv... | {
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 | the key for lookup
type ClientKey int
const (
// DomainName used for this sample
DomainName = "samples-domain"
// CadenceClientKey for retrieving cadence client from context
CadenceClientKey ClientKey = iota
// WorkflowExecutionCacheKey for retrieving executions cache from context
WorkflowExecutionCacheKey
)
... | }
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 | *mainchain.LeagueConsumers
}
func NewTxPool() *TxPool {
pool := new(TxPool)
pool.pdmgr = NewPendingMgr()
//pool.queue = NewTxQueue()
pool.maxPending = config.GlobalConfig.TxPoolCfg.MaxPending
pool.maxInPending = config.GlobalConfig.TxPoolCfg.MaxInPending
pool.maxInQueue = config.GlobalConfig.TxPoolCfg.MaxInQueu... |
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 | *mainchain.LeagueConsumers
}
func NewTxPool() *TxPool {
pool := new(TxPool)
pool.pdmgr = NewPendingMgr()
//pool.queue = NewTxQueue()
pool.maxPending = config.GlobalConfig.TxPoolCfg.MaxPending
pool.maxInPending = config.GlobalConfig.TxPoolCfg.MaxInPending
pool.maxInQueue = config.GlobalConfig.TxPoolCfg.MaxInQueu... |
}
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 | *mainchain.LeagueConsumers
}
func NewTxPool() *TxPool {
pool := new(TxPool)
pool.pdmgr = NewPendingMgr()
//pool.queue = NewTxQueue()
pool.maxPending = config.GlobalConfig.TxPoolCfg.MaxPending
pool.maxInPending = config.GlobalConfig.TxPoolCfg.MaxInPending
pool.maxInQueue = config.GlobalConfig.TxPoolCfg.MaxInQueu... | () {
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 | *mainchain.LeagueConsumers
}
func NewTxPool() *TxPool {
pool := new(TxPool)
pool.pdmgr = NewPendingMgr()
//pool.queue = NewTxQueue()
pool.maxPending = config.GlobalConfig.TxPoolCfg.MaxPending
pool.maxInPending = config.GlobalConfig.TxPoolCfg.MaxInPending
pool.maxInQueue = config.GlobalConfig.TxPoolCfg.MaxInQueu... | ret, err := pool.stateValidator.VerifyTx(tx)
if err != nil {
log.Error("range pool.mustPackTxs verifyTx error", "ret", ret, "error", err)
}
}*/
objectiveTxs, | /*for _, tx := range pool.mustPackTxs { | random_line_split |
titanic5.py | 0,:] # the final testing data
X_train = X_data_full[20:,:] # the training data
y_test = y_data_full[0:20] # the final testing outputs/labels (unknown)
y_train = y_data_full[20:] # the training outputs/labels (known)
feature_names = df.drop('survived', axis=1).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 | ,:] # the final testing data
X_train = X_data_full[20:,:] # the training data
y_test = y_data_full[0:20] # the final testing outputs/labels (unknown)
y_train = y_data_full[20:] # the training outputs/labels (known)
feature_names = df.drop('survived', axis=1).col... | # 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 | 0,:] # the final testing data
X_train = X_data_full[20:,:] # the training data
y_test = y_data_full[0:20] # the final testing outputs/labels (unknown)
y_train = y_data_full[20:] # the training outputs/labels (known)
feature_names = df.drop('survived', axis=1).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 | ,:] # the final testing data
X_train = X_data_full[20:,:] # the training data
y_test = y_data_full[0:20] # the final testing outputs/labels (unknown)
y_train = y_data_full[20:] # the training outputs/labels (known)
feature_names = df.drop('survived', axis=1).col... | rforest = rforest.fit(cv_data_train, cv_target_train)
trainng_score += [rforest.score(cv_data_train,cv_target_train)]
testing_score += [rforest.score(cv_data_test,cv_target_test)]
# Compute the average score for both traning and testing data
trainng_avgScore = 1.0 * ... | 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 | initLogger(a.config.LogFile, "")
if err != nil {
panic(err)
}
defer closeLogFile()
a.log = l
defer func() {
err := recover()
if err != nil {
a.log.Error("API server running error.")
a.log.Errorf("API Server running error: %v", err)
a.log.Errorf("API server running stack info: %s", string(debug.St... | 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 | initLogger(a.config.LogFile, "")
if err != nil {
panic(err)
}
defer closeLogFile()
a.log = l
defer func() {
err := recover()
if err != nil {
a.log.Error("API server running error.")
a.log.Errorf("API Server running error: %v", err)
a.log.Errorf("API server running stack info: %s", string(debug.St... | 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 | ctx.GzipResponseWriter().Write(d)
return
}
if t.TimeStamp <= 0 {
_, _ = ctx.Write(a.qualityDataCache)
} else {
data, err := queryNetQualityData(time.Unix(t.TimeStamp, 0), a.config.DataSourceUrl)
if err != nil {
errMsg := fmt.Sprintf("Retrieved quality data failed. error : %v", err)
respBody := &NetQu... | random_line_split | ||
apiserver.go | if err != nil {
a.log.Error(err)
}
}
func (a *APIServer) summaryPageHandler(ctx iris.Context) {
//err := ctx.ServeFile("index.html", false)
err := ctx.View("summary.html")
if err != nil {
a.log.Error(err)
}
}
type TimeStampFilterPayload struct {
TimeStamp int64 `json:"timestamp"`
}
type NetQualityDataResp... | DataResponse{200, "", dat | conditional_block | |
packages.py | quality):
"""Package data restriction."""
__slots__ = (
"_pull_attr_func",
"_attr_split",
"restriction",
"ignore_missing",
"negate",
)
__attr_comparison__ = ("__class__", "negate", "_attr_split", "restriction")
__inst_caching__ = True
type = restriction.... |
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 | quality):
"""Package data restriction."""
__slots__ = (
"_pull_attr_func",
"_attr_split",
"restriction",
"ignore_missing",
"negate",
)
__attr_comparison__ = ("__class__", "negate", "_attr_split", "restriction")
__inst_caching__ = True
type = restriction.... | 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 | ):
"""Package data restriction."""
__slots__ = (
"_pull_attr_func",
"_attr_split",
"restriction",
"ignore_missing",
"negate",
)
__attr_comparison__ = ("__class__", "negate", "_attr_split", "restriction")
__inst_caching__ = True
type = restriction.package... | (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 | ):
"""Package data restriction."""
__slots__ = (
"_pull_attr_func",
"_attr_split",
"restriction",
"ignore_missing",
"negate",
)
__attr_comparison__ = ("__class__", "negate", "_attr_split", "restriction")
__inst_caching__ = True
type = restriction.package... |
@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 | we use to communicate
with the store and manager.
"""
def __init__(self, buff, plasma_id, plasma_client):
"""Initialize a PlasmaBuffer."""
self.buffer = buff
self.plasma_id = plasma_id
self.plasma_client = plasma_client
def __del__(self):
"""Notify Plasma that the object is no longer n... |
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 | we use to communicate
with the store and manager.
"""
def __init__(self, buff, plasma_id, plasma_client):
"""Initialize a PlasmaBuffer."""
self.buffer = buff
self.plasma_id = plasma_id
self.plasma_client = plasma_client
def __del__(self):
"""Notify Plasma that the object is no longer n... | (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 | we use to communicate
with the store and manager.
"""
def __init__(self, buff, plasma_id, plasma_client):
"""Initialize a PlasmaBuffer."""
self.buffer = buff
self.plasma_id = plasma_id
self.plasma_client = plasma_client
def __del__(self):
"""Notify Plasma that the object is no longer n... | 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):
... | """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 | we use to communicate
with the store and manager.
"""
def __init__(self, buff, plasma_id, plasma_client):
"""Initialize a PlasmaBuffer."""
self.buffer = buff
self.plasma_id = plasma_id
self.plasma_client = plasma_client
def __del__(self):
"""Notify Plasma that the object is no longer n... | 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 | else {
orig(data)
}
}
pub unsafe fn chat_message_hook(
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'... |
// 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 | else {
orig(data)
}
}
pub unsafe fn | (
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 | 0;
bw_1161::add_to_replay_data(
*vars::replay_data,
replay_command.as_ptr(),
replay_command.len() as u32,
storm_player,
);
if storm_player == *vars::local_storm_id {
// Switch the message to be green to show it's player's own message
... | }
None
}
| random_line_split | |
observing.rs | else {
orig(data)
}
}
pub unsafe fn chat_message_hook(
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'... |
}
}
for (i, player) in actual_players.iter().enumerate() {
| {
// 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 | Expected seperator ',' after sorted order.")
IdentifierExpected error = errors.New("Expected identifier.")
ValueExpected error = errors.New("Expected value.")
EndOfStringExpected error = errors.New("Expected end of string.")
StringExpected error = errors.New("Expected string.")
OperatorExpected error = errors.New(... | (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 | i = strings.IndexFunc(rawQuery, charClassDetector(1, 1))
var value string
if i == -1 {
value = rawQuery
} else {
value = rawQuery[:i]
rawQuery = rawQuery[i+1:]
}
qs.fields[name] = value
if i == -1 {
break
}
}
return qs
}
// NewFromRawQuery creates a new QueryString from an existing URL ... | func parseSortOrders(s string) (os []*SortOrder, n string) {
os = make([]*SortOrder, 0, 4)
if len(s) > 0 { | random_line_split | |
parser.go | NewFromRawQuery creates a new QueryString from an existing URL object.
func NewFromURL(url *url.URL) *QueryString {
return NewFromRawQuery(url.RawQuery)
}
// Tests if specified name has been found in query string.
func (q *QueryString) Contains(name string) bool {
_, ok := q.fields[name]
return ok
}
// Returns ra... | {
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:]
}
}
} | identifier_body | |
parser.go | seperator ',' after sorted order.")
IdentifierExpected error = errors.New("Expected identifier.")
ValueExpected error = errors.New("Expected value.")
EndOfStringExpected error = errors.New("Expected end of string.")
StringExpected error = errors.New("Expected string.")
OperatorExpected error = errors.New("Expecte... |
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 | ..n {
let a = self.value.get(i).cloned().unwrap_or(0);
let b = rhs.value.get(i).cloned().unwrap_or(0);
// TODO: Try to use overflowing_sub instead (that way we don't need to go to
// 64bits)
let v = (a as i64) - (b as i64) + carry;
if v < 0 {
... | {
out = Ordering::Equal;
} | conditional_block | |
uint.rs | );
self.value.truncate(n);
}
///
pub fn truncate(&mut self, bit_width: usize) {
let n = ceil_div(bit_width, BASE_BITS);
// TODO: Also zero out any high bits
for i in n..self.value.len() {
assert_eq!(self.value[i], 0);
}
self.value.truncate(n);
... | {
for v in self.value.iter_mut() {
*v = 0;
}
} | identifier_body | |
uint.rs | as 'rhs'.
fn quorem(&self, rhs: &Self) -> (Self, Self) {
let mut q = Self::from_usize(0, self.bit_width()); // Range is [0, Self]
let mut r = Self::from_usize(0, rhs.bit_width()); // Range is [0, rhs).
// TODO: Implement a bit iterator so set_bit requires less work.
for i in (0..se... | ///
/// 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 | { 1 } else { 0 });
}
(q, r)
}
fn value_bits(&self) -> usize {
for i in (0..self.value.len()).rev() {
let zeros = self.value[i].leading_zeros() as usize;
if zeros == BASE_BITS {
continue;
}
return (i * BASE_BITS) + (BASE_... | shr_n | identifier_name | |
Parameter.py |
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 | '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 | response = requests.request("POST", request_url, headers=headers, data = payload)
data = response.json()
#回傳驗證碼
return data['data']
else:
request_url = "https://office.cf139.com/ValidateCodeLog/createValidateNo"
payload = random_phone
headers = {
'Connection': 'close',
'authority': 'office.cf139... | nt_type,'',current_time,package_name]
writed_csv.append(account_information)
#寫入CSV
writer.writerows(writed_csv)
| identifier_body | |
Parameter.py | .關彈窗廣告
#沒有彈出版本升級或廣告就跳過不執行
element_list = [package_name+':id/tv_skip',package_name+':id/btn_cancel',package_name+':id/close_btn']
for element in element_list:
try:
self.driver.find_element_by_id(element).click()
except NoSuchElementException:
continue
#跳過廣告(不等開屏七秒)
def skip_ads_no_wait(self):
#設置隱性等待2秒
s... | 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 | _resolver.configs.get(type) : null
if (service) {
// browse the dependencies and check that they haven't changed themselves.
// if require() sends a different instance of the dependency, this service
// is not reused.
for (let d of service._dependencies) {
let nd = this.... |
// 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 | prev_resolver
this.activating = false
if (err.message === 'redirecting' && err.screen)
return this.go(err.screen, ...err.configs)
return Promise.reject(err)
})
} catch (err) {
this.activating = false
return Promise.reject(err)
}
}
async popstate(idx:... | DisplayBlock | identifier_name | |
app.ts | _resolver.configs.get(type) : null
if (service) {
// browse the dependencies and check that they haven't changed themselves.
// if require() sends a different instance of the dependency, this service
// is not reused.
for (let d of service._dependencies) {
let nd = this.... | 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 | Input() image: ImagePath = null;
@Output() placeOnPage = new EventEmitter<ImagePath>();
@Output() close = new EventEmitter<void>();
@ViewChild('clipbox') public _clipbox: ElementRef;
get clipboxElem(): HTMLElement { return (this._clipbox.nativeElement as HTMLElement); }
@ViewChild(LoadingComponent) load... |
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 | Input() image: ImagePath = null;
@Output() placeOnPage = new EventEmitter<ImagePath>();
@Output() close = new EventEmitter<void>();
@ViewChild('clipbox') public _clipbox: ElementRef;
get clipboxElem(): HTMLElement { return (this._clipbox.nativeElement as HTMLElement); }
@ViewChild(LoadingComponent) load... | () {
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 | }
onSetCommand(event: string) {
this.changeDetector.detach();
switch (event) {
case 'PlaceOnPage':
this.onSaveImage();
break;
case 'Back':
this.close.emit();
}
}
onSaveImage() {
if (!this.image) return;
$((this.elementRef.nativeElement as HTMLElement).parentElement.parent... | random_line_split | ||
data_providers.go | .com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/goldendataset"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/idutils"
)
// DataProvider defines the interface for generators of test data used to drive various end-to-end tests.
type DataProvider interface {
... | (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 | Provider for use in performance tests.
// Tracing IDs are based on the incremented batch and data items counters.
type perfTestDataProvider struct {
options LoadOptions
traceIDSequence atomic.Uint64
dataItemsGenerated *atomic.Uint64
}
// NewPerfTestDataProvider creates an instance of perfTestDataProvi... | {
dp.dataItemsGenerated = dataItemsGenerated
} | identifier_body | |
data_providers.go | .com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/goldendataset"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/idutils"
)
// DataProvider defines the interface for generators of test data used to drive various end-to-end tests.
type DataProvider interface {
... |
}
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 | "github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/goldendataset"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/idutils"
)
// DataProvider defines the interface for generators of test data used to drive various end-to-end tests.
type DataProvider interf... | 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 | 5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e],
[0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf],
[0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]
]
INVSBOX = [
[0x52, 0x09, 0x6... | random_line_split | ||
AES.py | 42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]
]
INVSBOX = [
[0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb],
[0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb],
[0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x... | for i in xrange(1, 4): # to select row
state[i] = state[i][i:4] + state[i][0:i] | identifier_body | |
AES.py | 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b],
[0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4],
[0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f],
[0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0... | invmix_cols | identifier_name | |
AES.py | 5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e],
[0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf],
[0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]
]
INVSBOX = [
[0x52, 0x09, 0x6... | 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 | |
astutils.py |
else:
# Before Python 3.8 "foo" was parsed as ast.Str.
def get_str_value(expr:ast.expr) -> Optional[str]:
if isinstance(expr, ast.Str):
return expr.s
return None
def get_num_value(expr:ast.expr) -> Optional[Number]:
if isinstance(expr, ast.Num):
return expr.n... | break | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.