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
dialog.d.ts
import { BlockScrollStrategy, Overlay, ScrollStrategy } from '@angular/cdk/overlay'; import { ComponentType } from '@angular/cdk/portal'; import { Location } from '@angular/common'; import { InjectionToken, Injector, TemplateRef } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subject } fr...
* @param overlay Reference to the dialog's underlying overlay. * @param config The dialog configuration. * @returns A promise resolving to a ComponentRef for the attached container. */ private _attachDialogContainer(overlay, config); /** * Attaches the user-provided component to the alr...
*/ private _getOverlayConfig(dialogConfig); /** * Attaches an MatDialogContainer to a dialog's already-created overlay.
random_line_split
extra.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this
use layout::wrapper::LayoutNode; use script::layout_interface::LayoutChan; /// Functionality useful for querying the layout-specific data on DOM nodes. pub trait LayoutAuxMethods { fn initialize_layout_data(self, chan: LayoutChan); fn initialize_style_for_subtree(self, chan: LayoutChan); } impl<'ln> LayoutAux...
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Code for managing the layout data in the DOM. use layout::util::{PrivateLayoutData, LayoutDataAccess, LayoutDataWrapper};
random_line_split
extra.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Code for managing the layout data in the DOM. use layout::util::{PrivateLayoutData, LayoutDataAccess, LayoutD...
}
{ for n in self.traverse_preorder() { n.initialize_layout_data(chan.clone()); } }
identifier_body
extra.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! Code for managing the layout data in the DOM. use layout::util::{PrivateLayoutData, LayoutDataAccess, LayoutD...
(self, chan: LayoutChan) { let mut layout_data_ref = self.mutate_layout_data(); match *layout_data_ref.get() { None => { *layout_data_ref.get() = Some(LayoutDataWrapper { chan: Some(chan), data: ~PrivateLayoutData::new(), ...
initialize_layout_data
identifier_name
ilt_multi_gpu_feed.py
'Directory to store checkpoints') # Statistics flags.DEFINE_string('summaries_dir','./logs','Summaries directory') # Evaluation # Output dataset flags.DEFINE_string('output','./test_tracks_out/isabel_test_track_out.dat','When model evaluation, output the data here') # Input dataset flags.DEFINE_string('input','./tes...
run
identifier_name
ilt_multi_gpu_feed.py
s): grads = [] # g each individual gradient for g, _ in grad_and_vars: expanded_g = tf.expand_dims(g,0) grads.append(expanded_g) # grad average gradient across the gpu's grad = tf.concat(0,grads) grad = tf.reduce_mean(grad,0) # get...
if tf.gfile.Exists(FLAGS.output+'*'): tf.gfile.DeleteRecursively(FLAGS.output+'*') run()
conditional_block
ilt_multi_gpu_feed.py
points_dir', './models/save_two_layers_32_64_sept', 'Directory to store checkpoints') # Statistics flags.DEFINE_string('summaries_dir','./logs','Summaries directory') # Evaluation # Output dataset flags.DEFINE_string('output','./test_tracks_out/isabel_test_track_out.dat','When model evaluation, output the data here')...
# Make sure that the vars are reused for the next tower tf.get_variable_scope().reuse_variables() #summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, scope) # calculate the gradients and add them to the list ...
loss = tower_loss(x, y_, scope)
random_line_split
ilt_multi_gpu_feed.py
points_dir', './models/save_two_layers_32_64_sept', 'Directory to store checkpoints') # Statistics flags.DEFINE_string('summaries_dir','./logs','Summaries directory') # Evaluation # Output dataset flags.DEFINE_string('output','./test_tracks_out/isabel_test_track_out.dat','When model evaluation, output the data here')...
# combine the gradient and append it to the average_grads grad_and_var = (grad, v) average_grads.append(grad_and_var) return average_grads def train(): """ Build the graph and run training on multiple GPU's """ # Assign datasets train_dataset, valid_dataset, test_datas...
""" Calculate the average gradient for each shared variable across all towers tower_grads -- list of lists of tuples (gradient, variable) """ average_grads = [] # zip(*tower_grads) puts grads for each variable together # grad_and_vars is a tuple of tuples ((grad_gpu1, var1),(grad_gpu2, var1)) ...
identifier_body
summarize_tests.py
# -*- coding: utf-8 -*- # # summarize_tests.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License...
(fname): results = jp.JUnitXml.fromfile(fname) if isinstance(results, jp.junitparser.JUnitXml): # special case for pytest, which wraps all once more suites = list(results) assert len(suites) == 1, "JUnit XML files may only contain results from a single testsuite." results = suit...
parse_result_file
identifier_name
summarize_tests.py
# -*- coding: utf-8 -*- # # summarize_tests.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License...
print() print(tline) print('NEST Testsuite Results') print(tline) print('{:<20s}'.format('Phase'), end='') for c in cols: print('{:>10s}'.format(c), end='') print() print(tline) for pn, pr in results.items(): print('{:<20s}'.format(pn), end='') for c in cols...
assert len(sys.argv) == 2, 'summarize_tests must be called with TEST_OUTDIR.' test_outdir = sys.argv[1] results = {} totals = {'Tests': 0, 'Skipped': 0, 'Failures': 0, 'Errors': 0, 'Time': 0, 'Failed tests': []} for pfile in sorted(glob.glob(os.path.join(test_outdir, '*.xm...
conditional_block
summarize_tests.py
# -*- coding: utf-8 -*- # # summarize_tests.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License...
if __name__ == '__main__': assert len(sys.argv) == 2, 'summarize_tests must be called with TEST_OUTDIR.' test_outdir = sys.argv[1] results = {} totals = {'Tests': 0, 'Skipped': 0, 'Failures': 0, 'Errors': 0, 'Time': 0, 'Failed tests': []} for pfile in sorted(glob.g...
results = jp.JUnitXml.fromfile(fname) if isinstance(results, jp.junitparser.JUnitXml): # special case for pytest, which wraps all once more suites = list(results) assert len(suites) == 1, "JUnit XML files may only contain results from a single testsuite." results = suites[0] ass...
identifier_body
summarize_tests.py
# -*- coding: utf-8 -*- # # summarize_tests.py # # This file is part of NEST. # # Copyright (C) 2004 The NEST Initiative # # NEST is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License...
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with NEST. If not, see <http://www.gnu.org/licenses/>. # Invoke this script as # # python3 parse_test_output.py <path to test ...
# but WITHOUT ANY WARRANTY; without even the implied warranty of
random_line_split
route_stitching.py
child_resource) check_tree(routing_tree, child) def yield_branches(routing_branch): """ Yield all routing branches starting from the given route segment. This will yield the input route branch in addition to its children. An AssertionError will be raised for a circular route is detected. ...
def get_connection(self, connection_resource): """ Get list of segment ids connected to connection_resource. """ if self.connections is None: self.build_connections() return self.connections[connection_resource] def reroot(self): """ Determine which routing segme...
for connection in self.connections_for_segment_id(segment_id): if connection not in self.connections: self.connections[connection] = set() self.connections[connection].add(segment_id)
conditional_block
route_stitching.py
def create_id_map(id_to_segment, segments): """ Create or update dict from object ids of segments to segments. """ for segment in segments: segment_id = id(segment) assert segment_id not in id_to_segment id_to_segment[segment_id] = segment create_id_map(id_to_segment, segment.br...
random_line_split
route_stitching.py
child_resource) check_tree(routing_tree, child) def yield_branches(routing_branch): """ Yield all routing branches starting from the given route segment. This will yield the input route branch in addition to its children. An AssertionError will be raised for a circular route is detected. ...
# Populate id_to_segment and id_to_device_resource maps. create_id_map(self.id_to_segment, self.stubs) create_id_map(self.id_to_segment, self.sources) for segment_id, segment in self.id_to_segment.items(): self.id_to_device_resource[ segment_id] = segment.ge...
tuple_to_id = {} for stub in stubs: for branch in yield_branches(stub): tup = branch.to_tuple() assert tup not in tuple_to_id, tup tuple_to_id[tup] = id(branch) for source in sources: for branch in yield_branches(source): ...
identifier_body
route_stitching.py
.id_to_segment = {} self.id_to_device_resource = {} self.stubs = stubs self.sources = sources self.connections = None # Populate id_to_segment and id_to_device_resource maps. create_id_map(self.id_to_segment, self.stubs) create_id_map(self.id_to_segment, self.s...
stitch_segments
identifier_name
read_only_memory.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] use base::{MemoryMappingBuilder, SharedMemory}; use kvm::*; use kvm_sys::kvm_regs; use vm_me...
let kvm = Kvm::new().expect("new kvm failed"); let mut vm = Vm::new(&kvm, guest_mem).expect("new vm failed"); let vcpu = Vcpu::new(0, &kvm, &vm).expect("new vcpu failed"); let mut vcpu_sregs = vcpu.get_sregs().expect("get sregs failed"); vcpu_sregs.cs.base = 0; vcpu_sregs.cs.selector = 0; vc...
{ /* 0000 268A07 mov al,[es:bx] 0003 0401 add al,0x1 0005 268807 mov [es:bx],al 0008 F4 hlt */ let code = [0x26, 0x8a, 0x07, 0x04, 0x01, 0x26, 0x88, 0x07, 0xf4]; let mem_size = 0x2000; let load_addr = GuestAddress(0x1000); let guest_mem = GuestMemory::new(&[]).unwra...
identifier_body
read_only_memory.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] use base::{MemoryMappingBuilder, SharedMemory}; use kvm::*; use kvm_sys::kvm_regs; use vm_me...
GuestAddress(0), Box::new( MemoryMappingBuilder::new(mem_size as usize) .from_shared_memory(&mem) .build() .expect("failed to create memory mapping"), ), false, false, ) .expect("failed to register memory"); ...
random_line_split
read_only_memory.rs
// Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] use base::{MemoryMappingBuilder, SharedMemory}; use kvm::*; use kvm_sys::kvm_regs; use vm_me...
() { /* 0000 268A07 mov al,[es:bx] 0003 0401 add al,0x1 0005 268807 mov [es:bx],al 0008 F4 hlt */ let code = [0x26, 0x8a, 0x07, 0x04, 0x01, 0x26, 0x88, 0x07, 0xf4]; let mem_size = 0x2000; let load_addr = GuestAddress(0x1000); let guest_mem = GuestMemory::new(&[]).un...
test_run
identifier_name
spec.js
'use strict'; var assert = require('assert'), mongoose = require('mongoose'), mobgoose = require('../')(mongoose); var Foo = mongoose.model('Foo', new mongoose.Schema({}), 'foo_collection_name'); it('accepts configuration without url', function() { return mobgoose({ host: 'localhost', database: 'test123' }...
it('supports a simple conection string', function() { return mobgoose('mongodb://localhost:27017/test') .then(function(connection) { var model = connection.model('Foo'); assert(model.db.name === 'test'); }); }); it('keeps the model collection name', function() { return mobgoose('mongodb://loc...
}); });
random_line_split
push.service.ts
/* "l'Agenda Collaboratif" Copyright (C) 2016 Valentin VIENNOT Contact : vviennot@orange.fr This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your optio...
ocalStorage.setItem("pushservice", JSON.stringify(b)); this.activated = b; } }
identifier_body
push.service.ts
/* "l'Agenda Collaboratif" Copyright (C) 2016 Valentin VIENNOT Contact : vviennot@orange.fr This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your optio...
constructor(public _notif: NotificationService) { if (!window.localStorage.getItem("pushservice")) window.localStorage.setItem("pushservice", JSON.stringify(false)); } /** * Initialise le service de Push dans le cas où l'appareil y est inscrit */ abstract initPush(): void; /** * Enregist...
@Injectable() export abstract class PushService { activated: boolean;
random_line_split
push.service.ts
/* "l'Agenda Collaboratif" Copyright (C) 2016 Valentin VIENNOT Contact : vviennot@orange.fr This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your optio...
void { window.localStorage.setItem("pushservice", JSON.stringify(b)); this.activated = b; } }
: boolean):
identifier_name
limits.py
# Copyright 2010-2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
class ViewBuilder(object): """OpenStack API base limits view builder.""" def build(self, rate_limits, absolute_limits): rate_limits = self._build_rate_limits(rate_limits) absolute_limits = self._build_absolute_limits(absolute_limits) output = { "limits": { ...
random_line_split
limits.py
# Copyright 2010-2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
def _build_absolute_limits(self, absolute_limits): """Builder for absolute limits absolute_limits should be given as a dict of limits. For example: {"ram": 512, "gigabytes": 1024}. """ limit_names = { "ram": ["maxTotalRAMSize"], "instances": ["maxT...
rate_limits = self._build_rate_limits(rate_limits) absolute_limits = self._build_absolute_limits(absolute_limits) output = { "limits": { "rate": rate_limits, "absolute": absolute_limits, }, } return output
identifier_body
limits.py
# Copyright 2010-2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
(self, rate_limits): rate_limits = self._build_rate_limits(rate_limits) return {"limits": {"rate": rate_limits}}
build
identifier_name
limits.py
# Copyright 2010-2011 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless...
# ensure we have a key if we didn't find one if not _rate_limit_key: _rate_limit_key = { "uri": rate_limit["URI"], "regex": rate_limit["regex"], "limit": [], } limits.append(_rate_limit_...
_rate_limit_key = limit break
conditional_block
simple-imap.js
var Imap = require('imap'), MailParser = require('mailparser').MailParser, moment = require('moment') util = require('util'), events = require('events'); var SimpleImap = function(options) { this.options = options; this.imap = null; this.start = function() { if (this.imap === null)
bodies: '' }); f.on('message', function(msg, seqNo) { msg.on('body', function(stream, info) { var buffer = ''; stream.on('data', function(chunk) { buffer += chunk.toString('utf8'); }); stream.on('end', function() { var mailParser = new MailP...
{ this.imap = new Imap(this.options); var selfImap = this.imap, self = this; selfImap.on('ready', function() { self.emit('ready'); selfImap.openBox(self.options.mailbox, false, function() { self.emit('open'); }); }); selfImap.on('mail', function(num) { selfImap.search(['UNSEE...
conditional_block
simple-imap.js
var Imap = require('imap'), MailParser = require('mailparser').MailParser, moment = require('moment') util = require('util'), events = require('events'); var SimpleImap = function(options) { this.options = options; this.imap = null; this.start = function() { if (this.imap === null) { this.imap = new Imap...
if (result.length) { var f = selfImap.fetch(result, { markSeen: true, struct: true, bodies: '' }); f.on('message', function(msg, seqNo) { msg.on('body', function(stream, info) { var buffer = ''; stream.on('data', function(chunk) { buffer += c...
random_line_split
comparisonForManuallyOrderedInAttrsInheritance.py
from attr import dataclass class A7: x: int = 1 def __lt__(self, other): pass @dataclass(cmp=True) class B7(A7): y: str = "1" print(A7() < B7()) print(B7() <error descr="'__lt__' not supported between instances of 'B7' and 'A7'"><</error> A7()) print(A7() < object()) print(B7() <error descr="'__...
class B9(A9): y: str = "1" def __lt__(self, other): pass print(A9() < B9()) print(B9() < A9()) print(A9() <error descr="'__lt__' not supported between instances of 'A9' and 'object'"><</error> object()) print(B9() < object()) @dataclass(cmp=False) class A10: x: int = 1 class B10(A10): y: s...
x: int = 1
identifier_body
comparisonForManuallyOrderedInAttrsInheritance.py
from attr import dataclass class A7: x: int = 1 def __lt__(self, other): pass @dataclass(cmp=True) class B7(A7): y: str = "1" print(A7() < B7()) print(B7() <error descr="'__lt__' not supported between instances of 'B7' and 'A7'"><</error> A7()) print(A7() < object()) print(B7() <error descr="'__...
(self, other): pass @dataclass(cmp=False) class B8(A8): y: str = "1" print(A8() < B8()) print(B8() < A8()) print(A8() < object()) print(B8() < object()) @dataclass(cmp=True) class A9: x: int = 1 class B9(A9): y: str = "1" def __lt__(self, other): pass print(A9() < B9()) print(B9() ...
__lt__
identifier_name
comparisonForManuallyOrderedInAttrsInheritance.py
from attr import dataclass class A7: x: int = 1 def __lt__(self, other): pass @dataclass(cmp=True) class B7(A7): y: str = "1" print(A7() < B7()) print(B7() <error descr="'__lt__' not supported between instances of 'B7' and 'A7'"><</error> A7()) print(A7() < object()) print(B7() <error descr="'__...
def __lt__(self, other): pass print(A9() < B9()) print(B9() < A9()) print(A9() <error descr="'__lt__' not supported between instances of 'A9' and 'object'"><</error> object()) print(B9() < object()) @dataclass(cmp=False) class A10: x: int = 1 class B10(A10): y: str = "1" def __lt__(self, ot...
class B9(A9): y: str = "1"
random_line_split
__init__.py
# Copyright (C) 2008-2010 Adam Olsen # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2, or (at your option) # any later version. # # This program is distributed in the hope that...
# along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # # The developers of the Exaile media player hereby grant permission # for non-GPL compatible GStreamer and Exaile plugins to be used and # distributed together with GStream...
random_line_split
config.py
DEBUG = False USERNAME = 'hikaru' CHANNEL = 'random' VOCAB = { 'RANDOM': ['random', ':troll:', ':trollface:'], 'PASS': ['pass', 'skip'], 'RESIGN': ['resign', 'give up'], 'VOTE': ['vote', 'move', 'play'], 'VOTES': ['votes', 'moves', 'voted', 'chance'], 'CAPTURES': ['captures'], 'SHOW': ['s...
CRON = '0 9-18 * * 1-5' # Hourly between 9:00 and 18:00 on weekdays.
conditional_block
config.py
DEBUG = False USERNAME = 'hikaru' CHANNEL = 'random' VOCAB = { 'RANDOM': ['random', ':troll:', ':trollface:'], 'PASS': ['pass', 'skip'], 'RESIGN': ['resign', 'give up'], 'VOTE': ['vote', 'move', 'play'], 'VOTES': ['votes', 'moves', 'voted', 'chance'], 'CAPTURES': ['captures'], 'SHOW': ['s...
'RESIGN_CONFIRMATION': [ 'Are you sure you want to resign?', 'Sure?', ], 'RESIGN_CANCELLED': [ 'Ok.', 'Resignation cancelled.', ], 'UNKNOWN': [ "I don't know.", 'What do you mean?', "That doesn't make any sense.", "I'm just a bot.", ...
} RESPONSES = {
random_line_split
NumberOfReturns.py
# Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS # # This file is part of PyAnalyzer. # # PyAnalyzer is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (a...
node.NumberOfReturns = compiler.walk(node, ReturnsCounter()).result
identifier_body
NumberOfReturns.py
# Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS # # This file is part of PyAnalyzer. # # PyAnalyzer is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (a...
# or see <http://www.opensource.org/licenses/gpl-3.0.html> # # Contact: # Junior FLEURIAL MONFILS <frederic dot fleurialmonfils at cetic dot be> __author__ = "Frederic F. MONFILS" __version__ = "$Revision: $".split()[1] __revision__ = __version__ # $Source: $ __date__ = "$Date: $" __copyright__ = "Copyr...
# GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>.
random_line_split
NumberOfReturns.py
# Copyright (c) 2008-2009 Junior (Frederic) FLEURIAL MONFILS # # This file is part of PyAnalyzer. # # PyAnalyzer is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (a...
(self, node, *args): node.NumberOfReturns = compiler.walk(node, ReturnsCounter()).result
visitFunction
identifier_name
compensate.rs
#include <constants.rh> #include <crctools.rh> #include <math.rh> #include <util.rh> ; vim: syntax=fasm _start: mov r3, #0x1000 ; Output buffer address mov [r3], #0x6c6c6548 ; 'lleH' mov [r3+#4], #0x57202c6f ; 'W ,o' mov [r3+#8], #0x646c726f ; 'dlro'
jz $next call $_error next: push #0xDEADBEEF push #14 push #0x1000 call $_compensate_crc test r0, r0 jz $verify call $_error verify: push #14 push #0x1000 call $_crc_block cmp r0, #0xDEADBEEF jz $finish call ...
mov [r3+#12], #0x00000a21 ; '!\n' push #14 ; Length push r3 ; Pointer call $_crc_block cmp r0, #0x4b17617b ; Check value
random_line_split
finite_abelian_groups.py
#!/usr/bin/env python3.5 # Arun Debray, 24 Dec. 2015 # Given a group order, classifies finite abelian groups of that order. # ./finite_abelian_groups.py [-tpi] number # -t formats the output in TeX (as opposed to in the terminal) # -p chooses the primary components decomposition (default) # -i chooses the invariant f...
(groups: list, order: int, as_TeX: bool): if as_TeX: print('\\documentclass{amsart}') print('\\newcommand{\\Z}{\\mathbb Z}') print('\\title{Abelian Groups of Order %d}' % order) print('\\begin{document}') print('\\maketitle') print('%s of order %d.' % (format_plurals(len(groups)), order)) print('\\begin{...
output
identifier_name
finite_abelian_groups.py
#!/usr/bin/env python3.5 # Arun Debray, 24 Dec. 2015 # Given a group order, classifies finite abelian groups of that order. # ./finite_abelian_groups.py [-tpi] number # -t formats the output in TeX (as opposed to in the terminal) # -p chooses the primary components decomposition (default) # -i chooses the invariant f...
se: groups = primary_factor_decomp(factors) output(groups, arginfo.order, arginfo.t) if __name__ == '__main__': main()
ps = invariant_factor_decomp(factors) el
conditional_block
finite_abelian_groups.py
#!/usr/bin/env python3.5 # Arun Debray, 24 Dec. 2015 # Given a group order, classifies finite abelian groups of that order. # ./finite_abelian_groups.py [-tpi] number # -t formats the output in TeX (as opposed to in the terminal) # -p chooses the primary components decomposition (default) # -i chooses the invariant f...
# Uses the partitions in a different way to make a list of all abelian groups of a given order in # the invariant-factors decomposition. def invariant_factor_decomp(factors: collections.Counter) -> list: decomps_at_primes = [partitions(p, factors[p]) for p in factors] return [(functools.reduce(lambda x,y: x*y, inv_...
decomps_at_primes = [partitions(p, factors[p]) for p in factors] return [flatten(choice) for choice in itertools.product(*decomps_at_primes)]
identifier_body
finite_abelian_groups.py
#!/usr/bin/env python3.5 # Arun Debray, 24 Dec. 2015 # Given a group order, classifies finite abelian groups of that order. # ./finite_abelian_groups.py [-tpi] number # -t formats the output in TeX (as opposed to in the terminal) # -p chooses the primary components decomposition (default) # -i chooses the invariant f...
# Given the prime factors, returns a list of all abelian groups of the given order in primary- # factors format. def primary_factor_decomp(factors: collections.Counter) -> list: decomps_at_primes = [partitions(p, factors[p]) for p in factors] return [flatten(choice) for choice in itertools.product(*decomps_at_primes)...
# Flattens one level of a list, turning [[1, 2, 3], [4, 5]] into [1, 2, 3, 4, 5]. def flatten(xs: list) -> list: return [item for sublist in xs for item in sublist]
random_line_split
views.py
from django.shortcuts import render from django.views.generic import ListView from ..cms.models import Page from ..utils import JsonView from .models import Original, Print class ShopOriginalsView(ListView): context_object_name = 'shop_items' queryset = Original.objects.filter(disable=False).order_by('-order...
(ListView): context_object_name = 'shop_items' queryset = Print.objects.filter(disable=False).order_by('-order') template_name = 'shop/shop.html' def get_context_data(self, **kwargs): context = super(ShopPrintsView, self).get_context_data(**kwargs) context['page'] = Page.objects.get(nam...
ShopPrintsView
identifier_name
views.py
from django.shortcuts import render from django.views.generic import ListView from ..cms.models import Page from ..utils import JsonView from .models import Original, Print class ShopOriginalsView(ListView):
class ShopPrintsView(ListView): context_object_name = 'shop_items' queryset = Print.objects.filter(disable=False).order_by('-order') template_name = 'shop/shop.html' def get_context_data(self, **kwargs): context = super(ShopPrintsView, self).get_context_data(**kwargs) context['page']...
context_object_name = 'shop_items' queryset = Original.objects.filter(disable=False).order_by('-order') template_name = 'shop/shop.html' def get_context_data(self, **kwargs): context = super(ShopOriginalsView, self).get_context_data(**kwargs) context['page'] = Page.objects.get(name='shop/or...
identifier_body
views.py
from django.shortcuts import render from django.views.generic import ListView from ..cms.models import Page from ..utils import JsonView from .models import Original, Print class ShopOriginalsView(ListView): context_object_name = 'shop_items' queryset = Original.objects.filter(disable=False).order_by('-order...
elif shop_type == 'prints': klass = Print else: raise Exception("Unknown shop type %s." % shop_type) for item_id in ids: item = klass.objects.get(pk=item_id) item.order = index item.save() index -= 1
klass = Original
conditional_block
views.py
from django.shortcuts import render from django.views.generic import ListView from ..cms.models import Page from ..utils import JsonView from .models import Original, Print class ShopOriginalsView(ListView): context_object_name = 'shop_items' queryset = Original.objects.filter(disable=False).order_by('-order...
class ShopSortJson(JsonView): def json_post(self, request, *args, **kwargs): ids = request.POST.getlist('data[]') shop_type = request.POST.get('shop_type') index = len(ids) if shop_type == 'originals': klass = Original elif shop_type == 'prints': kl...
context['page'] = Page.objects.get(name='shop/prints') return context
random_line_split
wsgi_server.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. """ WSGI stack, common code. """ import httplib import urllib import xmlrpclib import StringIO import errno import logging import platform import socket import sys import threading import traceback import werkzeug.s...
(start_response, service, method, params, string_faultcode=False): """ Helper to call a service's method with some params, using a wsgi-supplied ``start_response`` callback. This is the place to look at to see the mapping between core exceptions and XML-RPC fault codes. """ # Map OpenERP co...
xmlrpc_return
identifier_name
wsgi_server.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. """ WSGI stack, common code. """ import httplib import urllib import xmlrpclib import StringIO import errno import logging import platform import socket import sys import threading import traceback import werkzeug.s...
def application(environ, start_response): if config['proxy_mode'] and 'HTTP_X_FORWARDED_HOST' in environ: return werkzeug.contrib.fixers.ProxyFix(application_unproxied)(environ, start_response) else: return application_unproxied(environ, start_response)
response = 'No handler found.\n' start_response('404 Not Found', [('Content-Type', 'text/plain'), ('Content-Length', str(len(response)))]) return [response]
random_line_split
wsgi_server.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. """ WSGI stack, common code. """ import httplib import urllib import xmlrpclib import StringIO import errno import logging import platform import socket import sys import threading import traceback import werkzeug.s...
elif isinstance(e, openerp.exceptions.DeferredException): info = e.traceback # Which one is the best ? formatted_info = "".join(traceback.format_exception(*info)) #formatted_info = openerp.tools.exception_to_unicode(e) + '\n' + info fault = xmlrpclib.Fault(RPC_FAULT_CODE_APP...
fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_DENIED, str(e)) response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
conditional_block
wsgi_server.py
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. """ WSGI stack, common code. """ import httplib import urllib import xmlrpclib import StringIO import errno import logging import platform import socket import sys import threading import traceback import werkzeug.s...
else: info = sys.exc_info() formatted_info = "".join(traceback.format_exception(*info)) fault = xmlrpclib.Fault(openerp.tools.exception_to_unicode(e), formatted_info) response = xmlrpclib.dumps(fault, allow_none=None, encoding=None) return response def wsgi_xmlrpc(environ, star...
if isinstance(e, openerp.exceptions.UserError): fault = xmlrpclib.Fault('warning -- %s\n\n%s' % (e.name, e.value), '') response = xmlrpclib.dumps(fault, allow_none=False, encoding=None) elif isinstance(e, openerp.exceptions.RedirectWarning): fault = xmlrpclib.Fault('warning -- Warning\n\n' +...
identifier_body
notify.js
Notify = function(text, callback, close_callback, style) { var time = '10000'; var $container = $('#notifications'); var icon = '<i class="fa fa-info-circle "></i>'; if (typeof style == 'undefined' ) style = 'warning' var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>...
var timer = setInterval(remove_notice, time); $(html).hover(function(){ clearInterval(timer); }, function(){ timer = setInterval(remove_notice, time); }); html.on('click', function () { clearInterval(timer) callback && callback() remove_notice() }); }
html.stop().fadeOut('slow').remove() }
identifier_body
notify.js
Notify = function(text, callback, close_callback, style) { var time = '10000'; var $container = $('#notifications'); var icon = '<i class="fa fa-info-circle "></i>'; if (typeof style == 'undefined' ) style = 'warning' var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>...
) { html.stop().fadeOut('slow').remove() } var timer = setInterval(remove_notice, time); $(html).hover(function(){ clearInterval(timer); }, function(){ timer = setInterval(remove_notice, time); }); html.on('click', function () { clearInterval(timer) callback && callback() remove_notice() }); ...
emove_notice(
identifier_name
notify.js
Notify = function(text, callback, close_callback, style) { var time = '10000'; var $container = $('#notifications'); var icon = '<i class="fa fa-info-circle "></i>'; if (typeof style == 'undefined' ) style = 'warning' var html = $('<div class="alert alert-' + style + ' hide">' + icon + " " + text + '</div>...
}
random_line_split
foundation.js
// Copyright 2012 Ofir Picazo. All Rights Reserved. /** * @fileoverview Foundation object, fill one per suit to complete the game. * * @author ofirpicazo@gmail.com (Ofir Picazo) */ goog.provide('solitario.game.Foundation'); goog.require('goog.dom.dataset'); goog.require('solitario.game.Card'); goog.require('soli...
// Check that card is a Ace when the foundation is empty, otherwise it must be // the next card for the suit of the pile. if (this.isEmpty()) { return (card.number == solitario.game.constants.CardNumber.ACE); } else { var topCard = this.getTopCard(); return (card.suit == this.suit && (card.value -...
{ return false; }
conditional_block
foundation.js
// Copyright 2012 Ofir Picazo. All Rights Reserved. /** * @fileoverview Foundation object, fill one per suit to complete the game. * * @author ofirpicazo@gmail.com (Ofir Picazo) */ goog.provide('solitario.game.Foundation'); goog.require('goog.dom.dataset'); goog.require('solitario.game.Card'); goog.require('soli...
* @override */ solitario.game.Foundation.prototype.pop = function() { var card = solitario.game.Foundation.superClass_.pop.call(this); if (this.isEmpty()) { this.suit = null; } return card; }; /** * Adds a new card to the foundation. Sets the foundation's suit if it's not yet * set. * * @param {so...
* * @return {?solitario.game.Card} The card popped from the pile.
random_line_split
test.py
import numpy as np import cv2 from sys import argv class Test: def __init__(self, name, image): self.image = image self.name = name self.list = [] def add(self, function): self.list.append(function) def run(self): cv2.imshow(self.name, self.image) ...
def unsharp(image): image2 = cv2.GaussianBlur(image, (21,21), 21) iamge = cv2.addWeighted(image, 1.5, image2, -0.5, 0, image) return image def harris(image): x33 = image.shape[1] / 3 x66 = image.shape[1] / 3 * 2 dst1 = cv2.goodFeaturesToTrack(image[:,:x33], 10, 0.1, 5) mean1 = np...
cv2.medianBlur(image, 9, image) return image
random_line_split
test.py
import numpy as np import cv2 from sys import argv class Test: def __init__(self, name, image): self.image = image self.name = name self.list = [] def add(self, function): self.list.append(function) def run(self): cv2.imshow(self.name, self.image) ...
def unsharp(image): image2 = cv2.GaussianBlur(image, (21,21), 21) iamge = cv2.addWeighted(image, 1.5, image2, -0.5, 0, image) return image def harris(image): x33 = image.shape[1] / 3 x66 = image.shape[1] / 3 * 2 dst1 = cv2.goodFeaturesToTrack(image[:,:x33], 10, 0.1, 5) mean1 ...
cv2.medianBlur(image, 9, image) return image
identifier_body
test.py
import numpy as np import cv2 from sys import argv class Test: def __init__(self, name, image): self.image = image self.name = name self.list = [] def add(self, function): self.list.append(function) def run(self): cv2.imshow(self.name, self.image) ...
image = cv2.imread(argv[1]) test = Test('Test', image) test.add(grayscale) test.add(median) test.add(harris) test.run()
conditional_block
test.py
import numpy as np import cv2 from sys import argv class
: def __init__(self, name, image): self.image = image self.name = name self.list = [] def add(self, function): self.list.append(function) def run(self): cv2.imshow(self.name, self.image) for function in self.list: cv2.waitKey() ...
Test
identifier_name
app.component.ts
import { Component } from '@angular/core'; import { IEmployee } from 'ng-org-chart'; @Component({ selector: 'demo-app', templateUrl: './app.component.html' }) export class
{ topEmployee: IEmployee = { name: 'Janis Martin', designation: 'CEO', subordinates: [ { name: 'Matthew Wikes', designation: 'VP', subordinates: [ { name: 'Tina Landry', designation: 'Budget Analyst', subordinates: [] } ] }, { name: 'Patricia Lyons', ...
AppComponent
identifier_name
app.component.ts
import { Component } from '@angular/core'; import { IEmployee } from 'ng-org-chart'; @Component({ selector: 'demo-app', templateUrl: './app.component.html' }) export class AppComponent { topEmployee: IEmployee = { name: 'Janis Martin', designation: 'CEO', subordinates: [ { name: 'Matthew Wikes', de...
name: 'Larry Phung', designation: 'VP', subordinates: [] } ] }; }
} ] }, {
random_line_split
dlg_subida.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ --------------------------------------------------------------------------------------------------- dlg_subida mantém as informações sobre a dialog de subida This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Pub...
------------------------------------------------- def __update_command(self): """ DOCUMENT ME! """ # para todas as subidas... for l_key, l_sub in self.__dct_sub.iteritems(): # é a subida selecionada ? if self.cbx_sub.currentText() == l_sub: ...
esta janela """ # obtém os settings l_set = QtCore.QSettings("sophosoft", "piloto") assert l_set # restaura geometria da janela self.restoreGeometry(l_set.value("%s/Geometry" % (self.__txt_settings)).toByteArray()) # --------------------------------------------
identifier_body
dlg_subida.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ --------------------------------------------------------------------------------------------------- dlg_subida mantém as informações sobre a dialog de subida This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Pub...
""" __version__ = "$revision: 0.2$" __author__ = "mlabru, sophosoft" __date__ = "2015/12" # < imports >-------------------------------------------------------------------------------------- # python library import json import os # PyQt library from PyQt4 import QtCore from PyQt4 import QtGui # view import view.pilo...
pep8 style conventions revision 0.1 2014/nov mlabru initial release (Linux/Python) ---------------------------------------------------------------------------------------------------
random_line_split
dlg_subida.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ --------------------------------------------------------------------------------------------------- dlg_subida mantém as informações sobre a dialog de subida This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Pub...
self.cbx_sub.addItems(sorted(self.__dct_sub.values())) # configura botões self.bbx_subida.button(QtGui.QDialogButtonBox.Cancel).setText("&Cancela") self.bbx_subida.button(QtGui.QDialogButtonBox.Ok).setFocus() # inicia os parâmetros da subida self.__update_command() # ---...
ia valores
conditional_block
dlg_subida.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ --------------------------------------------------------------------------------------------------- dlg_subida mantém as informações sobre a dialog de subida This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Pub...
fsck_http, fdct_config, f_strip_cur, fdct_sub, f_parent=None): """ @param fsck_http: socket de comunicação com o servidor @param fdct_config: dicionário de configuração @param f_strip_cur: strip selecionada @param fdct_sub: dicionário de subidas @param f_parent: janela p...
__(self,
identifier_name
abort.rs
(iss: u64) -> Result<Vec<FieldInfo>, DecodeError> { let res0a = FieldInfo::get(iss, "RES0", Some("Reserved"), 13, 25).check_res0()?; let fnv = FieldInfo::get_bit(iss, "FnV", Some("FAR not Valid"), 10).describe_bit(describe_fnv); let ea = FieldInfo::get_bit(iss, "EA", Some("External abort type"), 9); let...
decode_iss_instruction_abort
identifier_name
abort.rs
get(iss, "RES0", Some("Reserved"), 13, 25).check_res0()?; let fnv = FieldInfo::get_bit(iss, "FnV", Some("FAR not Valid"), 10).describe_bit(describe_fnv); let ea = FieldInfo::get_bit(iss, "EA", Some("External abort type"), 9); let res0b = FieldInfo::get_bit(iss, "RES0", Some("Reserved"), 8).check_res0()?; ...
} 0b010110 => { "Synchronous External abort on translation table walk or hardware update of \ translation table, level 2." } 0b010111 => { "Synchronous External abort on translation table walk or hardware update of \ translation table, le...
translation table, level 0." } 0b010101 => { "Synchronous External abort on translation table walk or hardware update of \ translation table, level 1."
random_line_split
lib.rs
//! // Return the interaction builder back to the pact framework //! i //! }) //! .await //! .build(); //! # }); //! ``` //! //! You can than use an HTTP client like `reqwest` to make requests against your //! server. //! //! ```rust //! # tokio_test::block_on(async { //! # use pact_models::...
random_line_split
UserActions.test.js
import * as actions from '../UserActions'; it('should setup loggingIn', () => { const action = actions.loggingIn(); const expected = { type: 'LOGGING_IN' }; expect(action).toEqual(expected); }); it('should setup loggedInSuccess', () => { const user = 'janesmith'; const action = actions.loggedInSuccess...
const expected = { type: 'LOGGED_IN_ERROR', error: err }; expect(action).toEqual(expected); }); it('should setup logoutSuccess', () => { const action = actions.logoutSuccess(); const expected = { type: 'LOGGED_OUT_SUCCESS' }; expect(action).toEqual(expected); });
const action = actions.loggedInError(err);
random_line_split
DisableIndexOperation.ts
import { HttpRequestParameters } from "../../../Primitives/Http"; import { IMaintenanceOperation, OperationResultType } from "../OperationAbstractions"; import { throwError } from "../../../Exceptions"; import { DocumentConventions } from "../../Conventions/DocumentConventions"; import { RavenCommand } from "../../...
public createRequest(node: ServerNode): HttpRequestParameters { const uri = node.url + "/databases/" + node.database + "/admin/indexes/disable?name=" + encodeURIComponent(this._indexName); return { method: "POST", uri }; } }
this._responseType = "Empty"; this._indexName = indexName; }
random_line_split
DisableIndexOperation.ts
import { HttpRequestParameters } from "../../../Primitives/Http"; import { IMaintenanceOperation, OperationResultType } from "../OperationAbstractions"; import { throwError } from "../../../Exceptions"; import { DocumentConventions } from "../../Conventions/DocumentConventions"; import { RavenCommand } from "../../...
(conventions: DocumentConventions) { return new DisableIndexCommand(this._indexName); } public get resultType(): OperationResultType { return "CommandResult"; } } export class DisableIndexCommand extends RavenCommand<void> { public get isReadRequest() { return fa...
getCommand
identifier_name
DisableIndexOperation.ts
import { HttpRequestParameters } from "../../../Primitives/Http"; import { IMaintenanceOperation, OperationResultType } from "../OperationAbstractions"; import { throwError } from "../../../Exceptions"; import { DocumentConventions } from "../../Conventions/DocumentConventions"; import { RavenCommand } from "../../...
this._responseType = "Empty"; this._indexName = indexName; } public createRequest(node: ServerNode): HttpRequestParameters { const uri = node.url + "/databases/" + node.database + "/admin/indexes/disable?name=" + encodeURIComponent(this._indexName); retu...
{ throwError("InvalidArgumentException", "IndexName cannot be null"); }
conditional_block
DisableIndexOperation.ts
import { HttpRequestParameters } from "../../../Primitives/Http"; import { IMaintenanceOperation, OperationResultType } from "../OperationAbstractions"; import { throwError } from "../../../Exceptions"; import { DocumentConventions } from "../../Conventions/DocumentConventions"; import { RavenCommand } from "../../...
}
{ const uri = node.url + "/databases/" + node.database + "/admin/indexes/disable?name=" + encodeURIComponent(this._indexName); return { method: "POST", uri }; }
identifier_body
ela-sep.py
import sys from pymongo import MongoClient from werkzeug.utils import secure_filename import os import sys client = MongoClient('mongodb://localhost:27017/') db = client.ir #li=[] #color=open("AllColors.txt","r") doc1=[] doc2=[] edgeConWT=[] edgeElaWT=[] edgeStart=[] edgeEnd=[] path="JVcode/Scripts/ForClassification/" ...
for i in range(0,len(edgeElaWT)): for j in range(0, len(edgeElaWT)): if (j < (len(edgeConWT) - 1)): if (edgeElaWT[j] < edgeElaWT[j + 1]): temp = edgeElaWT[j] edgeElaWT[j] = edgeElaWT[j + 1] e...
edgeElaWT.append(0.0)
conditional_block
ela-sep.py
import sys from pymongo import MongoClient from werkzeug.utils import secure_filename import os import sys client = MongoClient('mongodb://localhost:27017/') db = client.ir #li=[]
edgeConWT=[] edgeElaWT=[] edgeStart=[] edgeEnd=[] path="JVcode/Scripts/ForClassification/" for file in os.listdir(path): edgeElaWT = [] edgeConWT = [] edgeStart = [] edgeEnd = [] print (file) if file.endswith(".tab.scores"): fdTemp=open(path+file,"r") #fdOut=open("output/new/elab...
#color=open("AllColors.txt","r") doc1=[] doc2=[]
random_line_split
stats.py
# -*- coding: utf-8 -*- """ Created on Mon May 16 17:14:41 2016 @author: sdemyanov """ import numpy as np from sklearn import metrics def get_prob_acc(probs, labels): return np.mean(np.argmax(probs, axis=1) == labels) def get_auc_score(scores, labels): fpr, tpr, thresholds = metrics.roc_curve(labels, scores, p...
return mat def get_prob_confmat(probs, labels): classnum = probs.shape[1] mat = np.zeros((classnum, classnum), dtype=int) for pind in range(probs.shape[0]): mat[int(labels[pind]), np.argmax(probs[pind, :])] += 1 #mat = np.transpose(mat) return mat def get_block_confmat(confmat, blocks): assert(...
labind = np.where(classes == labels[pind]) predind = np.where(classes == preds[pind]) mat[labind[0], predind[0]] += 1 # mat = np.transpose(mat)
conditional_block
stats.py
# -*- coding: utf-8 -*- """ Created on Mon May 16 17:14:41 2016 @author: sdemyanov """ import numpy as np from sklearn import metrics def get_prob_acc(probs, labels): return np.mean(np.argmax(probs, axis=1) == labels) def get_auc_score(scores, labels): fpr, tpr, thresholds = metrics.roc_curve(labels, scores, p...
break if (is_missing): missing.append(i) newprob = np.delete(newprob, missing, axis=0) newlab = np.delete(newlab, missing, axis=0) return newprob, newlab def get_spec_for_sens(scores, labels, sens): fpr, tpr, thresholds = metrics.roc_curve(labels, scores, pos_label=0) curind = np.size(tpr...
if (labels[i] in blocks[j]): newlab[i] = j is_missing = False
random_line_split
stats.py
# -*- coding: utf-8 -*- """ Created on Mon May 16 17:14:41 2016 @author: sdemyanov """ import numpy as np from sklearn import metrics def get_prob_acc(probs, labels): return np.mean(np.argmax(probs, axis=1) == labels) def get_auc_score(scores, labels): fpr, tpr, thresholds = metrics.roc_curve(labels, scores, p...
(prob, labels, blocks): # IMPORTANT: blocks must not intersect, otherwise the result is not unique blocknum = len(blocks) assert prob.shape[0] == labels.shape[0] newprob = np.zeros((prob.shape[0], blocknum)) for i in range(blocknum): newprob[:, i] = np.sum(prob[:, blocks[i]], 1) #normalize to have sum =...
get_block_probs_labels
identifier_name
stats.py
# -*- coding: utf-8 -*- """ Created on Mon May 16 17:14:41 2016 @author: sdemyanov """ import numpy as np from sklearn import metrics def get_prob_acc(probs, labels): return np.mean(np.argmax(probs, axis=1) == labels) def get_auc_score(scores, labels): fpr, tpr, thresholds = metrics.roc_curve(labels, scores, p...
def get_sens_for_spec(scores, labels, spec): fpr, tpr, thresholds = metrics.roc_curve(labels, scores, pos_label=0) curind = 0 while (1 - fpr[curind+1] >= spec): curind += 1 return tpr[curind], 1 - fpr[curind], thresholds[curind] def get_average_precisions(probs, labels): print 'probshape:', np.shape(...
fpr, tpr, thresholds = metrics.roc_curve(labels, scores, pos_label=0) curind = np.size(tpr) - 1 while (tpr[curind-1] >= sens): curind -= 1 return tpr[curind], 1 - fpr[curind], thresholds[curind]
identifier_body
rtts_assert.ts
assert.argumentTypes) var POSITION_NAME = ['', '1st', '2nd', '3rd']; function argPositionName(i) { var position = (i / 2) + 1; return POSITION_NAME[position] || (position + 'th'); } var primitives; var genericType; if (typeof _global['$traceurRuntime'] === 'object') { primitives = _global['$traceurRuntime']....
(actual, T) { var errors = []; // currentStack = []; if (!isType(actual, T, errors)) { // console.log(JSON.stringify(errors, null, ' ')); // TODO(vojta): print "an instance of" only if T starts with uppercase. var msg = 'Expected to return an instance of ' + prettyPrint(T) + ', got ' + ...
returnType
identifier_name
rtts_assert.ts
else { // Allow to work without traceur runtime as well! primitives = { any: {name: 'any'}, boolean: {name: 'boolean'}, number: {name: 'number'}, string: {name: 'string'}, symbol: {name: 'symbol'}, void: {name: 'void'} }; genericType = function(type, args) { return { type: type, args: a...
// primitive value type; assert.string = string; assert.number = number;
random_line_split
rtts_assert.ts
assert.argumentTypes) var POSITION_NAME = ['', '1st', '2nd', '3rd']; function argPositionName(i) { var position = (i / 2) + 1; return POSITION_NAME[position] || (position + 'th'); } var primitives; var genericType; if (typeof _global['$traceurRuntime'] === 'object') { primitives = _global['$traceurRuntime']....
// TODO(vojta): define these with DSL? var string = type.string = define('string', function(value) { return typeof value === 'string'; }); var boolean = type.boolean = define('boolean', function(value) { return typeof value === 'boolean'; }); var number = type.number = define('number', function(value) { return ...
{ var errors = []; // currentStack = []; if (!isType(actual, T, errors)) { // console.log(JSON.stringify(errors, null, ' ')); // TODO(vojta): print "an instance of" only if T starts with uppercase. var msg = 'Expected to return an instance of ' + prettyPrint(T) + ', got ' + prettyPrint...
identifier_body
rtts_assert.ts
assert.argumentTypes) var POSITION_NAME = ['', '1st', '2nd', '3rd']; function argPositionName(i) { var position = (i / 2) + 1; return POSITION_NAME[position] || (position + 'th'); } var primitives; var genericType; if (typeof _global['$traceurRuntime'] === 'object') { primitives = _global['$traceurRuntime']....
// if (types.length > 1) { // currentStack.push(['has to be ' + types.map(prettyPrint).join(' or '), // ...allErrors]); // } else { currentStack.push(...allErrors); // }
{ var type = types[i]; errors = []; if (isType(value, type, errors)) { return true; } // if no errors, merge multiple "is not instance of " into x/y/z ? allErrors.push(prettyPrint(value) + ' is not instance of ' + prettyPrint(type))...
conditional_block
tsk_test.py
from rekall import resources from rekall_agent import testlib from rekall_agent.client_actions import files from rekall_agent.client_actions import tsk class TestTSK(testlib.ClientAcionTest): def setUp(self): super(TestTSK, self).setUp() # Add a fake mount point to the image. mount_tree_h...
(self): action = tsk.TSKListDirectoryAction(session=self.session) action.path = "/mnt/a" action.vfs_location = self.get_test_location("test") self.assert_baseline("testTSK", list(action.collect())) def testTSKRecursive(self): action = tsk.TSKListDirectoryAction(session=self....
testTSK
identifier_name
tsk_test.py
from rekall import resources from rekall_agent import testlib from rekall_agent.client_actions import files from rekall_agent.client_actions import tsk class TestTSK(testlib.ClientAcionTest): def setUp(self): super(TestTSK, self).setUp() # Add a fake mount point to the image. mount_tree_h...
testlib.main()
conditional_block
tsk_test.py
from rekall import resources from rekall_agent import testlib from rekall_agent.client_actions import files from rekall_agent.client_actions import tsk class TestTSK(testlib.ClientAcionTest): def setUp(self): super(TestTSK, self).setUp() # Add a fake mount point to the image. mount_tree_h...
self.session.SetParameter("mount_points", mount_tree) def testTSK(self): action = tsk.TSKListDirectoryAction(session=self.session) action.path = "/mnt/a" action.vfs_location = self.get_test_location("test") self.assert_baseline("testTSK", list(action.collect())) def tes...
prefix="test_data"), "ext2")
random_line_split
tsk_test.py
from rekall import resources from rekall_agent import testlib from rekall_agent.client_actions import files from rekall_agent.client_actions import tsk class TestTSK(testlib.ClientAcionTest): def setUp(self): super(TestTSK, self).setUp() # Add a fake mount point to the image. mount_tree_h...
if __name__ == "__main__": testlib.main()
action = tsk.TSKListDirectoryAction(session=self.session) action.path = "/mnt/a" action.depth = 2 action.vfs_location = self.get_test_location("test") self.assert_baseline("testTSKRecursive", list(action.collect()))
identifier_body
recipe-ad.component.ts
/** * @module HomeModule */ /** */ import { Component, Input, OnInit } from '@angular/core'; /** * @whatItDoes Displays a single recipe ad item. * @consumers {@link HomeModule} */ @Component({ selector: 'app-recipe-ad', templateUrl: './recipe-ad.component.html', styleUrls: ['./recipe-ad.component.scss'] }) ...
@Input() recipe; /** * Cycles through the {@link arrowColors} based on the current index */ updateColor() { const mod = this.index % this.arrowColors.length; this.arrowColor = this.arrowColors[mod]; } /** * Run once on component creation * * - Gets the blurb arrow color */ ngOnIni...
@Input() index; /** * Base data for the recipe including `id` and `title`. */
random_line_split
recipe-ad.component.ts
/** * @module HomeModule */ /** */ import { Component, Input, OnInit } from '@angular/core'; /** * @whatItDoes Displays a single recipe ad item. * @consumers {@link HomeModule} */ @Component({ selector: 'app-recipe-ad', templateUrl: './recipe-ad.component.html', styleUrls: ['./recipe-ad.component.scss'] }) ...
/** * Run once on component creation * * - Gets the blurb arrow color */ ngOnInit() { this.updateColor(); } }
{ const mod = this.index % this.arrowColors.length; this.arrowColor = this.arrowColors[mod]; }
identifier_body
recipe-ad.component.ts
/** * @module HomeModule */ /** */ import { Component, Input, OnInit } from '@angular/core'; /** * @whatItDoes Displays a single recipe ad item. * @consumers {@link HomeModule} */ @Component({ selector: 'app-recipe-ad', templateUrl: './recipe-ad.component.html', styleUrls: ['./recipe-ad.component.scss'] }) ...
() { const mod = this.index % this.arrowColors.length; this.arrowColor = this.arrowColors[mod]; } /** * Run once on component creation * * - Gets the blurb arrow color */ ngOnInit() { this.updateColor(); } }
updateColor
identifier_name
vdom-util.tsx
/* eslint max-classes-per-file: off */ import { __assign } from 'tslib' import { Component, Ref } from './vdom' import { ViewContextType, ViewContext } from './ViewContext' import { compareObjs, EqualityFuncs, getUnequalProps } from './util/object' import { Dictionary } from './options' export abstract class PureComp...
} // use other one export function setRef<RefType>(ref: Ref<RefType> | void, current: RefType) { if (typeof ref === 'function') { ref(current) } else if (ref) { // see https://github.com/facebook/react/issues/13029 (ref as any).current = current } }
this.prototype.stateEquality = hash
random_line_split
vdom-util.tsx
/* eslint max-classes-per-file: off */ import { __assign } from 'tslib' import { Component, Ref } from './vdom' import { ViewContextType, ViewContext } from './ViewContext' import { compareObjs, EqualityFuncs, getUnequalProps } from './util/object' import { Dictionary } from './options' export abstract class PureComp...
// use other one export function setRef<RefType>(ref: Ref<RefType> | void, current: RefType) { if (typeof ref === 'function') { ref(current) } else if (ref) { // see https://github.com/facebook/react/issues/13029 (ref as any).current = current } }
{ let hash = Object.create(this.prototype.stateEquality) __assign(hash, stateEquality) this.prototype.stateEquality = hash }
identifier_body
vdom-util.tsx
/* eslint max-classes-per-file: off */ import { __assign } from 'tslib' import { Component, Ref } from './vdom' import { ViewContextType, ViewContext } from './ViewContext' import { compareObjs, EqualityFuncs, getUnequalProps } from './util/object' import { Dictionary } from './options' export abstract class PureComp...
else if (ref) { // see https://github.com/facebook/react/issues/13029 (ref as any).current = current } }
{ ref(current) }
conditional_block
vdom-util.tsx
/* eslint max-classes-per-file: off */ import { __assign } from 'tslib' import { Component, Ref } from './vdom' import { ViewContextType, ViewContext } from './ViewContext' import { compareObjs, EqualityFuncs, getUnequalProps } from './util/object' import { Dictionary } from './options' export abstract class PureComp...
(nextProps: Props, nextState: State) { if (this.debug) { // eslint-disable-next-line no-console console.log(getUnequalProps(nextProps, this.props), getUnequalProps(nextState, this.state)) } return !compareObjs(this.props, nextProps, this.propEquality) || !compareObjs(this.state, nextState...
shouldComponentUpdate
identifier_name
game.rs
use std::cell::RefCell; use std::collections::HashSet; use std::rc::Rc; use slackbot::{CommandHandler, Sender}; use rand::{self, Rng}; pub struct GameCommandHandler {
GameCommandHandler { registered_users: user_store } } } impl CommandHandler for GameCommandHandler { fn handle(&mut self, sender: &mut Sender, args: &Vec<String>) { let team_size = if args.len() > 0 && args[0] == "1v1" { 1 } else { 2 }; let users = self.registered_us...
registered_users: Rc<RefCell<HashSet<String>>> } impl GameCommandHandler { pub fn new(user_store: Rc<RefCell<HashSet<String>>>) -> Self {
random_line_split
game.rs
use std::cell::RefCell; use std::collections::HashSet; use std::rc::Rc; use slackbot::{CommandHandler, Sender}; use rand::{self, Rng}; pub struct GameCommandHandler { registered_users: Rc<RefCell<HashSet<String>>> } impl GameCommandHandler { pub fn new(user_store: Rc<RefCell<HashSet<String>>>) -> Self { ...
; let users = self.registered_users.borrow(); if users.len() < team_size * 2 { sender.respond_in_channel(format!("Not enough players! Need {0} players to be registered to start a game.", team_size * 2)).unwrap(); } else { let mut users = &mut users.iter().collect::<Vec<_>...
{ 2 }
conditional_block
game.rs
use std::cell::RefCell; use std::collections::HashSet; use std::rc::Rc; use slackbot::{CommandHandler, Sender}; use rand::{self, Rng}; pub struct GameCommandHandler { registered_users: Rc<RefCell<HashSet<String>>> } impl GameCommandHandler { pub fn new(user_store: Rc<RefCell<HashSet<String>>>) -> Self { ...
(&mut self, sender: &mut Sender, args: &Vec<String>) { let team_size = if args.len() > 0 && args[0] == "1v1" { 1 } else { 2 }; let users = self.registered_users.borrow(); if users.len() < team_size * 2 { sender.respond_in_channel(format!("Not enough players! Need {0} players to be re...
handle
identifier_name
hash_join.rs
// http://rosettacode.org/wiki/Hash_join use std::collections::HashMap; type LeftTable<'a> = Vec<(i64, &'a str)>; type RightTable<'a> = Vec<(&'a str, &'a str)>; type ResultTable<'a> = Vec<(i64, &'a str, &'a str)>; fn hash_join<'a>(s: LeftTable<'a>, r: RightTable<'a>) -> ResultTable<'a> { let mut hash_map: HashMa...
() { let table1 = vec![(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "Popeye"), (28, "Alan")]; let table2 = vec![("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "Ghosts"), ("Alan", "Zombies"), ...
main
identifier_name
hash_join.rs
// http://rosettacode.org/wiki/Hash_join use std::collections::HashMap; type LeftTable<'a> = Vec<(i64, &'a str)>; type RightTable<'a> = Vec<(&'a str, &'a str)>; type ResultTable<'a> = Vec<(i64, &'a str, &'a str)>; fn hash_join<'a>(s: LeftTable<'a>, r: RightTable<'a>) -> ResultTable<'a>
} return result; } #[cfg(not(test))] pub fn main() { let table1 = vec![(27, "Jonah"), (18, "Alan"), (28, "Glory"), (18, "Popeye"), (28, "Alan")]; let table2 = vec![("Jonah", "Whales"), ("Jonah", "Spiders"), ("Alan", "G...
{ let mut hash_map: HashMap<&str, Vec<&str>> = HashMap::new(); //hash phase for (name, nemesis) in r { if hash_map.contains_key(name) { hash_map.get_mut(name).unwrap().push(nemesis); } else { hash_map.insert(name, vec![nemesis]); } } let mut result =...
identifier_body