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 |
|---|---|---|---|---|
lib.rs | //! See the `Bitmap` type.
/// A dense bitmap, intended to store small bitslices (<= width of usize).
pub struct Bitmap {
entries: usize,
width: usize,
// Avoid a vector here because we have our own bounds checking, and
// don't want to duplicate the length, or panic.
data: *mut u8,
}
#[inline(alw... | else {
let mut bit_offset = i * self.width;
let mut in_byte_offset = bit_offset % 8;
let mut byte_offset = (bit_offset - in_byte_offset) / 8;
let mut bits_left = self.width;
let mut value: usize = 0;
while bits_left > 0 {
// ho... | {
None
} | conditional_block |
lib.rs | //! See the `Bitmap` type.
/// A dense bitmap, intended to store small bitslices (<= width of usize).
pub struct Bitmap {
entries: usize,
width: usize,
// Avoid a vector here because we have our own bounds checking, and
// don't want to duplicate the length, or panic.
data: *mut u8,
}
#[inline(alw... |
while bits_left > 0 {
let can_set = std::cmp::min(8 - in_byte_offset, bits_left);
// pull out the highest can_set bits from value
let mut to_set: usize = value >> (usize - can_set);
// move them into where they will live
to_se... | let mut bits_left = self.width; | random_line_split |
lib.rs | //! See the `Bitmap` type.
/// A dense bitmap, intended to store small bitslices (<= width of usize).
pub struct Bitmap {
entries: usize,
width: usize,
// Avoid a vector here because we have our own bounds checking, and
// don't want to duplicate the length, or panic.
data: *mut u8,
}
#[inline(alw... |
pub fn iter(&self) -> Slices {
Slices { idx: 0, bm: self }
}
/// Get the raw pointer to this Bitmap's data.
pub unsafe fn get_ptr(&self) -> *mut u8 {
self.data
}
/// Set the raw pointer to this Bitmap's data, returning the old one. It needs to be free'd
/// with `Vec`'s d... | {
// can't overflow, since creation asserts that it doesn't.
let w = self.entries * self.width;
let r = w % 8;
(w + r) / 8
} | identifier_body |
message.go | package main
import (
"fmt"
"log"
"encoding/json"
"github.com/googollee/go-socket.io"
)
/******************************************************************************
This file contains all functionality that is sent between the communication
channel instances of Lobby and the User structs that it is responsi... |
(*l.tcpConn).Write(jsonMsg)
}
func (n NewSession) socketio(l *Lobby) {
(*l.socket).Emit("in", n)
}
/*
Sends an event from the Host User to inform the Application server that
it has loaded the Application and is ready to communicate.
Also implements Command (multiple interface implementation)
*/
type Launch str... | {
log.Print(err)
return
} | conditional_block |
message.go | package main
import (
"fmt"
"log"
"encoding/json"
"github.com/googollee/go-socket.io"
)
/******************************************************************************
This file contains all functionality that is sent between the communication
channel instances of Lobby and the User structs that it is responsi... | }
/*
Interface type: Commands received by the lobby for accessing/changing
the lobby data structure.
*/
type Command interface {
execute(l *Lobby)
}
/*
Contains all potential fields in the three specified events received from
Application servers: "created", "msgplayer" and "msgall"
Using omitempty, only requi... | (*l.tcpConn).Write(jsonMsg)
}
func (e End) socketio(l *Lobby) {
(*l.socket).Emit("in", e) | random_line_split |
message.go | package main
import (
"fmt"
"log"
"encoding/json"
"github.com/googollee/go-socket.io"
)
/******************************************************************************
This file contains all functionality that is sent between the communication
channel instances of Lobby and the User structs that it is responsi... | (l *Lobby) {
if len(l.users) != 0 {
(*h.Socket).Emit("hostlobby", false)
log.Print("manager.desktopSetup: lobby id entered already has a host user.")
return
}
err := l.addNewUser(h.Username, h.Socket)
if err != nil {
(*h.Socket).Emit("hostlobby", false)
log.Print(err)
return
}
(*h.Socket).Emit("hostlo... | execute | identifier_name |
message.go | package main
import (
"fmt"
"log"
"encoding/json"
"github.com/googollee/go-socket.io"
)
/******************************************************************************
This file contains all functionality that is sent between the communication
channel instances of Lobby and the User structs that it is responsi... |
/*
An event to force emit update for the list of users in the lobby.
*/
type Update struct {}
func (u Update) execute(l *Lobby) {
l.updateLobby()
}
/*
An event to attempt to prepare the Application server to begin the Application.
*/
type Start struct {}
func (s Start) execute(l *Lobby) {
room := l.lobbyId
va... | {
if len(l.users) == 0 {
(*j.Socket).Emit("joinlobby", false)
log.Print("manager.desktopSetup: lobby id entered does not have a host user.")
return
}
err := l.addNewUser(j.Username, j.Socket)
if err != nil {
(*j.Socket).Emit("joinlobby", false)
log.Print(err)
return
}
(*j.Socket).Emit("joinlobby", tru... | identifier_body |
ja-jp.ts | declare var define: any;
define([], (): IM365LPStrings => {
return {
WebpartTitleLabel: "Web パーツ タイトル (コンテンツのみモード)",
LPViewerPropertyDescription: "カスタム学習プロパティ",
LPViewerPropertyGroupName: "既定のビュー",
WebpartModeLabel: "Web パーツ モードを選択する",
WebpartModeDescription: "Web パーツの表示方法",
ShowNavigationLab... | PlaylistOverviewDesignMessage: "使用中、この領域には、表示されている再生リスト内の他の資産が表示されます。",
PlaylistOverviewHeading: "再生リストのすべての手順",
BurgerButton: "バーガー",
LinkButton: "リンク",
SearchButton: "検索",
AdministerPlaylist: "再生リストの管理",
NoSearchResults: "検索結果がクエリと一致しません。",
DefaultCDNLabel: "学習ソースを選択する",
DefaultCDN... | LinkPanelCopyLabel: "コピー",
HeaderPlaylistPanelCurrentPlaylistLabel: "現在の再生リスト:",
HeaderPlaylistPanelAdminHeader: "管理", | random_line_split |
torrent.go | /*
* Copyright (c) 2016 Mark Samman <https://github.com/marksamman/gotorrent>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the righ... |
func (torrent *Torrent) getDownloadedSize() int64 {
var downloadedSize int64
for k := range torrent.pieces {
if torrent.pieces[k].done {
downloadedSize += torrent.getPieceLength(uint32(k))
}
}
return downloadedSize
}
func (torrent *Torrent) connectToPeers(peers interface{}) {
switch peers := peers.(type)... | {
if res := torrent.totalSize % torrent.pieceLength; res != 0 {
return res
}
return torrent.pieceLength
} | identifier_body |
torrent.go | /*
* Copyright (c) 2016 Mark Samman <https://github.com/marksamman/gotorrent>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the righ... | } else {
if n, err := handle.ReadAt(buf[:bufPos], f.length-bufPos); err != nil || int64(n) != bufPos {
return
}
break
}
}
if torrent.checkPieceHash(buf[:pieceLength], pieceIndex) {
torrent.pieces[pieceIndex].done = true
torrent.completedPieces++
}
pos += pieceLength
pieceIndex++
... | }
bufPos -= f.length | random_line_split |
torrent.go | /*
* Copyright (c) 2016 Mark Samman <https://github.com/marksamman/gotorrent>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the righ... |
}
}
func (torrent *Torrent) checkPieceHash(data []byte, pieceIndex uint32) bool {
dataHash := sha1.Sum(data)
return bytes.Equal(dataHash[:], []byte(torrent.pieces[pieceIndex].hash))
}
func (torrent *Torrent) getPieceLength(pieceIndex uint32) int64 {
if pieceIndex == uint32(len(torrent.pieces))-1 {
if res := to... | {
select {
case trackerID := <-torrent.stoppedTrackerChannel:
for k, v := range torrent.activeTrackers {
if v == trackerID {
torrent.activeTrackers = append(torrent.activeTrackers[:k], torrent.activeTrackers[k+1:]...)
break
}
}
// Handle other messages that a Tracker may send
c... | conditional_block |
torrent.go | /*
* Copyright (c) 2016 Mark Samman <https://github.com/marksamman/gotorrent>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the righ... | () int64 {
if res := torrent.totalSize % torrent.pieceLength; res != 0 {
return res
}
return torrent.pieceLength
}
func (torrent *Torrent) getDownloadedSize() int64 {
var downloadedSize int64
for k := range torrent.pieces {
if torrent.pieces[k].done {
downloadedSize += torrent.getPieceLength(uint32(k))
}... | getLastPieceLength | identifier_name |
project_config.py | # -*- coding: utf-8 -*-
# author: Guixinyu
# create Time: 2019-10-17 18:15:39
from PyQt5.QtWidgets import *
import sys
import first
import fileselect
import shutil
from first import Ui_MainWindow
import AddLibraryPath
import Enterlibraries
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import os
import re
i... | conditional_block | ||
project_config.py | # -*- coding: utf-8 -*-
# author: Guixinyu
# create Time: 2019-10-17 18:15:39
from PyQt5.QtWidgets import *
import sys
import first
import fileselect
import shutil
from first import Ui_MainWindow
import AddLibraryPath
import Enterlibraries
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import os
import re
i... |
class BackendTread1(QThread):
startcompile1 = pyqtSignal(str)
endSig = pyqtSignal()
def __init__(self, parent=None):
super(BackendTread1, self).__init__(parent)
def startCom(self):
self.process = subprocess.Popen(cmd1)
def run(self):
#cmd1 = r'''%s\bin\make -j8 all >consol... | pyqtSignal(int)
def __init__(self, parent=None):
super(BackendTread, self).__init__(parent)
self.working=True
def stopSig(self):
self.working=False
def run(self):
#cmd1 = r'''%s\bin\make -j8 all >console.log 2>&1''' % Hdir
'''os.chdir(self.ProjectName_2.text() + '/De... | identifier_body |
project_config.py | # -*- coding: utf-8 -*-
# author: Guixinyu
# create Time: 2019-10-17 18:15:39
from PyQt5.QtWidgets import *
import sys
import first
import fileselect
import shutil
from first import Ui_MainWindow
import AddLibraryPath
import Enterlibraries
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import os
import re
i... | self.working=False
def run(self):
#cmd1 = r'''%s\bin\make -j8 all >console.log 2>&1''' % Hdir
'''os.chdir(self.ProjectName_2.text() + '/Default')
self.process = subprocess.call(cmd1)'''
while VAL<NUM and self.working:
num=0
for path,dir,files in os.walk(... | lf):
| identifier_name |
project_config.py | # -*- coding: utf-8 -*-
# author: Guixinyu
# create Time: 2019-10-17 18:15:39
from PyQt5.QtWidgets import *
import sys
import first
import fileselect
import shutil
from first import Ui_MainWindow
import AddLibraryPath
import Enterlibraries
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import os
import re
i... | for i in range(inn):
inpathNOW.append(self.includeList.item(i).text())
for i in range(exn):
expathNOW.append(self.excludeList.item(i).text())
f = open('./py.pyconfig', 'w', encoding='utf-8')
# lines=f.readlines()
tLink = re.spli... | ln = self.llist.count()
lnNOW = []
try: | random_line_split |
feature.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: tensorflow/core/example/feature.proto
/*
Package tensorflow is a generated protocol buffer package.
It is generated from these files:
tensorflow/core/example/feature.proto
It has these top-level messages:
BytesList
FloatList
Int64List
Feature
Features... | () string { return proto.CompactTextString(m) }
func (*FeatureList) ProtoMessage() {}
func (*FeatureList) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{5} }
func (m *FeatureList) GetFeature() []*Feature {
if m != nil {
return m.Feature
}
return nil
}
type FeatureLists stru... | String | identifier_name |
feature.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: tensorflow/core/example/feature.proto
/*
Package tensorflow is a generated protocol buffer package.
It is generated from these files:
tensorflow/core/example/feature.proto
It has these top-level messages:
BytesList
FloatList
Int64List
Feature
Features... |
func init() { proto.RegisterFile("tensorflow/core/example/feature.proto", fileDescriptor0) }
var fileDescriptor0 = []byte{
// 371 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x74, 0x92, 0xdf, 0x4a, 0xc3, 0x30,
0x14, 0xc6, 0x4d, 0xab, 0x9b, 0x3d, 0x9d, 0x30, 0... | {
proto.RegisterType((*BytesList)(nil), "tensorflow.BytesList")
proto.RegisterType((*FloatList)(nil), "tensorflow.FloatList")
proto.RegisterType((*Int64List)(nil), "tensorflow.Int64List")
proto.RegisterType((*Feature)(nil), "tensorflow.Feature")
proto.RegisterType((*Features)(nil), "tensorflow.Features")
proto.Re... | identifier_body |
feature.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: tensorflow/core/example/feature.proto
/*
Package tensorflow is a generated protocol buffer package.
It is generated from these files:
tensorflow/core/example/feature.proto
It has these top-level messages:
BytesList
FloatList
Int64List
Feature
Features... |
msg := new(BytesList)
err := b.DecodeMessage(msg)
m.Kind = &Feature_BytesList{msg}
return true, err
case 2: // kind.float_list
if wire != proto.WireBytes {
return true, proto.ErrInternalBadWireType
}
msg := new(FloatList)
err := b.DecodeMessage(msg)
m.Kind = &Feature_FloatList{msg}
return true,... | {
return true, proto.ErrInternalBadWireType
} | conditional_block |
feature.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: tensorflow/core/example/feature.proto
/*
Package tensorflow is a generated protocol buffer package.
It is generated from these files:
tensorflow/core/example/feature.proto
It has these top-level messages:
BytesList
FloatList
Int64List
Feature
Features... | type Int64List struct {
Value []int64 `protobuf:"varint,1,rep,packed,name=value" json:"value,omitempty"`
}
func (m *Int64List) Reset() { *m = Int64List{} }
func (m *Int64List) String() string { return proto.CompactTextString(m) }
func (*Int64List) ProtoMessage() {}
func (*I... | return nil
}
| random_line_split |
GridSave.py | """
Model to use the GridClass to make an image of radio astronomical observations
"""
# Functions to create a grid and place astronomical data on that
# grid with a convolving function
# HISTORY
# 20MAY15 GIL one more time on coordiante header updates in FITS
# 20MAY14 GIL update coordinates in FITS header
# 20MAY13 G... | rs.read_spec_ast(coldfile)
print("Observer: %s " % (rs.observer))
# first read through all data and find hot load
names = sys.argv[3:]
names = sorted(names)
firsttime = ""
lasttime = ""
count = 0
# setup grid indicies so that cpuIndex goes to the correct grid
# This assumes telesco... | print("Reading Observing parameters from: %s" % (coldfile)) | random_line_split |
GridSave.py | """
Model to use the GridClass to make an image of radio astronomical observations
"""
# Functions to create a grid and place astronomical data on that
# grid with a convolving function
# HISTORY
# 20MAY15 GIL one more time on coordiante header updates in FITS
# 20MAY14 GIL update coordinates in FITS header
# 20MAY13 G... | ( grid1, grid2):
"""
gridratio computes the ratio of two grids when the values in both grids are non-zero
This function is used to compute gain ratios
The average and rms of the ratios are provided along as the grid of ratios
"""
nx1 = grid1.img_width
ny1 = grid1.img_height
nx2 = grid2.... | gridratio | identifier_name |
GridSave.py | """
Model to use the GridClass to make an image of radio astronomical observations
"""
# Functions to create a grid and place astronomical data on that
# grid with a convolving function
# HISTORY
# 20MAY15 GIL one more time on coordiante header updates in FITS
# 20MAY14 GIL update coordinates in FITS header
# 20MAY13 G... |
if __name__ == "__main__":
main()
#SIMPLE = T / conforms to FITS standard
#BITPIX = -32 / array data type
#NAXIS = 2 / number of array dimensions
#NAXIS1 = 4323 ... | """
Main executable for gridding astronomical data
"""
dpi = 1
dpi = 2
width = int(360)
height = int(130)
mywidth = int(width*dpi)
myheight = int(height*dpi)
FWHM = 7.5 # degrees
FWHM = 10.0 # degrees
FWHM = 5.0 # degrees
FWHM = 3.0 # degrees
FWHM = 1.0 # degrees... | identifier_body |
GridSave.py | """
Model to use the GridClass to make an image of radio astronomical observations
"""
# Functions to create a grid and place astronomical data on that
# grid with a convolving function
# HISTORY
# 20MAY15 GIL one more time on coordiante header updates in FITS
# 20MAY14 GIL update coordinates in FITS header
# 20MAY13 G... |
# now for output image check all pixel values
for jjj in range (ny):
for iii in range (nx):
# if this image pixal has no value
pixout[0] = (iii,jjj)
oworld = wout.wcs_pix2world(pixout, 0)
xy = oworld[0]
if np.isnan(xy[0]):
continue
# ... | for iii in range (nx):
imageCopy[jjj][iii] = nan | conditional_block |
prec_climber.rs | // pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// 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. All files in the project carrying such no... | ///
/// # Examples
///
/// ```
/// # use pest::prec_climber::{Assoc, Operator};
/// # #[allow(non_camel_case_types)]
/// # #[allow(dead_code)]
/// # #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// # enum Rule {
/// # plus,
/// # minus
/// #... | random_line_split | |
prec_climber.rs | // pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// 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. All files in the project carrying such no... | }
/// List of operators and precedences, which can perform [precedence climbing][1] on infix
/// expressions contained in a [`Pairs`]. The token pairs contained in the `Pairs` should start
/// with a *primary* pair and then alternate between an *operator* and a *primary*.
///
/// [1]: https://en.wikipedia.org/wiki/Ope... |
fn assign_next<R: RuleType>(op: &mut Operator<R>, next: Operator<R>) {
if let Some(ref mut child) = op.next {
assign_next(child, next);
} else {
op.next = Some(Box::new(next));
}
}
assign_next(&mut self, rhs);
self
... | identifier_body |
prec_climber.rs | // pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// 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. All files in the project carrying such no... | 'i, P, F, G, T>(&self, mut pairs: P, mut primary: F, mut infix: G) -> T
where
P: Iterator<Item = Pair<'i, R>>,
F: FnMut(Pair<'i, R>) -> T,
G: FnMut(T, Pair<'i, R>, T) -> T,
{
let lhs = primary(
pairs
.next()
.expect("precedence climbing... | limb< | identifier_name |
prec_climber.rs | // pest. The Elegant Parser
// Copyright (c) 2018 Dragoș Tiselice
//
// 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. All files in the project carrying such no... | } else {
break;
}
}
lhs
}
}
|
break;
}
| conditional_block |
subscriber.rs | use super::error::{ErrorKind, Result, ResultExt};
use super::header::{decode, encode, match_field};
use super::{Message, Topic};
use crate::rosmsg::RosMsg;
use crate::util::lossy_channel::{lossy_channel, LossyReceiver, LossySender};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crossbeam::channel::{bo... |
}
| {
let input = [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 4, 0, 0, 0, 11, 12, 13, 14];
let mut cursor = std::io::Cursor::new(input);
let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR);
assert_eq!(data, [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7]);
let data = package_to_vec... | identifier_body |
subscriber.rs | use super::error::{ErrorKind, Result, ResultExt};
use super::header::{decode, encode, match_field};
use super::{Message, Topic};
use crate::rosmsg::RosMsg;
use crate::util::lossy_channel::{lossy_channel, LossyReceiver, LossySender};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crossbeam::channel::{bo... | assert_eq!(data, [4, 0, 0, 0, 11, 12, 13, 14]);
}
} | let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR);
assert_eq!(data, [7, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7]);
let data = package_to_vector(&mut cursor).expect(FAILED_TO_READ_WRITE_VECTOR); | random_line_split |
subscriber.rs | use super::error::{ErrorKind, Result, ResultExt};
use super::header::{decode, encode, match_field};
use super::{Message, Topic};
use crate::rosmsg::RosMsg;
use crate::util::lossy_channel::{lossy_channel, LossyReceiver, LossySender};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crossbeam::channel::{bo... | (&self) -> Vec<String> {
self.connected_publishers.iter().cloned().collect()
}
#[allow(clippy::useless_conversion)]
pub fn connect_to<U: ToSocketAddrs>(
&mut self,
publisher: &str,
addresses: U,
) -> std::io::Result<()> {
for address in addresses.to_socket_addrs(... | publisher_uris | identifier_name |
subscriber.rs | use super::error::{ErrorKind, Result, ResultExt};
use super::header::{decode, encode, match_field};
use super::{Message, Topic};
use crate::rosmsg::RosMsg;
use crate::util::lossy_channel::{lossy_channel, LossyReceiver, LossySender};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use crossbeam::channel::{bo... |
}
});
Ok(headers)
}
fn write_request<U: std::io::Write>(
mut stream: &mut U,
caller_id: &str,
topic: &str,
msg_definition: &str,
md5sum: &str,
msg_type: &str,
) -> Result<()> {
let mut fields = HashMap::<String, String>::new();
fields.insert(String::from("message_defini... | {
// Data receiver has been destroyed after
// Subscriber destructor's kill signal
break;
} | conditional_block |
snva.py | import argparse
import asyncio
import json
import logging
from logging.handlers import QueueHandler, SocketHandler
from multiprocessing import Process, Queue
import os
import platform
from queue import Empty
import signal
import socket
from subprocess import PIPE, Popen
from threading import Thread
from time import sle... | continue
except ConnectionRefusedError:
# log something else
logging.info('connection refused')
break
except ws.exceptions.ConnectionClosed:
logging.info('Connection lost. Attempting reconnect...')
continue
except Exception as e:
logging.error("Unknown Exception")
... | except socket.gaierror:
# log something
logging.info('gaierror') | random_line_split |
snva.py | import argparse
import asyncio
import json
import logging
from logging.handlers import QueueHandler, SocketHandler
from multiprocessing import Process, Queue
import os
import platform
from queue import Empty
import signal
import socket
from subprocess import PIPE, Popen
from threading import Thread
from time import sle... |
# Logger thread: listens for updates to log queue and writes them as they arrive
# Terminates after we add None to the queue
def child_logger_fn(main_log_queue, child_log_queue):
while True:
try:
message = child_log_queue.get()
if message is None:
break
main_log_queue.put(message)
... | while True:
try:
message = log_queue.get()
if message is None:
break
logger = logging.getLogger(__name__)
logger.handle(message)
except Exception as e:
logging.error(e)
break | identifier_body |
snva.py | import argparse
import asyncio
import json
import logging
from logging.handlers import QueueHandler, SocketHandler
from multiprocessing import Process, Queue
import os
import platform
from queue import Empty
import signal
import socket
from subprocess import PIPE, Popen
from threading import Thread
from time import sle... |
logging.debug('FFPROBE path set to: {}'.format(ffprobe_path))
# # TODO validate all video file paths in the provided text file if args.inputpath is a text file
# if path.isdir(args.inputpath):
# video_file_names = set(IO.read_video_file_names(args.inputpath))
# video_file_paths = [path.join(args.inputp... | ffprobe_path = '/usr/bin/ffprobe' | conditional_block |
snva.py | import argparse
import asyncio
import json
import logging
from logging.handlers import QueueHandler, SocketHandler
from multiprocessing import Process, Queue
import os
import platform
from queue import Empty
import signal
import socket
from subprocess import PIPE, Popen
from threading import Thread
from time import sle... | (video_file_path):
# Before popping the next video off of the list and creating a process to
# scan it, check to see if fewer than logical_device_count + 1 processes are
# active. If not, Wait for a child process to release its semaphore
# acquisition. If so, acquire the semaphore, pop the next video na... | start_video_processor | identifier_name |
selectionmenu.js | /*
SelectionMenu 1.1
http://github.com/molily/selectionmenu
by molily (molily@mailbox.org, http://molily.de/)
EN: SelectionMenu displays a context menu when the user selects some text on the page
DE: SelectionMenu blendet ein Kontextmenü beim Markieren von Text ein
EN: License: Public Domain
EN: You're allowed to cop... | // DE: Korrigiere Auswahl, verhindere das Markieren des Menüs
if (selection.removeRange) {
selection.removeRange(range);
} else {
selection.removeAllRanges();
}
selection.addRange(range);
} else if (selection.duplicate) {
// EN: Microsoft TextRange approach
// DE: Lösungsansat... | // DE: Füge das span-Element in die neue Range ein
newRange.insertNode(span);
// EN: Adjust the selection by removing and adding the range.
// EN: This prevents the selection of the menu text. | random_line_split |
selectionmenu.js | /*
SelectionMenu 1.1
http://github.com/molily/selectionmenu
by molily (molily@mailbox.org, http://molily.de/)
EN: SelectionMenu displays a context menu when the user selects some text on the page
DE: SelectionMenu blendet ein Kontextmenü beim Markieren von Text ein
EN: License: Public Domain
EN: You're allowed to cop... | ;
}
selection.addRange(range);
} else if (selection.duplicate) {
// EN: Microsoft TextRange approach
// DE: Lösungsansatz mit Microsoft TextRanges
// EN: Create a copy the the TextRange
// DE: Kopiere TextRange
var newRange = selection.duplicate();
// EN: Move the start of the new... | } else {
selection.removeAllRanges() | conditional_block |
selectionmenu.js | /*
SelectionMenu 1.1
http://github.com/molily/selectionmenu
by molily (molily@mailbox.org, http://molily.de/)
EN: SelectionMenu displays a context menu when the user selects some text on the page
DE: SelectionMenu blendet ein Kontextmenü beim Markieren von Text ein
EN: License: Public Domain
EN: You're allowed to cop... | .prototype = {
create : function () {
var instance = this;
// EN: Create the menu container if necessary
// DE: Erzeuge den Menü-Container, sofern noch nicht passiert
if (span) {
return;
}
span = document.createElement('span');
span.id = instance.id;
},
setupEvents : function () {
... | e = this;
// EN: Copy members from the options object to the instance
// DE: Kopiere Einstellungen aus dem options-Objekt herüber zur Instanz
instance.id = options.id || 'selection-menu';
instance.menuHTML = options.menuHTML;
instance.minimalSelection = options.minimalSelection || 5;
instance.container = o... | identifier_body |
selectionmenu.js | /*
SelectionMenu 1.1
http://github.com/molily/selectionmenu
by molily (molily@mailbox.org, http://molily.de/)
EN: SelectionMenu displays a context menu when the user selects some text on the page
DE: SelectionMenu blendet ein Kontextmenü beim Markieren von Text ein
EN: License: Public Domain
EN: You're allowed to cop... | ) {
// EN: Feature detection HTML5 / Microsoft
// DE: Fähigkeitenweiche HTML5 / Microsoft
return selection.toString ? selection.toString() : selection.text;
}
function contains (a, b) {
// EN: Feature detection DOM Core / Microsoft
// DE: Fähigkeitenweiche DOM Core / Microsoft
return a.compareDocumentPo... | Text (selection | identifier_name |
lib.rs | //! The `io_uring` library for Rust.
//!
//! The crate only provides a summary of the parameters.
//! For more detailed documentation, see manpage.
#![cfg_attr(sgx, no_std)]
#[cfg(sgx)]
extern crate sgx_types;
#[cfg(sgx)]
#[macro_use]
extern crate sgx_tstd as std;
#[cfg(sgx)]
extern crate sgx_trts;
#[cfg(sgx)]
use st... | }
#[inline]
pub fn params(&self) -> &Parameters {
&self.params
}
pub fn start_enter_syscall_thread(&self) {
sys::start_enter_syscall_thread(self.fd.as_raw_fd());
}
/// Initiate and/or complete asynchronous I/O
///
/// # Safety
///
/// This provides a ra... | #[inline]
pub fn submitter(&self) -> Submitter<'_> {
Submitter::new(&self.fd, self.params.0.flags, &self.sq) | random_line_split |
lib.rs | //! The `io_uring` library for Rust.
//!
//! The crate only provides a summary of the parameters.
//! For more detailed documentation, see manpage.
#![cfg_attr(sgx, no_std)]
#[cfg(sgx)]
extern crate sgx_types;
#[cfg(sgx)]
#[macro_use]
extern crate sgx_tstd as std;
#[cfg(sgx)]
extern crate sgx_trts;
#[cfg(sgx)]
use st... | #[cfg(feature = "unstable")]
pub fn is_feature_poll_32bits(&self) -> bool {
self.0.features & sys::IORING_FEAT_POLL_32BITS != 0
}
pub fn sq_entries(&self) -> u32 {
self.0.sq_entries
}
pub fn cq_entries(&self) -> u32 {
self.0.cq_entries
}
}
impl AsRawFd for IoUring {
... | self.0.features & sys::IORING_FEAT_FAST_POLL != 0
}
| identifier_body |
lib.rs | //! The `io_uring` library for Rust.
//!
//! The crate only provides a summary of the parameters.
//! For more detailed documentation, see manpage.
#![cfg_attr(sgx, no_std)]
#[cfg(sgx)]
extern crate sgx_types;
#[cfg(sgx)]
#[macro_use]
extern crate sgx_tstd as std;
#[cfg(sgx)]
extern crate sgx_trts;
#[cfg(sgx)]
use st... | (&self) -> bool {
self.0.features & sys::IORING_FEAT_SINGLE_MMAP != 0
}
/// If this flag is set, io_uring supports never dropping completion events. If a completion
/// event occurs and the CQ ring is full, the kernel stores the event internally until such a
/// time that the CQ ring has room f... | is_feature_single_mmap | identifier_name |
lib.rs | //! The `io_uring` library for Rust.
//!
//! The crate only provides a summary of the parameters.
//! For more detailed documentation, see manpage.
#![cfg_attr(sgx, no_std)]
#[cfg(sgx)]
extern crate sgx_types;
#[cfg(sgx)]
#[macro_use]
extern crate sgx_tstd as std;
#[cfg(sgx)]
extern crate sgx_trts;
#[cfg(sgx)]
use st... | else {
let sq_mmap = Mmap::new(fd, sys::IORING_OFF_SQ_RING as _, sq_len)?;
let cq_mmap = Mmap::new(fd, sys::IORING_OFF_CQ_RING as _, cq_len)?;
let sq = SubmissionQueue::new(&sq_mmap, &sqe_mmap, p);
let cq = CompletionQueue::new(&cq_mmap, p);
... | {
let scq_mmap =
Mmap::new(fd, sys::IORING_OFF_SQ_RING as _, cmp::max(sq_len, cq_len))?;
let sq = SubmissionQueue::new(&scq_mmap, &sqe_mmap, p);
let cq = CompletionQueue::new(&scq_mmap, p);
let mm = MemoryMap {
sq_m... | conditional_block |
seq2seq.py | import tensorflow as tf
from parameters import *
init_parameters()
class GRU(object):
def __init__(self, input_dimensions, hidden_size, name='', dtype=tf.float64):
# Initialize Init attributes
self.input_dimensions = input_dimensions
self.hidden_size = hidden_size
self.name = na... |
# Perform the scan operator (hacky as fac diud)
self.h_t_transposed = tf.scan(self.forward_pass, self.x_t, self.h_0, name='h_t_transposed')
# Transpose the result back
self.h_t = tf.transpose(self.h_t_transposed, [1, 0], name='h_t')
return self.h_t
def predict_sequence(s... | self.h_0 = h_0 | conditional_block |
seq2seq.py | import tensorflow as tf
from parameters import *
init_parameters()
class GRU(object):
def __init__(self, input_dimensions, hidden_size, name='', dtype=tf.float64):
# Initialize Init attributes
self.input_dimensions = input_dimensions
self.hidden_size = hidden_size
self.name = na... | h_tm1 = tf.reshape(h_tm1, shape=[1, -1])
# Definitions of z_t and r_t
z_t = tf.sigmoid(tf.matmul(x_t, self.Wz) + tf.matmul(h_tm1, self.Uz) + self.bz)
r_t = tf.sigmoid(tf.matmul(x_t, self.Wr) + tf.matmul(h_tm1, self.Ur) + self.br)
# Definition of h~_t
h_proposal = tf.tan... | :return:
"""
# Convert vector-tensor form into matrix-tensor form
x_t = tf.reshape(x_t, shape=[1, -1]) | random_line_split |
seq2seq.py | import tensorflow as tf
from parameters import *
init_parameters()
class GRU(object):
def __init__(self, input_dimensions, hidden_size, name='', dtype=tf.float64):
# Initialize Init attributes
self.input_dimensions = input_dimensions
self.hidden_size = hidden_size
self.name = na... |
def process_sequence(self, sequence, h_0=None):
# Put the time-dimension upfront for the scan operator
self.x_t = tf.transpose(sequence, [1, 0], name='x_t') # [n_words, embedding_dim]
if h_0 is None:
# A little hack (to obtain the same shape as the input matrix) to define th... | """Perform a forward pass.
:param h_tm1: np.matrix. The hidden state at the previous timestep (h_{t-1}).
:param x_t: np.matrix. The input vector.
:return:
"""
# Convert vector-tensor form into matrix-tensor form
x_t = tf.reshape(x_t, shape=[1, -1])
h_tm1 = tf.r... | identifier_body |
seq2seq.py | import tensorflow as tf
from parameters import *
init_parameters()
class GRU(object):
def __init__(self, input_dimensions, hidden_size, name='', dtype=tf.float64):
# Initialize Init attributes
self.input_dimensions = input_dimensions
self.hidden_size = hidden_size
self.name = na... | (self, h_tm1, x_t): # Function though to be used by tf.scan
"""Perform a forward pass.
:param h_tm1: np.matrix. The hidden state at the previous timestep (h_{t-1}).
:param x_t: np.matrix. The input vector.
:return:
"""
# Convert vector-tensor form into matrix-tensor ... | forward_pass | identifier_name |
error.rs | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 app... |
fn as_native_mut(&mut self) -> *mut sys::AStatus {
self.0
}
}
| {
self.0
} | identifier_body |
error.rs | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 app... | (&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description())
}
}
impl Debug for Status {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description())
}
}
impl PartialEq for Status {
fn eq(&self, other: &Status) -> bool {
let self_code =... | fmt | identifier_name |
error.rs | /*
* Copyright (C) 2020 The Android Open Source Project
*
* 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 app... | }
}
impl Debug for Status {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description())
}
}
impl PartialEq for Status {
fn eq(&self, other: &Status) -> bool {
let self_code = self.exception_code();
let other_code = other.exception_code();
match... | impl Display for Status {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
f.write_str(&self.get_description()) | random_line_split |
setup.rs | // Copyright 2020 Zachary Stewart
//
// 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... | (&self, id: I) -> Option<ShipEntry<I, D, S>> {
let grid = &self.grid;
self.ships
.get(&id)
.map(move |ship| ShipEntry { id, grid, ship })
}
/// Get the [`ShipEntryMut`] for the ship with the specified ID if such a ship exists.
pub fn get_ship_mut(&mut self, id: I) ->... | get_ship | identifier_name |
setup.rs | // Copyright 2020 Zachary Stewart
//
// 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... | placement,
));
}
_ => {}
}
}
// Already ensured that every position is valid and not occupied.
for coord in placement.iter() {
self.grid[coord].ship = Some(self... | ));
}
Some(cell) if cell.ship.is_some() => {
return Err(PlaceError::new(
CannotPlaceReason::AlreadyOccupied, | random_line_split |
ingredientsScraper.py | from bs4 import BeautifulSoup as bs
import urllib2
import pickle
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
import random as rnd
from sklearn import svm
from sklearn.metrics import confusion_matrix
from sklearn import cross_validation
from sklearn.grid_search import GridSearchCV
from labels impo... | (fooddish):
#dictionary for ingredients
I = {}
#dictionary for food recipes
R = {}
website = 'http://allrecipes.com'
for food in fooddish:
R[food] = {}
#search for food
print food
#for page in xrange(2):
resultspage = urllib2.urlopen("http://allrecipes.com/sear... | IngredientScraper2 | identifier_name |
ingredientsScraper.py | from bs4 import BeautifulSoup as bs
import urllib2
import pickle
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
import random as rnd
from sklearn import svm
from sklearn.metrics import confusion_matrix
from sklearn import cross_validation
from sklearn.grid_search import GridSearchCV
from labels impo... |
##allfeatures = sorted(list(set().union(*topfeatures)))
###print top features for each class
#for f in xrange(len(fooddish)):
#xlabels = [None]*30
#for ingIdx in xrange(30):
#print fooddish[f], I[ingsorted[topfeatures[f][ingIdx]]], svm_weights[f,topfeatures[f][ingIdx]]
#xlabels[ingIdx] = I[ingsorted[topfeat... | #topfeatures = [None]*svm_weights.shape[0] #topfeatures for each class
#for i in xrange(svm_weights.shape[0]):
#featureIdx=np.argsort(abs(svm_weights[i,:]))
#topfeatures[i] = featureIdx[::-1][0:30] #get top 30 | random_line_split |
ingredientsScraper.py | from bs4 import BeautifulSoup as bs
import urllib2
import pickle
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
import random as rnd
from sklearn import svm
from sklearn.metrics import confusion_matrix
from sklearn import cross_validation
from sklearn.grid_search import GridSearchCV
from labels impo... |
#normalize values
m = sum(R[food][recipename].values())
R[food][recipename]={ingid: R[food][recipename][ingid]/m for ingid in R[food][recipename].keys()}
#Recipes = {}
#ingsorted = sorted(I.keys())
#for food in R.keys():
##m = sum(R[food].values())
##normalize values
... | ingid = ing.attrs['data-ingredientid']
ingname = ing.find(id='lblIngName').text
if ingid not in I:
I[ingid] = ingname
amt=float(ing.attrs['data-grams'])
R[food][recipename][ingid] = amt | conditional_block |
ingredientsScraper.py | from bs4 import BeautifulSoup as bs
import urllib2
import pickle
import numpy as np
import scipy.io
import matplotlib.pyplot as plt
import random as rnd
from sklearn import svm
from sklearn.metrics import confusion_matrix
from sklearn import cross_validation
from sklearn.grid_search import GridSearchCV
from labels impo... |
#=================================================================================
# Ingredient Scraper with cooking terms and nutritional info
def IngredientScraper(fooddish):
#dictionary for ingredients
I = {}
#dictionary for food recipes
R = {}
website = 'http://allrecipes.com'
for f... | I = {}
#dictionary for food recipes
R = {}
website = 'http://allrecipes.com'
for food in fooddish:
R[food] = {}
#search for food
print food
#for page in xrange(2):
resultspage = urllib2.urlopen("http://allrecipes.com/search/default.aspx?qt=k&wt="+food)
results = bs(re... | identifier_body |
buffered.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | self) -> &W {
self.inner.get_ref()
}
/// Gets a mutable reference to the underlying writer.
///
/// Caution must be taken when calling methods on the mutable reference
/// returned as extra writes could corrupt the output stream.
///
pub fn get_mut(&mut self) -> &mut W {
sel... | t_ref(& | identifier_name |
buffered.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
if total_len >= self.buf.capacity() {
self.panicked = true;
let r = self.get_mut().write_vectored(bufs);
self.panicked = false;
r
} else {
self.buf.write_vectored(bufs)
}
}
fn flush(&mut self) -> io::Result<()> {
self.... | {
self.flush_buf()?;
} | conditional_block |
buffered.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
impl<W: Write> Write for LineWriter<W> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
if self.need_flush {
self.flush()?;
}
// Find the last newline character in the buffer provided. If found then
// we're going to write all the data up to that point and then... | self.inner.into_inner().map_err(|IntoInnerError(buf, e)| {
IntoInnerError(LineWriter { inner: buf, need_flush: false }, e)
})
}
} | identifier_body |
buffered.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | }
impl<W: Write> LineWriter<W> {
/// Creates a new `LineWriter`.
///
pub fn new(inner: W) -> LineWriter<W> {
// Lines typically aren't that long, don't use a giant buffer
LineWriter::with_capacity(1024, inner)
}
/// Creates a new `LineWriter` with a specified capacity for the inter... | pub struct LineWriter<W: Write> {
inner: BufWriter<W>,
need_flush: bool, | random_line_split |
util.ts | import { Player } from "@/model/Api";
import { parseISO } from "date-fns";
import { MapMetaMap, ModeMetaMap } from "~/model/MetaEntry";
export const camelToSnakeCase = (str: string) => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
export const camelToKebab = (s: string) =>
s.replace(/([a-z0-9]|(?=[A-Z... | */
/**
* Encode tag string into 64bit unsigned integer string.
* TODO: Use BigInt if tags are >2^53 at some point.
*/
export function tagToId(tag: string) {
if (!tagPattern.test(tag)) {
throw new Error('Cannot encode tag ' + tag)
}
if (tag.startsWith('#')) {
tag = tag.substring(1)
}
const result ... | arraySum((c, i) -> (position('0289PYLQGRJCUV', c)-1)*pow(14, length(player_club_tag)-i-1-1), arraySlice(splitByString('', player_club_tag), 2), range(if(player_club_tag <> '', toUInt64(length(player_club_tag)-1), 0))) as player_club_id, | random_line_split |
util.ts | import { Player } from "@/model/Api";
import { parseISO } from "date-fns";
import { MapMetaMap, ModeMetaMap } from "~/model/MetaEntry";
export const camelToSnakeCase = (str: string) => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
export const camelToKebab = (s: string) =>
s.replace(/([a-z0-9]|(?=[A-Z... |
export const formatList = (l: string[], joiner = 'or') => l.slice(0, l.length - 1).join(', ') + ' ' + joiner + ' ' + l[l.length - 1]
export const clamp = (min: number, max: number, n: number) => Math.min(max, Math.max(min, n))
export const minMaxScale = (fromMin: number, fromMax: number, n: number) => (n - fromMin) /... | {
const uncapitalize = (str: string) => str.replace(/(?:^|\s)\S/g, (a) => a.toLowerCase())
return uncapitalize(mode.replace(/^Showdown$/, 'Solo Showdown').split(' ').join(''))
} | identifier_body |
util.ts | import { Player } from "@/model/Api";
import { parseISO } from "date-fns";
import { MapMetaMap, ModeMetaMap } from "~/model/MetaEntry";
export const camelToSnakeCase = (str: string) => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
export const camelToKebab = (s: string) =>
s.replace(/([a-z0-9]|(?=[A-Z... | () {
const twoWeeksAgo = new Date()
twoWeeksAgo.setDate(twoWeeksAgo.getDate() - 14)
return getSeasonEnd(twoWeeksAgo)
}
/**
* Get the end date of the current database-season
*/
export function getTodaySeasonEnd() {
return getSeasonEnd(new Date())
}
export function parseClickhouse(timestamp: string) {
retur... | getMonthSeasonEnd | identifier_name |
util.ts | import { Player } from "@/model/Api";
import { parseISO } from "date-fns";
import { MapMetaMap, ModeMetaMap } from "~/model/MetaEntry";
export const camelToSnakeCase = (str: string) => str.replace(/[A-Z]/g, letter => `_${letter.toLowerCase()}`);
export const camelToKebab = (s: string) =>
s.replace(/([a-z0-9]|(?=[A-Z... |
}
return Math.round(num / si[i].value)
.toFixed(digits)
.replace(rx, '$1') + si[i].symbol
}
const propPriority = ['winRateAdj', 'winRate', 'wins', 'rank1', 'duration', 'useRate', 'pickRate']
/**
* Get brawlers by event: {
* [eventId]: [
* brawler id,
* brawler name,
* brawler stats,
* ... | {
break
} | conditional_block |
parameter_noise.py | from gymnasium.spaces import Box, Discrete
import numpy as np
from typing import Optional, TYPE_CHECKING, Union
from ray.rllib.env.base_env import BaseEnv
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_action_dist import Categorical,... |
@override(Exploration)
def set_state(self, state: dict, sess: Optional["tf.Session"] = None) -> None:
self.stddev_val = state["cur_stddev"]
# Set self.stddev to calculated value.
if self.framework == "tf":
self.stddev.load(self.stddev_val, session=sess)
elif isinsta... | return {"cur_stddev": self.stddev_val} | identifier_body |
parameter_noise.py | from gymnasium.spaces import Box, Discrete
import numpy as np
from typing import Optional, TYPE_CHECKING, Union
from ray.rllib.env.base_env import BaseEnv
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_action_dist import Categorical,... | (self, *, tf_sess=None):
"""Adds the stored `self.noise` to the model's parameters.
Note: No new sampling of noise here.
Args:
tf_sess (Optional[tf.Session]): The tf-session to use to add the
stored noise to the (currently noise-free) weights.
override: ... | _add_stored_noise | identifier_name |
parameter_noise.py | from gymnasium.spaces import Box, Discrete
import numpy as np
from typing import Optional, TYPE_CHECKING, Union
from ray.rllib.env.base_env import BaseEnv
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_action_dist import Categorical,... |
elif isinstance(self.action_space, Box):
sub_exploration = {
"type": "OrnsteinUhlenbeckNoise",
"random_timesteps": random_timesteps,
}
# TODO(sven): Implement for any action space.
else:
raise No... | sub_exploration = {
"type": "EpsilonGreedy",
"epsilon_schedule": {
"type": "PiecewiseSchedule",
# Step function (see [2]).
"endpoints": [
(0, 1.0),
(ran... | conditional_block |
parameter_noise.py | from gymnasium.spaces import Box, Discrete
import numpy as np
from typing import Optional, TYPE_CHECKING, Union
from ray.rllib.env.base_env import BaseEnv
from ray.rllib.models.action_dist import ActionDistribution
from ray.rllib.models.modelv2 import ModelV2
from ray.rllib.models.tf.tf_action_dist import Categorical,... | # a special schedule.
if isinstance(self.action_space, Discrete):
sub_exploration = {
"type": "EpsilonGreedy",
"epsilon_schedule": {
"type": "PiecewiseSchedule",
# Step function (see [2]).
... | random_line_split | |
hazard2.py | from nmigen import *
from nmigen.asserts import *
from enum import IntEnum
XLEN = 32
class ALUOp(IntEnum):
ADD = 0x0
SUB = 0x1
LT = 0x2
LTU = 0x4
AND = 0x6
OR = 0x7
XOR = 0x8
SRL = 0x9
SRA = 0xa
SLL = 0xb
class RVOpc(IntEnum):
LOAD = 0b00_000
MISC_MEM = 0b00_011
OP_IMM = 0b... | (instr):
return Cat(C(0, 12), instr[12:])
def imm_j(instr):
return Cat(C(0, 1), instr[21:31], instr[20], instr[12:20], Repl(instr[-1], 12))
class Hazard2Shifter(Elaboratable):
def __init__(self):
self.i = Signal(XLEN)
self.shamt = Signal(range(XLEN))
self.right = Signal()
self.arith = Signal()
self.... | imm_u | identifier_name |
hazard2.py | from nmigen import *
from nmigen.asserts import *
from enum import IntEnum
XLEN = 32
class ALUOp(IntEnum):
ADD = 0x0
SUB = 0x1
LT = 0x2
LTU = 0x4
AND = 0x6
OR = 0x7
XOR = 0x8
SRL = 0x9
SRA = 0xa
SLL = 0xb
class RVOpc(IntEnum):
LOAD = 0b00_000
MISC_MEM = 0b00_011
OP_IMM = 0b... | ### Stage F ###
i_dph_active = Signal()
d_dph_active = Signal()
d_dph_write = Signal()
d_dph_addr = Signal(2)
d_dph_size = Signal(2)
d_dph_signed = Signal()
cir = Signal(32)
cir_valid = Signal()
load_rdata = Signal(XLEN)
with m.If(i_dph_active & ~stall):
m.d.sync += cir.eq(self.hrdata)
... | m = Module()
stall = ~self.hready
| random_line_split |
hazard2.py | from nmigen import *
from nmigen.asserts import *
from enum import IntEnum
XLEN = 32
class ALUOp(IntEnum):
ADD = 0x0
SUB = 0x1
LT = 0x2
LTU = 0x4
AND = 0x6
OR = 0x7
XOR = 0x8
SRL = 0x9
SRA = 0xa
SLL = 0xb
class RVOpc(IntEnum):
LOAD = 0b00_000
MISC_MEM = 0b00_011
OP_IMM = 0b... |
m.d.comb += self.o.eq(Mux(self.right, accum, accum[::-1]))
return m
class Hazard2ALU(Elaboratable):
def __init__(self):
self.i0 = Signal(XLEN)
self.i1 = Signal(XLEN)
self.op = Signal(Shape.cast(ALUOp))
self.take4 = Signal()
self.cmp = Signal()
self.o = Signal(XLEN)
def elaborate(se... | accum_next = Signal(XLEN, name=f"shift_accum{i}")
m.d.comb += accum_next.eq(Mux(self.shamt[i],
Cat(accum[1 << i:], Repl(accum[-1] & self.arith, 1 << i)),
accum
))
accum = accum_next | conditional_block |
hazard2.py | from nmigen import *
from nmigen.asserts import *
from enum import IntEnum
XLEN = 32
class ALUOp(IntEnum):
ADD = 0x0
SUB = 0x1
LT = 0x2
LTU = 0x4
AND = 0x6
OR = 0x7
XOR = 0x8
SRL = 0x9
SRA = 0xa
SLL = 0xb
class RVOpc(IntEnum):
LOAD = 0b00_000
MISC_MEM = 0b00_011
OP_IMM = 0b... |
class Hazard2ALU(Elaboratable):
def __init__(self):
self.i0 = Signal(XLEN)
self.i1 = Signal(XLEN)
self.op = Signal(Shape.cast(ALUOp))
self.take4 = Signal()
self.cmp = Signal()
self.o = Signal(XLEN)
def elaborate(self, platform):
m = Module()
m.submodules.shifter = shifter = Hazard2S... | m = Module()
accum = Signal(XLEN, name="shift_pre_reverse")
m.d.comb += accum.eq(Mux(self.right, self.i, self.i[::-1]))
for i in range(self.shamt.width):
accum_next = Signal(XLEN, name=f"shift_accum{i}")
m.d.comb += accum_next.eq(Mux(self.shamt[i],
Cat(accum[1 << i:], Repl(accum[-1] & self.arith, 1 << ... | identifier_body |
server.go | /*
*
* Copyright 2018 huayuan-iot
*
* Author: lynn
* Date: 2018/07/03
* Despcription: bus server implement
*
*/
package module
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
pb "clc.hmu/app/busmanager/buspb"
"clc.hmu/app/busmana... | buslog.LOG.Infof("software restart: %d times", cfg.Web.Restart.Times)
// software rstart
if err := public.RestartApp(cfg.Model, errors.New(public.RestartByCommunicationInterrupt)); err != nil {
buslog.LOG.Warning(errors.As(err))
}
} else {
// clear times
cfg.Web.Restart.... | if err := sys.SaveBusManagerCfg(cfg); err != nil {
buslog.LOG.Warningf("save bus config failed, errmsg {%v}", err)
}
| random_line_split |
server.go | /*
*
* Copyright 2018 huayuan-iot
*
* Author: lynn
* Date: 2018/07/03
* Despcription: bus server implement
*
*/
package module
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
pb "clc.hmu/app/busmanager/buspb"
"clc.hmu/app/busmana... | fs := ifl[cfg.Cache.MaxFile:]
// remove files
for _, f := range rfs {
os.Remove(filepath.Join(cfg.Cache.Directory, strconv.Itoa(f)))
}
}
var nf int
if l == 0 {
nf = 0
} else {
nf = ifl[0] + 1
}
filepath := filepath.Join(cfg.Cache.Directory, strconv.Itoa(nf))
f, err := os.Create(filepath)
if err ... | tSlice(ifl)))
log.Println(ifl)
l := len(ifl)
if l > cfg.Cache.MaxFile {
r | conditional_block |
server.go | /*
*
* Copyright 2018 huayuan-iot
*
* Author: lynn
* Date: 2018/07/03
* Despcription: bus server implement
*
*/
package module
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
pb "clc.hmu/app/busmanager/buspb"
"clc.hmu/app/busmana... | y
downloadDependentDeviceLibrary()
if err := web.ReadVideoConfig(); err != nil {
log.Printf("open video config file failed, errmsg {%v}", err)
}
s.enableCache = true
// check directory exist or not
_, err := os.Stat(sys.GetBusManagerCfg().Cache.Directory)
if err != nil {
if os.IsNotExist(err) {
// do n... | brar | identifier_name |
server.go | /*
*
* Copyright 2018 huayuan-iot
*
* Author: lynn
* Date: 2018/07/03
* Despcription: bus server implement
*
*/
package module
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"time"
pb "clc.hmu/app/busmanager/buspb"
"clc.hmu/app/busmana... | fg := sys.GetBusManagerCfg()
// download element library
downloadDependentDeviceLibrary()
if err := web.ReadVideoConfig(); err != nil {
log.Printf("open video config file failed, errmsg {%v}", err)
}
s.enableCache = true
// check directory exist or not
_, err := os.Stat(sys.GetBusManagerCfg().Cache.Directo... | atusSync.Unlock()
if networkStatus == Online && !mqtt {
// 当mqtt在线时,只能由mqtt处理
return
}
networkStatus = status
}
// Init do some init operation
func (s *BusServer) Init() {
c | identifier_body |
TempTaker_old.py | import serial #library for interfacing with the serial port
import time #library for pausing the script
import math
import sys
import os #for file operations
import pickle #for easy exporting/importing of datatypes
import types #for recognizing types of objects, functions on multiple data types
from numpy import *
impo... |
def saveIntegralError(self,integError):
#print integError
self.INTEGFILE.seek(0) #moves position to the beginning of the file
pickle.dump(integError, self.INTEGFILE)
self.INTEGFILE.truncate()
def finderrorSig(self, CurTemp): #takes array with current temperatures and finds the error signal array
err... | random_line_split | |
TempTaker_old.py | import serial #library for interfacing with the serial port
import time #library for pausing the script
import math
import sys
import os #for file operations
import pickle #for easy exporting/importing of datatypes
import types #for recognizing types of objects, functions on multiple data types
from numpy import *
impo... | (self):
self.INTEGFILE.close()
class DataAcquisition():
def binarytoTempC(self,bin, ch): #converts binary output to a physical temperature in C
Vin = 2.56*(float(bin)+1)/1024 #voltage that is read in 1023 is 2.56 0 is 0
dV = (15/HardwareG[ch])*(Vin/1.2 - 1) #when G = 15 (most channels) dV of 2.4 correspond... | __del__ | identifier_name |
TempTaker_old.py | import serial #library for interfacing with the serial port
import time #library for pausing the script
import math
import sys
import os #for file operations
import pickle #for easy exporting/importing of datatypes
import types #for recognizing types of objects, functions on multiple data types
from numpy import *
impo... |
def printbinfull(self):
print 'Running Average Operational'
def addNumber(self,newnumber):
self.historyArr[self.historyCounter,:] = newnumber #updates history by cycling through rows of historyArr and replacing old data with readTemp
self.historyCounter = (self.historyCounter + 1) % self.RunningAvgNum
if(sel... | print '\n' + 'Filling up history for ' + str(self.RunningAvgNum) +' seconds \n' | identifier_body |
TempTaker_old.py | import serial #library for interfacing with the serial port
import time #library for pausing the script
import math
import sys
import os #for file operations
import pickle #for easy exporting/importing of datatypes
import types #for recognizing types of objects, functions on multiple data types
from numpy import *
impo... |
return average
class ManualController():
def __init__(self):
if(os.path.isfile(mancontrolfile)):#if file exists open it in read mode
pass
else: #if file doesn't exist, create it
self.FILE = open(mancontrolfile,"w");
pickle.dump(0,self.FILE) #indicates automatic control, 1 is manual
pickle.dump(z... | average = sum(self.historyArr[0:(self.historyCounter+1),:],axis=0)/(self.historyCounter) | conditional_block |
Decryption.py | import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding, asymmetric
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, hmac, serialization
from cryptography.hazmat.primitives.asymme... |
def MyDecrypt(C, IV, key):
#make cipher
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.CBC(IV), backend=backend)
#make decryptor
decryptor = cipher.decryptor()
#decrypt ciphertext
plaintext_padded = decrypto... | try:
key = CheckRSAKeys()
except:
print("Error: keys has issue")
return
try:
for root, dirs, filres in os.walk(directory):
for file in filres:
try:
RSACipher, C, IV, tag, ext = MyRSAEncrypt(os.path.join(root,file),key[0])
... | identifier_body |
Decryption.py | import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding, asymmetric
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, hmac, serialization
from cryptography.hazmat.primitives.asymme... | with open(jsonFile) as decryptFile:
data = json.load(decryptFile)
decryptFile.close()
#getting data from dictionary
C = (data['C']).encode('cp437')
IV = (data['IV']).encode('cp437')
tag = (data['tag']).encode('cp437')
EncKey = (data['EncKey']).encode('cp437')
message = MyDec... |
jsonFile = filename + ".json"
#open file to decrypt | random_line_split |
Decryption.py | import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding, asymmetric
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, hmac, serialization
from cryptography.hazmat.primitives.asymme... | ():
#testFile = "test.txt"
testFile = "test_photo.jpg"
'''Regular'''
C, IV, key, ext = MyFileEncrypt(testFile)
input("File encrypted! Press enter to decrypt.")
MyFileDecrypt(testFile, IV, key, ext)
print("\nFile decrypted!")
'''HMAC'''
#C, IV, tag, EncKey, HMACKey, ext... | main | identifier_name |
Decryption.py | import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding, asymmetric
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, hmac, serialization
from cryptography.hazmat.primitives.asymme... |
#open and read file to encrypt
file = open(filepath, "rb")
m = file.read()
file.close()
#getting file name and extension
filename_ext = os.path.basename(filepath) #gets file name with extension from path
filename, ext = os.path.splitext(filename_ext) #separates file name and exten... | raise Exception("HMACKey less than 32 bytes!") | conditional_block |
skim.rs | ///! The fuzzy matching algorithm used by skim
///! It focus more on path matching
///
///! # Example:
///! ```edition2018
///! use fuzzy_matcher::skim::{fuzzy_match, fuzzy_indices};
///!
///! assert_eq!(None, fuzzy_match("abc", "abx"));
///! assert!(fuzzy_match("axbycz", "abc").is_some());
///! assert!(fuzzy_match("ax... |
pub fn fuzzy_indices(choice: &str, pattern: &str) -> Option<(i64, Vec<usize>)> {
if pattern.is_empty() {
return Some((0, Vec::new()));
}
let mut picked = vec![];
let scores = build_graph(choice, pattern)?;
let last_row = &scores[scores.len() - 1];
let (mut next_col, &MatchingStatus {... | {
if pattern.is_empty() {
return Some(0);
}
let scores = build_graph(choice, pattern)?;
let last_row = &scores[scores.len() - 1];
let (_, &MatchingStatus { final_score, .. }) = last_row
.iter()
.enumerate()
.max_by_key(|&(_, x)| x.final_score)
.expect("fuzzy... | identifier_body |
skim.rs | ///! The fuzzy matching algorithm used by skim
///! It focus more on path matching
///
///! # Example:
///! ```edition2018
///! use fuzzy_matcher::skim::{fuzzy_match, fuzzy_indices};
///!
///! assert_eq!(None, fuzzy_match("abc", "abx"));
///! assert!(fuzzy_match("axbycz", "abc").is_some());
///! assert!(fuzzy_match("ax... | &[
"camel case",
"camelCase",
"camelcase",
"CamelCase",
"camel ace",
],
);
assert_order(
"Da.Te",
&["Data.Text", "Data.Text.Lazy", "Data.Aeson.Encoding.text"],
);
... | random_line_split | |
skim.rs | ///! The fuzzy matching algorithm used by skim
///! It focus more on path matching
///
///! # Example:
///! ```edition2018
///! use fuzzy_matcher::skim::{fuzzy_match, fuzzy_indices};
///!
///! assert_eq!(None, fuzzy_match("abc", "abx"));
///! assert!(fuzzy_match("axbycz", "abc").is_some());
///! assert!(fuzzy_match("ax... | else {
score += PENALTY_CASE_UNMATCHED;
}
// apply bonus for camelCases
if choice_role == CharRole::Head {
score += BONUS_CAMEL;
}
// apply bonus for matches after a separator
if choice_prev_ch_type == CharType::Separ {
score += BONUS_SEPARATOR;
}
if pat_idx =... | {
if pat_ch.is_uppercase() {
score += BONUS_UPPER_MATCH;
} else {
score += BONUS_CASE_MATCH;
}
} | conditional_block |
skim.rs | ///! The fuzzy matching algorithm used by skim
///! It focus more on path matching
///
///! # Example:
///! ```edition2018
///! use fuzzy_matcher::skim::{fuzzy_match, fuzzy_indices};
///!
///! assert_eq!(None, fuzzy_match("abc", "abx"));
///! assert!(fuzzy_match("axbycz", "abc").is_some());
///! assert!(fuzzy_match("ax... | (line: &str, pattern: &str) -> Option<String> {
let (_score, indices) = fuzzy_indices(line, pattern)?;
Some(wrap_matches(line, &indices))
}
fn assert_order(pattern: &str, choices: &[&'static str]) {
let result = filter_and_sort(pattern, choices);
if result != choices {
... | wrap_fuzzy_match | identifier_name |
ex1a_sim_vanillaSEIR_model_old.py | import numpy as np
from scipy.integrate import odeint
from scipy.integrate import solve_ivp
from scipy.optimize import fsolve
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import rc
# Importing models and plotting functions
from epimodels.seir import *
rc('font',**{'family':'serif',... | (x):
return np.log(x) + r0_test*(1-x)
###################################################
######## SEIR Model simulation Simulation ########
###################################################
if sim_num == 0:
''' Compartment structure of armed forces SEIR model
N = S + E + I + R
''' ... | epi_size | identifier_name |
ex1a_sim_vanillaSEIR_model_old.py | import numpy as np
from scipy.integrate import odeint
from scipy.integrate import solve_ivp
from scipy.optimize import fsolve
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import rc
# Importing models and plotting functions
from epimodels.seir import *
rc('font',**{'family':'serif',... | # Unpack timseries
if sim_num == 0:
t = sol_ode_timeseries[0]
S = sol_ode_timeseries[1]
E = sol_ode_timeseries[2]
I = sol_ode_timeseries[3]
R = sol_ode_timeseries[4]
else:
t = sol_ode_timeseries[0]
S = sol_ode_timeseries[1]
E = sol_ode_timeseries[2]
... | SEIRparams = N, beta, gamma, sigma
sol_ode_timeseries = simulate_seirModel(seir_type, SEIRparams, solver_type, y0, N, days, 1)
| random_line_split |
ex1a_sim_vanillaSEIR_model_old.py | import numpy as np
from scipy.integrate import odeint
from scipy.integrate import solve_ivp
from scipy.optimize import fsolve
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import rc
# Importing models and plotting functions
from epimodels.seir import *
rc('font',**{'family':'serif',... |
ax1.text(peak_inf_idx+10, peak_inf/N, txt_title.format(peak_inf=peak_inf, peak_days= peak_inf_idx), fontsize=12, color="r")
ax1.text(peak_inf_idx+10, peak_total_inf/N, txt_title2.format(peak_total=peak_total_inf, peak_days= peak_inf_idx), fontsize=12, color="r")
# Making things beautiful
ax1.set_xlabel('Time /days'... | txt_title = r"Peak infected: {peak_inf:5.0f} by day {peak_days:2.0f} from March 21"
txt_title2 = r"Total Cases: {peak_total:5.0f} by day {peak_days:2.0f} from March 21" | conditional_block |
ex1a_sim_vanillaSEIR_model_old.py | import numpy as np
from scipy.integrate import odeint
from scipy.integrate import solve_ivp
from scipy.optimize import fsolve
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import rc
# Importing models and plotting functions
from epimodels.seir import *
rc('font',**{'family':'serif',... |
###################################################
######## SEIR Model simulation Simulation ########
###################################################
if sim_num == 0:
''' Compartment structure of armed forces SEIR model
N = S + E + I + R
'''
# Initial conditions vect... | return np.log(x) + r0_test*(1-x) | identifier_body |
clustering.py | #!/usr/bin/env python
# coding: utf-8
"""
Author: Mahsa Khalili
Date: 2021 April 15th
Purpose: This Python script prepare IMU data for terrain classification.
"""
import os
import glob
import pathlib
import random
import numpy as np
import pandas as pd
import pickle
import joblib
import ma... | # list of all maneuvers
maneuvers = ['Obstacles15', 'Obstacles35', 'RampA', 'StraightF', 'Turn90FR', 'Turn90FL', 'Turn180L', 'Turn180R']
# choose the feature subsets for clustering
featureSet_list = ['ALL', 'ALL_TORQUE', '2D_TORQUE', 'LR_TORQUE', 'LR_TORQUE_MEAN', '2D_TORQUE_MEAN']
dataset_to_import = 'featured_data... |
# DEFINITIONS
USER = 'Mahsa' # ['Mahsa', 'Jaimie'] # participant name
WIN_SIZE = 32 # window size
| random_line_split |
clustering.py | #!/usr/bin/env python
# coding: utf-8
"""
Author: Mahsa Khalili
Date: 2021 April 15th
Purpose: This Python script prepare IMU data for terrain classification.
"""
import os
import glob
import pathlib
import random
import numpy as np
import pandas as pd
import pickle
import joblib
import ma... | (df_clus):
""" add all cluster labels to the original dataframe """
df_all_labeled = df_all_columns.copy()
df_all_labeled['Clus_label'] = df_clus['Clus_label'].copy()
df_all_labeled['Clus_label']= df_all_labeled['Clus_label'].astype(int)
for i in range(0, clus_params['n_components']):
df_al... | labeling_func | identifier_name |
clustering.py | #!/usr/bin/env python
# coding: utf-8
"""
Author: Mahsa Khalili
Date: 2021 April 15th
Purpose: This Python script prepare IMU data for terrain classification.
"""
import os
import glob
import pathlib
import random
import numpy as np
import pandas as pd
import pickle
import joblib
import ma... |
datasets, dataset_labels = import_func(dataset_paths)
data_columns = [col for col in datasets[dataset_labels[0]].columns if col != 'trial' and
col != 'Time' and col != 'maneuver'] # get columns/features of the imported datasets
df_all_stand, df_all_columns, featureSet_dic = prep_func(datasets)
# ru... | """
input: input original dataframe (with maneuver columns), clustered dataframe, number of clusteres,
and selected features to plot
output: plotting clustered time series data with different colors
"""
clusterNum = clus_params['n_components']
color_dict = {i: cmap(i) for i in range(clus... | identifier_body |
clustering.py | #!/usr/bin/env python
# coding: utf-8
"""
Author: Mahsa Khalili
Date: 2021 April 15th
Purpose: This Python script prepare IMU data for terrain classification.
"""
import os
import glob
import pathlib
import random
import numpy as np
import pandas as pd
import pickle
import joblib
import ma... |
if not np.any(Y_ == i):
continue
if "MEAN" in clus_params['feat_list']:
plt.scatter(XX[Y_ == i, 0], XX[Y_ == i, 1], color=color, s=60)
else:
plt.scatter(XX[Y_ == i, 0], XX[Y_ == i, 5], color=color, s=60)
# Plot an ellipse to show the Gaussian compo... | subset = [0, 5] # mean torque L & R
v, w = linalg.eigh(cov[np.ix_(subset, subset)])
mean = np.array([mean[0], mean[5]]) | conditional_block |
dataflows.rs | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by ... | (&self) -> impl Iterator<Item = GlobalId> + '_ {
self.index_exports
.keys()
.chain(self.sink_exports.keys())
.cloned()
}
/// Identifiers of exported subscribe sinks.
pub fn subscribe_ids(&self) -> impl Iterator<Item = GlobalId> + '_ {
self.sink_exports
... | export_ids | identifier_name |
dataflows.rs | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by ... |
/// Calls r and s on any sub-members of those types in self. Halts at the first error return.
pub fn visit_children<R, S, E>(&mut self, r: R, s: S) -> Result<(), E>
where
R: Fn(&mut OptimizedMirRelationExpr) -> Result<(), E>,
S: Fn(&mut MirScalarExpr) -> Result<(), E>,
{
for Bu... | {
for (source_id, (source, _monotonic)) in self.source_imports.iter() {
if source_id == id {
return source.typ.arity();
}
}
for IndexImport { desc, typ, .. } in self.index_imports.values() {
if &desc.on_id == id {
return typ.ari... | identifier_body |
dataflows.rs | // Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Use of this software is governed by the Business Source License
// included in the LICENSE file.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by ... | /// Returns true iff `id` is already imported.
pub fn is_imported(&self, id: &GlobalId) -> bool {
self.objects_to_build.iter().any(|bd| &bd.id == id)
|| self.source_imports.keys().any(|i| i == id)
}
/// Assigns the `as_of` frontier to the supplied argument.
///
/// This meth... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.