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 |
|---|---|---|---|---|
message.go | "encoding/hex"
"dad-go/common"
"dad-go/node"
)
const (
MSGCMDLEN = 12
CMDOFFSET = 4
CHECKSUMLEN = 4
HASHLEN = 32 // hash length in byte
MSGHDRLEN = 24
)
// The Inventory type
const (
TXN = 0x01 // Transaction
BLOCK = 0x02
CONSENSUS = 0xe0
)
type messager interface {
verify([]byte) error
serialization... | "crypto/sha256"
"encoding/binary" | random_line_split | |
message.go | 0
var sum []byte
sum = []byte{0x5d, 0xf6, 0xe0, 0xe2}
msg.msgHdr.init("verack", sum, 0)
buf, err := msg.serialization()
if (err != nil) {
return nil, err
}
str := hex.EncodeToString(buf)
fmt.Printf("The message tx verack length is %d, %s", len(buf), str)
return buf, err
}
func newGetAddr() ([]byte, error... | {
var val uint64
var size uint8
len := binary.LittleEndian.Uint64(msg.p.blk[0:1])
if (len < 0xfd) {
val = len
size = 1
} else if (len == 0xfd) {
val = binary.LittleEndian.Uint64(msg.p.blk[1 : 3])
size = 3
} else if (len == 0xfe) {
val = binary.LittleEndian.Uint64(msg.p.blk[1 : 5])
size = 5
} else if... | identifier_body | |
message.go | Header struct {
hdr msgHdr
blkHdr []byte
}
type addr struct {
msgHdr
// TBD
}
type invPayload struct {
invType uint8
blk []byte
}
type inv struct {
hdr msgHdr
p invPayload
}
type dataReq struct {
msgHdr
// TBD
}
type block struct {
msgHdr
// TBD
}
// Transaction message
type trn struct {
msgHdr
... |
str := hex.EncodeToString(buf)
fmt.Printf("The message tx verack length is %d, %s", len(buf), str)
return buf, err
}
func newGetAddr() ([]byte, error) {
var msg addrReq
// Fixme the check is the []byte{0} instead of 0
var sum []byte
sum = []byte{0x5d, 0xf6, 0xe0, 0xe2}
msg.Hdr.init("getaddr", sum, 0)
buf,... | {
return nil, err
} | conditional_block |
Reinforcement_Learning_second_train.py | 'done': []}
#最多要保留幾筆紀錄
self.memory_capacity = memory_capacity
#最少保留幾筆紀錄後開始做訓練
self.min_memory = min_memory
#每次訓練的取樣數量
self.batch_size = batch_size
#目前主流的Deep Q learning會用兩個一樣的模型來做訓練
#只對train_model做訓練
#target_model只被動接收權重
#訓練模型
self... | return len(self.memory['state'])
def get_loss_value(self):
return self.loss_value
#對於在eager model中的tensorflow運算可以在function前面加上@tf.function來改善運算效率
#但是該function會不能用debug監看
@tf.function
def calculate_gradient(self, train_state, train_action, nextq_value):
#在GradientTape中計算loss_valu... | for key, value in new_memory.items():
self.memory[key].append(value)
def get_memory_size(self):
| conditional_block |
Reinforcement_Learning_second_train.py | [], 'done': []}
#最多要保留幾筆紀錄
self.memory_capacity = memory_capacity
#最少保留幾筆紀錄後開始做訓練
self.min_memory = min_memory
#每次訓練的取樣數量
self.batch_size = batch_size
#目前主流的Deep Q learning會用兩個一樣的模型來做訓練
#只對train_model做訓練
#target_model只被動接收權重
#訓練模型
... | t = self.train_model.trainable_variables
gradients = tape.gradient(loss_value, weight)
#根據梯度更新權重
self.optimizer.apply_gradients(zip(gradients, weight))
#self.loss_value = loss_value.numpy()
def training_model(self):
if len(self.memory['state']) > self.min_memory:
... | 計算梯度
weigh | identifier_name |
Reinforcement_Learning_second_train.py | 'done': []}
#最多要保留幾筆紀錄
self.memory_capacity = memory_capacity
#最少保留幾筆紀錄後開始做訓練
self.min_memory = min_memory
#每次訓練的取樣數量
self.batch_size = batch_size
#目前主流的Deep Q learning會用兩個一樣的模型來做訓練
#只對train_model做訓練
#target_model只被動接收權重
#訓練模型
self... | * tf.one_hot(train_action, self.num_actions, dtype = 'float64'), axis=1)
loss_value = self.loss_function(nextq_value, q_value)
#計算梯度
weight = self.train_model.trainable_variables
gradients = tape.gradient(loss_value, weight)
#根據梯度更新權重
... | in_model_output
| identifier_body |
Reinforcement_Learning_second_train.py | self.memory_capacity = memory_capacity
#最少保留幾筆紀錄後開始做訓練
self.min_memory = min_memory
#每次訓練的取樣數量
self.batch_size = batch_size
#目前主流的Deep Q learning會用兩個一樣的模型來做訓練
#只對train_model做訓練
#target_model只被動接收權重
#訓練模型
self.train_model = creat_model()
... | #每一筆memory資料包含 state, action, reward, next_state
self.memory = {'state': [], 'action': [], 'reward': [], 'next_state': [], 'done': []}
#最多要保留幾筆紀錄 | random_line_split | |
useful.rs | 4,
pub quartz: i64,
pub ruby: i64,
pub rust: i64,
pub shale: i64,
pub sulfur: i64,
pub tar: i64,
pub uranium: i64,
pub zillium: i64,
}
// Useful functions for Player
impl Player {
pub fn empty() -> Self {
return Player {
id: 0,
sprite:... |
send_embed(ctx, msg, exile_3[rand_index as usize]).await;
} e | conditional_block | |
useful.rs | ,
uranium: 0,
zillium: 0,
}
}
}
// Makes it so you can iterate through materials
impl IntoIterator for Materials {
type Item = i64;
type IntoIter = std::array::IntoIter<i64, 20>;
fn into_iter(self) -> Self::IntoIter {
std::array::IntoIter::new([
... |
impl<T: std::fmt::Display> FormatVec for Vec<T> {
fn format_vec(&self) -> String {
| random_line_split | |
useful.rs | ,
pub materials: Materials,
pub inventory: Vec<String>,
pub storage: Vec<String>,
pub sylladex_type: String,
}
#[derive(Debug, Clone)]
pub struct Materials {
pub build: i64,
pub amber: i64,
pub amethyst: i64,
pub caulk: i64,
pub chalk: i64,
pub cobalt: i64,
pu... | (statement: &str) -> Result<(), Error> {
let (client, connection) = tokio_postgres::connect(POSTGRE, NoTls).await.unwrap();
tokio::spawn(async move {
if let Err(e) = connection.await {
eprintln!("connection error: {}", e);
}
});
let _ = client.execu... | sqlstatement | identifier_name |
main.go | returns a TransferRecord filled out with a UUID,
// StartTime, Status of "requested", and a Kind of "download".
func NewDownloadRecord() *TransferRecord {
return &TransferRecord{
UUID: uuid.New(),
StartTime: time.Now(),
Status: RequestedStatus,
Kind: DownloadKind,
}
}
// NewUploadRecord returns... |
// GetUploadStatus returns the status of the possibly running upload.
func (a *App) GetUploadStatus(writer http.ResponseWriter, request *http.Request) {
id := mux.Vars(request)["id"]
foundRecord := a.uploadRecords.FindRecord(id)
if foundRecord == nil {
writer.WriteHeader(http.StatusNotFound)
return
}
if er... | {
id := mux.Vars(request)["id"]
foundRecord := a.downloadRecords.FindRecord(id)
if foundRecord == nil {
writer.WriteHeader(http.StatusNotFound)
return
}
if err := foundRecord.MarshalAndWrite(writer); err != nil {
log.Error(err)
http.Error(writer, err.Error(), http.StatusInternalServerError)
}
} | identifier_body |
main.go | string) {
r.mutex.Lock()
r.Status = status
r.mutex.Unlock()
}
// HistoricalRecords maintains a list of []*TransferRecords and provides thread-safe access
// to them.
type HistoricalRecords struct {
records []*TransferRecord
mutex sync.Mutex
}
// Append adds another *TransferRecord to the list.
func (h *Histor... | User string `long:"user" required:"true" description:"The user to run the transfers for"`
UploadDestination string `long:"upload-destination" required:"true" description:"The destination directory for uploads"`
DownloadDestination string `long:"download-destination" default:"/input-files" d... | random_line_split | |
main.go | LogDirectory string
User string
UploadDestination string
DownloadDestination string
InvocationID string
InputPathList string
ExcludesPath string
ConfigPath string
FileMetadata []string
downloadWait sync.WaitGroup
uploadWait sync.Wait... | {
if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp {
os.Exit(0)
}
log.Fatal(err)
} | conditional_block | |
main.go | returns a TransferRecord filled out with a UUID,
// StartTime, Status of "requested", and a Kind of "download".
func NewDownloadRecord() *TransferRecord {
return &TransferRecord{
UUID: uuid.New(),
StartTime: time.Now(),
Status: RequestedStatus,
Kind: DownloadKind,
}
}
// NewUploadRecord returns... | () *TransferRecord {
return &TransferRecord{
UUID: uuid.New(),
StartTime: time.Now(),
Status: RequestedStatus,
Kind: DownloadKind,
}
}
// MarshalAndWrite serializes the TransferRecord to json and writes it out using writer.
func (r *TransferRecord) MarshalAndWrite(writer io.Writer) error {
var ... | NewUploadRecord | identifier_name |
server.go | json:"temperature"`
Precipitation float64 `json:"precipitation"`
Humidity float64 `json:"humidity"`
}
type AirData struct {
TagDate string `json:"timestamp"`
ObsName string `json:"observatory_name"`
Location [2]float64 `json:"coordinates"`
Wind [2]float64 `json:... | for i := 0; i < len(observatory); i++ {
air := AirData{}
idxAir := getIndexAirPollution(airPollution, observatory[i].AWSName)
idxWeather := getIndexWeatherData(weatherData, observatory[i].AWSName)
if idxAir != -1 && idxWeather != -1 {
air.TagDate = airPollution[idxAir].TagDate
air.ObsName = airPollution... | {
db, err := gorm.Open("mysql", "user:passwd@tcp(localhost:3306)/dev_gowind?charset=utf8")
if err != nil {
log.Fatal(err)
}
defer db.Close()
airPollution := []AirPollution{}
weatherData := []WeatherData{}
observatory := []Observatory{}
airPollutionItem := AirPollution{}
db.Last(&airPollutionItem)
timeStri... | identifier_body |
server.go | json:"temperature"`
Precipitation float64 `json:"precipitation"`
Humidity float64 `json:"humidity"`
}
type AirData struct {
TagDate string `json:"timestamp"`
ObsName string `json:"observatory_name"`
Location [2]float64 `json:"coordinates"`
Wind [2]float64 `json:... | trValue string) float64 {
val, err := strconv.ParseFloat(strValue, 64)
if err == nil {
return val
} else {
return -999
}
}
func weatherDataScrape(c echo.Context) error {
db, err := gorm.Open("mysql", "user:passwd@tcp(localhost:3306)/dev_gowind?charset=utf8")
if err != nil {
log.Fatal(err)
}
defer db.Clos... | ringToFloat(s | identifier_name |
server.go | air.ObsName = airPollution[idxAir].ObsName
air.Location[0] = observatory[i].AWSLongitude
air.Location[1] = observatory[i].AWSLatitude
air.Wind[0] = weatherData[idxWeather].WindDirection
air.Wind[1] = weatherData[idxWeather].WindSpeed
air.Temperature = weatherData[idxWeather].Temperature
air.Humidity ... | data[i].ItemPM10 == -999 {
return -1
}
if data[i].ItemPM25 == -999 {
return -1
}
if data[i].ItemCO == -999 {
return -1
}
if data[i].ItemNO2 == -999 {
return -1
}
if data[i].ItemSO2 == -999 {
return -1
}
if data[i].ItemO3 == -999 {
return -1
}
return i | conditional_block | |
server.go | (localhost:3306)/dev_gowind?charset=utf8")
if err != nil {
log.Fatal(err)
}
defer db.Close()
airPollution := []AirPollution{}
weatherData := []WeatherData{}
observatory := []Observatory{}
airPollutionItem := AirPollution{}
db.Last(&airPollutionItem)
timeString := airPollutionItem.TagDate
db.Where("tag_da... | obs.ItemCO = co
obs.ItemSO2 = so2 | random_line_split | |
main.rs | 3.0;
const BALL_ACC: f32 = 0.005;
// AI constants
const AI_ENABLED: bool = true;
const AI_MAX_ITERS: u32 = 400; // Experimentation results: around 800 is more than sufficient,
// 400 is quite good though is insufficient for a short time after ball leaves enemy paddle
const AI_WAIT_FOR_P... |
}
fn update_ball(&mut self, _ctx: &mut Context){
self.update_ai(_ctx);
self.ball.position += self.ball.velocity;
if !self.simulated {
GameState::update_collision(&mut self.ball, &self.player_paddle);
GameState::update_collision(&mut self.ball, &self.enemy_paddl... | {
GameState::apply_collision_response(ball, paddle);
} | conditional_block |
main.rs | = 3.0;
const BALL_ACC: f32 = 0.005;
// AI constants
const AI_ENABLED: bool = true;
const AI_MAX_ITERS: u32 = 400; // Experimentation results: around 800 is more than sufficient,
// 400 is quite good though is insufficient for a short time after ball leaves enemy paddle
const AI_WAIT_FOR... | {
ball_texture: Texture,
position: Vec2<f32>,
velocity: Vec2<f32>,
}
impl Ball {
fn reset(&mut self){
self.position = Vec2::new(
(SCREEN_WIDTH as f32)/2.0 - (self.ball_texture.width() as f32)/2.0,
(SCREEN_HEIGHT as f32)/2.0 - (self.ball_texture.height() as f32)/2.0
... | Ball | identifier_name |
main.rs | = 3.0;
const BALL_ACC: f32 = 0.005;
// AI constants
const AI_ENABLED: bool = true;
const AI_MAX_ITERS: u32 = 400; // Experimentation results: around 800 is more than sufficient,
// 400 is quite good though is insufficient for a short time after ball leaves enemy paddle
const AI_WAIT_FOR... | fn draw_paddle(ctx: &mut Context, paddle: &Paddle){
graphics::draw(ctx, &paddle.paddle_texture, paddle.position)
}
fn handle_inputs(&mut self, ctx: &mut Context){
if input::is_key_down(ctx, Key::W) {
self.player_paddle.position.y -= PADDLE_SPEED;
}
if input::is_k... | }
| random_line_split |
ffi.rs |
#[allow(non_camel_case_types)]
pub type io_object_t = mach_port_t;
#[allow(non_camel_case_types)]
pub type io_iterator_t = io_object_t;
#[allow(non_camel_case_types)]
pub type io_registry_entry_t = io_object_t;
// This is a hack, `io_name_t` should normally be `[c_char; 128]` but Rust makes it very annoying
// to dea... |
// Note: IOKit is only available on MacOS up until very recent iOS versions: https://developer.apple.com/documentation/iokit | random_line_split | |
ffi.rs |
// to deal with that so we go around it a bit.
#[allow(non_camel_case_types, dead_code)]
pub type io_name = [c_char; 128];
#[allow(non_camel_case_types)]
pub type io_name_t = *const c_char;
pub type IOOptionBits = u32;
#[allow(non_upper_case_globals)]
pub const kIOServicePlane: &[u8] = b"IOService\0";
#[allow(non_up... | {
pub version: u16,
pub length: u16,
pub cpu_plimit: u32,
pub gpu_plimit: u32,
pub mem_plimit: u32,
}
#[cfg_attr(feature = "debug", derive(Debug, Eq, Hash, PartialEq))]
#[repr(C)]
pub struct KeyData_keyInfo_t {
pub data_size: u32,
pub data_type: ... | KeyData_pLimitData_t | identifier_name |
dma.py | ),strides=(2,2), data_format = 'channels_last', input_shape = input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization(axis=-1,momentum=0.99,epsilon=0.001))
model.add(Conv2D(64,(5,5),padding='valid'))
model.add(Activation('relu'))
mod... |
validation_generator = generate_sequences(n_train_batches,images1,images2,images3,images4,images5,labels,mean1,mean2,mean3,mean4,mean5,train_idxs)
ReduceLR = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10,
verbose=1, mode='min', epsilon=1e-4, cooldown=0, min_lr... | n_validation_batches = n_validation_batches + 1 | conditional_block |
dma.py | ),strides=(2,2), data_format = 'channels_last', input_shape = input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization(axis=-1,momentum=0.99,epsilon=0.001))
model.add(Conv2D(64,(5,5),padding='valid'))
model.add(Activation('relu'))
mod... | (xx):
print xx.shape
x_min=tf.reduce_min(xx,axis=1)
print x_min.shape
x_max=tf.reduce_max(xx,axis=1)
x_sum=tf.reduce_sum(xx,axis=1)
x_mean=tf.reduce_mean(xx,axis=1)
x_sta=tf.concat([x_min,x_max,x_sum,x_mean],1)
print x_sta.shape
return x_sta
if __name__ == '__main__':
input... | statistics_layer | identifier_name |
dma.py | ),strides=(2,2), data_format = 'channels_last', input_shape = input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization(axis=-1,momentum=0.99,epsilon=0.001))
model.add(Conv2D(64,(5,5),padding='valid'))
model.add(Activation('relu'))
mod... | validation_idxs = idxs[int(len(images1) * (1 - validation_ratio)) :]
images2 = train_file2['images']
mean2 = train_file2['mean'][...]
images3 = train_file3['images']
mean3 = train_file3['mean'][...]
images4 = train_file4['images']
... | random_line_split | |
dma.py | ),strides=(2,2), data_format = 'channels_last', input_shape = input_shape))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(BatchNormalization(axis=-1,momentum=0.99,epsilon=0.001))
model.add(Conv2D(64,(5,5),padding='valid'))
model.add(Activation('relu'))
mod... | xx1 = images1[i, ...].astype(np.float32)
xx1 -= mean1
xx2 = images2[i, ...].astype(np.float32)
xx2 -= mean2
xx3 = images3[i, ...].astype(np.float32)
xx3 -= mean3
xx4 = images4[i, ...].astype(np.float32)
... | while True:
for bid in xrange(0, n_batches):
if bid == n_batches - 1:
batch_idxs = idxs[bid * batch_size:]
else:
batch_idxs = idxs[bid * batch_size: (bid + 1) * batch_size]
batch_length=len(batch_idxs)
X1= np.zeros(... | identifier_body |
test_helper.go | that has a path by the value of TEST_ENV_FILE_PATH environment variable.
func LoadEnvFile(t *testing.T) error {
envFileName := os.Getenv(TestEnvFilePath)
err := godotenv.Load(envFileName)
if err != nil {
return fmt.Errorf("Can not read .env file: %s", envFileName)
}
return nil
}
// InitializeTestValu... |
return false
},
)
return err == nil
}
//CheckSQLConnectivity checks if we can successfully connect to a SQL Managed Instance, MySql server or Azure SQL | {
t.Log("Warning: 404 response from endpoint. Test will still PASS.")
return true
} | conditional_block |
test_helper.go | that has a path by the value of TEST_ENV_FILE_PATH environment variable.
func LoadEnvFile(t *testing.T) error {
envFileName := os.Getenv(TestEnvFilePath)
err := godotenv.Load(envFileName)
if err != nil {
return fmt.Errorf("Can not read .env file: %s", envFileName)
}
return nil
}
// InitializeTestValu... | }
return s
}
func getPropertyValueFromString(object string, propertyKey string) string {
// compile regex to look for key="value"
regexString := fmt.Sprintf(`%s=\"(.*?)\"`, propertyKey)
re := regexp.MustCompile(regexString)
match := string(re.Find([]byte(object)))
if len(match) == 0 {
log.Printf("W... | {
fields := reflect.ValueOf(s).Elem()
// iterate across all configuration properties
for i := 0; i < fields.NumField(); i++ {
typeField := fields.Type().Field(i)
environmentVariablesKey := typeField.Tag.Get("env")
if fields.Field(i).Kind() == reflect.String {
// check if we want a property inside a c... | identifier_body |
test_helper.go | }
func getPropertyValueFromString(object string, propertyKey string) string {
// compile regex to look for key="value"
regexString := fmt.Sprintf(`%s=\"(.*?)\"`, propertyKey)
re := regexp.MustCompile(regexString)
match := string(re.Find([]byte(object)))
if len(match) == 0 {
log.Printf("Warning: Could no... | redis.DialUseTLS(true))
if err != nil {
| random_line_split | |
test_helper.go | that has a path by the value of TEST_ENV_FILE_PATH environment variable.
func | (t *testing.T) error {
envFileName := os.Getenv(TestEnvFilePath)
err := godotenv.Load(envFileName)
if err != nil {
return fmt.Errorf("Can not read .env file: %s", envFileName)
}
return nil
}
// InitializeTestValuesE fill the value from environment variables.
func InitializeTestValues(s interface{}) in... | LoadEnvFile | identifier_name |
yolo-and-dlib.py | nets.Darknet19)
ct = CentroidTracker(maxDisappeared=5, maxDistance=50) # Look into 'CentroidTracker' for further info about parameters
trackers = [] # List of all dlib trackers
trackableObjects = {} # Dictionary of trackable objects containing object's ID and its' corresponding centroid/s
skip_frames = 10 # Numbers o... | (img, center, radius, color, thickness, width_scale=width_scale, height_scale=height_scale):
center = (int(center[0] * width_scale), int(center[1] * height_scale))
cv2.circle(img, center, radius, color, thickness)
# Python 3.5.6 does not support f-strings (next line will generate syntax error)
... | drawCircleCV2 | identifier_name |
yolo-and-dlib.py | , nets.Darknet19)
ct = CentroidTracker(maxDisappeared=5, maxDistance=50) # Look into 'CentroidTracker' for further info about parameters
trackers = [] # List of all dlib trackers
trackableObjects = {} # Dictionary of trackable objects containing object's ID and its' corresponding centroid/s
skip_frames = 10 # Numbers ... |
def drawCircleCV2(img, center, radius, color, thickness, width_scale=width_scale, height_scale=height_scale):
center = (int(center[0] * width_scale), int(center[1] * height_scale))
cv2.circle(img, center, radius, color, thickness)
# Python 3.5.6 does not support f-strings (next line will ... | pt = (int(pt[0] * width_scale), int(pt[1] * height_scale))
cv2.putText(img, text, pt, font, font_scale, color, lineType) | identifier_body |
yolo-and-dlib.py | trackableObjects = {} # Dictionary of trackable objects containing object's ID and its' corresponding centroid/s
skip_frames = 10 # Numbers of frames to skip from detecting
confidence_level = 0.40 # The confidence level of a detection
total = 0 # Total number of detected objects from classes of interest
use_original_vi... | total += 1
to.counted = True | conditional_block | |
yolo-and-dlib.py | import os
# For 'disable_v2_behavior' see https://github.com/theislab/scgen/issues/14
tf.disable_v2_behavior()
# Image size must be '416x416' as YoloV3 network expects that specific image size as input
img_size = 416
inputs = tf.placeholder(tf.float32, [None, img_size, img_size, 3])
model = nets.YOLOv3COCO(inputs, n... | import tensorflow.compat.v1 as tf | random_line_split | |
main.ts | [n] * this.times[n];
}
return total / this.totalTime;
}
}
export class GameScene extends Phaser.Scene {
private square: Phaser.GameObjects.Rectangle & { body: Phaser.Physics.Arcade.Body };
private terrain: Terrain = new Terrain();
private truck: Truck = new Truck();
private pickupTruck: Vehicles.Pic... |
public preload() {
Vehicles.PickupTruck.preload(this);
this.sceneData = (<BetweenLevelState>this.scene.settings.data) || new BetweenLevelState();
if (this.sceneData.startImmediately) {
this.isScrolling = true;
} else {
this.isScrolling = false;
}
this.truck.preload(this);
... | {
this.terrain = new Terrain();
this.truck = new Truck();
this.totalTime = 0;
this.startTruckTime = 0;
this.startTruckX = 0;
this.truckProgress = new ProgressCounter();
this.isLosing = false;
this.isLosingStartTime = 0;
this.isWinning = false;
this.isWinningStartTime =... | identifier_body |
main.ts | this.terrain = new Terrain();
this.truck = new Truck();
this.totalTime = 0;
this.startTruckTime = 0;
this.startTruckX = 0;
this.truckProgress = new ProgressCounter();
this.isLosing = false;
this.isLosingStartTime = 0;
this.isWinning = false;
this.isWinningStartTime = 0;
... | random_line_split | ||
main.ts |
this.progress.splice(0, cutoff);
this.times.splice(0, cutoff);
this.totalTime = 0;
this.times.forEach( time => this.totalTime += time );
}
}
getAverage() {
let total = 0;
for (let n = 0; n < this.progress.length; n++) {
total += this.progress[n] * this.times[n];
}
... | {
time -= this.times[n];
if (time < 1000) {
cutoff = n;
break;
}
} | conditional_block | |
main.ts | [n] * this.times[n];
}
return total / this.totalTime;
}
}
export class GameScene extends Phaser.Scene {
private square: Phaser.GameObjects.Rectangle & { body: Phaser.Physics.Arcade.Body };
private terrain: Terrain = new Terrain();
private truck: Truck = new Truck();
private pickupTruck: Vehicles.Pic... | () {
Vehicles.PickupTruck.preload(this);
this.sceneData = (<BetweenLevelState>this.scene.settings.data) || new BetweenLevelState();
if (this.sceneData.startImmediately) {
this.isScrolling = true;
} else {
this.isScrolling = false;
}
this.truck.preload(this);
this.load.imag... | preload | identifier_name |
lib.rs | of [`Child::wait_with_output`] to read output while setting a timeout.
//! This crate aims to fill in those gaps and simplify the implementation,
//! now that [`Receiver::recv_timeout`] exists.
//!
//! # Examples
//!
//! ```
//! use std::io;
//! use std::process::Command;
//! use std::process::Stdio;
//! use std::... | (&self, formatter: &mut Formatter<'_>) -> fmt::Result {
self.0.fmt(formatter)
}
}
impl From<process::ExitStatus> for ExitStatus {
#[inline]
fn from(value: process::ExitStatus) -> Self {
#[cfg_attr(windows, allow(clippy::useless_conversion))]
Self(value.into())
}
}
/// Equivalen... | fmt | identifier_name |
lib.rs | {
/// Terminates a process as immediately as the operating system allows.
///
/// Behavior should be equivalent to calling [`Child::kill`] for the same
/// process. However, this method does not require a reference of any kind
/// to the [`Child`] instance of the process, meaning that it can be cal... | {
imp::Handle::new(self).map(Terminator)
} | identifier_body | |
lib.rs | of [`Child::wait_with_output`] to read output while setting a timeout.
//! This crate aims to fill in those gaps and simplify the implementation,
//! now that [`Receiver::recv_timeout`] exists.
//!
//! # Examples
//!
//! ```
//! use std::io;
//! use std::process::Command;
//! use std::process::Stdio;
//! use std::... | ///
/// Instances can only be constructed using [`ChildExt::terminator`].
#[derive(Debug)]
pub struct Terminator(imp::Handle);
impl Terminator {
/// Terminates a process as immediately as the operating system allows.
///
/// Behavior should be equivalent to calling [`Child::kill`] for the same
/// proc... | mod timeout;
/// A wrapper that stores enough information to terminate a process. | random_line_split |
boundarypslg.py | :param points numpy.ndarray: array of PLC vertex coordinates.
:param adges numpy.ndarray: array of PLC tris (vertex topology).
:param holes numpy.ndarray: array of coordinates of holes in the PLC.
"""
self.points = points
self.tris = tris
self.holes = holes
def ... | """
def __init__(self, points, tris, holes):
"""Constructs BoundaryPLC object. | random_line_split | |
boundarypslg.py | dtype=np.int32)
v_adj[tris[:,0], tris[:,1]] = v_adj[tris[:,1], tris[:,0]] = 1
v_adj[tris[:,1], tris[:,2]] = v_adj[tris[:,2], tris[:,1]] = 1
v_adj[tris[:,2], tris[:,0]] = v_adj[tris[:,0], tris[:,2]] = 1
return np.array(np.where(np.triu(v_adj) == 1), dtype=np.int32).T
... |
holes[i] = np.vstack(holes[i]) if len(holes[i])\
else np.empty((0,2), dtype=np.float64)
return holes
def reindex_edges(points, points_ax, edges_ax):
"""Reindexes edges along a given axis.
:param points numpy.ndarray: all point coordinates.
:param points_... | points_ax = points[np.isclose(points[:,i], 0.)]
if points_ax.shape[0]:
holes[i].append([
0.5 * (points_ax[:,j].max() + points_ax[:,j].min()),
0.5 * (points_ax[:,k].max() + points_ax[:,k].min())
]) | conditional_block |
boundarypslg.py | dtype=np.int32)
v_adj[tris[:,0], tris[:,1]] = v_adj[tris[:,1], tris[:,0]] = 1
v_adj[tris[:,1], tris[:,2]] = v_adj[tris[:,2], tris[:,1]] = 1
v_adj[tris[:,2], tris[:,0]] = v_adj[tris[:,0], tris[:,2]] = 1
return np.array(np.where(np.triu(v_adj) == 1), dtype=np.int32).T
... |
perim = filter_colocated_points(perim, axis)
refined_points = [perim[0]]
for e in [[i, i+1] for i in range(perim.shape[0]-1)]:
e_len = perim[e[1], axis] - perim[e[0], axis]
ne = int(np.ceil(e_len / ds))
if ne > 1:
dse = e_len / ne
... | delta = np.diff(perim[:,axis])
keep_idx = np.hstack(([0], np.where(~np.isclose(delta,0.))[0] + 1))
return perim[keep_idx] | identifier_body |
boundarypslg.py | x[i] = vidx[0]
else:
perim_vidx[i] = v_count + v_count_new
v_count_new += 1
perim_edges[j] = np.array([
[perim_vidx[k], perim_vidx[k+1]] for k in range(v_count_perim-1)
])
perim_refined[j] = perim_refined[j][mask... | boundarypslg | identifier_name | |
config.go | environments = []string{development, integration, preproduction, production}
)
type (
KafkaReportingConfig struct {
SmsReportingTopic *string
SubscribeUnsubscribeReportingTopic *string
FcmReportingTopic *string
ApnsReportingTopic *string
}
// Postgres... | APNS: apns.Config{
Enabled: kingpin.Flag("apns", "Enable the APNS connector (by default, in Development mode)").
Envar(g("APNS")).
Bool(),
Production: kingpin.Flag("apns-production", "Enable the APNS connector in Production mode").
Envar(g("APNS_PRODUCTION")).
Bool(),
CertificateFileName: kin... | String(),
IntervalMetrics: &defaultFCMMetrics,
}, | random_line_split |
config.go | (),
PrometheusEndpoint: kingpin.Flag("prometheus-endpoint", `The metrics Prometheus endpoint to be used by the HTTP server (value for disabling it: "")`).
Default(defaultPrometheusEndpoint).
Envar(g("PROMETHEUS_ENDPOINT")).
String(),
TogglesEndpoint: kingpin.Flag("toggles-endpoint", `The Feature-Toggles en... | {
slist := make(tcpAddrList, 0)
s.SetValue(&slist)
return &slist
} | identifier_body | |
config.go | : file | memory | postgres ").
Default(defaultKVSBackend).
Envar(g("KVS")).
String(),
MS: kingpin.Flag("ms", "The message storage backend : file | memory").
Default(defaultMSBackend).
HintOptions("file", "memory").
Envar(g("MS")).
String(),
StoragePath: kingpin.Flag("storage-path", "The path f... | parseConfig | identifier_name | |
config.go | (defaultKVSBackend).
Envar(g("KVS")).
String(),
MS: kingpin.Flag("ms", "The message storage backend : file | memory").
Default(defaultMSBackend).
HintOptions("file", "memory").
Envar(g("MS")).
String(),
StoragePath: kingpin.Flag("storage-path", "The path for storing messages and key-value data if ... | {
return
} | conditional_block | |
SelectOneView.js | 外部赋值给该fiield,在值改变的同时
//* 需要同步调用rc-form的onchange和获取到对应的label来显示
//! 所以如果是data_source 就无法同步进行赋值,尽量减少外部修改data_source的值
const options = this.getOptions();
if (_.isEmpty(options) || !_.isEmpty(this.dataSource)) return;
const selected = _.find(options, { value: currentValue });
//* 传递valu... | && apiName === 'customer') {
_.set(selected, 'selected', [relatedParentData]);
_.set(selected, 'apiName', apiName);
_.set(selected, 'renderType', renderType);
}
this.setState({
selected: selected.selected,
});
if (onChange) {
const value = _.get(selected, 'selected[0].valu... | }
}
};
// 调用的回调函数
handleSelect = (selected) => {
const { handleCreate, fieldDesc, onChange, renderType, relatedParentData } = this.props;
const apiName = _.get(fieldDesc, 'api_name');
_.set(selected, 'apiName', apiName);
_.set(selected, 'renderType', renderType);
if (selected['selected'... | conditional_block |
SelectOneView.js | this.hasLayoutOptions = false;
this.state = {
selected: null,
ModalSelector: false,
subordinateList: [],
};
}
componentDidMount() {
const { multipleSelect, token, renderType, placeholderVa
lue } = this.props;
if (!_.isEmpty(this.dataSource)) {
const { object_api_name, ... | fieldLayout, fieldDesc } = props;
const mergedObjectFieldDescribe = Object.assign({}, fieldDesc, fieldLayout);
//* data_source 配置项
this.dataSource = _.get(fieldLayout, 'data_source', {});
this.target_field = '';
// * 单选多选配置查询布局
this.targetRecordType =
_.get(fieldLayout, 'target_record_ty... | identifier_body | |
SelectOneView.js | 是外部赋值给该fiield,在值改变的同时
//* 需要同步调用rc-form的onchange和获取到对应的label来显示
//! 所以如果是data_source 就无法同步进行赋值,尽量减少外部修改data_source的值
const options = this.getOptions();
if (_.isEmpty(options) || !_.isEmpty(this.dataSource)) return;
const selected = _.find(options, { value: currentValue });
//* 传递val... | const tmpData = this.target_field ? _.get(fetchData, this.target_field) : fetchData;
if (_.get(tmpData, 'id') == val) {
selected.push({
label: labelExp ? executeDetailExp(labelExp, tmpData) : _.get(tmpData, 'name'),
value: val,
});
}
... | const selected = [];
const labelExp = _.get(fieldLayout, 'render_label_expression');
if (renderType === 'select_multiple' && placeholderValue) {
_.each(placeholderValue, (val) => {
_.each(fetchList, (fetchData) => { | random_line_split |
SelectOneView.js | const { fieldLayout, fieldDesc } = props;
const mergedObjectFieldDescribe = Object.assign({}, fieldDesc, fieldLayout);
//* data_source 配置项
this.dataSource = _.get(fieldLayout, 'data_source', {});
this.target_field = '';
// * 单选多选配置查询布局
this.targetRecordType =
_.get(fieldLayout, 'target_r... | rops);
| identifier_name | |
GUI test backup.py | _queue = mp.Queue()
# Creating the basic layouts.
root = FloatLayout()
scroll = ScrollView(pos_hint={"x": 0.12, "top": 0.92}, size_hint=(0.9, 1))
layout = GridLayout(cols=5, padding=0, spacing=5)
layout.bind(minimum_height=layout.setter("height"))
# Create the ActionBar... | path: The path to the photos shown, in "showphotos" layout.
"""
global layout
#Removes the widgets in the scroll layout, if there is any.
scroll.remove_widget(layout)
#Loads the new updated layout, and updates the showphotos layout.
layout = self._showphotos(... | random_line_split | |
GUI test backup.py | _queue = mp.Queue()
# Creating the basic layouts.
root = FloatLayout()
scroll = ScrollView(pos_hint={"x": 0.12, "top": 0.92}, size_hint=(0.9, 1))
layout = GridLayout(cols=5, padding=0, spacing=5)
layout.bind(minimum_height=layout.setter("height"))
# Create the ActionBar... |
def _validate(self, fileChooser):
"""
Function to add the path chosen by user to "curdir" and initiate functions that needs to be run.
Args:
fileChooser: Takes the path chosen by the user.
Returns:
None, but initiates several other functions.
"""... | global progress
progress_bar = ProgressBar(max=max)
popup = Popup(title="Filtering and sorting pictures",
content=progress_bar)
progress_bar.value = progress
popup.open() | identifier_body |
GUI test backup.py | _queue = mp.Queue()
# Creating the basic layouts.
root = FloatLayout()
scroll = ScrollView(pos_hint={"x": 0.12, "top": 0.92}, size_hint=(0.9, 1))
layout = GridLayout(cols=5, padding=0, spacing=5)
layout.bind(minimum_height=layout.setter("height"))
# Create the ActionBar... | (self):
global sorting_queue
filter_path = join(curdir, "filtered")
onlyfiles = [f for f in listdir(filter_path) if isfile(join(filter_path, f))]
for i in range(0, len(onlyfiles)):
j = onlyfiles[i]
onlyfiles[i] = join(filter_path, j)
files = []
... | _cnn | identifier_name |
GUI test backup.py | , 0.92))
#If "curdir" contains folders, a button is created for each, and bind the button to update the
# showphotos layout.
if curdir == " ":
return sidepanel_layout
else:
root.remove_widget(sidepanel_layout)
for folders in sorted(glob(join(curdir, "... | print("Pictures belongs to Gabrielle")
thumb.save(join(curdir, "thumb", "Gabrielle", picture_name), "JPEG") | conditional_block | |
app.rs | {
name: String,
nunlinked: u64,
nunlinks: u64,
nread: u64,
reads: u64,
nwritten: u64,
writes: u64,
}
impl Snapshot {
fn compute(&self, prev: Option<&Self>, etime: f64) -> Element {
if let Some(prev) = prev {
Element {
name: self.na... | Snapshot | identifier_name | |
app.rs | Map<String, Snapshot>,
prev_ts: Option<TimeSpec>,
cur: BTreeMap<String, Snapshot>,
cur_ts: Option<TimeSpec>,
pools: Vec<String>,
}
impl DataSource {
fn new(children: bool, pools: Vec<String>) -> Self {
DataSource {
children,
pools,
..Default::d... | None => NonZeroUsize::new(1),
Some(x) => NonZeroUsize::new(x.get() + 1),
} | random_line_split | |
vr-party-participant.js | }
function clearMessage() {
$('#layer3').hide();
$('#layer2').show();
}
function launchViewer(urn) {
_baseDir = null;
_leftLoaded = _rightLoaded = false;
_updatingLeft = _updatingRight = false;
//_upVector = new THREE.Vector3(0, 1, 0);
_orbitInitialPosition = null;
if (urn) {
... |
function unwatchCameras() {
if (_viewerLeft) {
_viewerLeft | {
_viewerLeft.addEventListener('cameraChanged', left2right);
_viewerRight.addEventListener('cameraChanged', right2left);
} | identifier_body |
vr-party-participant.js | else {
Autodesk.Viewing.Initializer(getViewingOptions(), function() {
var avp = Autodesk.Viewing.Private;
avp.GPU_OBJECT_LIMIT = 100000;
avp.onDemandLoading = false;
showMessage('Waiting...');
if (_sessionId === "demo") {
launchVi... | initConnection();
});
}
);
} | random_line_split | |
vr-party-participant.js | ('Disconnected', true);
_viewerLeft.uninitialize();
_viewerRight.uninitialize();
_viewerLeft = new Autodesk.Viewing.Viewer3D($('#viewerLeft')[0]);
_viewerRight = new Autodesk.Viewing.Viewer3D($('#viewerRight')[0]);
}
}
function forceWidth(viewer) {
viewer.contai... | orb | identifier_name | |
vr-party-participant.js | }
function clearMessage() {
$('#layer3').hide();
$('#layer2').show();
}
function launchViewer(urn) {
_baseDir = null;
_leftLoaded = _rightLoaded = false;
_updatingLeft = _updatingRight = false;
//_upVector = new THREE.Vector3(0, 1, 0);
_orbitInitialPosition = null;
if (urn) {
... |
console.log('Applied zoom');
watchTilt();
}
if (_model_state.explode_factor !== undefined) {
viewersApply('explode', _model_state.explode_factor);
_model_state.explode_factor = undefined;
console.log('Applied explode');
}
if (_model_state.isolate_... | {
orbitViews(_lastVert, _lastHoriz);
} | conditional_block |
main.py | = df.drop("birth_year", axis=1) #Drop birth_year for clustering; consider it for interpretation
df = df[df["first_policy"]<50000] #Drop one case where first_policy year <50000
#df = df[~(df["premium_motor"]==0)&~(df["premium_household"]==0)&~(df["premium_health"]==0)&~(df["premium_life"]==0)&~(df["premium_work_comp"]... | temp = [sum(1 for p in premiums if p < 0) for i, premiums in df[['premium_motor','premium_household','premium_health', 'premium_life','premium_work_comp']].iterrows()]
df["cancelled_contracts"] = [1 if i != 0 else 0 for i in temp]
# True if customers has premium for every part
temp = [sum(1 for p in premiums if p > 0) ... | random_line_split | |
main.py | = df.drop("birth_year", axis=1) #Drop birth_year for clustering; consider it for interpretation
df = df[df["first_policy"]<50000] #Drop one case where first_policy year <50000
#df = df[~(df["premium_motor"]==0)&~(df["premium_household"]==0)&~(df["premium_health"]==0)&~(df["premium_life"]==0)&~(df["premium_work_comp"]... |
else:
X = df[cols | y_pred = trained_models[', '.join(cols)].predict([df_topredc.loc[i,cols]])
pred_cclusters.append(y_pred[0])
continue | conditional_block |
moc_guestagent_exec.pb.go | 3" json:"Execs,omitempty"`
Result *wrappers.BoolValue `protobuf:"bytes,2,opt,name=Result,proto3" json:"Result,omitempty"`
Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized ... | () int {
return xxx_messageInfo_ExecResponse.Size(m)
}
func (m *ExecResponse) XXX_DiscardUnknown() {
xxx_messageInfo_ExecResponse.DiscardUnknown(m)
}
var xxx_messageInfo_ExecResponse proto.InternalMessageInfo
func (m *ExecResponse) GetExecs() []*Exec {
if m != nil {
return m.Execs
}
return nil
}
func (m *Exec... | XXX_Size | identifier_name |
moc_guestagent_exec.pb.go | 3" json:"Execs,omitempty"`
Result *wrappers.BoolValue `protobuf:"bytes,2,opt,name=Result,proto3" json:"Result,omitempty"`
Error string `protobuf:"bytes,3,opt,name=Error,proto3" json:"Error,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized ... |
return nil
}
func (m *ExecResponse) GetError() string {
if m != nil {
return m.Error
}
return ""
}
type Exec struct {
Command string `protobuf:"bytes,1,opt,name=command,proto3" json:"command,omitempty"`
Output string `protobuf:"bytes,2,opt,name=output,proto3" json:"... | {
return m.Result
} | conditional_block |
moc_guestagent_exec.pb.go | x95, 0x3a, 0x30, 0x21, 0x02, 0x62, 0x40, 0x82, 0x2a, 0x75, 0xdd,
0x10, 0x91, 0xe4, 0x67, 0xfc, 0x07, 0xca, 0x2b, 0xf0, 0xd4, 0xc8, 0x76, 0x4a, 0x85, 0x84, 0x3a,
0x30, 0x45, 0x9f, 0xbf, 0x7f, 0xf1, 0x97, 0xa0, 0x31, 0xdf, 0x70, 0x46, 0x1b, 0x60, 0x8b, 0xd2,
0x70, 0xa5, 0x8b, 0x92, 0xb7, 0x7a, 0x61, 0xcf, 0x88, 0x90, ... | random_line_split | ||
moc_guestagent_exec.pb.go |
func (m *ExecRequest) XXX_Merge(src proto.Message) {
xxx_messageInfo_ExecRequest.Merge(m, src)
}
func (m *ExecRequest) XXX_Size() int {
return xxx_messageInfo_ExecRequest.Size(m)
}
func (m *ExecRequest) XXX_DiscardUnknown() {
xxx_messageInfo_ExecRequest.DiscardUnknown(m)
}
var xxx_messageInfo_ExecRequest proto.Int... | {
return xxx_messageInfo_ExecRequest.Marshal(b, m, deterministic)
} | identifier_body | |
generate_synthetic_immunoblot_dataset.py | 'norm_EC-RP']],
measured_variables={'norm_IC-RP': 'semi-quantitative',
'norm_EC-RP': 'semi-quantitative'})
dataset.measurement_error_df = fluorescence_data[['nrm_var_IC-RP', 'nrm_var_EC-RP']].\
rename(columns={'nrm_var_IC-RP': 'norm_IC-RP__error',
... |
IC_RP__n_cats = immunoblot_number_of_categories(dataset.measurement_error_df['norm_IC-RP__error'])
EC_RP__n_cats = immunoblot_number_of_categories(dataset.measurement_error_df['norm_EC-RP__error'])
# ------- Immunoblot Data Set -------
ordinal_dataset_size = 14 # 28, 16, 14, 7 divide evenly into the total 112 rows... | data_rms = np.sqrt(variances).mean()
z_stat = norm.ppf(1 - expected_misclassification_rate)
peak_noise = z_stat*data_rms
signal_to_noise_ratio = 20*np.log10(peak_noise/data_range)
effective_number_of_bits = -(signal_to_noise_ratio+1.76)/6.02
return int(np.floor(0.70*(2**effective_number_of_bits))) ... | identifier_body |
generate_synthetic_immunoblot_dataset.py | '__main__':
plt.plot(measurement_results['time'], measurement_results['cPARP_obs'], label=f'simulated PARP cleavage')
plt.plot(fluorescence_data['time'], fluorescence_data['norm_EC-RP'], '--', label=f'norm_EC-RP data', color=cm.colors[0])
plt.fill_between(fluorescence_data['time'],
flu... | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 6), sharey='all', gridspec_kw={'width_ratios': [2, 1]})
ax1.scatter(x=synthetic_immunoblot_data.data['time'],
y=synthetic_immunoblot_data.data['cPARP_blot'].values / (EC_RP__n_cats-1),
s=10, color=cm.colors[0], label=f'cPARP blot data... | conditional_block | |
generate_synthetic_immunoblot_dataset.py | 'norm_EC-RP']],
measured_variables={'norm_IC-RP': 'semi-quantitative',
'norm_EC-RP': 'semi-quantitative'})
dataset.measurement_error_df = fluorescence_data[['nrm_var_IC-RP', 'nrm_var_EC-RP']].\
rename(columns={'nrm_var_IC-RP': 'norm_IC-RP__error',
... | lc_results = lc.transform(plot_domain)
cPARP_results = lc_results.filter(regex='cPARP_blot')
tBID_results = lc_results.filter(regex='tBID_blot')
# ------- Synthetic Immunoblot Data -------
n = 180
time_span = list(range(fluorescence_data['time'].max()))[::n] # ::30 = one measurement per 30s; 6x fluorescence data
x_s... |
# plot classifier
lc.do_fit_transform = False
plot_domain = pd.DataFrame({'tBID_obs': np.linspace(0, 1, 100), 'cPARP_obs': np.linspace(0, 1, 100)}) | random_line_split |
generate_synthetic_immunoblot_dataset.py | 'norm_EC-RP']],
measured_variables={'norm_IC-RP': 'semi-quantitative',
'norm_EC-RP': 'semi-quantitative'})
dataset.measurement_error_df = fluorescence_data[['nrm_var_IC-RP', 'nrm_var_EC-RP']].\
rename(columns={'nrm_var_IC-RP': 'norm_IC-RP__error',
... | (variances, expected_misclassification_rate=0.05, data_range=1):
# Effective Number of Bits in Fluorescence Data
# ref -- https://en.wikipedia.org/wiki/Effective_number_of_bits
# Fluorescence data was normalized to 0-1 :. data_range=1.
data_rms = np.sqrt(variances).mean()
z_stat = norm.ppf(1 - expec... | immunoblot_number_of_categories | identifier_name |
media.py | 64
import typing
import logging
import pathlib
import zipfile
import functools
import mimetypes
import urllib.parse
import urllib.request
from clldutils.misc import lazyproperty, log_or_raise
import pycldf
from pycldf import orm
from csvw.datatypes import anyURI
__all__ = ['Mimetype', 'MediaTable', 'File']
class Fi... |
def __eq__(self, other):
return self.string == other if isinstance(other, str) else \
(self.type, self.subtype) == (other.type, other.subtype)
@property
def is_text(self) -> bool:
return self.type == 'text'
@property
def extension(self) -> typing.Union[None, str]:
... | self.string = s
mtype, _, param = self.string.partition(';')
param = param.strip()
self.type, _, self.subtype = mtype.partition('/')
if param.startswith('charset='):
self.encoding = param.replace('charset=', '').strip()
else:
self.encoding = 'utf8' | identifier_body |
media.py | base64
import typing
import logging
import pathlib
import zipfile
import functools
import mimetypes
import urllib.parse
import urllib.request
from clldutils.misc import lazyproperty, log_or_raise
import pycldf
from pycldf import orm
from csvw.datatypes import anyURI
__all__ = ['Mimetype', 'MediaTable', 'File']
cla... | zipcontent = self.local_path(d).read_bytes()
if self.url:
zipcontent = self.url_reader[self.scheme](
self.parsed_url, Mimetype('application/zip'))
if zipcontent:
zf = zipfile.ZipFile(io.BytesIO(zipcontent))
retur... | if d: | random_line_split |
media.py | 64
import typing
import logging
import pathlib
import zipfile
import functools
import mimetypes
import urllib.parse
import urllib.request
from clldutils.misc import lazyproperty, log_or_raise
import pycldf
from pycldf import orm
from csvw.datatypes import anyURI
__all__ = ['Mimetype', 'MediaTable', 'File']
class Fi... | (self, d=None) -> typing.Union[None, str, bytes]:
"""
:param d: A local directory where the file has been saved before. If `None`, the content \
will read from the file's URL.
"""
if self.path_in_zip:
zipcontent = None
if d:
zipcontent = se... | read | identifier_name |
media.py | 64
import typing
import logging
import pathlib
import zipfile
import functools
import mimetypes
import urllib.parse
import urllib.request
from clldutils.misc import lazyproperty, log_or_raise
import pycldf
from pycldf import orm
from csvw.datatypes import anyURI
__all__ = ['Mimetype', 'MediaTable', 'File']
class Fi... |
if self.url:
self.url = anyURI.to_string(self.url)
self.parsed_url = urllib.parse.urlparse(self.url)
self.scheme = self.parsed_url.scheme
@classmethod
def from_dataset(
cls, ds: pycldf.Dataset, row_or_object: typing.Union[dict, orm.Media]) -> 'File':
... | if media.id_col and media.id_col.valueUrl:
self.url = media.id_col.valueUrl.expand(**row) | conditional_block |
ui.js | AVANT DE RECEVOIR-UN-DOIGT()
//
if (doigt.estLeve) {
if (dessus) {
//on a eu un mouseDOWN
if (this.actionOnClick) {
//console.log("mUp YES YES YES ", this)
this.actionOnClick( doigt )
ok = true
}
else {
console.log("mUp (without an action?)")
}
... | var i,tot,d,circ,p, zonesDoigts
zonesDoigts = luimeme.zonesDoigts
tot = zonesDoigts.length
for(i=0; i<tot; i++) {
circ = zonesDoigts[i]
circ.visible = false
//c.position.x = -100
//c.position.y = -100
}
var layer = luimeme.layer
tot = someFingers.length
for(i=0; i<tot; i++) {
... | identifier_body | |
ui.js | ==undefined) derniers = 10
//
var tot,i,j,d,sum,ponderation, a
ponderation = 0.0
sum = {x:0, y:0}
tot = dlst.length
a = Math.max( 0, tot-derniers )
for(i=a, j=1; i<tot; i++, j++) {
d = dlst[i]
sum.x = sum.x + (d.x * j)
sum.y = sum.y + (d.y * j)
ponderation += j
//onsole.log( " ... | CI ON S'EN FOUT SI INSIDE OU NON?
btn = doigt.target
//
if (btn && btn.hitArea) dessus = btn.hitArea.contains( tempPoint.x, tempPoint.y )
//onsole.log("on connait l'objet, YÉ: ", btn.hitArea, dessus, tempPoint )
}
//secu | conditional_block | |
ui.js | var w,h,ln, coin, scale
scale = this.scales[ icoScale ]
coin = this.coins[ icoScale ]
ln = this.lineSize[ icoScale ]
w = this.sizes[ icoScale ]
h = w - Math.floor(w/10)
// pale 59b6b9
// dark 2f6771
sp = new PIXI.Graphics()
base.addChild( sp )
sp.lineStyle( 0 ) //ln, this.lineCo... | st, derniers ) {
if (derniers==null || derniers==undefined) derniers = 10
//
var tot,i,j,d,sum,ponderation, a
ponderation = 0.0
sum = {x:0, y:0}
tot = dlst.length
a = Math.max( 0, tot-derniers )
for(i=a, j=1; i<tot; i++, j++) {
d = dlst[i]
sum.x = sum.x + (d.x * j)
sum.y = sum.y + (d... | Vitesse( dl | identifier_name |
ui.js | textColorLT : 0x95e3ff,
path : svp_paths( "app/media/ui/" )
//app_paths.app + '/media/ui/'
}
ui.addBtn = function( layer, icoName, icoScale, actionOnClick, bigw, bigh ) {
var sp,ico
var baseAlpha = 0.8
var base = new PIXI.Container()
layer.addChild( base )
//sp.anchor.x = sp.anchor.y ... | fillColor : 0x95e3ff, //0x77d4f4, //0xb2f1ff, //0x95e4f6, ////0x89d3e4, //0x59b6b9,
textColor : 0x6fcbf0, //0x8dd0d5, //0xb7f2ff, //0xdbfbff, ///0xcef6ff, //b2f8f3, | random_line_split | |
manterGrupoTaxaControle.js | }else{
consultar = true;
}
if (consultar){
//_this.$el.find('#listaGrupoTaxa').removeClass("hidden");
loadCCR.start();
// var codigo=0;
// var nome="teste";
// lista taxas
_this.getCollection().buscar(codigo,nome)
.done(function sucesso(data) {
_thi... |
atualizar: function(){
_/*this.consultarTaxaIOF();
$('ul.nav a#manterTaxaIOF.links-menu').trigger('click');*/
} | random_line_split | |
manterGrupoTaxaControle.js | id : null,
codRet : null,
nomeRet : null,
/**
* Função que faz bind das ações e interações da pagina com as funções
* javascript
*
*/
events : {
'click a#btnConsultarGrupoTaxa' : 'consultarGrupoTaxa',
'click a#btnNovoGrupoTaxa' : 'novoGrupoTaxa',
'click a#btnLimparForm' : 'l... | //'oLanguage' : {'sEmptyTable' : 'Nenhum registro encontrado.', 'sLengthMenu': '_MENU_ registros por página'} //Sobrescreve o sEmptyTable do jquery.dataTable.js do fec-web.
'oLanguage' : {'sEmptyTable' : 'Nenhum registro encontrado.', 'sLengthMenu': '_MENU_ registros por página', 'sInfoFiltered' : '(Filtrad... | .find('#listaGrupoTaxa').removeClass("hidden");
loadCCR.start();
// var codigo=0;
// var nome="teste";
// lista taxas
_this.getCollection().buscar(codigo,nome)
.done(function sucesso(data) {
_this.$el.find('#divListaGrupoTaxaShow').removeClass("hidden");
Retorno.trataR... | conditional_block |
bip32.rs | _be_bytes(n as u64 + (1 << 31), 4, |raw| hmac.input(raw));
}
}
hmac.raw_result(result.as_mut_slice());
let mut sk = try!(SecretKey::from_slice(result.slice_to(32)).map_err(EcdsaError));
try!(sk.add_assign(&self.secret_key).map_err(EcdsaError));
Ok(ExtendedPrivKey {
network: self.network... | data.slice(45, 78)).map_err(|e|
OtherBase5 | {
if data.len() != 78 {
return Err(InvalidLength(data.len()));
}
let cn_int = u64_from_be_bytes(data.as_slice(), 9, 4) as u32;
let child_number = if cn_int < (1 << 31) { Normal(cn_int) }
else { Hardened(cn_int - (1 << 31)) };
Ok(ExtendedPubKey {
network: match da... | identifier_body |
bip32.rs | (master: &ExtendedPrivKey, path: &[ChildNumber])
-> Result<ExtendedPrivKey, Error> {
let mut sk = *master;
for &num in path.iter() {
sk = try!(sk.ckd_priv(num));
}
Ok(sk)
}
/// Private->Private child key derivation
pub fn ckd_priv(&self, i: ChildNumber) -> Result<Extended... | from_path | identifier_name | |
bip32.rs | impl Default for Fingerprint {
fn default() -> Fingerprint { Fingerprint([0, 0, 0, 0]) }
}
/// Extended private key
#[deriving(Clone, PartialEq, Eq, Encodable, Decodable, Show)]
pub struct ExtendedPrivKey {
/// The network this key is to be used on
pub network: Network,
/// How many derivations this key is fro... | impl_array_newtype!(Fingerprint, u8, 4)
impl_array_newtype_show!(Fingerprint)
impl_array_newtype_encodable!(Fingerprint, u8, 4)
| random_line_split | |
f2s.rs | 0 >> 32) + bits1;
let shifted_sum = sum >> (shift - 32);
debug_assert!(shifted_sum <= u32::max_value() as u64);
shifted_sum as u32
}
#[cfg_attr(feature = "no-panic", inline)]
fn mul_pow5_inv_div_pow2(m: u32, q: u32, j: i32) -> u32 {
debug_assert!(q < FLOAT_POW5_INV_SPLIT.len() as u32);
unsafe { mul... | {
// Specialized for the common case (~96.0%). Percentages below are relative to this.
// Loop iterations below (approximately):
// 0: 13.6%, 1: 70.7%, 2: 14.1%, 3: 1.39%, 4: 0.14%, 5+: 0.01%
while vp / 10 > vm / 10 {
last_removed_digit = (vr % 10) as u8;
vr /= 10... | conditional_block | |
f2s.rs | 958651173080,
340282366920938464,
544451787073501542,
435561429658801234,
348449143727040987,
557518629963265579,
446014903970612463,
356811923176489971,
570899077082383953,
456719261665907162,
365375409332725730,
1 << 63,
];
static FLOAT_POW5_SPLIT: [u64; 47] = [
115292... | (m: u32, q: u32, j: i32) -> u32 {
debug_assert!(q < FLOAT_POW5_INV_SPLIT.len() as u32);
unsafe { mul_shift(m, *FLOAT_POW5_INV_SPLIT.get_unchecked(q as usize), j) }
}
#[cfg_attr(feature = "no-panic", inline)]
fn mul_pow5_div_pow2(m: u32, i: u32, j: i32) -> u32 {
debug_assert!(i < FLOAT_POW5_SPLIT.len() as u... | mul_pow5_inv_div_pow2 | identifier_name |
f2s.rs | 958651173080,
340282366920938464,
544451787073501542,
435561429658801234,
348449143727040987,
557518629963265579,
446014903970612463,
356811923176489971,
570899077082383953,
456719261665907162,
365375409332725730,
1 << 63,
];
static FLOAT_POW5_SPLIT: [u64; 47] = [
115292... |
// Returns true if value is divisible by 5^p.
#[cfg_attr(feature = "no-panic", inline)]
fn multiple_of_power_of_5(value: u32, p: u32) -> bool {
pow5_factor(value) >= p
}
// Returns true if value is divisible by 2^p.
#[cfg_attr(feature = "no-panic", inline)]
fn multiple_of_power_of_2(value: u32, p: u32) -> bool {
... | }
count
} | random_line_split |
discovery.pb.go | ,proto3,enum=grafeas.v1.NoteKind" json:"analysis_kind,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Discovery) Reset() { *m = Discovery{} }
func (m *Discovery) ... | proto.RegisterEnum("grafeas.v1.discovery.Discovered_ContinuousAnalysis", Discovered_ContinuousAnalysis_name, Discovered_ContinuousAnalysis_value)
proto.RegisterEnum("grafeas.v1.discovery.Discovered_AnalysisStatus", Discovered_AnalysisStatus_name, Discovered_AnalysisStatus_value)
proto.RegisterType((*Discovery)(nil),... | return nil
}
func init() { | random_line_split |
discovery.pb.go | 3,enum=grafeas.v1.NoteKind" json:"analysis_kind,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Discovery) Reset() { *m = Discovery{} }
func (m *Discovery) String... |
return nil
}
func init() {
proto.RegisterEnum("grafeas.v1.discovery.Discovered_ContinuousAnalysis", Discovered_ContinuousAnalysis_name, Discovered_ContinuousAnalysis_value)
proto.RegisterEnum("grafeas.v1.discovery.Discovered_AnalysisStatus", Discovered_AnalysisStatus_name, Discovered_AnalysisStatus_value)
proto.R... | {
return m.AnalysisStatusError
} | conditional_block |
discovery.pb.go | ,proto3,enum=grafeas.v1.NoteKind" json:"analysis_kind,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *Discovery) Reset() { *m = Discovery{} }
func (m *Discovery) ... | () *Discovered {
if m != nil {
return m.Discovered
}
return nil
}
// Provides information about the analysis status of a discovered resource.
type Discovered struct {
// Whether the resource is continuously analyzed.
ContinuousAnalysis Discovered_ContinuousAnalysis `protobuf:"varint,1,opt,name=continuous_analys... | GetDiscovered | identifier_name |
discovery.pb.go |
func (Discovered_AnalysisStatus) EnumDescriptor() ([]byte, []int) {
return fileDescriptor_046437f686d0269e, []int{2, 1}
}
// DO NOT USE: UNDER HEAVY DEVELOPMENT.
// TODO(aysylu): finalize this.
//
// A note that indicates a type of analysis a provider would perform. This note
// exists in a provider's project. A `D... | {
return proto.EnumName(Discovered_AnalysisStatus_name, int32(x))
} | identifier_body | |
word2vec.py | 1
from mixins import BoardRecorderMixin
class DistributedRepresentations:
|
def inspect(self):
rels = np.dot(self.normalized_vecs, self.normalized_vecs.T)
printoptions = np.get_printoptions()
np.set_printoptions(linewidth=200, precision=6)
for word, vec in zip(self.words, rels):
print(f'{word + ":":8s} {vec}')
np.set_printoptions(**print... | """Distributed Represendations of the words.
Args:
words (list): List of words
vectors (numpy.array): Vectors encoded words
Attributes:
vecs (numpy.array): Vectors encoded words
words (list): List of words
"""
def __init__(self, words, vectors):
self.words = wor... | identifier_body |
word2vec.py | 1
from mixins import BoardRecorderMixin
class DistributedRepresentations:
"""Distributed Represendations of the words.
Args:
words (list): List of words
vectors (numpy.array): Vectors encoded words
Attributes:
vecs (numpy.array): Vectors encoded words
words (list): List ... | (self):
raise NotImplementedError
def get_labels(self):
raise NotImplementedError
def fetch_batch(self, incomes, labels, epoch_i, batch_i, batch_size):
raise NotImplementedError
def train(self, log_dir=None, max_epoch=10000, learning_rate=0.001,
batch_size=None, inte... | get_incomes | identifier_name |
word2vec.py | the words.
Args:
words (list): List of words
vectors (numpy.array): Vectors encoded words
Attributes:
vecs (numpy.array): Vectors encoded words
words (list): List of words
"""
def __init__(self, words, vectors):
self.words = words
self.vecs = vectors
... | writer.add_run_metadata(metadata, f'step: {step}') | conditional_block | |
word2vec.py | 1
from mixins import BoardRecorderMixin
class DistributedRepresentations:
"""Distributed Represendations of the words.
Args:
words (list): List of words
vectors (numpy.array): Vectors encoded words
Attributes:
vecs (numpy.array): Vectors encoded words
words (list): List ... | feed_dict=fd,
options=options,
run | }
sess.run(self.training_op, | random_line_split |
elasticsearch_adapter.js | Successfully removed indices: "${indicesToRemove}"`);
} catch (err) {
Services.logger.warning(`Error when trying to remove indices: ${err}`);
}
}
}
/**
*
* @param {FilterBuilder} builder
* @return {Object} The result of <code>builder.build()</code> but with a few translations for ES
*... | {
res.items.forEach(error => {
errors.push(new NexxusError('ServerFailure', `Error creating ${error.index._type}: ${error.index.error}`));
});
} | conditional_block | |
elasticsearch_adapter.js | ;
this[tryConnectionMethod]();
}
[tryConnectionMethod] () {
let error = false;
async.doWhilst(callback => {
this.connection.ping({}, (err, res) => {
if (!err) {
Services.logger.info('Connected to ElasticSearch MainDatabase');
this.connected = true;
return setImmediate(callback);
}
... |
if (modifications.deleted.schema) {
const removedModels = Object.keys(modifications.deleted.schema);
const indicesToRemove = removedModels.map(modelName => `${constants.CHANNEL_KEY_PREFIX}-${applicationId}-${modelName}`);
try {
await this.connection.indices.delete({
index: indicesToRemove
});
... | {
if (modifications.added.schema) {
const addedModels = Object.keys(modifications.added.schema);
await addedModels.reduce(async (promise, modelName) => {
await promise;
try {
await this.connection.indices.create({
index: `${constants.CHANNEL_KEY_PREFIX}-${applicationId}-${modelName}`
}... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.