file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
indexable.py | #===============================================================================
# Copyright (c) 2015, Max Zwiessele
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source... |
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 | #===============================================================================
# Copyright (c) 2015, Max Zwiessele
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source... | """
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 | #===============================================================================
# Copyright (c) 2015, Max Zwiessele
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source... |
### 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 | #===============================================================================
# Copyright (c) 2015, Max Zwiessele
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source... | (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 | /* Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... |
// Validate item is either a valid ip or ip range.
func validNetwork(i string) bool {
_, _, err := net.ParseCIDR(i)
if err == nil {
return true
}
if net.ParseIP(i) != nil {
return true
}
return false
}
// Validate every item is either a valid ip or ip range.
func validNetworks(nets []string) bool {
for _,... | {
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 | /* Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... | (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 | /* Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... | only = true
case strings.Contains(v, ","):
s := strings.Split(v, ",")
i, err := strconv.Atoi(s[0])
if err != nil {
return fmt.Errorf("fast_pattern offset is not an int: %s; %s", s[0], err)
}
offset = i
i, err = strconv.Atoi(s[1])
if err != nil {
return fmt.Errorf("fast_patte... | random_line_split | |
parser.go | /* Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
dis... |
return false
}
ports := portSplitRE.Split(u, -1)
for _, port := range ports {
port = strings.TrimPrefix(port, "!")
if port == "any" || port == "" || strings.HasPrefix(port, "$") {
continue
}
x, err := strconv.Atoi(port)
if err != nil {
return false
}
if x > 65535 || x < 0 {
r... | {
continue
} | conditional_block |
types.go | package luno
import "github.com/luno/luno-go/decimal"
type AccountBalance struct {
// ID of the account.
AccountId string `json:"account_id"`
// Currency code for the asset held in this account.
Asset string `json:"asset"`
// The amount available to send or trade.
Balance decimal.Decimal `json:"balance"`
//... |
// <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 | use crate::prelude::{ChunkKey, ChunkKey3, ChunkUnits, OctreeNode, OctreeSet, VisitStatus};
use building_blocks_core::prelude::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ClipMapConfig3 {
/// The number of levels of detail.
num_lods: u8,
/// The radius (in chunks) of a clipbox at any level o... | )
.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 | use crate::prelude::{ChunkKey, ChunkKey3, ChunkUnits, OctreeNode, OctreeSet, VisitStatus};
use building_blocks_core::prelude::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ClipMapConfig3 {
/// The number of levels of detail.
num_lods: u8,
/// The radius (in chunks) of a clipbox at any level o... | (
&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 | use crate::prelude::{ChunkKey, ChunkKey3, ChunkUnits, OctreeNode, OctreeSet, VisitStatus};
use building_blocks_core::prelude::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ClipMapConfig3 {
/// The number of levels of detail.
num_lods: u8,
/// The radius (in chunks) of a clipbox at any level o... | // We should end up with the same result from moving the clipmap as we do just constructing it from scratch at the
// new location.
assert_eq!(
active_chunks,
ActiveChunks::new(config, octree, new_lod0_center),
"Failed on edge: {:?} -->... |
ClipMapUpdate3::new(config, old_lod0_center, new_lod0_center)
.find_chunk_updates(octree, |update| active_chunks.apply_update(update));
| random_line_split |
clipmap.rs | use crate::prelude::{ChunkKey, ChunkKey3, ChunkUnits, OctreeNode, OctreeSet, VisitStatus};
use building_blocks_core::prelude::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ClipMapConfig3 {
/// The number of levels of detail.
num_lods: u8,
/// The radius (in chunks) of a clipbox at any level o... |
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 | package services
import (
"context"
"crypto/md5"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"strconv"
"strings"
"time"
"unicode/utf8"
bot "github.com/MixinNetwork/bot-api-go-client"
number "github.com/MixinNetwork/go-number"
"github.com/MixinNetwork/supergroup.mixin.one/config"
"githu... | (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 | package services
import (
"context"
"crypto/md5"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"strconv"
"strings"
"time"
"unicode/utf8"
bot "github.com/MixinNetwork/bot-api-go-client"
number "github.com/MixinNetwork/go-number"
"github.com/MixinNetwork/supergroup.mixin.one/config"
"githu... | }
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 | package services
import (
"context"
"crypto/md5"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"strconv"
"strings"
"time"
"unicode/utf8"
bot "github.com/MixinNetwork/bot-api-go-client"
number "github.com/MixinNetwork/go-number"
"github.com/MixinNetwork/supergroup.mixin.one/config"
"githu... |
func handleOrderPayment(ctx context.Context, mc *MessageContext, transfer TransferView, order *models.Order) error {
if order.PayMethod == models.PayMethodMixin &&
number.FromString(transfer.Amount).Equal(number.FromString(order.Amount).RoundFloor(8)) &&
order.AssetId == transfer.AssetId {
_, err := models.Mar... | {
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 | package services
import (
"context"
"crypto/md5"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"strconv"
"strings"
"time"
"unicode/utf8"
bot "github.com/MixinNetwork/bot-api-go-client"
number "github.com/MixinNetwork/go-number"
"github.com/MixinNetwork/supergroup.mixin.one/config"
"githu... |
}()
}
if _, err := models.CreateMessage(ctx, user, message.MessageID, message.Category, message.QuoteMessageID, message.Data, message.CreatedAt, message.UpdatedAt); err != nil {
return err
}
return nil
}
func sendHelpMessage(ctx context.Context, user *models.User, mc *MessageContext, message *mixin.MessageVie... | {
broadcastChan <- bmsg
} | conditional_block |
main.go | package main
import (
"flag"
"fmt"
"golang.org/x/sys/unix"
"io/ioutil"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"unicode/utf8"
)
// Key Definitions
const (
DummyKey = -1
ControlA = 1
ControlB = 2
ControlC = 3
ControlE = 5
ControlF = 6
ControlH = 8
Tab = 9
Enter = 13... | }
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 | package main
import (
"flag"
"fmt"
"golang.org/x/sys/unix"
"io/ioutil"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"unicode/utf8"
)
// Key Definitions
const (
DummyKey = -1
ControlA = 1
ControlB = 2
ControlC = 3
ControlE = 5
ControlF = 6
ControlH = 8
Tab = 9
Enter = 13... |
rows[e.n-1] = &Row{chars: gt}
e.rows = rows
return e
}
func (e *Editor) exit() {
e.restoreTerminal(0)
}
func (e *Editor) parseKey(b []byte) (rune, int) {
// Try parsing escape sequence
if len(b) == 3 {
if b[0] == byte(27) && b[1] == '[' {
switch b[2] {
case 'A':
return ArrowUp, 3
case 'B':
... | {
// 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 | package main
import (
"flag"
"fmt"
"golang.org/x/sys/unix"
"io/ioutil"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"unicode/utf8"
)
// Key Definitions
const (
DummyKey = -1
ControlA = 1
ControlB = 2
ControlC = 3
ControlE = 5
ControlF = 6
ControlH = 8
Tab = 9
Enter = 13... | (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 | package main
import (
"flag"
"fmt"
"golang.org/x/sys/unix"
"io/ioutil"
"os"
"path/filepath"
"strings"
"syscall"
"time"
"unicode/utf8"
)
// Key Definitions
const (
DummyKey = -1
ControlA = 1
ControlB = 2
ControlC = 3
ControlE = 5
ControlF = 6
ControlH = 8
Tab = 9
Enter = 13... |
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 | // Copyright 2020 Thomas.Hoehenleitner [at] seerose.net
// Use of this source code is governed by a license that can be found in the LICENSE file.
// Package decoder provides several decoders for differently encoded trice streams.
package decoder
import (
"encoding/binary"
"fmt"
"io"
"regexp"
"strings"
"sync"
... | string) (o string, u []int) {
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 posi... | eplaceN(i | identifier_name |
decoder.go | // Copyright 2020 Thomas.Hoehenleitner [at] seerose.net
// Use of this source code is governed by a license that can be found in the LICENSE file.
// Package decoder provides several decoders for differently encoded trice streams.
package decoder
import (
"encoding/binary"
"fmt"
"io"
"regexp"
"strings"
"sync"
... | // Dump prints the byte slice as hex in one line
func Dump(w io.Writer, b []byte) {
for _, x := range b {
fmt.Fprintf(w, "%02x ", x)
}
fmt.Fprintln(w, "")
}
| 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 | // Copyright 2020 Thomas.Hoehenleitner [at] seerose.net
// Use of this source code is governed by a license that can be found in the LICENSE file.
// Package decoder provides several decoders for differently encoded trice streams.
package decoder
import (
"encoding/binary"
"fmt"
"io"
"regexp"
"strings"
"sync"
... |
// 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 | // Copyright 2020 Thomas.Hoehenleitner [at] seerose.net
// Use of this source code is governed by a license that can be found in the LICENSE file.
// Package decoder provides several decoders for differently encoded trice streams.
package decoder
import (
"encoding/binary"
"fmt"
"io"
"regexp"
"strings"
"sync"
... | u = append(u, 1) // keep sign in all other cases(also negative values)
}
}
// Dump prints the byte slice as hex in one line
func Dump(w io.Writer, b []byte) {
for _, x := range b {
fmt.Fprintf(w, "%02x ", x)
}
fmt.Fprintln(w, "")
}
| // 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 | // This module provides a relatively simple thread-safe pool of reusable
// objects. For the most part, it's implemented by a stack represented by a
// Mutex<Vec<T>>. It has one small trick: because unlocking a mutex is somewhat
// costly, in the case where a pool is accessed by the first thread that tried
// to get a ... |
}
impl<'a, T: Send> PoolGuard<'a, T> {
/// Return the underlying value.
pub fn value(&self) -> &T {
match self.value {
None => &self.pool.owner_val,
Some(ref v) => &**v,
}
}
}
impl<'a, T: Send> Drop for PoolGuard<'a, T> {
#[cfg_attr(feature = "perf-inline", inl... | {
PoolGuard { pool: self, value: Some(value) }
} | identifier_body |
pool.rs | // This module provides a relatively simple thread-safe pool of reusable
// objects. For the most part, it's implemented by a stack represented by a
// Mutex<Vec<T>>. It has one small trick: because unlocking a mutex is somewhat
// costly, in the case where a pool is accessed by the first thread that tried
// to get a ... | <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 | // This module provides a relatively simple thread-safe pool of reusable
// objects. For the most part, it's implemented by a stack represented by a
// Mutex<Vec<T>>. It has one small trick: because unlocking a mutex is somewhat
// costly, in the case where a pool is accessed by the first thread that tried
// to get a ... | /// 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 | import random
import re
import string
import torch
from torch import nn
import csv
import os
import argparse
import json
import shutil
import logging
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, Dataset
from torch.nn.utils.rnn import pad_sequence
from rouge import Rouge
im... |
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 | import random
import re
import string
import torch
from torch import nn
import csv
import os
import argparse
import json
import shutil
import logging
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, Dataset
from torch.nn.utils.rnn import pad_sequence
from rouge import Rouge
im... | (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 | import random
import re
import string
import torch
from torch import nn
import csv
import os
import argparse
import json
import shutil
import logging
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, Dataset
from torch.nn.utils.rnn import pad_sequence
from rouge import Rouge
im... |
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 | import random
import re
import string
import torch
from torch import nn
import csv
import os
import argparse
import json
import shutil
import logging
import numpy as np
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader, Dataset
from torch.nn.utils.rnn import pad_sequence
from rouge import Rouge
im... | 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 | """ Python script to manage running jobs, checking the results, etc. """
import argparse
import os
import pprint
import subprocess
import sys
from argparse import RawTextHelpFormatter
def run(cmd):
print(cmd)
try:
res = subprocess.check_output(cmd, shell=True).decode('utf-8')
except subprocess.Ca... |
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 | """ Python script to manage running jobs, checking the results, etc. """
import argparse
import os
import pprint
import subprocess
import sys
from argparse import RawTextHelpFormatter
def run(cmd):
|
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 | """ Python script to manage running jobs, checking the results, etc. """
import argparse
import os
import pprint
import subprocess
import sys
from argparse import RawTextHelpFormatter
def run(cmd):
print(cmd)
try:
res = subprocess.check_output(cmd, shell=True).decode('utf-8')
except subprocess.Ca... | (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 | """ Python script to manage running jobs, checking the results, etc. """
import argparse
import os
import pprint
import subprocess
import sys
from argparse import RawTextHelpFormatter
def run(cmd):
print(cmd)
try:
res = subprocess.check_output(cmd, shell=True).decode('utf-8')
except subprocess.Ca... | #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 | // Copyright 2018 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... | 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 | // Copyright 2018 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... |
func (i *installer) Install(r io.Reader, info *os.FileInfo) error {
_, err := io.Copy(ioutil.Discard, r)
return err
}
func writeDataFile(t *testing.T, name, data string) io.Reader {
comp := artifact.NewCompressorGzip()
buf := bytes.NewBuffer(nil)
gz, err := comp.NewWriter(buf)
assert.NoError(t, err)
tw := ta... | {
return nil
} | identifier_body |
reader_test.go | // Copyright 2018 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... | () string {
return ""
}
func (i *installer) Copy() handlers.Installer {
return i
}
func (i *installer) ReadHeader(r io.Reader, path string) error {
return nil
}
func (i *installer) Install(r io.Reader, info *os.FileInfo) error {
_, err := io.Copy(ioutil.Discard, r)
return err
}
func writeDataFile(t *testing.T,... | GetType | identifier_name |
reader_test.go | // Copyright 2018 Northern.tech AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable ... |
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 | #!/usr/bin/env python
''' Analysis script for standard plots
'''
#
# Standard imports and batch mode
#
import ROOT, os
ROOT.gROOT.SetBatch(True)
import itertools
from math import sqrt, cos, sin, pi, acos, cosh
from RootTools.core.standard import *
from TopEFT.Tools.user import p... |
stack.extend( [ [s] for s in signals ] )
if args.small:
for sample in stack.samples:
sample.reduceFiles( to = 1 )
# Use some defaults
Plot.setDefaults(stack = stack, weight = staticmethod(weight_), selectionString = cutInterpreter.cutString(args.selection), addOverFlowBin='bo... | stack = Stack(mc) | conditional_block |
analysisPlots_TWZ_nLep.py | #!/usr/bin/env python
''' Analysis script for standard plots
'''
#
# Standard imports and batch mode
#
import ROOT, os
ROOT.gROOT.SetBatch(True)
import itertools
from math import sqrt, cos, sin, pi, acos, cosh
from RootTools.core.standard import *
from TopEFT.Tools.user import p... | ( 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 | #!/usr/bin/env python
''' Analysis script for standard plots
'''
#
# Standard imports and batch mode
#
import ROOT, os
ROOT.gROOT.SetBatch(True)
import itertools
from math import sqrt, cos, sin, pi, acos, cosh
from RootTools.core.standard import *
from TopEFT.Tools.user import p... |
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 | #!/usr/bin/env python
''' Analysis script for standard plots
'''
#
# Standard imports and batch mode
#
import ROOT, os
ROOT.gROOT.SetBatch(True)
import itertools
from math import sqrt, cos, sin, pi, acos, cosh
from RootTools.core.standard import *
from TopEFT.Tools.user import p... | sample.setSelectionString(getLeptonSelection(mode))
#sample.setSelectionString([getFilterCut(isData=False, year=args.year), getLeptonSelection(mode), tr.getSelection("MC")])
if not args.noData:
stack = Stack(mc, data_sample)
else:
stack = Stack(mc)
stack.extend( [ [s] for s in sign... | # 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 | package main
import (
"encoding/binary"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
)
const (
OP_IMM = 0x13
OP_LUI = 0x37
OP_AUIPC = 0x17
OP = 0x33
OP_JAL = 0x6f
OP_JALR = 0x67
OP_BRANCH = 0x63
OP_LOAD = 0x03
OP_STORE = 0x23
OP_SYSTEM = 0x73
)
// OP_IMM
const (
FUNCT_ADDI = 0
FUNCT_SL... | case OP_JAL:
_, rd, imm := jtype(inst)
cpu.SetReg(rd, cpu.pc)
cpu.pc += imm - 4
case OP_JALR:
_, rd, _, rs1, imm := itype(inst)
rs1v := cpu.GetReg(rs1)
cpu.SetReg(rd, cpu.pc)
cpu.pc = (rs1v + imm) & 0xfffffffe
case OP_BRANCH:
_, funct3, rs1, rs2, imm := btype(inst)
rs1v := cpu.GetReg(rs1)
rs2v :=... | trap(ExceptionIllegalInstruction, inst)
break decode
}
cpu.SetReg(rd, res) | random_line_split |
main.go | package main
import (
"encoding/binary"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
)
const (
OP_IMM = 0x13
OP_LUI = 0x37
OP_AUIPC = 0x17
OP = 0x33
OP_JAL = 0x6f
OP_JALR = 0x67
OP_BRANCH = 0x63
OP_LOAD = 0x03
OP_STORE = 0x23
OP_SYSTEM = 0x73
)
// OP_IMM
const (
FUNCT_ADDI = 0
FUNCT_SL... | else {
res = rs1v - rs2v
}
case FUNCT_SLT:
if int32(rs1v) < int32(rs2v) {
res = 1
} else {
res = 0
}
case FUNCT_SLTU:
if rs1v < rs2v {
res = 1
} else {
res = 0
}
case FUNCT_AND:
res = rs1v & rs2v
case FUNCT_OR:
res = rs1v | rs2v
case FUNCT_XOR:
res = rs1v ^ r... | {
res = rs1v + rs2v
} | conditional_block |
main.go | package main
import (
"encoding/binary"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
)
const (
OP_IMM = 0x13
OP_LUI = 0x37
OP_AUIPC = 0x17
OP = 0x33
OP_JAL = 0x6f
OP_JALR = 0x67
OP_BRANCH = 0x63
OP_LOAD = 0x03
OP_STORE = 0x23
OP_SYSTEM = 0x73
)
// OP_IMM
const (
FUNCT_ADDI = 0
FUNCT_SL... | (inst uint32) (opcode, funct3, rs1, rs2 uint8, imm uint32) {
imm |= bitrange(inst, 8, 4) << 1
imm |= bitrange(inst, 25, 6) << 5
imm |= bitrange(inst, 7, 1) << 11
imm |= bitrange(inst, 31, 1) << 12
imm = signExtend(imm, 12)
return uint8(bitrange(inst, 0, 7)),
uint8(bitrange(inst, 12, 3)),
uint8(bitrange(inst, ... | btype | identifier_name |
main.go | package main
import (
"encoding/binary"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
)
const (
OP_IMM = 0x13
OP_LUI = 0x37
OP_AUIPC = 0x17
OP = 0x33
OP_JAL = 0x6f
OP_JALR = 0x67
OP_BRANCH = 0x63
OP_LOAD = 0x03
OP_STORE = 0x23
OP_SYSTEM = 0x73
)
// OP_IMM
const (
FUNCT_ADDI = 0
FUNCT_SL... |
func (cpu *Cpu) SetCsr(csr uint32, v uint32) {
if csr == CsrHalt {
cpu.halt = true
cpu.haltValue = v
return
}
priv := csr & ^uint32(0xcff) // save priv
if priv != CsrM {
panic(fmt.Sprintf("invalid csr: 0x%03x\n", csr))
}
csr &= 0xcff // ignore priv
switch csr {
case CsrTvec:
cpu.mtvec = v & 0xffffff... | {
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 | // Copyright 2023 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package storer
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"math/big"
"os"
"path"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/e... |
}()
bgCacheWorkersClosed := make(chan struct{})
go func() {
defer close(bgCacheWorkersClosed)
db.bgCacheLimiterWg.Wait()
}()
var err error
closerDone := make(chan struct{})
go func() {
defer close(closerDone)
err = db.dbCloser.Close()
}()
done := make(chan struct{})
go func() {
defer close(done)... | {
db.logger.Warning("db shutting down with running goroutines")
} | conditional_block |
storer.go | // Copyright 2023 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package storer
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"math/big"
"os"
"path"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/e... | 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 | // Copyright 2023 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package storer
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"math/big"
"os"
"path"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/e... | (uint8) {}
func performEpochMigration(ctx context.Context, basePath string, opts *Options) (retErr error) {
store, err := initStore(basePath, opts)
if err != nil {
return err
}
defer store.Close()
sharkyBasePath := path.Join(basePath, sharkyPath)
var sharkyRecover *sharky.Recovery
// if this is a fresh node ... | SetStorageRadius | identifier_name |
storer.go | // Copyright 2023 The Swarm Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package storer
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"math/big"
"os"
"path"
"path/filepath"
"sync"
"sync/atomic"
"time"
"github.com/e... |
func (db *DB) SetRetrievalService(r retrieval.Interface) {
db.retrieval = r
}
func (db *DB) StartReserveWorker(ctx context.Context, s Syncer, radius func() (uint8, error)) {
db.setSyncerOnce.Do(func() {
db.syncer = s
go db.startReserveWorkers(ctx, db.opts.warmupDuration, db.opts.wakeupDuration, radius)
})
}
... | {
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 | package userrolemod
import (
"database/sql"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/intrntsrfr/meido/base"
"github.com/intrntsrfr/meido/database"
"github.com/intrntsrfr/meido/utils"
"go.uber.org/zap"
"github.com/bwmarrin/discordgo"
"github.com/intrntsrfr/owo"
)
type UserRoleMod struct {
syn... | 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 | package userrolemod
import (
"database/sql"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/intrntsrfr/meido/base"
"github.com/intrntsrfr/meido/database"
"github.com/intrntsrfr/meido/utils"
"go.uber.org/zap"
"github.com/bwmarrin/discordgo"
"github.com/intrntsrfr/owo"
)
type UserRoleMod struct {
syn... |
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 | package userrolemod
import (
"database/sql"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/intrntsrfr/meido/base"
"github.com/intrntsrfr/meido/database"
"github.com/intrntsrfr/meido/utils"
"go.uber.org/zap"
"github.com/bwmarrin/discordgo"
"github.com/intrntsrfr/owo"
)
type UserRoleMod struct {
syn... | () 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 | package userrolemod
import (
"database/sql"
"fmt"
"strconv"
"strings"
"sync"
"time"
"github.com/intrntsrfr/meido/base"
"github.com/intrntsrfr/meido/database"
"github.com/intrntsrfr/meido/utils"
"go.uber.org/zap"
"github.com/bwmarrin/discordgo"
"github.com/intrntsrfr/owo"
)
type UserRoleMod struct {
syn... | 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 | /**
* A Library Adapter Layer for ThreeJS
*/
CONSTRUCTORS_DECORATED = false;
GUID_PROPERTY_ADDED = false;
/**
* Constructor for the ThreeJS Library Adapter Layer.
* @param {object} config - A configuration object. Must contain a 'shareConf'
* function.
*/
ThreeAdapter = function (config) {
this.config = c... |
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 | /**
* A Library Adapter Layer for ThreeJS
*/
CONSTRUCTORS_DECORATED = false;
GUID_PROPERTY_ADDED = false;
/**
* Constructor for the ThreeJS Library Adapter Layer.
* @param {object} config - A configuration object. Must contain a 'shareConf'
* function.
*/
ThreeAdapter = function (config) {
this.config = c... | // "XHRLoader",
// "ImageLoader",
// "JSONLoader",
// "LoadingManager",
// "DefaultLoadingManager",
// "BufferGeometryLoader",
// "MaterialLoader",
// "ObjectLoader",
// "TextureLoader",
// "BinaryTextureLoader",
// "DataTextureLoader",
// "CompressedTextureLoader",
/... | // "HemisphereLight",
"PointLight",
// "SpotLight",
// "Cache",
// "Loader", | random_line_split |
threejs_adapter.js | /**
* A Library Adapter Layer for ThreeJS
*/
CONSTRUCTORS_DECORATED = false;
GUID_PROPERTY_ADDED = false;
/**
* Constructor for the ThreeJS Library Adapter Layer.
* @param {object} config - A configuration object. Must contain a 'shareConf'
* function.
*/
ThreeAdapter = function (config) {
this.config = c... | (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 | # $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
... |
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 | # $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
... | (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 | # $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
... | 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 | # $Filename$
# $Authors$
# Last Changed: $Date$ $Committer$ $Revision-Id$
#
# Copyright (c) 2003-2011, German Aerospace Center (DLR)
# All rights reserved.
#
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are
#met:
#
... |
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 | package local
import (
"archive/tar"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/buildpacks/imgutil/layer"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/dock... |
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 | package local
import (
"archive/tar"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/buildpacks/imgutil/layer"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/dock... |
}
return nil
}
func addTextToTar(tw *tar.Writer, name string, contents []byte) error {
hdr := &tar.Header{Name: name, Mode: 0644, Size: int64(len(contents))}
if err := tw.WriteHeader(hdr); err != nil {
return err
}
_, err := tw.Write(contents)
return err
}
func addFileToTar(tw *tar.Writer, name string, con... | {
return errors.New("failed to download all base layers from daemon")
} | conditional_block |
local.go | package local
import (
"archive/tar"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/buildpacks/imgutil/layer"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/dock... | (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 | package local
import (
"archive/tar"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/buildpacks/imgutil/layer"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/dock... | 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 | import inspect
import json
from contextlib import contextmanager
from time import perf_counter
from typing import Optional, Callable
from ._backend import Backend, BACKENDS, _DEFAULT
class BackendCall:
def __init__(self, start: float, stop: float, backend: 'ProfilingBackend', function_name):
self._start... | (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 | import inspect
import json
from contextlib import contextmanager
from time import perf_counter
from typing import Optional, Callable
from ._backend import Backend, BACKENDS, _DEFAULT
class BackendCall:
def __init__(self, start: float, stop: float, backend: 'ProfilingBackend', function_name):
self._start... |
def _format_values(values: dict, backend):
def format_val(value):
if isinstance(value, str):
return f'"{value}"'
if isinstance(value, (int, float, complex, bool)):
return value
if isinstance(value, (tuple, list)):
return str([format_val(v) for v in val... | """
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 | import inspect
import json
from contextlib import contextmanager
from time import perf_counter
from typing import Optional, Callable
from ._backend import Backend, BACKENDS, _DEFAULT
class BackendCall:
def __init__(self, start: float, stop: float, backend: 'ProfilingBackend', function_name):
self._start... | 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 | import inspect
import json
from contextlib import contextmanager
from time import perf_counter
from typing import Optional, Callable
from ._backend import Backend, BACKENDS, _DEFAULT
class BackendCall:
def __init__(self, start: float, stop: float, backend: 'ProfilingBackend', function_name):
self._start... |
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 | // SECUREAUTH LABS. Copyright 2018 SecureAuth Corporation. All rights reserved.
//
// This software is provided under under a slightly modified version
// of the Apache Software License. See the accompanying LICENSE file
// for more information.
//
// Description:
// WPS packets
//
// Author:
// Aureliano Calvo
impo... | 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 | //! Interfaces for accessing instance data from hostcalls.
//!
//! This module contains both a Rust-friendly API ([`Vmctx`](struct.Vmctx.html)) as well as C-style
//! exports for compatibility with hostcalls written against `lucet-runtime-c`.
pub use crate::c_api::lucet_vmctx;
use crate::alloc::instance_heap_offset;
... |
/// 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 | //! Interfaces for accessing instance data from hostcalls.
//!
//! This module contains both a Rust-friendly API ([`Vmctx`](struct.Vmctx.html)) as well as C-style
//! exports for compatibility with hostcalls written against `lucet-runtime-c`.
pub use crate::c_api::lucet_vmctx;
use crate::alloc::instance_heap_offset;
... | } | HOST_CTX.with(|host_ctx| unsafe { Context::set(&*host_ctx.get()) })
} | random_line_split |
vmctx.rs | //! Interfaces for accessing instance data from hostcalls.
//!
//! This module contains both a Rust-friendly API ([`Vmctx`](struct.Vmctx.html)) as well as C-style
//! exports for compatibility with hostcalls written against `lucet-runtime-c`.
pub use crate::c_api::lucet_vmctx;
use crate::alloc::instance_heap_offset;
... | (&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 | /* jshint camelcase:false, nomen:false, latedef:false, forin:false */
/* jshint maxparams:4 */
/* global Components */
(function executeTombfixService(global) {
'use strict';
const EXTENSION_ID = 'tombfix@tombfix.github.io',
{interfaces: Ci, classes: Cc, results: Cr, utils: Cu} = Components,
// ht... |
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 | /* jshint camelcase:false, nomen:false, latedef:false, forin:false */
/* jshint maxparams:4 */
/* global Components */
(function executeTombfixService(global) {
'use strict';
const EXTENSION_ID = 'tombfix@tombfix.github.io',
{interfaces: Ci, classes: Cc, results: Cr, utils: Cu} = Components,
// ht... | 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 | /* jshint camelcase:false, nomen:false, latedef:false, forin:false */
/* jshint maxparams:4 */
/* global Components */
(function executeTombfixService(global) {
'use strict';
const EXTENSION_ID = 'tombfix@tombfix.github.io',
{interfaces: Ci, classes: Cc, results: Cr, utils: Cu} = Components,
// ht... | 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 | /* jshint camelcase:false, nomen:false, latedef:false, forin:false */
/* jshint maxparams:4 */
/* global Components */
(function executeTombfixService(global) {
'use strict';
const EXTENSION_ID = 'tombfix@tombfix.github.io',
{interfaces: Ci, classes: Cc, results: Cr, utils: Cu} = Components,
// ht... |
});
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 | """
A space game written in Python.
"""
# Standard imports.
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 ... |
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 | """
A space game written in Python.
"""
# Standard imports.
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 ... |
# 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 | """
A space game written in Python.
"""
# Standard imports.
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 ... | 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 | """
A space game written in Python.
"""
# Standard imports.
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 ... | (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 | use anyhow::anyhow;
use nom::character::complete::{newline, satisfy, space0};
use nom::combinator::{map, map_res, opt};
use nom::multi::{many1, separated_list1};
use nom::sequence::{preceded, terminated, tuple};
use nom::Parser;
use nom_supreme::tag::complete::tag;
use tako::hwstats::GpuFamily;
use tako::internal::has... |
}
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() -> anyhow::Result<u64> {
... | {
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 | use anyhow::anyhow;
use nom::character::complete::{newline, satisfy, space0};
use nom::combinator::{map, map_res, opt};
use nom::multi::{many1, separated_list1};
use nom::sequence::{preceded, terminated, tuple};
use nom::Parser;
use nom_supreme::tag::complete::tag;
use tako::hwstats::GpuFamily;
use tako::internal::has... |
/// GPU resource that can be detected from an environment variable.
pub struct GpuEnvironmentRecord {
env_var: &'static str,
pub resource_name: &'static str,
pub family: GpuFamily,
}
impl GpuEnvironmentRecord {
const fn new(env_var: &'static str, resource_name: &'static str, family: GpuFamily) -> Sel... | {
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 | use anyhow::anyhow;
use nom::character::complete::{newline, satisfy, space0};
use nom::combinator::{map, map_res, opt};
use nom::multi::{many1, separated_list1};
use nom::sequence::{preceded, terminated, tuple};
use nom::Parser;
use nom_supreme::tag::complete::tag;
use tako::hwstats::GpuFamily;
use tako::internal::has... | () -> 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 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This file implem... |
}
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 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This file implem... | /// 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 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This file implem... |
}
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 | // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// This file implem... | {
// 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 | import random
from collections import deque
from environment import get_env
import numpy as np
import heapq
from itertools import count
class BufferSizeManager:
def __init__(self, initial_capacity, size_change=20):
"""Adaptive buffer size.
If size_change > 1: Linear buffer update as in: https:/... | return self.container.memory_full()
def push(self, error, sample):
self.container.add(error, sample)
def sample(self, n):
return self.container.get_batch(n)
def update(self, idx, error):
self.container.update(idx, error)
def resize_memory(self, new_size=None):
... | self.container = RankBased(max_capacity)
else:
raise ValueError("Bad replay method")
def memory_full(self): | random_line_split |
replay.py | import random
from collections import deque
from environment import get_env
import numpy as np
import heapq
from itertools import count
class BufferSizeManager:
def __init__(self, initial_capacity, size_change=20):
"""Adaptive buffer size.
If size_change > 1: Linear buffer update as in: https:/... | (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 | import random
from collections import deque
from environment import get_env
import numpy as np
import heapq
from itertools import count
class BufferSizeManager:
def __init__(self, initial_capacity, size_change=20):
"""Adaptive buffer size.
If size_change > 1: Linear buffer update as in: https:/... |
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 | import random
from collections import deque
from environment import get_env
import numpy as np
import heapq
from itertools import count
class BufferSizeManager:
def __init__(self, initial_capacity, size_change=20):
"""Adaptive buffer size.
If size_change > 1: Linear buffer update as in: https:/... |
# sanity check
if __name__ == "__main__":
capacity = 10
# CombinedReplayMemory(capacity)#NaiveReplayMemory(capacity)
memory = PrioritizedReplayMemory(capacity)
env, _ = get_env("Acrobot-v1")
# Sample a transition
s = env.reset()
a = env.action_space.sample()
s_next, r, done, _ = env... | 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 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import type { nbformat } from '@jupyterlab/coreutils';
import { inject, injectable } from 'inversify';
import * as os from 'os';
import * as path from 'path';
import * as uuid from 'uuid/v4';
import { Uri } fr... | (
@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 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import type { nbformat } from '@jupyterlab/coreutils';
import { inject, injectable } from 'inversify';
import * as os from 'os';
import * as path from 'path';
import * as uuid from 'uuid/v4';
import { Uri } fr... | else {
const array = source
.toString()
.split('\n')
.map((s) => `${s}\n`);
if (array.length > 0 && cellMatcher.isCell(array[0])) {
return array.slice(1);
}
}
return source;
};
private extractP... | {
if (cellMatcher.isCell(source[0])) {
return source.slice(1);
}
} | conditional_block |
jupyterExporter.ts | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import type { nbformat } from '@jupyterlab/coreutils';
import { inject, injectable } from 'inversify';
import * as os from 'os';
import * as path from 'path';
import * as uuid from 'uuid/v4';
import { Uri } fr... | 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 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
'use strict';
import type { nbformat } from '@jupyterlab/coreutils';
import { inject, injectable } from 'inversify';
import * as os from 'os';
import * as path from 'path';
import * as uuid from 'uuid/v4';
import { Uri } fr... |
private showInformationMessage(
message: string,
question1: string,
question2?: string
): Thenable<string | undefined> {
if (question2) {
return this.applicationShell.showInformationMessage(message, question1, question2);
} else {
return this.app... | {
// 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 | package routex
import (
"broker"
"encoding/json"
"fmt"
"github.com/googollee/go-pubsub"
"github.com/googollee/go-rest"
"logger"
"math/rand"
"model"
"net/http"
"net/url"
"notifier"
"os"
"routex/model"
"sync"
"time"
)
type RouteMap struct {
rest.Service `prefix:"/v3/routex" mime:"application/json"`
up... |
if err := m.breadcrumbCache.EnableCross(identity.UserID, crossId, afterInSeconds); err != nil {
logger.ERROR("set user %d enable cross %d breadcrumb cache failed: %s", identity.UserID, crossId, err)
}
} else {
if err := m.breadcrumbsRepo.DisableCross(identity.UserID, crossId); err != nil {
logger.ERROR("s... | {
logger.ERROR("set user %d enable cross %d breadcrumbs repo failed: %s", identity.UserID, crossId, err)
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.