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
leaderboard.go
runs against each other Timing TimingMethod // the chosen variables (keys) and values (values) for the leaderboard, both // given as their respective IDs Values map[string]string // the runs, sorted from best to worst Runs []RankedRun // API links to related resources Links []Link // do not use this field...
return toLevel(lb.LevelData, true), nil } // Platforms returns a list of all platforms that are used in the leaderboard. // If they have not been embedded, an empty collection is returned. func (lb *Leaderboard) Platforms() *PlatformCollection { return toPlatformCollection(lb.PlatformsData) } // Regions returns a l...
}
random_line_split
leaderboard.go
against each other Timing TimingMethod // the chosen variables (keys) and values (values) for the leaderboard, both // given as their respective IDs Values map[string]string // the runs, sorted from best to worst Runs []RankedRun // API links to related resources Links []Link // do not use this field dire...
return fetchLeaderboard(request{"GET", "/leaderboards/" + game.ID + "/category/" + cat.ID, options, nil, nil, embeds}) } // LevelLeaderboard retrieves a the leaderboard for a specific game and one of // its levels in a specific category. An error is returned if no category or // level is given or if a full-game cat...
{ var err *Error game, err = cat.Game("") if err != nil { return nil, err } }
conditional_block
leaderboard.go
against each other Timing TimingMethod // the chosen variables (keys) and values (values) for the leaderboard, both // given as their respective IDs Values map[string]string // the runs, sorted from best to worst Runs []RankedRun // API links to related resources Links []Link // do not use this field dire...
// Level returns the level that the leaderboard is for. If it's a full-game // leaderboard, nil is returned. If the level was not embedded, it is fetched // from the network. func (lb *Leaderboard) Level(embeds string) (*Level, *Error) { if lb.LevelData == nil { return nil, nil } // we only have the level ID at...
{ // we only have the category ID at hand asserted, okay := lb.CategoryData.(string) if okay { return CategoryByID(asserted, embeds) } return toCategory(lb.CategoryData, true), nil }
identifier_body
leaderboard.go
runs against each other Timing TimingMethod // the chosen variables (keys) and values (values) for the leaderboard, both // given as their respective IDs Values map[string]string // the runs, sorted from best to worst Runs []RankedRun // API links to related resources Links []Link // do not use this field...
() *VariableCollection { return toVariableCollection(lb.VariablesData) } // Players returns a list of all players that are present in the leaderboard. // If they have not been embedded, an empty slice is returned. func (lb *Leaderboard) Players() *PlayerCollection { return toPlayerCollection(lb.PlayersData) } // fo...
Variables
identifier_name
cyclone.go
is the datatype for sending out alarm notifications type AlarmEvent struct { Source string `json:"source"` EventID string `json:"event_id"` Version string `json:"version"` Sourcehost string `json:"sourcehost"` Oncall string `json:"on_call"` Targethost string `json:"targethost"` Message string `...
runloop: for { select { case <-c.Shutdown: // received shutdown, drain input channel which will be // closed by main goto drainloop case msg := <-c.Input: if msg == nil { // this can happen if we read the closed Input channel // before the closed Shutdown channel continue runloop } ...
) {
identifier_name
cyclone.go
is the datatype for sending out alarm notifications type AlarmEvent struct { Source string `json:"source"` EventID string `json:"event_id"` Version string `json:"version"` Sourcehost string `json:"sourcehost"` Oncall string `json:"on_call"` Targethost string `json:"targethost"` Message string `...
m.Update(m) m = mm.Calculate() c.MemData[id] = mm case `/sys/disk/blk_total`: fallthrough case `/sys/disk/blk_used`: fallthrough case `/sys/disk/blk_read`: fallthrough case `/sys/disk/blk_wrtn`: if len(m.Tags) == 0 { m = nil break } d := disk.Disk{} id := m.AssetID mpt := m.Tags[0] if c...
mm = c.MemData[id] } m
conditional_block
cyclone.go
is the datatype for sending out alarm notifications type AlarmEvent struct { Source string `json:"source"` EventID string `json:"event_id"` Version string `json:"version"` Sourcehost string `json:"sourcehost"` Oncall string `json:"on_call"` Targethost string `json:"targethost"` Message string `...
drainloop: for { select { case msg := <-c.Input: if msg == nil { // channel is closed break drainloop } c.process(msg) } } } // process evaluates a metric and raises alarms as required func (c *Cyclone) process(msg *erebos.Transport) error { if msg == nil || msg.Value == nil { logrus.Warn...
unloop: for { select { case <-c.Shutdown: // received shutdown, drain input channel which will be // closed by main goto drainloop case msg := <-c.Input: if msg == nil { // this can happen if we read the closed Input channel // before the closed Shutdown channel continue runloop } i...
identifier_body
cyclone.go
CTXData map[int64]cpu.CTX DskData map[int64]map[string]disk.Disk redis *redis.Client internalInput chan *legacy.MetricSplit } // AlarmEvent is the datatype for sending out alarm notifications type AlarmEvent struct { Source string `json:"source"` EventID string `json:"event_id"` Versi...
random_line_split
server.rs
::net::tcp::TcpStream; use http::buffer::BufferedStream; use std::thread::Thread; use std::sync::mpsc::{channel, Sender, Receiver}; use http::server::{Server, Request, ResponseWriter}; use http::status::SwitchingProtocols; use http::headers::HeaderEnum; use http::headers::response::Header::ExtensionHeader; use http::...
let mut sh = Sha1::new(); let mut out = [0u8; 20]; sh.input_str((String::from_str(sec_websocket_key) + WEBSOCKET_SALT).as_slice()); sh.result(out.as_mut_slice()); return out.to_base64(STANDARD); } // check if the http request is a web socket upgrade request, and return ...
{ // NOTE from RFC 6455 // // To prove that the handshake was received, the server has to take two // pieces of information and combine them to form a response. The first // piece of information comes from the |Sec-WebSocket-Key| header field // in the client handshake: ...
identifier_body
server.rs
::net::tcp::TcpStream;
use http::server::{Server, Request, ResponseWriter}; use http::status::SwitchingProtocols; use http::headers::HeaderEnum; use http::headers::response::Header::ExtensionHeader; use http::headers::connection::Connection::Token; use http::method::Method::Get; pub use message::Payload::{Text, Binary, Empty}; pub use messa...
use http::buffer::BufferedStream; use std::thread::Thread; use std::sync::mpsc::{channel, Sender, Receiver};
random_line_split
server.rs
::net::tcp::TcpStream; use http::buffer::BufferedStream; use std::thread::Thread; use std::sync::mpsc::{channel, Sender, Receiver}; use http::server::{Server, Request, ResponseWriter}; use http::status::SwitchingProtocols; use http::headers::HeaderEnum; use http::headers::response::Header::ExtensionHeader; use http::...
(&self, r: Request, w: &mut ResponseWriter) -> bool { // TODO allow configuration of endpoint for websocket match (r.method.clone(), r.headers.upgrade.clone()){ // (&Get, &Some("websocket"), &Some(box [Token(box "Upgrade")])) => //\{ FIXME this doesn't work. but client must have the header "...
handle_possible_ws_request
identifier_name
site.js
notificationBell.offsetWidth; translate = "translate(-" + width + "px, 40px)"; dropDown.style.transform = translate; dropDown.style.transition = "transform .25s"; } } //adjust notificaiton header text function notificationHeader(){ let num = dropDown.children.length - 1; dropDownHeader.textContent ...
{ toggleOn(i); localStorage.setItem('toggle' + i, 'on'); }
conditional_block
site.js
=== 0){ liveNotification.style.opacity = "0"; } } //add notifications to dropdown function addNotification(messages) { messages.forEach((message) => { let notification = document.createElement("div"); notification.className = "dropdown-item"; notification.innerHTML = message + ...
toggleOn
identifier_name
site.js
// var result = instantiatePage(); // var t1 = performance.now(); // console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:', result); instantiatePage(); //Instantiate listeners, constructors function instantiatePage(){ document.addEventListener("DOMContentLoaded", () => { displayAlert(alertMessag...
/////////////////////////////// //File performance // var t0 = performance.now();
random_line_split
site.js
function globalKeyListener(){ search.addEventListener("keyup", (e) => { if(!search.value){ count = -1; } //if user has typed and there are results if(search.value && searchList.children){ search.style.textTransform = "capitalize"; //up arrow key if(e.key === 'ArrowUp'){ ...
{ document.addEventListener("click", (e) => { if (dropDown.style.display === "block" && !(e.target.className.includes("bell") || e.target.parentElement.className.includes("dropdown-container") || e.target.className.includes("notification-clear"))) { dropDown.style.display = "none"; dropDow...
identifier_body
generator.go
typeName is the name of a struct we're working on. outputName is where the generated code should go. //genFn is the most important part, and recieves all the meta info about the targeted Type func (g *Generator) Run(pathArgs []string, typeName string, outputName string, genFn GeneratorFunc) error { //Parse the package...
fmt.Fprint(&g.Buf, output) } //format returns the gofmt-ed contents of the Generator's buffer.
random_line_split
generator.go
the output for format.Source. type Generator struct { Buf bytes.Buffer // Accumulated output. pkg *Package // Package we are scanning. dir string } //Run parses the target package and generates the code, verifying the package before and after generation. //pathArgs is a list of file paths, to either individual...
if len(astFiles) == 0 { log.Fatalf("%s: no buildable Go files", directory) } g.pkg.name = astFiles[0].Name.Name g.pkg.files = files g.pkg.dir = directory // Type check the package. g.pkg.check(fs, astFiles) } // parsePackageFiles parses the package occupying the named files. func (g *Generator) parsePackageF...
{ var files []*File var astFiles []*ast.File g.pkg = new(Package) fs := token.NewFileSet() for _, name := range names { if !strings.HasSuffix(name, ".go") { continue } log.Printf("Parsing file: %s", name) parsedFile, err := parser.ParseFile(fs, name, text, 0) if err != nil { log.Fatalf("parsing pac...
identifier_body
generator.go
the output for format.Source. type Generator struct { Buf bytes.Buffer // Accumulated output. pkg *Package // Package we are scanning. dir string } //Run parses the target package and generates the code, verifying the package before and after generation. //pathArgs is a list of file paths, to either individual...
(pathName string, imports []Import) bool { for _, val := range imports { if pathName == val.ImportedName { return true } } return false } // parsePackageDir parses the package residing in the directory. func (g *Generator) parsePackageDir(directory string) { log.Printf("Collecting objects in package %s for ...
importExists
identifier_name
generator.go
output for format.Source. type Generator struct { Buf bytes.Buffer // Accumulated output. pkg *Package // Package we are scanning. dir string } //Run parses the target package and generates the code, verifying the package before and after generation. //pathArgs is a list of file paths, to either individual fil...
fieldObj, _, _ := types.LookupFieldOrMethod(typesObj.Type(), false, f.pkg.typesPkg, field.Name) typeStr := fieldObj.Type().String() tags := parseFieldTags(fieldLine.Tag) //Skip here so we don't include rubbish import lines if tags["exclude_dao"].Value == "true" { continue } processed...
{ continue }
conditional_block
s3driver.go
err } if !strings.HasSuffix(prefix, "/") { prefix = prefix + "/" } var nextContinuationToken *string files := []os.FileInfo{} for { objects, err := d.s3.ListObjectsV2(&s3.ListObjectsV2Input{ Bucket: aws.String(d.bucket), Prefix: aws.String(prefix), Delimiter: aws.String...
func (d S3Driver) Rename(oldpath string, newpath string) error { translatedOldpath, err := TranslatePath(d.prefix, d.homePath, oldpath) if err != nil { return err } translatedNewpath, err := TranslatePath(d.prefix, d.homePath, newpath) if err != nil { return err } input := &s3.CopyObjectInput{ Bucket: ...
{ translatedPath, err := TranslatePath(d.prefix, d.homePath, path) if err != nil { return err } _, err = d.s3.DeleteObject(&s3.DeleteObjectInput{ Bucket: aws.String(d.bucket), Key: aws.String(translatedPath), }) return err }
identifier_body
s3driver.go
363c": "", "610c95d3f8fe797dd7069926": "", "572227ff2ccd540100000942": "", "5d94ff814070e90001c74ae9": "", "562a767542fcde0100000cd3": "", "5d727c3d091c7a0001b6167b": "", "577ec13a78ef4c010000010c": "", "5a2eae046e18690001b2b671": "", "596923cd7eb87f000134bd31": "", "5d96661ed0c8470001afd962": "", "...
func getIPAndPort(combined string) (string, string) {
random_line_split
s3driver.go
, err } if !strings.HasSuffix(prefix, "/") { prefix = prefix + "/" } var nextContinuationToken *string files := []os.FileInfo{} for { objects, err := d.s3.ListObjectsV2(&s3.ListObjectsV2Input{ Bucket: aws.String(d.bucket), Prefix: aws.String(prefix), Delimiter: aws.Strin...
(path string) error { translatedPath, err := TranslatePath(d.prefix, d.homePath, path) if err != nil { return err } // s3 DeleteObject needs a trailing slash for directories directoryPath := translatedPath if !strings.HasSuffix(translatedPath, "/") { directoryPath = translatedPath + "/" } _, err = d.s3.De...
DeleteDir
identifier_name
s3driver.go
err } if !strings.HasSuffix(prefix, "/") { prefix = prefix + "/" } var nextContinuationToken *string files := []os.FileInfo{} for { objects, err := d.s3.ListObjectsV2(&s3.ListObjectsV2Input{ Bucket: aws.String(d.bucket), Prefix: aws.String(prefix), Delimiter: aws.String...
files = append(files, &fileInfo{ name: strings.TrimPrefix(*o.Key, prefix), size: *o.Size, mtime: *o.LastModified, }) } for _, o := range objects.CommonPrefixes { files = append(files, &fileInfo{ name: strings.TrimSuffix(strings.TrimPrefix(*o.Prefix, prefix), "/"), size: 4096, m...
{ continue }
conditional_block
app.js
(Math.random() * 10); var item = ` <a href="./products-detail.html" id="${dataProducts[k].id}" class="sale__item-link"> <div class="sale__wrap-img"> <img style="width:100%;" src="${dataProducts[k].url}" alt="" class="sa...
tion(e) { e.preventDefault(); var productID = this.id; w
conditional_block
app.js
còn hợp vs ai bỉm sữa mà vẫn muốn trend :))" + "Túi rất nhẹ gập gọn cất cốp được, sống ảo xịn sò luôn nha 😌😌", orderQty: 3 }, { id: "item-8", name: "TÚI XÁCH NỮ 2 NGĂN PHỐI NƠ KIỂU DÁNG HÀN QUỐC CỰC ĐẸP SL15", url: "../assets/img/items/item-8.jpg", price: 6...
) { var product = dataProducts.find(function(value) { return value.id == item.id; }); product.orderQ
identifier_body
app.js
-5.jpg", price: 259000, describe1: "KARA Shop xin gửi quý khách sản phẩm HOT: Túi Kẹp Nách Nữ Caro Vintage Hottrend KR 180- 7 Màu Lựa chọn, Chất liệu cao cấp, Có 2 Dây- KARA 180", describe2: "Túi Kẹp nách nữ có kích thước: Dài 24 cm, Rộng 5 cm, Cao 14 cmTúi Kẹp nách nữ có kích thước: Dài 26 cm,...
c="${product
identifier_name
app.js
"> </td> <td class="text-center" >${product.name}</td> <td class="text-center">${product.price}</td> <td class="text-center d-flex justify-content-center"> <input style="width: 45px; border: none; outline: none;" type="number" class="d-block" name="number" id="nu...
var lbNhapLaiMatKhau = document.querySelector("#lbNhapLaiMatKhau"); var lbTen = document.querySelector("#lbTen"); var lbDiaChi = document.querySelector("#lbDiaChi"); var lbDt = document.querySelector("#lbDt");
random_line_split
x25519.rs
} } impl Drop for DHOutput { fn drop(&mut self) { Mem::wipe(self.0) } } /// A public key. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub struct PublicKey([u8; POINT_BYTES]); impl PublicKey { /// Number of raw bytes in a public key. pub const BYTES: usize = POINT_BYTES; /// Creat...
sk_.copy_from_slice(sk); Ok(SecretKey::new(sk_)) } /// Perform the X25519 clamping magic pub fn clamped(&self) -> SecretKey { let mut clamped = self.clone(); clamped[0] &= 248; clamped[31] &= 63; clamped[31] |= 64; clamped } /// Recover the ...
{ return Err(Error::InvalidSecretKey); }
conditional_block
x25519.rs
(dh: DHOutput) -> Self { PublicKey(dh.0) } } impl From<DHOutput> for SecretKey { fn from(dh: DHOutput) -> Self { SecretKey(dh.0) } } impl Drop for DHOutput { fn drop(&mut self) { Mem::wipe(self.0) } } /// A public key. #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub...
from
identifier_name
x25519.rs
_)) } /// Multiply a point by the cofactor, returning an error if the element is /// in a small-order group. pub fn clear_cofactor(&self) -> Result<[u8; PublicKey::BYTES], Error> { let cofactor = [ 8u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...
#[cfg(not(feature = "disable-signatures"))] pub use from_ed25519::*; #[test] fn test_x25519() {
random_line_split
nasdaq_itch_vwap.py
def parse_itch_data(itch_data): # read the first byte of each message in the data file: msg_header = itch_data.read(1) # initialize the csv file that will store parsed Add Order and Add Order # with MPID messages: add_order_data = open('add_order_data.csv','w') add_order_wrtr = csv.wr...
# advance the file position to the next message: msg_header = itch_data.read(1) # close the csv files: add_order_data.close() ord_exec_data.close() ord_exec_pr_data.close() trade_data.close() # function to calculate the hourly VWAP based on parsed ITCH data: def cal...
message = itch_data.read(43) if len(message) < 43: break un_pkd = struct.unpack('>4s6sQcI8cIQ',message) re_pkd = struct.pack('>s4s2s6sQsI8sIQ',msg_header,un_pkd[0], b'\x00\x00',un_pkd[1],un_pkd[2],un_pkd[3],un_pkd[4], b''.join(list(un_pkd[5:13])),...
conditional_block
nasdaq_itch_vwap.py
def parse_itch_data(itch_data): # read the first byte of each message in the data file: msg_header = itch_data.read(1) # initialize the csv file that will store parsed Add Order and Add Order # with MPID messages: add_order_data = open('add_order_data.csv','w') add_order_wrtr = csv.wr...
sha = parsed_oewp[5] # shares pri = float(parsed_oewp[8])/1e4 # new price ord_exec_pr_wrtr.writerow([ref, sha, pri]) # process Trade messages: if msg_header == b'P': message = itch_data.read(43) if len(message) < 43: break ...
if (parsed_oewp[4] < 1e14 and parsed_oewp[5] < 1e6 and parsed_oewp[6] < 1e10 and parsed_oewp[7] == b'Y'): # write the parsed message to the csv file: ref = parsed_oewp[4] # order reference number
random_line_split
nasdaq_itch_vwap.py
parse_itch_data(itch_data): # read the first byte of each message in the data file: msg_header = itch_data.read(1) # initialize the csv file that will store parsed Add Order and Add Order # with MPID messages: add_order_data = open('add_order_data.csv','w') add_order_wrtr = csv.write...
trade_2_df = trade_2_df.rename(columns={"Shares_x": "Shares"}) trade_2_df['Product'] = trade_2_df['Price']*trade_2_df['Shares'] # merge the Order Executed With Price data with the Add Order data # to extract the executed trades data within: trade_3_df = ord_exec_pr_df.merge(add_order_df,on=['R...
add_order_df = pd.read_csv('add_order_data.csv', index_col = None, names = ['Stock', 'Timestamp', 'Reference', 'Shares', 'Price']) # import the parsed Order Executed data into a Pandas dataframe: ord_exec_df = pd.read_csv('ord_exec_data.csv', index_col = None, names = ['Referenc...
identifier_body
nasdaq_itch_vwap.py
def parse_itch_data(itch_data): # read the first byte of each message in the data file: msg_header = itch_data.read(1) # initialize the csv file that will store parsed Add Order and Add Order # with MPID messages: add_order_data = open('add_order_data.csv','w') add_order_wrtr = csv.wr...
(): # import the parsed Add Order data into a Pandas dataframe: add_order_df = pd.read_csv('add_order_data.csv', index_col = None, names = ['Stock', 'Timestamp', 'Reference', 'Shares', 'Price']) # import the parsed Order Executed data into a Pandas dataframe: ord_exec_df = pd.read_...
calculate_vwap
identifier_name
physically_monotonic.rs
use std::collections::BTreeSet; use std::marker::PhantomData; use differential_dataflow::lattice::Lattice; use mz_expr::{EvalError, Id, MapFilterProject, MirScalarExpr, TableFunc}; use mz_repr::{Diff, GlobalId, Row}; use timely::PartialOrder; use crate::plan::interpret::{BoundedLattice, Context, Interpreter}; use cra...
( &self, ctx: &Context<Self::Domain>, id: &Id, _keys: &AvailableCollections, _plan: &GetPlan, ) -> Self::Domain { // A get operator yields physically monotonic output iff the corresponding // `Plan::Get` is on a local or global ID that is known to provide phys...
get
identifier_name
physically_monotonic.rs
use std::collections::BTreeSet; use std::marker::PhantomData; use differential_dataflow::lattice::Lattice; use mz_expr::{EvalError, Id, MapFilterProject, MirScalarExpr, TableFunc}; use mz_repr::{Diff, GlobalId, Row}; use timely::PartialOrder; use crate::plan::interpret::{BoundedLattice, Context, Interpreter}; use cra...
&self, _ctx: &Context<Self::Domain>, input: Self::Domain, _forms: &AvailableCollections, _input_key: &Option<Vec<MirScalarExpr>>, _input_mfp: &MapFilterProject, ) -> Self::Domain { // `Plan::ArrangeBy` is better thought of as `ensure_collections`, i.e., it ...
fn arrange_by(
random_line_split
spinning_table_states.py
): "stores last message" last_msg = None def __init__(self,topic_name,msg_type): self.sub = rospy.Subscriber(topic_name,msg_type,self.callback) rospy.loginfo('waiting for the first message: %s'%topic_name) while self.last_msg is None: rospy.sleep(.01) ...
self.vel_limits = [0.42, 0.42,0.65,0.66,0.72, 0.62,0.72] def goto_posture(self, name): l_joints = self.L_POSTURES[name] joints = l_joints if self.lr == 'l' else mirror_arm_joints(l_joints) self.goto_joint_positions(joints) def goto_joint_positions(self, positions...
self.lr = lr self.lrlong = {"r":"right", "l":"left"}[lr] self.tool_frame = "%s_gripper_tool_frame"%lr self.cart_command = rospy.Publisher('%s_cart/command_pose'%lr, gm.PoseStamped)
random_line_split
spinning_table_states.py
(object): "stores last message" last_msg = None def __init__(self,topic_name,msg_type): self.sub = rospy.Subscriber(topic_name,msg_type,self.callback) rospy.loginfo('waiting for the first message: %s'%topic_name) while self.last_msg is None: rospy.sleep(.01) ...
return angle class Head(TrajectoryControllerWrapper): def __init__(self, listener): TrajectoryControllerWrapper.__init__(self,"head_traj_controller",listener) self.vel_limits = [1.,1.] def set_pan_tilt(self, pan, tilt): self.goto_joint_positions([pan, tilt]) ...
angle = angle + 2*math.pi
conditional_block
spinning_table_states.py
.1 , -2.106, 3.074] ) def __init__(self, lr,listener): TrajectoryControllerWrapper.__init__(self,"%s_arm_controller"%lr, listener) self.lr = lr self.lrlong = {"r":"right", "l":"left"}[lr] self.tool_frame = "%s_gripper_tool_frame"%lr ...
ExecuteGrasp
identifier_name
spinning_table_states.py
): "stores last message" last_msg = None def __init__(self,topic_name,msg_type): self.sub = rospy.Subscriber(topic_name,msg_type,self.callback) rospy.loginfo('waiting for the first message: %s'%topic_name) while self.last_msg is None: rospy.sleep(.01) ...
joints = l_joints if self.lr == 'l' else mirror_arm_joints(l_joints) self.goto_joint_positions(joints) def goto_joint_positions(self, positions_goal): positions_cur = self.get_joint_positions() positions_goal = closer_joint_angles(positions_goal, positions_cur) ...
L_POSTURES = dict( untucked = [0.4, 1.0, 0.0, -2.05, 0.0, -0.1, 0.0], tucked = [0.06, 1.25, 1.79, -1.68, -1.73, -0.10, -0.09], up = [ 0.33, -0.35, 2.59, -0.15, 0.59, -1.41, -0.27], side = [ 1.832, -0.332, 1.011, -1.437, 1.1 , -2.106, 3.074] ) ...
identifier_body
action.py
Action: """ The class for an action we want to track. This class is used to manage the data of an individual Action. It is used to perform the following: - set mandatory/optional fields - set meta fields - cast an validate data so that it knows how to read datafields from ...
f"<a href='{source}' target='_blank'>{urlparse(source).netloc}</a>" ) ret.append(tag) td.append(BeautifulSoup(html.unescape(", ".join(ret)), "html.parser")) else: td.string = value return td @classmethod def create_fro...
elif field == "sources": ret = [] for source in value: tag = (
random_line_split
action.py
Action: """ The class for an action we want to track. This class is used to manage the data of an individual Action. It is used to perform the following: - set mandatory/optional fields - set meta fields - cast an validate data so that it knows how to read datafields from ...
return False def sort(self, *args, **kwargs) -> "Actions": """ Sorts the list of actions. """ self.actions.sort(*args, **kwargs) return self def append(self, action: Action): """ Append an action onto this instance of Actions. """ self.actions.append(action) ...
return self.actions == other.actions
conditional_block
action.py
: """ The class for an action we want to track. This class is used to manage the data of an individual Action. It is used to perform the following: - set mandatory/optional fields - set meta fields - cast an validate data so that it knows how to read datafields from markdo...
(self, field: Union[List[Any], Any]) -> List[Any]: if self.is_none(field): return None else: if isinstance(field, (list,)): return field else: return [s.strip().lower() for s in field.split(",")] def __post_init__(self): ""...
listify
identifier_name
action.py
Action: """ The class for an action we want to track. This class is used to manage the data of an individual Action. It is used to perform the following: - set mandatory/optional fields - set meta fields - cast an validate data so that it knows how to read datafields from ...
def to_md(self, field: str, td: bs4.element.Tag) -> str: """ Convert field for markdown Takes a td BeautifulSoup object and updates it according to the field type so that it renders correctly in markdown. """ assert ( field in self.__dataclass_fields__ ...
""" Return the value of the field rendered for df. """ value = self.__getattribute__(field) if field in ["date", "workers"]: return str(value) elif field in ["locations", "struggles", "companies", "tags", "sources"]: return str(value).strip("[").strip("]").replace("'", ""...
identifier_body
web.rs
!("Listening on 0.0.0.0:8080"); rouille::start_server("0.0.0.0:8080", |request| { rouille::log(request, io::stderr(), || { let conn = &db::connection(); let user_model = &UserModel::new(conn); let user_service = &UserService::new(user_model, b"...."); router!...
#[test] fn test_form_to_password_grant() { assert_eq!( form_to_password_grant(&vec![ ("grant_type".into(), "password".into()), ("username".into(), "test-user".into()), ("password".into(), "test-password
{ let fields = form_to_map(fields); let username = fields.get("username").ok_or(WebError::MissingUsername)?; let password = fields.get("password").ok_or(WebError::MissingPassword)?; Ok(user::PasswordGrantRequest { username, password }) }
identifier_body
web.rs
!("Listening on 0.0.0.0:8080"); rouille::start_server("0.0.0.0:8080", |request| { rouille::log(request, io::stderr(), || { let conn = &db::connection(); let user_model = &UserModel::new(conn); let user_service = &UserService::new(user_model, b"...."); router!...
<'a> { pub status: &'a str, } /// this is the status endpoint fn status(user_model: &UserModel) -> Response { let status = user_model .find(&Uuid::new_v4()) .map(|_| Status { status: "up" }) .unwrap_or_else(|_| Status { status: "down" }); Response::json(&status) } #[derive(Deseria...
Status
identifier_name
web.rs
, (GET) (/status) => { status(user_model) }, (POST) (/oauth/register) => { oauth_register(user_service, request) }, (GET) (/oauth/register/confirm) => { oauth_register_confirm(user_service, request) }, (POST) (/oauth/token) => { oauth_token(user_service...
WebError::MissingPassword
random_line_split
chmod.rs
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE ...
.validator_os(validate_mode) .required(true)) //.conflicts_with("reference")) .arg(Arg::with_name("FILES") .index(2) .required(true) ...
random_line_split
chmod.rs
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE O...
(data: String) -> Self { Self { kind: MessageKind::Stdout, data, } } pub fn stderr(data: String) -> Self { Self { kind: MessageKind::Stderr, data, } } } struct Options<'a> { verbosity: Verbosity, preserve_root: bool, ...
stdout
identifier_name
chmod.rs
([rwxXst]*|[ugo]))+|[-+=]?[0-7]+'. "; #[derive(Fail, Debug)] enum ChmodError { #[fail(display = "cannot stat attributes of '{}': {}", _0, _1)] Stat(String, #[cause] io::Error), } #[derive(PartialEq)] enum Verbosity { None, Changes, Quiet, Verbose, } enum MessageKind { Stdout, Stderr, ...
{ let cmode_unwrapped = options.cmode.clone().unwrap(); for mode in cmode_unwrapped.split(',') { // cmode is guaranteed to be Some in this case let arr: &[char] = &['0', '1', '2', '3', '4', '5', '6', '7']; let result = if mode.contains(arr) { ...
conditional_block
cnn.py
50, use_pretrained=True): # Initialize these variables which will be set in this if statement. Each of these # variables is model specific. model_ft = None input_size = 0 if model_name == "resnet": """ Resnet18 """ model_ft = models.resnet18(pretrained=use_pretrained) ...
res_grad == True and\ name == "0.quantize": print('Y',param.data[0]*255) print('Cb',param.data[1]*255) print('Cr',param.data[2]*255) break # Let's v
conditional_block
cnn.py
As input, it takes a PyTorch model, a dictionary of # dataloaders, a loss function, an optimizer, a specified number of epochs # to train and validate for, and a boolean flag for when the model is an # Inception model. The *is_inception* flag is used to accomodate the # *Inception v3* model, as that architecture uses ...
running_corrects = 0 # Iterate over data. for inputs, labels in dataloaders[phase]: inputs = inputs.to(device) labels = labels.to(device) # zero the parameter gradients if train: optimizer.zero_grad(...
nce = time.time() val_acc_history = [] best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 phases =['train', 'val'] if not train: phases = ['val'] for epoch in range(num_epochs): print('Epoch {}/{}'.format(epoch, num_epochs - 1)) print('-' * 10) #...
identifier_body
cnn.py
input, it takes a PyTorch model, a dictionary of # dataloaders, a loss function, an optimizer, a specified number of epochs # to train and validate for, and a boolean flag for when the model is an # Inception model. The *is_inception* flag is used to accomodate the # *Inception v3* model, as that architecture uses an ...
odel, dataloaders, criterion, optimizer, num_epochs=25, is_inception=False, train = True): since = time.time() val_acc_history = [] best_model_wts = copy.deepcopy(model.state_dict()) best_acc = 0.0 phases =['train', 'val'] if not train: phases = ['val'] for epoch in range(num_epoch...
ain_model(m
identifier_name
cnn.py
== 'train'): # Get model outputs and calculate loss # Special case for inception because in training it has an auxiliary output. In train # mode we calculate the loss by summing the final output and the auxiliary output # but in testin...
# (1): Conv2d(512, 1000, kernel_size=(1, 1), stride=(1, 1))
random_line_split
Server.go
") c.TCPReader = bufio.NewReader(c.Socket) c.TCPWriter = bufio.NewWriter(c.Socket) //c.UDPCon = net.ResolveUDPAddr(c.Socket.RemoteAddr().Network(), c.Socket.RemoteAddr().String()) var ( buf = make([]byte, 1024) ) for { bufLength, err := c.TCPReader.Read(buf) //[0:]) //log.Printf("buffer length = %d", b...
) _, addr, err := UDP_Listner.ReadFromUDP(buf[0:]) if err != nil { log.Printf("AcceptUDP error:" + err.Error()) continue } if buf[0] == ID_ResolveUDP { PlayerID = ID(buf[3]) | (ID(buf[4]) << 8) | (ID(buf[5])<<16 | ID(buf[6])<<24) for _, c := range MainServer.Clients { if PlayerID == c.ID { /...
for { var ( buf = make([]byte, 1024) PlayerID ID
random_line_split
Server.go
c.TCPReader = bufio.NewReader(c.Socket) c.TCPWriter = bufio.NewWriter(c.Socket) //c.UDPCon = net.ResolveUDPAddr(c.Socket.RemoteAddr().Network(), c.Socket.RemoteAddr().String()) var ( buf = make([]byte, 1024) ) for { bufLength, err := c.TCPReader.Read(buf) //[0:]) //log.Printf("buffer length = %d", bufLe...
buf = make([]byte, 1024) continue } } } func StartServer() { TCP_addr, TCP_err := net.ResolveTCPAddr("tcp", "0.0.0.0:4354") if TCP_err != nil { log.Println(TCP_err) return } ln, err := net.ListenTCP("tcp", TCP_addr) if err != nil { log.Println(err) return } log.Printf("Server started (TCP)! at...
{ if PlayerID == c.ID { // TODO: must be reply TCP message with approve connection log.Printf("%s pid=%d", addr.String(), PlayerID) c.UDPCon = UDP_Listner c.UDPAddr = addr } }
conditional_block
Server.go
() { defer c.OnPanic() log.Println("Income connection") c.TCPReader = bufio.NewReader(c.Socket) c.TCPWriter = bufio.NewWriter(c.Socket) //c.UDPCon = net.ResolveUDPAddr(c.Socket.RemoteAddr().Network(), c.Socket.RemoteAddr().String()) var ( buf = make([]byte, 1024) ) for { bufLength, err := c.TCPReader.Re...
Run
identifier_name
Server.go
case io.EOF: return case nil: { var i uint16 = 0 for true { pLength := uint16(buf[i+1]) | (uint16(buf[i+2]) << 8) //log.Printf("packet length = %d", pLength) copySlice := buf[i : i+pLength] // copy value hope this is work :) MainServer.Jobs <- func() { c.HandlePacket(copySlice, pL...
{ defer c.OnPanic() log.Println("Income connection") c.TCPReader = bufio.NewReader(c.Socket) c.TCPWriter = bufio.NewWriter(c.Socket) //c.UDPCon = net.ResolveUDPAddr(c.Socket.RemoteAddr().Network(), c.Socket.RemoteAddr().String()) var ( buf = make([]byte, 1024) ) for { bufLength, err := c.TCPReader.Read(...
identifier_body
plugins.go
string{ "AssOnTheGlass", "BoltedOnBooty", "BubbleButts", "ButtsAndBareFeet", "Cheeking", "HighResASS", "LoveToWatchYouLeave", "NoTorso", "SpreadEm", "TheUnderbun", "Top_Tier_Asses", "Tushy", "Underbun", "ass", "assgifs", "bigasses", "booty", "booty_gifs", "datass", "datbuttfromthefront", "hugeass", "j...
func (p *Misc) buzz(source *irc.Prefix, target string, cmd string, args []string) (bool, error) { if len(args) == 0 { return true, nil } perms, err := p.bot.Auth(source) if err != nil { return false, err } if perms == nil || !perms.Can("annoy") { return true, nil } lines := []string{ "%s", "%s!", ...
{ if len(args) == 0 { return true, nil } msg := fmt.Sprintf("%s: I am bullshitting you!", args[0]) p.bot.Message(bot.PrivMsg(target, msg)) return true, nil }
identifier_body
plugins.go
[]string{ "AssOnTheGlass", "BoltedOnBooty", "BubbleButts", "ButtsAndBareFeet", "Cheeking", "HighResASS", "LoveToWatchYouLeave", "NoTorso", "SpreadEm", "TheUnderbun", "Top_Tier_Asses", "Tushy", "Underbun", "ass", "assgifs", "bigasses", "booty", "booty_gifs", "datass", "datbuttfromthefront", "hugeass",...
() error { return nil } func (p *Misc) Load(b *bot.Bot) (*bot.PluginInfo, error) { p.bot = b p.textCmd("cmd.hey", []string{"how are you?", "heya!", "hello"}) p.bot.HandleCmdRateLimited("cmd.buzz", p.buzz) file, _ := os.Open("config/reply.json") defer file.Close() decoder := json.NewDecoder(file) replyTerms := ...
Unload
identifier_name
plugins.go
"blonde", "blondes", }, What: []string{"blonde"}, Check: checkIsImage, NSFW: true, }, RedditSearch{ Commands: []string{"brunette"}, Subreddits: []string{ "brunette", "brunetteass", }, What: []string{"brunette"}, Check: checkIsImage, NSFW: true, }, } func (p *AutoJoin) Load(b *bot.Bot) (*bot.P...
RedditSearch := RedditSearches[rand.Intn(len(RedditSearches))]
random_line_split
plugins.go
.invite) p.bot.HandleIRC("irc.kick", p.kick) p.bot.HandleIRC("irc.join", p.join) p.bot.HandleCmdRateLimited("cmd.bs", p.bullshit) p.bannedUsers = make(map[string]string) return &bot.PluginInfo{ Name: "Misc", Description: "Miscellaneous commands.", }, nil } func (p *Misc) Unload() error { return nil } func ...
{ plug.bot.Message(bot.PrivMsg(target, fmt.Sprintf("%s: haven't indexed any %s yet", source.Name, what))) return true, nil }
conditional_block
partitions.go
return s.partitionDisk(dev, devAlias) }, "partitioning %q", devAlias) if err != nil { return err } } return nil } // partitionMatches determines if the existing partition matches the spec given. See doc/operator notes for what // what it means for an existing partition to match the spec. spec must have ...
(sgdiskOut string, partitionNumbers []int) (map[int]sgdiskOutput, error) { if len(partitionNumbers) == 0 { return nil, nil } startRegex := regexp.MustCompile(`^First sector: (\d*) \(.*\)$`) endRegex := regexp.MustCompile(`^Last sector: (\d*) \(.*\)$`) const ( START = iota END = iota...
parseSgdiskPretend
identifier_name
partitions.go
did not match (specified %q, got %q)", *spec.Label, existing.Label) } return nil } // partitionShouldBeInspected returns if the partition has zeroes that need to be resolved to sectors. func partitionShouldBeInspected(part sgdisk.Partition) bool { if part.Number == 0 { return false } return (part.StartSector !...
resolvedPartitions, err := s.getRealStartAndSize(dev, devAlias, diskInfo) if err != nil { return err
random_line_split
partitions.go
return s.partitionDisk(dev, devAlias) }, "partitioning %q", devAlias) if err != nil { return err } } return nil } // partitionMatches determines if the existing partition matches the spec given. See doc/operator notes for what // what it means for an existing partition to match the spec. spec must have ...
if end != -1 { current.size = 1 + end - current.start output[partitionNumbers[i]] = current i++ if i == len(partitionNumbers) { state = FAIL_ON_START_END } else { current = sgdiskOutput{} state = START } } case FAIL_ON_START_END: if len(startRegex.FindStringSubmatch(li...
{ return nil, err }
conditional_block
partitions.go
return s.partitionDisk(dev, devAlias) }, "partitioning %q", devAlias) if err != nil { return err } } return nil } // partitionMatches determines if the existing partition matches the spec given. See doc/operator notes for what // what it means for an existing partition to match the spec. spec must have ...
func convertMiBToSectors(mib *int, sectorSize int) *int64 { if mib != nil { v := int64(*mib) * (1024 * 1024 / int64(sectorSize)) return &v } else { return nil } } // getRealStartAndSize returns a map of partition numbers to a struct that contains what their real start // and end sector should be. It runs sg...
{ if part.Number == 0 { return false } return (part.StartSector != nil && *part.StartSector == 0) || (part.SizeInSectors != nil && *part.SizeInSectors == 0) }
identifier_body
file.rs
32-bit emb.proc", 77 => "Infineon Technologies 32-bit emb.proc", 78 => "Element 14 64-bit DSP Processor", 79 => "LSI Logic 16-bit DSP Processor", 80 => "Donald Knuth's educational 64-bit proc", 81 => "Harvard University machine-independent object files", 82 => "SiTera Pr...
pub enum FileClass { // Invalid class None, // 32-bit objects ElfClass32, // 64 bit objects ElfClass64, // Unknown class Invalid(u8), } #[derive(Debug)] pub enum Encoding { // Invalid data encoding None, // 2's complement, little endian LittleEndian, // 2's complemen...
#[derive(Debug)]
random_line_split
file.rs
32-bit emb.proc", 77 => "Infineon Technologies 32-bit emb.proc", 78 => "Element 14 64-bit DSP Processor", 79 => "LSI Logic 16-bit DSP Processor", 80 => "Donald Knuth's educational 64-bit proc", 81 => "Harvard University machine-independent object files", 82 => "SiTera Pr...
{ // Invalid data encoding None, // 2's complement, little endian LittleEndian, // 2's complement big endian BigEndian, // Uknown data encoding Invalid(u8), } #[derive(Debug)] pub enum OsAbi { // UNIX System V ABI UnixVSystem, // HP-UX HpUx, // NetBDS NetBsd, ...
Encoding
identifier_name
mod.rs
strm: StreamWrapper, } const GZIP_HEADER_ID1: u8 = 0x1f; const GZIP_HEADER_ID2: u8 = 0x8b; impl ZlibInner { #[allow(clippy::too_many_arguments)] fn start_write( &mut self, input: &[u8], in_off: u32, in_len: u32, out: &mut [u8], out_off: u32, out_len: u32, flush: Flush, ) -> Resu...
(state: &mut OpState, handle: u32) -> Result<(), AnyError> { let resource = zlib(state, handle)?; let mut zlib = resource.inner.borrow_mut(); // If there is a pending write, defer the close until the write is done. zlib.close()?; Ok(()) } #[op] pub fn op_zlib_write_async( state: Rc<RefCell<OpState>>, h...
op_zlib_close
identifier_name
mod.rs
: StreamWrapper, } const GZIP_HEADER_ID1: u8 = 0x1f; const GZIP_HEADER_ID2: u8 = 0x8b; impl ZlibInner { #[allow(clippy::too_many_arguments)] fn start_write( &mut self, input: &[u8], in_off: u32, in_len: u32, out: &mut [u8], out_off: u32, out_len: u32, flush: Flush, ) -> Result<()...
} self.err = match self.mode { Mode::Deflate | Mode::Gzip | Mode::DeflateRaw => self.strm.deflate_init( self.level, self.window_bits, self.mem_level, self.strategy, ), Mode::Inflate | Mode::Gunzip | Mode::InflateRaw | Mode::Unzip => { self.strm.inflate...
{}
conditional_block
mod.rs
: StreamWrapper, } const GZIP_HEADER_ID1: u8 = 0x1f; const GZIP_HEADER_ID2: u8 = 0x8b; impl ZlibInner { #[allow(clippy::too_many_arguments)] fn start_write( &mut self, input: &[u8], in_off: u32, in_len: u32, out: &mut [u8], out_off: u32, out_len: u32, flush: Flush, ) -> Result<()...
} struct Zlib { inner: RefCell<ZlibInner>, } impl deno_core::Resource for Zlib { fn name(&self) -> Cow<str> { "zlib".into() } } #[op] pub fn op_zlib_new(state: &mut OpState, mode: i32) -> Result<u32, AnyError> { let mode = Mode::try_from(mode)?; let inner = ZlibInner { mode, ..Default::defaul...
{ self.err = self.strm.reset(self.mode); Ok(()) }
identifier_body
mod.rs
strm: StreamWrapper, } const GZIP_HEADER_ID1: u8 = 0x1f; const GZIP_HEADER_ID2: u8 = 0x8b; impl ZlibInner { #[allow(clippy::too_many_arguments)] fn start_write( &mut self, input: &[u8], in_off: u32, in_len: u32, out: &mut [u8], out_off: u32, out_len: u32, flush: Flush, ) -> Resu...
self.pending_close = false; check(self.init_done, "close before init")?; self.strm.end(self.mode); self.mode = Mode::None; Ok(true) } fn reset_stream(&mut self) -> Result<(), AnyError> { self.err = self.strm.reset(self.mode); Ok(()) } } struct Zlib { inner: RefCell<ZlibInner>, } ...
self.pending_close = true; return Ok(false); }
random_line_split
seq2seq_chatbot_Learning.py
사 if type == DECODER_TARGET: # 디코더 목표일 경우 맨 뒤에 END 태그 추가 if len(sentence_index) >= max_sequences: sentence_index = sentence_index[:max_sequences-1] + [vocabulary[END]] else: sentence_index += [vocabulary[END]] else: if len(s...
edict(
conditional_block
seq2seq_chatbot_Learning.py
의 출력을 띄어쓰기로 구분하여 붙임
words.append(word) # 길이가 0인 단어는 삭제 words = [word for word in words if len(word) > 0] # 중복된 단어 삭제 words = list(set(words)) # 제일 앞에 태그 단어 삽입 words[:0] = [PAD, STA, END, OOV] # 단어 개수 len(words) # 단어와 인덱스의 딕셔너리 생성 word_to_index = {word: index for index, word in enumerate(words)} index_to_word = {index: word fo...
sentence = " ".join(tagger.morphs(sentence)) sentences_pos.append(sentence) return sentences_pos # 형태소분석 수행 question = pos_tag(question) answer = pos_tag(answer) # 질문과 대답 문장들을 하나로 합침 sentences = [] sentences.extend(question) sentences.extend(answer) words = [] # 단어들의 배열 생성 for sentence in se...
identifier_body
seq2seq_chatbot_Learning.py
석의 출력을 띄어쓰기로 구분하여 붙임 sentence = " ".join(tagger.morphs(sentence)) sentences_pos.append(sentence) return sentences_pos # 형태소분석 수행 question = pos_tag(question) answer = pos_tag(answer) # 질문과 대답 문장들을 하나로 합침 sentences = [] sentences.extend(question) sentences.extend(answer) words = [] # 단어...
dropout=0.1, recurrent_dropout=0.5, return_state=True)(encoder_outputs) # 히든 상태와 셀 상태를 하나로 묶음 encoder_states = [state_h, state_c] #-----------------------------------------...
random_line_split
seq2seq_chatbot_Learning.py
0])) # 문장을 인덱스로 변환 def convert_text_to_index(sentences, vocabulary, type): sentences_index = [] # 모든 문장에 대해서 반복 for sentence in sentences: sentence_index = [] # 디코더 입력일 경우 맨 앞에 START 태그 추가 if type == DECODER_INPUT: sentence_index.extend([vocabulary[ST...
return input
identifier_name
mod.rs
Box<dyn Fn(&Shell<'_>, &Pipeline<RefinedJob<'_>>) + 'a>; /// A callback that is executed when a background event occurs pub type BackgroundEventCallback = Arc<dyn Fn(usize, Pid, BackgroundEvent) + Send + Sync>; impl<'a> Default for Shell<'a> { #[must_use] fn default() -> Self { Self::new() } } impl<'a> Shell...
builtins_mut
identifier_name
mod.rs
fg` command is run, this will be used to communicate with the specified /// background process. foreground_signals: Arc<foreground::Signals>, // Callbacks /// Custom callback for each command call on_command: Option<OnCommandCallback<'a>>, /// Custom callback before each command call ...
{ &mut self.pre_command }
identifier_body
mod.rs
Error<Self>> for IonError { #[must_use] fn from(cause: ExpansionError<Self>) -> Self { Self::ExpansionError(cause) } } /// Options for the shell #[derive(Debug, Clone, Hash, Default)] pub struct Options { /// Exit from the shell on the first error. pub err_exit: bool, /// Activates the -p option, ...
flow_control: Block, /// Contains the directory stack parameters. directory_stack: DirectoryStack, /// When a command is executed, the final result of that command is stored /// here. previous_status: Status, /// The job ID of the previous command sent to the background. prev...
/// started. builtins: BuiltinMap<'a>, /// Contains the aliases, strings, and array variable maps. variables: Variables, /// Contains the current state of flow control parameters.
random_line_split
lib.rs
::SGX_SUCCESS } #[no_mangle] pub extern "C" fn get_firmware_version( p_firmware_version_buf: *mut u8, fv_buf_size: usize, ) -> sgx_status_t { let version = env!("CARGO_PKG_VERSION"); assert!(version.len() <= fv_buf_size); let version_buf_slice = unsafe { std::slice::from_raw_parts_mut(p_fir...
let dh_msg3_raw_len = mem::size_of::<sgx_dh_msg3_t>() as u32 + dh_msg3_raw.msg3_body.additional_prop_length; let dh_msg3 = unsafe { SgxDhMsg3::from_raw_dh_msg3_t(dh_msg3_raw, dh_msg3_raw_len) }; assert!(!dh_msg3.is_none()); let dh_msg3 = match dh_msg3 { Some(msg) => msg, None =...
identifier_body
lib.rs
= 0x06, PKCS8Error = 0x07, StateError = 0x08, PrivateKeyNotPopulated = 0x09, } #[no_mangle] pub extern "C" fn g
p_fwv_len: &mut usize) -> sgx_status_t { let version = env!("CARGO_PKG_VERSION"); *p_fwv_len = version.len(); sgx_status_t::SGX_SUCCESS } #[no_mangle] pub extern "C" fn get_firmware_version( p_firmware_version_buf: *mut u8, fv_buf_size: usize, ) -> sgx_status_t { let version = env!("CARGO_PKG_V...
et_firmware_version_len(
identifier_name
lib.rs
= 0x06, PKCS8Error = 0x07, StateError = 0x08, PrivateKeyNotPopulated = 0x09, } #[no_mangle] pub extern "C" fn get_firmware_version_len(p_fwv_len: &mut usize) -> sgx_status_t { let version = env!("CARGO_PKG_VERSION"); *p_fwv_len = version.len(); sgx_status_t::SGX_SUCCESS } #[no_mangl...
} #[no_mangle] pub extern "C" fn sgx_get_collateral_report( p_pubkey_challenge: *const u8, pubkey_challenge_size: usize, p_target_info: *const sgx_target_info_t, report: *mut sgx_types::sgx_report_t, csr_buffer: *mut u8, csr_buf_size: usize, p_csr_size: *mut usize, ) -> sgx_status_t { l...
*private_key_guard = Some(pkcs8_bytes.as_ref().to_vec()); pkcs8_bytes.as_ref().to_vec() } }; return Ok(pkcs8_bytes);
random_line_split
config.pb.go
() ([]byte, []int) { return fileDescriptor0, []int{2} } func (m *LinkTemplate) GetOptions() []*LinkOptionsTemplate { if m != nil { return m.Options } return nil } // A simple key/value pair for link options. type LinkOptionsTemplate struct { // The key for the option. This is not expanded. Key string `protobuf...
Descriptor
identifier_name
config.pb.go
func (TestGroup_TestsName) EnumDescriptor() ([]byte, []int) { return fileDescriptor0, []int{0, 0} } // Specifies a group of tests to gather. type TestGroup struct { // Name of this TestGroup, for mapping dashboard tabs to tests. Name string `protobuf:"bytes,1,opt,name=name" yaml:"name,omitempty"` // Path to the te...
{ return proto.EnumName(TestGroup_TestsName_name, int32(x)) }
identifier_body
config.pb.go
} // A simple key/value pair for link options. type LinkOptionsTemplate struct { // The key for the option. This is not expanded. Key string `protobuf:"bytes,1,opt,name=key" yaml:"key,omitempty"` // The value for the option. This is expanded the same as the LinkTemplate. Value string `protobuf:"bytes,2,opt,name=va...
} func (m *DashboardTab) GetResultsUrlTemplate() *LinkTemplate { if m != nil { return m.ResultsUrlTemplate } return nil } func (m *DashboardTab) GetCodeSearchUrlTemplate() *LinkTemplate { if m != nil { return m.CodeSearchUrlTemplate } return nil } // A service configuration consisting of multiple test grou...
random_line_split
config.pb.go
// A simple key/value pair for link options. type LinkOptionsTemplate struct { // The key for the option. This is not expanded. Key string `protobuf:"bytes,1,opt,name=key" yaml:"key,omitempty"` // The value for the option. This is expanded the same as the LinkTemplate. Value string `protobuf:"bytes,2,opt,name=value...
return nil } type DefaultConfiguration struct { // A default testgroup with default initialization data DefaultTestGroup *TestGroup `protobuf:"bytes,1,opt,name=default_test_group,json=defaultTestGroup" yaml:"default_test_group,omitempty"` // A default dashboard with default initialization data DefaultDashboardTa...
{ return m.Dashboards }
conditional_block
main.rs
data ^= key; let zero = Simd::splat(0); data = data.aes_dec_last(zero).aes_enc(zero); return data.aes_enc_last(zero); } fn inv_aes_decx4(mut hash: Simd<u8, 16>) -> Simd<u8, 16> { let zero = Simd::splat(0); hash = hash.aes_dec_last(zero); hash = hash.aes_enc(zero); hash = hash.aes_enc(zero)...
fn chosen_prefix(prefix: &[u8]) { let zero = Simd::splat(0); let mut message = prefix.to_vec(); let remainder = 16 - (message.len() % 16); message.extend((0..remainder).map(|_| b'A')); message.extend((0..16).map(|_| 0)); let hash = ComputeGlyphHash(&message); let pre_current = invert_last(...
{ let mut target_hash = Simd::<u64, 2>::from_array([message.len() as u64, 0]).to_ne_bytes(); target_hash ^= DEFAULT_SEED; let prefix = single_prefix(message.len(), target_hash); println!("Demonstrating prefix attack"); println!("message: {:x?}", message); println!("hash: {:x?}", ComputeGlyph...
identifier_body
main.rs
data ^= key; let zero = Simd::splat(0); data = data.aes_dec_last(zero).aes_enc(zero); return data.aes_enc_last(zero); } fn inv_aes_decx4(mut hash: Simd<u8, 16>) -> Simd<u8, 16> { let zero = Simd::splat(0); hash = hash.aes_dec_last(zero); hash = hash.aes_enc(zero); hash = hash.aes_enc(zero)...
(prefix: Simd<u8, 16>, target: &[u8]) -> Vec<u8> { let mut image = prefix.to_array().to_vec(); image.extend_from_slice(target); image } fn prefix_collision_attack(message: &[u8]) { let mut target_hash = Simd::<u64, 2>::from_array([message.len() as u64, 0]).to_ne_bytes(); target_hash ^= DEFAULT_SEED...
concat
identifier_name
main.rs
u8]) { let zero = Simd::splat(0); let mut message = prefix.to_vec(); let remainder = 16 - (message.len() % 16); message.extend((0..remainder).map(|_| b'A')); message.extend((0..16).map(|_| 0)); let hash = ComputeGlyphHash(&message); let pre_current = invert_last(&[], hash); let pre_targe...
br#" two strings "A" and "B\x00" yield the same hash, because"#, b" the padding is constant, so zero byte in the end doens't", b" matter, and the first byte is `xor`ed with input length.", b" If you'd like to, you can read this blog post explaining", b" these attacks in detail and how to avoid them us...
random_line_split
main.rs
data ^= key; let zero = Simd::splat(0); data = data.aes_dec_last(zero).aes_enc(zero); return data.aes_enc_last(zero); } fn inv_aes_decx4(mut hash: Simd<u8, 16>) -> Simd<u8, 16> { let zero = Simd::splat(0); hash = hash.aes_dec_last(zero); hash = hash.aes_enc(zero); hash = hash.aes_enc(zero)...
buffer[0] ^= len as u8; let recovered = &buffer[..len]; println!("recovered: {:x?}", recovered); println!("hash: {:x?}", ComputeGlyphHash(recovered)); println!(); } pub fn check_alphanum(bytes: Simd<u8, 16>) -> bool { // check if the characters are outside of '0'..'z' range if (bytes ...
{ println!("the plaintext mus be shorter than 16 bytes, cannot invert"); return; }
conditional_block
constants.go
a while) AverecmdRetrySleepSeconds = 10 ShellcmdRetryCount = 60 // wait 10 minutes (ex. apt install waiting for lock to release) ShellcmdRetrySleepSeconds = 10 ClusterAliveRetryCount = 3 // try 3 times to see if the cluster is alive ClusterAliveRetrySleepSeconds = 5 AverecmdLogFile ...
cifs_netbios_domain_name = "cifs_netbios_domain_name" cifs_dc_addreses = "cifs_dc_addreses" cifs_server_name = "cifs_server_name" cifs_username = "cifs_username" cifs_password = "cifs_password" cifs_flatfile_pas...
active_support_upload = "active_support_upload" enable_secure_proactive_support = "enable_secure_proactive_support" cifs_ad_domain = "cifs_ad_domain"
random_line_split
FRB_MCMC.py
# #################################################################### #EoR parameters (fixed in this version) zeta = 500 Mturn = 10 Rmfp = 30 #Cosmology constants nHI = 10 H0 = float(68)/float(3.086e19) OMm = 0.25 OMl = 0.75 baryon2DMfrac = 0.05 #constants pc = 3.08*10**16 # pc in terms of m cm2m = 0...
def lnprob(x, fiducial_DM_z ): lp = lnprior(x) if not np.isfinite(lp): return -np.inf return lp + lnlike(x, fiducial_DM_z) beta_list = [] zeta_list = [] Mturn_list = [] model_DM_z = [] Rmfp_list = [] chi2_model = [] def lnlike(x, fiducial_DM_z): #draw a tag for this run OUTPUT_NUMBER = i...
beta = x[0] zeta = x[1] Mturn = x[2] Rmfp = x[3] if -1 < beta < 1 and 200 < zeta < 1000 and 1e7 < (Mturn*5e7) < 9e9 and 5 < Rmfp < 60: os.system("echo RUN " + str(RUN) + " accepting the fuck out of beta " + str(beta) + " " + str(zeta) + " " + str(Mturn) + " " + str(Rmfp) ) return...
identifier_body
FRB_MCMC.py
else: sign = np.sign(-np.pi*(beta) - np.pi) sigma = np.abs(-np.pi*(beta) - np.pi) return (sign*sigma) #################################################################### # Cosmology and Astrophysical Parameters # ###################################################...
sign = np.sign(-np.pi*(beta) + np.pi) sigma = np.abs(-np.pi*(beta) + np.pi) return (sign*sigma)
conditional_block
FRB_MCMC.py
# #################################################################### #EoR parameters (fixed in this version) zeta = 500 Mturn = 10 Rmfp = 30 #Cosmology constants nHI = 10 H0 = float(68)/float(3.086e19) OMm = 0.25 OMl = 0.75 baryon2DMfrac = 0.05 #constants pc = 3.08*10**16 # pc in terms of m cm2m = 0...
(x): beta = x[0] zeta = x[1] Mturn = x[2] Rmfp = x[3] if -1 < beta < 1 and 200 < zeta < 1000 and 1e7 < (Mturn*5e7) < 9e9 and 5 < Rmfp < 60: os.system("echo RUN " + str(RUN) + " accepting the fuck out of beta " + str(beta) + " " + str(zeta) + " " + str(Mturn) + " " + str(Rmfp) ) ...
lnprior
identifier_name
FRB_MCMC.py
Parameters # #################################################################### #EoR parameters (fixed in this version) zeta = 500 Mturn = 10 Rmfp = 30 #Cosmology constants nHI = 10 H0 = float(68)/float(3.086e19) OMm = 0.25 OMl = 0.75 baryon2DMfrac = 0.05 #constants pc = 3.08*10**16 # pc in terms of...
#################################################################### # FRB script loader # #################################################################### #Constants for the script Box_length = 300 HII_DIM = 200 DIM = 800 #######################################################...
#os.chdir("/home/grx40/projects/def-acliu/grx40/soft/21cmFASTM/Programs/") #dimensions and walkers of EnsembleSampler ndim = 4 nwalkers = 24
random_line_split
marker_detector.py
), cv2.COLOR_BGR2HSV) self.gray = cv2.cvtColor(self.blurred, cv2.COLOR_BGR2GRAY) self.edged = cv2.Canny(self.blurred, 50, 150) self.lab = cv2.cvtColor(self.blurred, cv2.COLOR_BGR2LAB) self.thresh = cv2.threshold(self.gray, 60, 255, cv2.THRESH_BINARY)[1] self.cnts = None def ...
def draw_train_status(self, image, idx): string = "Train: " + str(idx) cv2.putText(image, string, (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) pass def draw_crosshair(self, image, shape): (startX, endX) = (int(shape.centerX - (shape.w * 0.15)), int(shape.centerX ...
string = "Station: " + text cv2.putText(image, string, (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) pass
identifier_body
marker_detector.py
init__(self): pass def draw_station_status(self, image, text): string = "Station: " + text cv2.putText(image, string, (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 2) pass def draw_train_status(self, image, idx): string = "Train: " + str(idx) cv2.putTe...
for j in range(0, len(cnts_array)): if cnts_array[j].area != 0: ratio = cnts_array[i].area / cnts_array[j].area if abs(ratio-expected_ratio) <= err and self.check_similarity_of_two_cw(cnts_array[i], cnts_array[j]): return cnts_array[i], cnt...
conditional_block
marker_detector.py
), cv2.COLOR_BGR2HSV) self.gray = cv2.cvtColor(self.blurred, cv2.COLOR_BGR2GRAY) self.edged = cv2.Canny(self.blurred, 50, 150) self.lab = cv2.cvtColor(self.blurred, cv2.COLOR_BGR2LAB) self.thresh = cv2.threshold(self.gray, 60, 255, cv2.THRESH_BINARY)[1] self.cnts = None def ...
(self): self.__contours(self.thresh) return self.cnts class ContourWrapper: def __init__(self, contour, ratio=1): self.contour = contour self.ratio = ratio self.peri = cv2.arcLength(self.contour, True) self.approx = cv2.approxPolyDP(self.contour, 0.04 * self.peri, T...
contours_color
identifier_name
marker_detector.py
55), 3) pass def draw_contour(self, image, approx): cv2.drawContours(image, [approx], -1, (0, 255, 255), 4) pass square_str = "square" triangle_str = "triangle" class Shape: def __init__(self, type="", area=0, center_x=0, center_y=0, x=0, y=0, w=0, h=0): self.type = type ...
# #
random_line_split
application.py
#StdLibs import json from os import path import csv ################################################### #Programmato da Alex Prosdocimo e Matteo Mirandola# ################################################### application = Flask(__name__) @application.route("/") # Index def index(): return mak...
import requests #Apache 2.0
random_line_split