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
indexable.py
the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither th...
else: raise AttributeError("An index operation with the name {} was already taken".format(name)) def _add_io(self, name, operations): self._index_operations[name] = operations def do_raise(self, x): self._index_operations.__setitem__(name, x) self._conne...
self._add_io(name, operations)
conditional_block
indexable.py
retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Nei...
""" if param.has_parent(): p = param._parent_._get_original(param) if p in self.parameters: return reduce(lambda a,b: a + b.size, self.parameters[:p._parent_index_], 0) return self._offset_for(param._parent_) + param._parent_._offset_for(param) ...
def _offset_for(self, param): """ Return the offset of the param inside this parameterized object. This does not need to account for shaped parameters, as it basically just sums up the parameter sizes which come before param.
random_line_split
indexable.py
retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Nei...
### Global index operations (from highest_parent) ### These indices are for gradchecking, so that we ### can index the optimizer array and manipulate it directly ### The indices here do not reflect the indices in ### index_operations, as index operations handle ### the offset themselves and ca...
""" Return the offset of the param inside this parameterized object. This does not need to account for shaped parameters, as it basically just sums up the parameter sizes which come before param. """ if param.has_parent(): p = param._parent_._get_original(param) ...
identifier_body
indexable.py
the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # * Neither th...
(self, name): if name in self._index_operations: delitem(self._index_operations, name) #delattr(self, name) else: raise AttributeError("No index operation with the name {}".format(name)) def _disconnect_parent(self, *args, **kw): """ From Parentab...
remove_index_operation
identifier_name
parser.go
[2] b.Variable = name } if k == bTest { // Parse operator. b.Operator = strings.TrimSpace(parts[1]) // Parse value. Can use a variable. b.Value = strings.TrimSpace(parts[2]) // Parse offset. offset, err := strconv.Atoi(strings.TrimSpace(parts[3])) if err != nil { return nil, fmt.Errorf("%s offset ...
{ for _, u := range p { if strings.Count(u, "[") != strings.Count(u, "]") { // unbalanced groups. return false } u = strings.TrimPrefix(u, "!") // If this port range is a grouping, check the inner group. if strings.HasPrefix(u, "[") { if portsValid(strings.Split(strings.Trim(u, "[]"), ",")) { ...
identifier_body
parser.go
(content string) ([]byte, error) { // Decode and replace all occurrences of hexadecimal content. var errpanic error defer func() { r := recover() if r != nil { errpanic = fmt.Errorf("recovered from panic: %v", r) } }() if containsUnescaped(content) { return nil, fmt.Errorf("invalid special characters e...
parseContent
identifier_name
parser.go
group. if strings.HasPrefix(u, "[") { if portsValid(strings.Split(strings.Trim(u, "[]"), ",")) { continue } return false } ports := portSplitRE.Split(u, -1) for _, port := range ports { port = strings.TrimPrefix(port, "!") if port == "any" || port == "" || strings.HasPrefix(port, "$") { ...
random_line_split
parser.go
", b.Kind, parts[1], err) } b.Offset = offset } if k == bExtract { // Parse variable name. name := parts[2] b.Variable = name } if k == bTest { // Parse operator. b.Operator = strings.TrimSpace(parts[1]) // Parse value. Can use a variable. b.Value = strings.TrimSpace(parts[2]) // Parse offset....
{ continue }
conditional_block
types.go
} type AddressMeta struct { Label string `json:"label"` Value string `json:"value"` } type CryptoDetails struct { Address string `json:"address"` Txid string `json:"txid"` } type DetailFields struct { CryptoDetails CryptoDetails `json:"crypto_details"` TradeDetails TradeDetails `json:"trade_details"` } t...
// <code>PENDING</code> The order has been placed. Some trades may have // taken place but the order is not filled yet.<br> // <code>COMPLETE</code> The order is no longer active. It has been settled // or has been cancelled. State OrderState `json:"state"` // <code>BID</code> bid (buy) limit order.<br> // <co...
// Specifies the market. Pair string `json:"pair"`
random_line_split
clipmap.rs
(); if lod >= config.num_lods { return VisitStatus::Continue; } let offset_from_center = get_offset_from_lod_center(octant, &centers); if lod == 0 || offset_from_center > high_lod_boundary { // This octant can be rendered at this level of detail. act...
) .abs() .max_component() } fn octant_chunk_key(chunk_log2: i32, octant: &Octant) -> ChunkKey3 { let lod = octant.exponent(); ChunkKey { lod, minimum: (octant.minimum() << chunk_log2) >> lod, } } // ████████╗███████╗███████╗████████╗ // ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝ /...
{ c }
conditional_block
clipmap.rs
(); if lod >= config.num_lods { return VisitStatus::Continue; } let offset_from_center = get_offset_from_lod_center(octant, &centers); if lod == 0 || offset_from_center > high_lod_boundary { // This octant can be rendered at this level of detail. act...
( &self, octree: &OctreeSet, mut update_rx: impl FnMut(LodChunkUpdate3), ) { octree.visit_all_octants_in_preorder(&mut |node: &OctreeNode| { let octant = node.octant(); let lod = octant.exponent(); if lod >= self.num_lods || lod == 0 { ...
find_chunk_updates
identifier_name
clipmap.rs
, &self.old_centers); let offset_from_center = get_offset_from_lod_center(octant, &self.new_centers); if old_offset_from_center > self.high_lod_boundary && offset_from_center <= self.high_lod_boundary { // Increase the detail for this octant. ...
ClipMapUpdate3::new(config, old_lod0_center, new_lod0_center) .find_chunk_updates(octree, |update| active_chunks.apply_update(update));
random_line_split
clipmap.rs
(); if lod >= config.num_lods { return VisitStatus::Continue; } let offset_from_center = get_offset_from_lod_center(octant, &centers); if lod == 0 || offset_from_center > high_lod_boundary { // This octant can be rendered at this level of detail. act...
.max_component() } fn octant_chunk_key(chunk_log2: i32, octant: &Octant) -> ChunkKey3 { let lod = octant.exponent(); ChunkKey { lod, minimum: (octant.minimum() << chunk_log2) >> lod, } } // ████████╗███████╗███████╗████████╗ // ╚══██╔══╝██╔════╝██╔════╝╚══██╔══╝ // ██║ █████...
{ let lod = octant.exponent(); let lod_p = octant.minimum() >> lod; let lod_center = centers[lod as usize]; (lod_p - lod_center) // For calculating offsets from the clipmap center, we need to bias any nonnegative components to make voxel coordinates // symmetric about the center. ...
identifier_body
message.go
session.Logger(ctx).Error("ACKNOWLEDGE_MESSAGE_RECEIPT FindDistributedMessageRecipientId", err) return nil } if id == "" { return nil } if time.Since(mc.recipientID[id]) > models.UserActivePeriod { if err := models.PingUserActiveAt(ctx, id); err != nil { session.Logger(ctx).Error("ACKNOWLEDGE_MESSAGE_RE...
(ctx context.Context, mc *MessageContext, transfer TransferView, userId string) error { id, err := bot.UuidFromString(transfer.TraceId) if err != nil { return nil } user, err := models.FindUser(ctx, userId) if user == nil || err != nil { log.Println("No such a user", userId) return err } if inst, err := cr...
handleTransfer
identifier_name
message.go
session.Logger(ctx).Error("ACKNOWLEDGE_MESSAGE_RECEIPT FindDistributedMessageRecipientId", err) return nil } if id == "" { return nil } if time.Since(mc.recipientID[id]) > models.UserActivePeriod { if err := models.PingUserActiveAt(ctx, id); err != nil { session.Logger(ctx).Error("ACKNOWLEDGE_MESSAGE_R...
} if err := models.CreateRewardsMessage(ctx, user, targetUser, transfer.Amount, inst.Param2); err != nil { log.Println("can't create rewards message", err) // return err } } return nil } func handleOrderPayment(ctx context.Context, mc *MessageContext, transfer TransferView, order *models.Order) error {...
random_line_split
message.go
session.Logger(ctx).Error("ACKNOWLEDGE_MESSAGE_RECEIPT FindDistributedMessageRecipientId", err) return nil } if id == "" { return nil } if time.Since(mc.recipientID[id]) > models.UserActivePeriod { if err := models.PingUserActiveAt(ctx, id); err != nil { session.Logger(ctx).Error("ACKNOWLEDGE_MESSAGE_RE...
} if err := bot.CreateTransfer(ctx, in, config.AppConfig.Mixin.ClientId, config.AppConfig.Mixin.SessionId, config.AppConfig.Mixin.SessionKey, config.AppConfig.Mixin.SessionAssetPIN, config.AppConfig.Mixin.PinToken); err != nil { log.Println("can't transfer to recipient", err) return err } if user.UserId != ta...
{ userId := inst.Param1 targetUser, err := models.FindUser(ctx, userId) if err != nil { log.Println("can't find user to reward", userId, err) return nil } memo := "Rewards from " + strconv.FormatInt(user.IdentityNumber, 10) log.Println("Rewards from " + user.FullName + " to " + targetUser.UserId + " with trac...
identifier_body
message.go
nil } user, err := models.FindUser(ctx, userId) if user == nil || err != nil { log.Println("No such a user", userId) return err } if inst, err := crackTransferProtocol(ctx, mc, transfer, user); err == nil && inst.Action != "" { if inst.Action == "rewards" { return handleRewardsPayment(ctx, mc, transfer, ...
{ broadcastChan <- bmsg }
conditional_block
main.go
} } func (e *Editor) debugRowRunes() { if e.debug { i := 0 for i < e.n { _, _ = fmt.Fprintln(os.Stderr, i, ":", e.rows[i].chars.Runes()) i += 1 } } } // Terminal func makeRaw(fd int) *unix.Termios { termios, err := unix.IoctlGetTermios(fd, unix.TIOCGETA) if err != nil { panic(err) } termios.Ifla...
} func (e *Editor) setRowCol(row int, col int) { if row > e.n && col > e.currentRow().visibleLen() { return } e.setRowPos(row) e.setColPos(col) } // Models func (r *Row) deleteAt(col int) { if col >= r.len() { return } r.chars.DeleteAt(col) } func (r *Row) insertAt(colPos int, newRune rune) { if colPos...
} e.ccol = col e.moveCursor(e.crow, e.ccol)
random_line_split
main.go
.write(buf) } } func (e *Editor) flush() { e.write([]byte("\033[2J")) } func (e *Editor) flushRow() { e.write([]byte("\033[2K")) } func (e *Editor) setBgColor(color color) { s := fmt.Sprintf("\033[%dm", color) e.write([]byte(s)) } func (e *Editor) moveCursor(row, col int) { s := fmt.Sprintf("\033[%d;%dH", row...
{ // Treat TAB as 4 spaces. if b == Tab { gt.AppendRune(rune(0x20)) gt.AppendRune(rune(0x20)) gt.AppendRune(rune(0x20)) gt.AppendRune(rune(0x20)) continue } // ASCII-only gt.AppendRune(rune(b)) if b == '\n' { rows[e.n-1] = &Row{chars: gt} e.n += 1 gt = NewGapTable(128) } }
conditional_block
main.go
} } func (e *Editor) debugRowRunes() { if e.debug { i := 0 for i < e.n { _, _ = fmt.Fprintln(os.Stderr, i, ":", e.rows[i].chars.Runes()) i += 1 } } } // Terminal func makeRaw(fd int) *unix.Termios { termios, err := unix.IoctlGetTermios(fd, unix.TIOCGETA) if err != nil { panic(err) } termios.Ifla...
(row, col int) { s := fmt.Sprintf("\033[%d;%dH", row+1, col+1) // 0-origin to 1-origin e.write([]byte(s)) } func (e *Editor) updateRowRunes(row *Row) { if e.crow < e.terminal.height { e.debugPrint("DEBUG: row's view updated at", e.crow + e.scroolrow, "for", row.chars.Runes()) e.writeRow(row) } } func (e *Edit...
moveCursor
identifier_name
main.go
} } func (e *Editor) debugRowRunes() { if e.debug { i := 0 for i < e.n { _, _ = fmt.Fprintln(os.Stderr, i, ":", e.rows[i].chars.Runes()) i += 1 } } } // Terminal func makeRaw(fd int) *unix.Termios { termios, err := unix.IoctlGetTermios(fd, unix.TIOCGETA) if err != nil { panic(err) } termios.Iflag...
func (r *Row) insertAt(colPos int, newRune rune) { if colPos > r.len() { colPos = r.len() } r.chars.InsertAt(colPos, newRune) } func (r *Row) len() int { return r.chars.Len() } func (r *Row) visibleLen() int { return r.chars.VisibleLen() } func (e *Editor) currentRow() *Row { return e.rows[e.crow + e....
{ if col >= r.len() { return } r.chars.DeleteAt(col) }
identifier_body
decoder.go
9\.0-9])*(b|c|d|e|f|g|E|F|G|h|i|l|L|n|o|O|p|q|t|u|x|X)` // assumes no `%%` inside string! // patNextFormatUSpecifier is a regex to find next format u specifier in a string // It does also match %%u positions! //patNextFormatUSpecifier = `(?:%[0-9]*u)` patNextFormatUSpecifier = `%[0-9]*u` // assumes no `%%` inside ...
eplaceN(i
identifier_name
decoder.go
|X|b|p|t)` // assumes no `%%` inside string! // patNextFormatFSpecifier is a regex to find next format f specifier in a string // It does also match %%f positions! patNextFormatFSpecifier = `%[(+\-0-9\.0-9#]*(e|E|f|F|g|G)` // assumes no `%%` inside string! // patNextFormatBoolSpecifier is a regex to find next for...
o = i i = strings.ReplaceAll(i, "%%", "__") // this makes regex easier and faster var offset int for { s := i[offset:] // remove processed part loc := matchNextFormatSpecifier.FindStringIndex(s) if nil == loc { // no (more) fm found return } offset += loc[1] // track position fm := s[loc[0]:loc[1]] ...
identifier_body
decoder.go
O|p|q|u|x|X|n|b))` //patNextFormatSpecifier = `%([+\-#'0-9\.0-9])*(c|d|e|E|f|F|g|G|h|i|l|L|o|O|p|q|u|x|X|n|b|t)` // assumes no `%%` inside string! patNextFormatSpecifier = `%([+\-#'0-9\.0-9])*(b|c|d|e|f|g|E|F|G|h|i|l|L|n|o|O|p|q|t|u|x|X)` // assumes no `%%` inside string! // patNextFormatUSpecifier is a regex to fi...
// SetInput allows switching the input stream to a different source. // // This function is for easier testing with cycle counters. func (p *DecoderData) SetInput(r io.Reader) { p.In = r } // ReadU16 returns the 2 b bytes as uint16 according the specified endianness func (p *DecoderData) ReadU16(b []byte) uint16 { ...
random_line_split
decoder.go
bool // ShowID is used as format string for displaying the first trice ID at the start of each line if not "". ShowID string // decoder.LastTriceID is last decoded ID. It is used for switch -showID. LastTriceID id.TriceID // TestTableMode is a special option for easy decoder test table generation. TestTableMo...
// a %nx, %nX or, %no, %nO or %nb found if Unsigned { u = append(u, 0) // no negative values } else { u = append(u, 1) // also negative values } continue }
conditional_block
pool.rs
1, Ordering::Relaxed); // SAFETY: We cannot permit the reuse of thread IDs since reusing a // thread ID might result in more than one thread "owning" a pool, // and thus, permit accessing a mutable value from multiple threads // simultaneously without synchronization. The intent of this ...
{ PoolGuard { pool: self, value: Some(value) } }
identifier_body
pool.rs
/regex/issues/362 // for example. (Why do I want it to be simple? Well, I suppose what I mean is, // "use as much safe code as possible to minimize risk and be as sure as I can // be that it is correct.") // // My guess is that the thread_local design is probably not appropriate for // regex since its memory usage scal...
<T> { /// A stack of T values to hand out. These are used when a Pool is /// accessed by a thread that didn't create it. stack: Mutex<Vec<Box<T>>>, /// A function to create more T values when stack is empty and a caller /// has requested a T. create: CreateFn<T>, /// The ID of the thread tha...
Pool
identifier_name
pool.rs
-lang/regex/issues/362 // for example. (Why do I want it to be simple? Well, I suppose what I mean is, // "use as much safe code as possible to minimize risk and be as sure as I can // be that it is correct.") // // My guess is that the thread_local design is probably not appropriate for // regex since its memory usage...
/// gets 'owner_val' directly instead of returning a T from 'stack'. /// See comments elsewhere for details, but this is intended to be an /// optimization for the common case that makes getting a T faster. /// /// It is initialized to a value of zero (an impossible thread ID) as a /// sentinel ...
/// The ID of the thread that owns this pool. The owner is the thread /// that makes the first call to 'get'. When the owner calls 'get', it
random_line_split
common.py
rg['rouge-2']['f']:.02f}, RL {rg['rouge-l']['f']:.02f}" DEVICE = None def set_device(device): global DEVICE DEVICE = device if torch.cuda.is_available(): print(torch.cuda.get_device_properties(0)) print('Using', DEVICE) def get_device(): global DEVICE return DEVICE def set_seed(s...
def __call__(self, batch): return ( encode_text_end(self.tokenizer, [txt for txt, title in batch], self.max_len_src), encode_text(self.tokenizer, [title for txt, title in batch], self.max_len_tgt) ) def decode_text(tokenizer, vocab_ids): return tokenizer.decode( ...
self.tokenizer = tokenizer self.max_len_src = max_len_src self.max_len_tgt = max_len_tgt
identifier_body
common.py
rg['rouge-2']['f']:.02f}, RL {rg['rouge-l']['f']:.02f}" DEVICE = None def set_device(device): global DEVICE DEVICE = device if torch.cuda.is_available(): print(torch.cuda.get_device_properties(0)) print('Using', DEVICE) def get_device(): global DEVICE return DEVICE def set_seed(s...
(tokenizer, texts, max_len=None): if isinstance(texts, str): texts = [texts] assert isinstance(texts, list) if max_len is None: max_len = 999999999 enc_texts = [tokenizer.encode( txt, return_tensors='pt', max_length=max_len, truncation=max_len is not None).squeeze(0) for txt in t...
encode_text
identifier_name
common.py
for k1, d in res.items(): for k2 in d: res[k1][k2] /= len(rouges) return res def str_rouge(rg): return f"R1 {rg['rouge-1']['f']:.02f}, R2 {rg['rouge-2']['f']:.02f}, RL {rg['rouge-l']['f']:.02f}" DEVICE = None def set_device(device): global DEVICE DEVICE = device if t...
for k2 in d: res[k1][k2] += item[k1][k2]
conditional_block
common.py
def str_rouge(rg): return f"R1 {rg['rouge-1']['f']:.02f}, R2 {rg['rouge-2']['f']:.02f}, RL {rg['rouge-l']['f']:.02f}" DEVICE = None def set_device(device): global DEVICE DEVICE = device if torch.cuda.is_available(): print(torch.cuda.get_device_properties(0)) print('Using', DEVICE) def ...
random_line_split
manager.py
in your current directory).", "create-tables": "Deletes the currently existing user and content tables and recreates them from DDL.", "import-ratings": "Run an express job to import movie ratings", "import-user-info": "Run an express job to import user inf...
print(actions_str) sys.exit(0) def _setup_parser(self): """ Add actions for the command-line arguments parser """ parser = argparse.ArgumentParser(formatter_class=RawTextHelpFormatter, description="Manage Kiji stuff for MovieAdvisor. Availa...
actions_str += "command: %s\n%s\n\n" % (key, value)
conditional_block
manager.py
class TimeInterval: def __init__(self, start, end): """ TODO: Check times formatting properly here """ self.start = start self.end = end class MovieAdvisorManager: # Put these into a sensible order possible_actions = [ 'help-actions', 'install-bento', 'cr...
print(cmd) try: res = subprocess.check_output(cmd, shell=True).decode('utf-8') except subprocess.CalledProcessError as cpe: print("Error runn command " + cmd) print("Output = " + cpe.output.decode('utf-8')) raise cpe return res
identifier_body
manager.py
in your current directory).", "create-tables": "Deletes the currently existing user and content tables and recreates them from DDL.", "import-ratings": "Run an express job to import movie ratings", "import-user-info": "Run an express job to import user inf...
(self, class_name, options=""): """ Run any express job. Handles a lot of boilerplate for all of the Directv jobs (specifying dates, kiji table, etc. """ cmd = "source {bento_home}/bin/kiji-env.sh; express job {jar} {myclass} --kiji {kiji_uri}" cmd = cmd.format( ...
_run_express_job
identifier_name
manager.py
in your current directory).", "create-tables": "Deletes the currently existing user and content tables and recreates them from DDL.", "import-ratings": "Run an express job to import movie ratings", "import-user-info": "Run an express job to import user inf...
#if not 'install-bento' in self.actions: assert os.path.isdir(opts.bento_home) self.movie_advisor_home = opts.movie_advisor_home self.bento_home = opts.bento_home self.bento_tgz = opts.bento_tgz self.kiji_uri = "kiji://.env/tutorial" # "express job" takes a jar file as ...
# Check that these directories actually exist assert os.path.isdir(opts.movie_advisor_home)
random_line_split
reader_test.go
/4ce3rLNjnbIn1o9L6pzV4CcVJ8+iNhne5vbA+63vRCnrc8QuYwIDAQAB AoGAQKIRELQOsrZsxZowfj/ia9jPUvAmO0apnn2lK/E07k2lbtFMS1H4m1XtGr8F oxQU7rLyyP/FmeJUqJyRXLwsJzma13OpxkQtZmRpL9jEwevnunHYJfceVapQOJ7/ 6Oz0pPWEq39GCn+tTMtgSmkEaSH8Ki9t32g9KuQIKBB2hbECQQDsg7D5fHQB1BXG HJm9JmYYX0Yk6Z2SWBr4mLO0C4hHBnV5qPCLyevInmaCV2cOjDZ5Sz6iF5RK5mw7 qz...
err = aReader.ReadArtifact() assert.NoError(t, err) assert.Len(t, aReader.GetHandlers(), 1) assert.Equal(t, "rootfs-image", aReader.GetHandlers()[0].GetType()) } func TestReadBroken(t *testing.T) { broken := []byte("this is broken artifact") buf := bytes.NewBuffer(broken) aReader := NewReader(buf) err := aRe...
random_line_split
reader_test.go
C kS5yTngwVOmcnT65Vnycygn+tZan2A0h7QJBAJNlowZovDdjgEpeCqXp51irD6Dz gsLwa6agK+Y6Ba0V5mJyma7UoT//D62NYOmdElnXPepwvXdMUQmCtpZbjBsCQD5H VHDJlCV/yzyiJz9+tZ5giaAkO9NOoUBsy6GvdfXWn2prXmiPI0GrrpSvp7Gj1Tjk r3rtT0ysHWd7l+Kx/SUCQGlitd5RDfdHl+gKrCwhNnRG7FzRLv5YOQV81+kh7SkU 73TXPIqLESVrqWKDfLwfsfEpV248MSRou+y0O1mtFpo= -----END RSA ...
{ return nil }
identifier_body
reader_test.go
PAkEA46Anom3cNXO5pjfDmn2CoqUvMeyrJUFL5aU6W1S6iFprZ/YwdHcC kS5yTngwVOmcnT65Vnycygn+tZan2A0h7QJBAJNlowZovDdjgEpeCqXp51irD6Dz gsLwa6agK+Y6Ba0V5mJyma7UoT//D62NYOmdElnXPepwvXdMUQmCtpZbjBsCQD5H VHDJlCV/yzyiJz9+tZ5giaAkO9NOoUBsy6GvdfXWn2prXmiPI0GrrpSvp7Gj1Tjk r3rtT0ysHWd7l+Kx/SUCQGlitd5RDfdHl+gKrCwhNnRG7FzRLv5YOQV81+kh7SkU 73...
GetType
identifier_name
reader_test.go
4ce3rLNjnbIn1o9L6pzV4CcVJ8+iNhne5vbA+63vRCnrc8QuYwIDAQAB AoGAQKIRELQOsrZsxZowfj/ia9jPUvAmO0apnn2lK/E07k2lbtFMS1H4m1XtGr8F oxQU7rLyyP/FmeJUqJyRXLwsJzma13OpxkQtZmRpL9jEwevnunHYJfceVapQOJ7/ 6Oz0pPWEq39GCn+tTMtgSmkEaSH8Ki9t32g9KuQIKBB2hbECQQDsg7D5fHQB1BXG HJm9JmYYX0Yk6Z2SWBr4mLO0C4hHBnV5qPCLyevInmaCV2cOjDZ5Sz6iF5RK5mw7 qzv...
assert.NoError(t, err) assert.Equal(t, TestUpdateFileContent, updFileContent.String()) devComp := aReader.GetCompatibleDevices() assert.Len(t, devComp, 1) assert.Equal(t, "vexpress", devComp[0]) if test.handler != nil { assert.Len(t, aReader.GetHandlers(), 1) assert.Equal(t, test.handler.GetType(),...
{ assert.Equal(t, test.readError.Error(), err.Error()) continue }
conditional_block
analysisPlots_TWZ_nLep.py
Level, logFile = None) if args.small: args.plot_directory += "_small" if args.noData: args.plot_directory += "_noData" if args.normalize: args.plot_directory += "_normalize" # # Make samples, will be searched for in the postProcessing directory # if args.year == 2016: ...
stack = Stack(mc)
conditional_block
analysisPlots_TWZ_nLep.py
# quadlep-lepSelQuad-njet2p-btag0p-onZ1-offZ2 or quadlep-lepSelQuad-njet2p-btag1p-onZ1-offZ2 for signal regions argParser.add_argument('--normalize', action='store_true', default=False, help="Normalize yields" ) argParser.add_argument('--year', action='store', default=2016, ...
( plotData, dataMCScale, lumi_scale ): tex = ROOT.TLatex() tex.SetNDC() tex.SetTextSize(0.04) tex.SetTextAlign(11) # align right lines = [ (0.15, 0.95, 'CMS Preliminary' if plotData else 'CMS Simulation'), (0.45, 0.95, 'L=%3.1f fb{}^{-1} (13 TeV) Scale %3.2f'% ( lumi_scale, dataMCScale ...
drawObjects
identifier_name
analysisPlots_TWZ_nLep.py
# quadlep-lepSelQuad-njet2p-btag0p-onZ1-offZ2 or quadlep-lepSelQuad-njet2p-btag1p-onZ1-offZ2 for signal regions argParser.add_argument('--normalize', action='store_true', default=False, help="Normalize yields" ) argParser.add_argument('--year', action='store', default=2016, ...
sequence.append( getLooseLeptonMult ) # # Loop over channels # yields = {} allPlots = {} allModes = ['nLep'] for index, mode in enumerate(allModes): yields[mode] = {} logger.info("Working on mode %s", mode) if not args.noData: data_sample = Run2016 if args.year == 2016 else Run2017 ...
leptons = [getObjDict(event, 'lep_', ['eta','pt','phi','charge', 'pdgId', 'sourceId','mediumMuonId'], i) for i in range(len(event.lep_pt))] lepLoose = [ l for l in leptons if l['pt'] > 10 and ((l['mediumMuonId'] and abs(l['pdgId'])==13) or abs(l['pdgId'])==11) ] event.nLepLoose = len(lepLoose)
identifier_body
analysisPlots_TWZ_nLep.py
ightingFunction from TopEFT.samples.helpers import fromHeppySample # # Logger # import TopEFT.Tools.logger as logger import RootTools.core.logger as logger_rt logger = logger.get_logger( args.logLevel, logFile = None) logger_rt = logger_rt.get_logger(args.logLevel, logFile = None) if args.small: ...
# sample.weight = lambda event, sample: event.reweightBTagDeepCSV_SF*event.reweightTrigger_tight_4l*event.reweightPU36fb*event.reweightLeptonSF_tight_4l #*event.reweightLeptonSF_tight_4l #*nTrueInt36fb_puRW(event.nTrueInt) # tr = triggerSelector(args.year)
random_line_split
main.go
LoadByte(addr uint32) uint8 { return cpu.memory.LoadByte(addr) } func (cpu *Cpu) StoreWord(addr uint32, v uint32) { cpu.memory.StoreWord(addr, v) } func (cpu *Cpu) StoreHalfWord(addr uint32, v uint16) { cpu.memory.StoreHalfWord(addr, v) } func (cpu *Cpu) StoreByte(addr uint32, v uint8) { cpu.memory.StoreByte(addr,...
trap(ExceptionIllegalInstruction, inst) break decode } cpu.SetReg(rd, res)
random_line_split
main.go
) { s.StoreByte(addr, uint8(v)) } func (s *MmioSerial) StoreByte(addr uint32, v uint8) { if s.w == nil { return } b := []uint8{v} s.w.Write(b) } type Cpu struct { initialAddr uint32 registers [32]uint32 pc uint32 memory Memory halt bool cycles uint64 ticks uint64 instr...
{ res = rs1v + rs2v }
conditional_block
main.go
8x ", _RegNames[i], cpu.GetReg(i)) } res += fmt.Sprintf("pc: 0x%08x ", cpu.pc) return res } func (cpu *Cpu) fetch() uint32 { inst := cpu.LoadWord(cpu.pc) cpu.pc += 4 return inst } func (cpu *Cpu) decode(inst uint32) { // we are only allowed to trap in the decode phase // this makes it so the trap function is...
btype
identifier_name
main.go
binary.LittleEndian.Uint16(mem.memory[addr : addr+2]) } func (mem *Ram) LoadByte(addr uint32) uint8 { return mem.memory[addr] } func (mem *Ram) StoreWord(addr uint32, v uint32) { binary.LittleEndian.PutUint32(mem.memory[addr:addr+4], v) } func (mem *Ram) StoreHalfWord(addr uint32, v uint16) { binary.LittleEndian...
// we only have machine mode csrs for everything else if priv != CsrM { panic(fmt.Sprintf("invalid csr: 0x%03x\n", csr)) } switch csr { case CsrTvec: return cpu.mtvec & 0xfffffffc case CsrTval: return cpu.mtval case CsrCause: return cpu.mcause case CsrEpc: return cpu.mepc & 0xfffffffe case CsrScrat...
{ if csr == CsrHalt { return cpu.haltValue } priv := csr & ^uint32(0xcff) // save priv csr &= 0xcff // ignore priv switch csr { case CsrCycle: return uint32(cpu.cycles) case CsrCycleh: return uint32(cpu.cycles >> 32) case CsrTime: return uint32(cpu.ticks) case CsrTimeh: return uint32(...
identifier_body
storer.go
store.NewTxChunkStore(txStore, sharky) if err := txChunkStore.Recover(); err != nil { return nil, nil, fmt.Errorf("failed to recover chunk store: %w", err) } return storage.NewRepository(txStore, txChunkStore, locker), closer(store, sharky, recoveryCloser), nil } func initCache(ctx context.Context, capacity uint...
{ db.logger.Warning("db shutting down with running goroutines") }
conditional_block
storer.go
indexes which // will keep track of the chunk in the cache.
Cache() storage.Putter } // NetStore is a logical component of the storer that deals with network. It will // push/retrieve chunks from the network. type NetStore interface { // DirectUpload provides a session which can be used to push chunks directly // to the network. DirectUpload() PutterSession // Download pr...
random_line_split
storer.go
, error) ReserveHas(addr swarm.Address, batchID []byte) (bool, error) ReservePutter() storage.Putter SubscribeBin(ctx context.Context, bin uint8, start uint64) (<-chan *BinC, func(), <-chan error) ReserveLastBinIDs() ([]uint64, error) RadiusChecker } // RadiusChecker provides the radius related functionality. typ...
SetStorageRadius
identifier_name
storer.go
Store, txChunkStore, locker), closer(store, sharky, recoveryCloser), nil } func initCache(ctx context.Context, capacity uint64, repo storage.Repository) (*cache.Cache, error) { ctx, cancel := context.WithCancel(ctx) defer cancel() txnRepo, commit, rollback := repo.NewTx(ctx) c, err := cache.New(ctx, txnRepo, capa...
{ close(db.quit) bgReserveWorkersClosed := make(chan struct{}) go func() { defer close(bgReserveWorkersClosed) if c := db.inFlight.Wait(5 * time.Second); c > 0 { db.logger.Warning("db shutting down with running goroutines") } }() bgCacheWorkersClosed := make(chan struct{}) go func() { defer close(bgC...
identifier_body
userrole.go
func (m *UserRoleMod) AllowedTypes() base.MessageType { return m.allowedTypes } func (m *UserRoleMod) AllowDMs() bool { return m.allowDMs } func (m *UserRoleMod) Hook() error { m.bot.Discord.Sess.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) { refreshTicker := time.NewTicker(time.Hour) go func() { ...
} func (m *UserRoleMod) Commands() map[string]*base.ModCommand { return m.commands }
random_line_split
userrole.go
iscord.Sess.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) { refreshTicker := time.NewTicker(time.Hour) go func() { for range refreshTicker.C { for _, g := range m.bot.Discord.Guilds() { if g.Unavailable { continue } var userRoles []*database.UserRole err := m.db.Get(&...
func (m *UserRoleMod) setuserroleCommand(msg *base.DiscordMessage) { if msg.LenArgs() < 3 { return } targetMember, err := msg.GetMemberAtArg(1) if err != nil { msg.Reply("could not find that user") return } if targetMember.User.Bot { msg.Reply("Bots dont get to join the fun") return } g, err := m...
{ return &base.ModCommand{ Mod: m, Name: "setuserrole", Description: "Binds, unbinds or changes a userrole bind to a user", Triggers: []string{"m?setuserrole"}, Usage: "m?setuserrole 1231231231231 cool role", Cooldown: 3, RequiredPerms: discordgo.PermissionManageRol...
identifier_body
userrole.go
() bool { return m.allowDMs } func (m *UserRoleMod) Hook() error { m.bot.Discord.Sess.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) { refreshTicker := time.NewTicker(time.Hour) go func() { for range refreshTicker.C { for _, g := range m.bot.Discord.Guilds() { if g.Unavailable { cont...
AllowDMs
identifier_name
userrole.go
iscord.Sess.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) { refreshTicker := time.NewTicker(time.Hour) go func() { for range refreshTicker.C { for _, g := range m.bot.Discord.Guilds() { if g.Unavailable { continue } var userRoles []*database.UserRole err := m.db.Get(&...
else if msg.Args()[1] == "color" { clr := msg.Args()[2] if strings.HasPrefix(clr, "#") { clr = clr[1:] } color, err := strconv.ParseInt(clr, 16, 64) if err != nil || color < 0 || color > 0xFFFFFF { msg.ReplyEmbed(&discordgo.MessageEmbed{Description: "Invalid color code.", Color: utils.ColorCrit...
{ newName := strings.Join(msg.RawArgs()[2:], " ") _, err = msg.Discord.Sess.GuildRoleEdit(g.ID, oldRole.ID, newName, oldRole.Color, oldRole.Hoist, oldRole.Permissions, oldRole.Mentionable) if err != nil { if strings.Contains(err.Error(), strconv.Itoa(discordgo.ErrCodeMissingPermissions)) { msg.ReplyE...
conditional_block
threejs_adapter.js
this.getDependencies(node.mulwapp_create_spec), 'props' : {}, 'children' : {} }; if (node instanceof THREE.Object3D) { var conf = this.config.shareConf(node, undefined, root); // Return if this object is not to be synchronized if (!conf) return; // If called b...
F.prototype = THREE[spec.type].prototype; // Parse argument list var args = []; spec.args.forEach(function (e) { if (e.primitive) args.push(e.value); else args.push(this.lookupNodeByGuid(e.value)); }, this); // Create object var o = new F(args); o.mulwapp_guid = spec.mulwapp_guid; this.allL...
{ this._mulwapp_remote_create = true; this.mulwapp_create_spec = spec; return THREE[spec.type].apply(this, args); }
identifier_body
threejs_adapter.js
}).call(this, root, undefined); return doc; } /** * Intercepts constructor calls to create a create specification before * creating the object. * @param {Mulwapp} mulwapp - A reference to a Mulwapp object * @param {Array} constructors - A list of constructors to intercept */ ThreeAdapter.prototype.setupConst...
// "HemisphereLight", "PointLight", // "SpotLight", // "Cache", // "Loader",
random_line_split
threejs_adapter.js
this.getDependencies(node.mulwapp_create_spec), 'props' : {}, 'children' : {} }; if (node instanceof THREE.Object3D) { var conf = this.config.shareConf(node, undefined, root); // Return if this object is not to be synchronized if (!conf) return; // If called b...
(args) { this._mulwapp_remote_create = true; this.mulwapp_create_spec = spec; return THREE[spec.type].apply(this, args); } F.prototype = THREE[spec.type].prototype; // Parse argument list var args = []; spec.args.forEach(function (e) { if (e.primitive) args.push(e.value); else args.push(t...
F
identifier_name
main.py
IMPLIED WARRANTIES, INCLUDING, BUT NOT #LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BU...
def activateRefreshButton(self): """ Activates the refresh button. """ self.refreshButton.show() def deactivateRefreshButton(self): """ De-activates the refresh button. """ self.refreshButton.hide() model = property(_getModel, _se...
""" Getter of the property model. """ return self._model
identifier_body
main.py
WARRANTIES, INCLUDING, BUT NOT #LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ...
(self, propertyTypes, model, parent=None): """ Constructor. @param propertyTypes: Property types available for this property @type propertyTypes: C{list} of C{unicode} @param parent: Parent object of the delegate. @type parent: L{QWidget<PyQt4.QtGui.QWidget>} ...
__init__
identifier_name
main.py
WARRANTIES, INCLUDING, BUT NOT #LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ...
and has to handle the conversion of the editor input to a proper model format. """ def __init__(self, propertyTypes, model, parent=None): """ Constructor. @param propertyTypes: Property types available for this property @type propertyTypes: C{list} of C{unicode} ...
This item delegate has to choose the right editor for the expected property type
random_line_split
main.py
WARRANTIES, INCLUDING, BUT NOT #LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR #A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT #OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, #SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ...
def _refreshClickedSlot(self): """ Slot is called when the refresh button is used. """ if self._model.dirty: button = QtGui.QMessageBox.information(self, self.tr("Refresh information"), self.tr("All changes will be lost after t...
if index.isValid(): self._model.revert(index)
conditional_block
local.go
.Wrap(err, "adding base layer to image") } return nil } func (i *Image) Label(key string) (string, error) { labels := i.inspect.Config.Labels return labels[key], nil } func (i *Image) Labels() (map[string]string, error) { copiedLabels := make(map[string]string) for i, l := range i.inspect.Config.Labels { cop...
func (i *Image) Identifier() (imgutil.Identifier, error) { return IDIdentifier{ ImageID: strings.TrimPrefix(i.inspect.ID, "sha256:"), }, nil } func (i *Image) CreatedAt() (time.Time, error) { createdAtTime := i.inspect.Created createdTime, err := time.Parse(time.RFC3339Nano, createdAtTime) if err != nil { ...
{ return i.inspect.ID != "" }
identifier_body
local.go
} return os.Open(i.layerPaths[l]) } return nil, fmt.Errorf("image %q does not contain layer with diff ID %q", i.repoName, diffID) } func (i *Image) AddLayer(path string) error { f, err := os.Open(filepath.Clean(path)) if err != nil { return errors.Wrapf(err, "AddLayer: open layer: %s", path) } defer f.Clo...
{ return errors.New("failed to download all base layers from daemon") }
conditional_block
local.go
(defaultPlatform imgutil.Platform, optionPlatform imgutil.Platform) error { if optionPlatform.OS != "" && optionPlatform.OS != defaultPlatform.OS { return fmt.Errorf("invalid os: platform os %q must match the daemon os %q", optionPlatform.OS, defaultPlatform.OS) } return nil } func processPreviousImageOption(ima...
validatePlatformOption
identifier_name
local.go
errors.Wrap(err, "adding base layer to image") } return nil } func (i *Image) Label(key string) (string, error) { labels := i.inspect.Config.Labels return labels[key], nil } func (i *Image) Labels() (map[string]string, error) { copiedLabels := make(map[string]string) for i, l := range i.inspect.Config.Labels ...
ignoreCase := i.inspect.Os == "windows" for idx, kv := range i.inspect.Config.Env { parts := strings.SplitN(kv, "=", 2) foundKey := parts[0] searchKey := key if ignoreCase { foundKey = strings.ToUpper(foundKey) searchKey = strings.ToUpper(searchKey) } if foundKey == searchKey { i.inspect.Config.E...
delete(i.inspect.Config.Labels, key) return nil } func (i *Image) SetEnv(key, val string) error {
random_line_split
_profile.py
if not self._converted: if self._parent is None: return "/" return f"{self._name} ({self._level})" else: context = self._code_context return f"sum {1000 * self._duration:.2f} ms {context}" def __len__(self): return len(self._children...
(self): parent = self._parent while parent._parent is not None: if len(parent._children) > 1: return parent parent = parent._parent return parent def _calling_code(self, backtrack=0): if self._level > backtrack + 1: call: ExtCall =...
_closest_non_trivial_parent
identifier_name
_profile.py
if not self._converted: if self._parent is None: return "/" return f"{self._name} ({self._level})" else: context = self._code_context return f"sum {1000 * self._duration:.2f} ms {context}" def __len__(self): return len(self._c...
self._total_trace_time = 0 def _add_call(self, backend_call: BackendCall, args: tuple, kwargs: dict, result): if self._retime_index >= 0: prev_call = self._backend_calls[self._retime_index] assert prev_call._function_name == backend_call._function_name if self._a...
""" Stores information about calls to backends and their timing. Profile may be created through `profile()` or `profile_function()`. Profiles can be printed or saved to disc. """ def __init__(self, trace: bool, backends: tuple or list, subtract_trace_time: bool): self._start = perf_counte...
identifier_body
_profile.py
if not self._converted: if self._parent is None: return "/" return f"{self._name} ({self._level})" else: context = self._code_context return f"sum {1000 * self._duration:.2f} ms {context}" def __len__(self): return len(self._c...
self._stop = perf_counter() self._children_to_properties() @property def duration(self) -> float: """ Total time passed from creation of the profile to the end of the last operation. """ return self._stop - self._start if self._stop is not None else None def print(self, min...
random_line_split
_profile.py
if not self._converted: if self._parent is None: return "/" return f"{self._name} ({self._level})" else: context = self._code_context return f"sum {1000 * self._duration:.2f} ms {context}" def __len__(self): return len(self._children...
if self._trace: stack = inspect.stack()[2:] call = self._last_ext_call.common_call(stack) for i in range(call._level, len(stack)): stack_frame = stack[len(stack) - i - 1] name = ExtCall.determine_name(stack_frame) # if...
backend_call.add_arg("Outputs", _format_values({0: result}, backend_call._backend))
conditional_block
wps.go
type ByteBuilder struct { // object: func (self TYPE) from_ary(ary interface{}){ return ary[0] func (self TYPE) to_ary(value interface{}){ return array.array('B', [value]) type StringBuilder struct { // object: func (self TYPE) from_ary(ary interface{}){ return ary.to...
return ary func (self TYPE) to_ary(value interface{}){ return array.array("B", value)
random_line_split
vmctx.rs
the instance and its `Alloc`. globals_view: RefCell<Box<[GlobalValue]>>, } impl Drop for Vmctx { fn drop(&mut self) { let heap_view = self.heap_view.replace(Box::new([])); let globals_view = self.globals_view.replace(Box::new([])); // as described in the definition of `Vmctx`, we canno...
/// Return the underlying `vmctx` pointer. pub fn as_raw(&self) -> *mut lucet_vmctx { self.vmctx } /// Return the WebAssembly heap as a slice of bytes. /// /// If the heap is already mutably borrowed by `heap_mut()`, the instance will /// terminate with `TerminationDetails::Borrow...
{ let inst = instance_from_vmctx(vmctx); assert!(inst.valid_magic()); let res = Vmctx { vmctx, heap_view: RefCell::new(Box::<[u8]>::from_raw(inst.heap_mut())), globals_view: RefCell::new(Box::<[GlobalValue]>::from_raw(inst.globals_mut())), }; ...
identifier_body
vmctx.rs
self .heap_view .try_borrow_mut() .unwrap_or_else(|_| panic!(TerminationDetails::BorrowError("heap_mut"))); RefMut::map(r, |b| b.borrow_mut()) } /// Check whether the heap has grown, and replace the heap view if it has. /// /// This handles the case where `V...
HOST_CTX.with(|host_ctx| unsafe { Context::set(&*host_ctx.get()) }) }
random_line_split
vmctx.rs
the instance and its `Alloc`. globals_view: RefCell<Box<[GlobalValue]>>, } impl Drop for Vmctx { fn drop(&mut self) { let heap_view = self.heap_view.replace(Box::new([])); let globals_view = self.globals_view.replace(Box::new([])); // as described in the definition of `Vmctx`, we canno...
(&self) -> RefMut<'_, [GlobalValue]> { let r = self .globals_view .try_borrow_mut() .unwrap_or_else(|_| panic!(TerminationDetails::BorrowError("globals_mut"))); RefMut::map(r, |b| b.borrow_mut()) } /// Get a function pointer by WebAssembly table and function ...
globals_mut
identifier_name
tombfix.js
FileProtocolHandler = getService( 'network/protocol;1?name=file', Ci.nsIFileProtocolHandler ), {nsILocalFile: ILocalFile} = Ci; const SCRIPT_FILES = [ // library/third_party 'MochiKit.js', 'twitter-text.js', // library 'component.js', 'expand.js', 'uti...
function getService(clsName, ifc) { try { let cls = Cc['@mozilla.org/' + clsName]; return cls ? (ifc ? cls.getService(ifc) : cls.getService()) : null; } catch (err) { return null; } } function loadAllSubScripts() { /* jshint validthis:true */ // libraryの読み込み loadSubScr...
function log(msg) { console[typeof msg === 'object' ? 'dir' : 'log'](msg); } /* jshint ignore:end */
random_line_split
tombfix.js
FileProtocolHandler = getService( 'network/protocol;1?name=file', Ci.nsIFileProtocolHandler ), {nsILocalFile: ILocalFile} = Ci; const SCRIPT_FILES = [ // library/third_party 'MochiKit.js', 'twitter-text.js', // library 'component.js', 'expand.js', 'uti...
ts')) { // パッチの読み込み loadSubScripts(getScriptFiles(this.getPatchDir()), this); } } function loadSubScripts(files, global = function () {}) { var now = Date.now(); for (let file of files) { // クエリを付加しキャッシュを避ける ScriptLoader.loadSubScript( FileProtocolHandler.getURLSpecFrom...
('disableAllScrip
identifier_name
tombfix.js
FileProtocolHandler = getService( 'network/protocol;1?name=file', Ci.nsIFileProtocolHandler ), {nsILocalFile: ILocalFile} = Ci; const SCRIPT_FILES = [ // library/third_party 'MochiKit.js', 'twitter-text.js', // library 'component.js', 'expand.js', 'uti...
ls ? (ifc ? cls.getService(ifc) : cls.getService()) : null; } catch (err) { return null; } } function loadAllSubScripts() { /* jshint validthis:true */ // libraryの読み込み loadSubScripts(getLibraries(), this); if (!this.getPref('disableAllScripts')) { // パッチの読み込み loadSubScrip...
{ let cls = Cc['@mozilla.org/' + clsName]; return c
identifier_body
tombfix.js
FileProtocolHandler = getService( 'network/protocol;1?name=file', Ci.nsIFileProtocolHandler ), {nsILocalFile: ILocalFile} = Ci; const SCRIPT_FILES = [ // library/third_party 'MochiKit.js', 'twitter-text.js', // library 'component.js', 'expand.js', 'uti...
}); return scripts; } function getLibraries() { var libDir, thirdPartyDir, scripts; libDir = getContentDir(); libDir.append('library'); thirdPartyDir = getContentDir(); thirdPartyDir.setRelativeDescriptor(thirdPartyDir, 'library'); thirdPartyDir.append('third_party'); scrip...
{ scripts.push(file); }
conditional_block
game.py
. import pygame import os import sys # Local imports. import components import drawing import ecs import input_handling import physics import resource import systems import utils class SpaceGameServices(ecs.GameServices): """ The services exposed to the entities. This is separate from the game class itself t...
def get_renderer(self): return self.game.renderer def get_entity_manager(self): """ Return the entity manager. """ return self.game.entity_manager def get_resource_loader(self): """ Get the resource loader. """ return self.game.resource_loader def get_info(se...
self.game = game self.info = ecs.GameInfo() self.debug_level = 0
identifier_body
game.py
. import pygame import os import sys # Local imports. import components import drawing import ecs import input_handling import physics import resource import systems import utils class SpaceGameServices(ecs.GameServices): """ The services exposed to the entities. This is separate from the game class itself t...
# Input for e in pygame.event.get(): response = self.input_handling.handle_input(e) if response.quit_requested: self.running = False # Update the systems. self.entity_manager.update(tick_time) # Draw ...
self.entity_manager.unpause() self.want_pause = True self.want_step = False
conditional_block
game.py
. import pygame import os import sys # Local imports. import components import drawing import ecs import input_handling import physics import resource import systems import utils class SpaceGameServices(ecs.GameServices): """ The services exposed to the entities. This is separate from the game class itself t...
limited_fps = 1.0/(clock.get_time() / 1000.0) raw_fps = 1.0/(clock.get_rawtime() / 1000.0) time_ratio = (1.0/fps) / (clock.get_time()/1000.0) self.game_services.info.update_framerate(limited_fps, raw_fps, ...
# Maintain frame rate. clock.tick(fps) # Remember how long the frame took.
random_line_split
game.py
. import pygame import os import sys # Local imports. import components import drawing import ecs import input_handling import physics import resource import systems import utils class SpaceGameServices(ecs.GameServices): """ The services exposed to the entities. This is separate from the game class itself t...
(self): """ Return the entity manager. """ return self.game.entity_manager def get_resource_loader(self): """ Get the resource loader. """ return self.game.resource_loader def get_info(self): """ Return the information. """ return self.info def end_game(sel...
get_entity_manager
identifier_name
hwdetect.rs
crate::common::format::human_size; use crate::common::parser::{consume_all, p_u32, NomResult}; pub fn detect_cpus() -> anyhow::Result<ResourceDescriptorKind> { read_linux_numa() .map(|numa_nodes| { let filtered = filter_masked_cpus(numa_nodes.clone()); if filtered.iter().flatten()....
} } } gpus } /// Try to find out how many Nvidia GPUs are available on the current node. fn read_nvidia_linux_gpu_count() -> anyhow::Result<usize> { Ok(std::fs::read_dir("/proc/driver/nvidia/gpus")?.count()) } /// Try to get total memory on the current node. fn read_linux_memory() -> ...
{ if let Ok(devices) = parse_comma_separated_values(&devices_str) { log::info!( "Detected GPUs {} from `{}`", format_comma_delimited(&devices), gpu_env.env_var, ); if !has_unique_elements(&devices) {...
conditional_block
hwdetect.rs
crate::common::format::human_size; use crate::common::parser::{consume_all, p_u32, NomResult}; pub fn detect_cpus() -> anyhow::Result<ResourceDescriptorKind> { read_linux_numa() .map(|numa_nodes| { let filtered = filter_masked_cpus(numa_nodes.clone()); if filtered.iter().flatten()....
gpu_families.insert(gpu.family); items.push(ResourceDescriptorItem { name: gpu.resource_name.to_string(), kind: gpu.resource, }); } } } if !has_resource(items, MEM_RESOURCE_NAME) { if let Ok(mem)...
{ let mut gpu_families = Set::new(); let has_resource = |items: &[ResourceDescriptorItem], name: &str| items.iter().any(|x| x.name == name); let detected_gpus = detect_gpus_from_env(); if detected_gpus.is_empty() && !has_resource(items, NVIDIA_GPU_RESOURCE_NAME) { if let Ok(count) = rea...
identifier_body
hwdetect.rs
use nom::sequence::{preceded, terminated, tuple}; use nom::Parser; use nom_supreme::tag::complete::tag; use tako::hwstats::GpuFamily; use tako::internal::has_unique_elements; use tako::resources::{ ResourceDescriptorItem, ResourceDescriptorKind, ResourceIndex, ResourceLabel, AMD_GPU_RESOURCE_NAME, MEM_RESOURCE...
use anyhow::anyhow; use nom::character::complete::{newline, satisfy, space0}; use nom::combinator::{map, map_res, opt}; use nom::multi::{many1, separated_list1};
random_line_split
hwdetect.rs
crate::common::format::human_size; use crate::common::parser::{consume_all, p_u32, NomResult}; pub fn detect_cpus() -> anyhow::Result<ResourceDescriptorKind> { read_linux_numa() .map(|numa_nodes| { let filtered = filter_masked_cpus(numa_nodes.clone()); if filtered.iter().flatten()....
() -> anyhow::Result<u64> { Ok(psutil::memory::virtual_memory()?.total()) } /// Try to find the CPU NUMA configuration. /// /// Returns a list of NUMA nodes, each node contains a list of assigned CPUs. fn read_linux_numa() -> anyhow::Result<Vec<Vec<ResourceIndex>>> { let nodes = parse_range(&std::fs::read_to_s...
read_linux_memory
identifier_name
server.rs
. anti_replay: AntiReplay, /// A function for determining if 0-RTT can be accepted. zero_rtt_checker: ServerZeroRttChecker, /// A connection ID generator. cid_generator: Rc<RefCell<dyn ConnectionIdGenerator>>, /// Connection parameters. conn_params: ConnectionParameters, /// Active conne...
} if c.borrow().has_events() { qtrace!([self], "Connection active: {:?}", c); self.active.insert(ActiveConnectionRef { c: Rc::clone(&c) }); } if *c.borrow().state() > State::Handshaking { // Remove any active connection attempt now that this is no lo...
{ self.remove_timer(&c); }
conditional_block
server.rs
/// as this depends on there being some distribution of events. const TIMER_GRANULARITY: Duration = Duration::from_millis(4); /// The number of buckets in the timer. As mentioned in the definition of `Timer`, /// the granularity and capacity need to multiply to be larger than the largest /// delay that might be used. ...
const MIN_INITIAL_PACKET_SIZE: usize = 1200; /// The size of timer buckets. This is higher than the actual timer granularity
random_line_split
server.rs
} impl DerefMut for ServerConnectionState { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.c } } /// A `AttemptKey` is used to disambiguate connection attempts. /// Multiple connection attempts with the same key won't produce multiple connections. #[derive(Clone, Debug, Hash, PartialEq, Eq)...
{ &self.c }
identifier_body
server.rs
{ // Using the remote address is sufficient for disambiguation, // until we support multiple local socket addresses. remote_address: SocketAddr, odcid: ConnectionId, } /// A `ServerZeroRttChecker` is a simple wrapper around a single checker. /// It uses `RefCell` so that the wrapped checker can be sha...
AttemptKey
identifier_name
replay.py
0 then the algorithm works in the inverse manner as described in the paper. You should imagine the buffer manager as a mid-aged fat man that believes his role is key in the success of the company, even though many people think they could do without him.""" self.capacity = initial_capacity ...
self.container = RankBased(max_capacity) else: raise ValueError("Bad replay method") def memory_full(self):
random_line_split
replay.py
then the algorithm works in the inverse manner as described in the paper. You should imagine the buffer manager as a mid-aged fat man that believes his role is key in the success of the company, even though many people think they could do without him.""" self.capacity = initial_capacity ...
(self, idx, error): self.data[idx] = (error, *self.data[idx][1:]) def get_batch(self, n): self._update_priorities() self.total = np.sum(self.priorities) self.cum_sum = np.cumsum(self.priorities) batch = [] priorities = [] # sample hole batch indicies is fas...
update
identifier_name
replay.py
then the algorithm works in the inverse manner as described in the paper. You should imagine the buffer manager as a mid-aged fat man that believes his role is key in the success of the company, even though many people think they could do without him.""" self.capacity = initial_capacity ...
return batch, batch_idx, priorities def get_len(self): return len(self.data) def _update_priorities(self): # order is inverse of actual position in heap order = np.array(range(self.get_len() + 1, 1, -1)) self.priorities = 1. / order class PrioritizedReplayMemory: ...
batch.append(self.data[idx][2:]) priorities.append(self.priorities[idx])
conditional_block
replay.py
.capacity = initial_capacity self.k = size_change self.td_error = 0 def update_td_error(self, new_td_error): self.td_error = abs(new_td_error) def update_memory_size(self, new_td_error): new_td_error = abs(new_td_error) # update = -1 if new_td_error < self.td_error, th...
def __init__(self, max_capacity, method="prop"): if method == "prop": self.container = SumTree(max_capacity) elif method == "rank": self.container = RankBased(max_capacity) else: raise ValueError("Bad replay method") def memory_full(self): return ...
identifier_body
jupyterExporter.ts
upyterlab/coreutils'; import { inject, injectable } from 'inversify'; import * as os from 'os'; import * as path from 'path'; import * as uuid from 'uuid/v4'; import { Uri } from 'vscode'; import { concatMultilineStringInput } from '../../../datascience-ui/common'; import { createCodeCell } from '../../../datascience-...
( @inject(IJupyterExecution) private jupyterExecution: IJupyterExecution, @inject(IWorkspaceService) private workspaceService: IWorkspaceService, @inject(IConfigurationService) private configService: IConfigurationService, @inject(IFileSystem) private fileSystem: IFileSystem, @in...
constructor
identifier_name
jupyterExporter.ts
upyterlab/coreutils'; import { inject, injectable } from 'inversify'; import * as os from 'os'; import * as path from 'path'; import * as uuid from 'uuid/v4'; import { Uri } from 'vscode'; import { concatMultilineStringInput } from '../../../datascience-ui/common'; import { createCodeCell } from '../../../datascience-...
else { const array = source .toString() .split('\n') .map((s) => `${s}\n`); if (array.length > 0 && cellMatcher.isCell(array[0])) {
{ if (cellMatcher.isCell(source[0])) { return source.slice(1); } }
conditional_block
jupyterExporter.ts
upyterlab/coreutils'; import { inject, injectable } from 'inversify'; import * as os from 'os'; import * as path from 'path'; import * as uuid from 'uuid/v4'; import { Uri } from 'vscode'; import { concatMultilineStringInput } from '../../../datascience-ui/common'; import { createCodeCell } from '../../../datascience-...
if (this.workspaceService.hasWorkspaceFolders) { const workspacePath = await this.firstWorkspaceFolder(cells); // Make sure that we have everything that we need here if ( workspacePath && path.isAbsolute(workspacePath) ...
const notebookFilePath = path.dirname(notebookFile); // First see if we have a workspace open, this only works if we have a workspace root to be relative to
random_line_split
jupyterExporter.ts
upyterlab/coreutils'; import { inject, injectable } from 'inversify'; import * as os from 'os'; import * as path from 'path'; import * as uuid from 'uuid/v4'; import { Uri } from 'vscode'; import { concatMultilineStringInput } from '../../../datascience-ui/common'; import { createCodeCell } from '../../../datascience-...
version: pythonNumber }, orig_nbformat: 2 }; // Create an object for matching cell definitions const matcher = new CellMatcher(this.configService.getSettings().datascience); // Combine this into a JSON object return { cells: t...
{ // If requested, add in a change directory cell to fix relative paths if (changeDirectory && this.configService.getSettings().datascience.changeDirOnImportExport) { cells = await this.addDirectoryChangeCell(cells, changeDirectory); } const pythonNumber = await this.extract...
identifier_body
routex.go
err = ctx.Render(map[string]interface{}{ "type": "command", "action": "close_after", "args": []interface{}{willEnd}, }) if err != nil { return } toMars := coordinate == "mars" isTutorial := false if token.Cross.By.UserID == m.config.Routex.TutorialCreator { isTutorial = true } hasCreated := fals...
{ logger.ERROR("set user %d enable cross %d breadcrumbs repo failed: %s", identity.UserID, crossId, err) }
conditional_block