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
Histo.js
/** * @jsx React.DOM */ var React = require('react/addons'); var cx = React.addons.classSet; var moment = require('moment'); var Router = require('react-router'); var Route = Router.Route; var NotFoundRoute = Router.NotFoundRoute; var DefaultRoute = Router.DefaultRoute; var Link = Router.Link; var RouteHandler = Ro...
() { var x0 = x.invert(d3.mouse(this)[0]), i = bisectDate(values, x0, 1), d0 = values[i - 1], d1 = values[i], d = x0 - d0.Date > d1.Date - x0 ? d1 : d0; if(chartType === 'pi') { focus.attr("transform", "translate(" ...
mousemove
identifier_name
ws.rs
// Copyright 2021, The Tremor Team // // 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 t...
let after_close = self.stream.next().await; debug_assert!( after_close.is_none(), "WS reader not behaving as expected after receiving a close message" ); return Ok(Sour...
Message::Close(_) => { // read from the stream once again to drive the closing handshake
random_line_split
ws.rs
// Copyright 2021, The Tremor Team // // 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 t...
; Ok(SourceReply::Data { origin_uri: self.origin_uri.clone(), stream: Some(stream), meta: Some(meta), data, port: None, codec_overwrite: None, }) } ...
{ meta.insert("binary", Value::const_true())?; }
conditional_block
ws.rs
// Copyright 2021, The Tremor Team // // 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 t...
(sink: SplitSink<WebSocketStream<TcpStream>, Message>) -> Self { Self { sink } } } impl WsWriter<TlsStream<TcpStream>> { fn new_tls_server(sink: SplitSink<WebSocketStream<TlsStream<TcpStream>>, Message>) -> Self { Self { sink } } } impl WsWriter<TcpStream> { fn new_tungstenite_client(s...
new
identifier_name
ws.rs
// Copyright 2021, The Tremor Team // // 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 t...
} impl WsWriter<TcpStream> { fn new_tungstenite_client(sink: SplitSink<WebSocketStream<TcpStream>, Message>) -> Self { Self { sink } } } impl WsWriter<tokio_rustls::client::TlsStream<TcpStream>> { fn new_tls_client( sink: SplitSink<WebSocketStream<tokio_rustls::client::TlsStream<TcpStream...
{ Self { sink } }
identifier_body
cabi.rs
use std::ptr; use std::mem; use std::slice; use std::panic; use std::ffi::{CStr, OsStr}; use std::borrow::Cow; use std::os::raw::{c_int, c_uint, c_char}; use std::os::unix::ffi::OsStrExt; use proguard::MappingView; use sourcemap::Error as SourceMapError; use errors::{Error, ErrorKind, Result}; use unified::{View, Toke...
format!("{}\x00", path) }; Ok(Box::into_raw(s.into_boxed_str()) as *mut u8) });
} else {
random_line_split
cabi.rs
use std::ptr; use std::mem; use std::slice; use std::panic; use std::ffi::{CStr, OsStr}; use std::borrow::Cow; use std::os::raw::{c_int, c_uint, c_char}; use std::os::unix::ffi::OsStrExt; use proguard::MappingView; use sourcemap::Error as SourceMapError; use errors::{Error, ErrorKind, Result}; use unified::{View, Toke...
<'a>(out: *mut Token, tm: &'a TokenMatch<'a>) { (*out).dst_line = tm.dst_line; (*out).dst_col = tm.dst_col; (*out).src_line = tm.src_line; (*out).src_col = tm.src_col; (*out).name = match tm.name { Some(name) => name.as_ptr(), None => ptr::null() }; (*out).name_len = tm.name....
set_token
identifier_name
main.rs
/** * Rust's module/package system is *very* fully-featured and rich. * It's worth revisiting the rust book chapter, which is chock full of * special-case details, synonyms, tricks and tips. * * https://doc.rust-lang.org/book/ch07-00-packages-crates-and-modules.html * * * Here are a few of the highest-le...
(msg: &str) { println!("Blort says: {}", msg); } } // next, the series of *declarations*, each of which points to one of the // module implementations discussed above. The declaration phase is easy to // forget, because the implementations are all part of the project, and so // their source files are ver...
blort
identifier_name
main.rs
/** * Rust's module/package system is *very* fully-featured and rich. * It's worth revisiting the rust book chapter, which is chock full of * special-case details, synonyms, tricks and tips. * * https://doc.rust-lang.org/book/ch07-00-packages-crates-and-modules.html * * * Here are a few of the highest-le...
} // next, the series of *declarations*, each of which points to one of the // module implementations discussed above. The declaration phase is easy to // forget, because the implementations are all part of the project, and so // their source files are very close by. But you are *required* to make an // explicit dec...
{ println!("Blort says: {}", msg); }
identifier_body
main.rs
/** * Rust's module/package system is *very* fully-featured and rich. * It's worth revisiting the rust book chapter, which is chock full of * special-case details, synonyms, tricks and tips. * * https://doc.rust-lang.org/book/ch07-00-packages-crates-and-modules.html * * * Here are a few of the highest-le...
// module implementations discussed above. The declaration phase is easy to // forget, because the implementations are all part of the project, and so // their source files are very close by. But you are *required* to make an // explicit declaration nontheless. If you throw in references to `crate::x::y` // without h...
println!("Blort says: {}", msg); } } // next, the series of *declarations*, each of which points to one of the
random_line_split
validate.rs
use crate::{ config::{self, Config, ConfigDiff}, topology::{self, builder::Pieces}, }; use colored::*; use exitcode::ExitCode; use std::collections::HashMap; use std::{fmt, fs::remove_dir_all, path::PathBuf}; use structopt::StructOpt; const TEMPORARY_DIRECTORY: &str = "validate_tmp"; #[derive(StructOpt, Debug...
} /// Performs topology, component, and health checks. pub async fn validate(opts: &Opts, color: bool) -> ExitCode { let mut fmt = Formatter::new(color); let mut validated = true; let mut config = match validate_config(opts, &mut fmt) { Some(config) => config, None => return exitcode::CO...
{ config::merge_path_lists(vec![ (&self.paths, None), (&self.paths_toml, Some(config::Format::Toml)), (&self.paths_json, Some(config::Format::Json)), (&self.paths_yaml, Some(config::Format::Yaml)), ]) .map(|(path, hint)| config::ConfigPath::File(pa...
identifier_body
validate.rs
use crate::{ config::{self, Config, ConfigDiff}, topology::{self, builder::Pieces}, }; use colored::*; use exitcode::ExitCode; use std::collections::HashMap; use std::{fmt, fs::remove_dir_all, path::PathBuf}; use structopt::StructOpt; const TEMPORARY_DIRECTORY: &str = "validate_tmp"; #[derive(StructOpt, Debug...
t self) { if self.print_space { self.print_space = false; println!(); } } fn print(&mut self, print: impl AsRef<str>) { let width = print .as_ref() .lines() .map(|line| { String::from_utf8_lossy(&strip_ansi_esca...
e(&mu
identifier_name
validate.rs
use crate::{ config::{self, Config, ConfigDiff}, topology::{self, builder::Pieces}, }; use colored::*; use exitcode::ExitCode; use std::collections::HashMap; use std::{fmt, fs::remove_dir_all, path::PathBuf}; use structopt::StructOpt; const TEMPORARY_DIRECTORY: &str = "validate_tmp"; #[derive(StructOpt, Debug...
} /// Standalone line fn success(&mut self, msg: impl AsRef<str>) { self.print(format!("{} {}\n", self.success_intro, msg.as_ref())) } /// Standalone line fn warning(&mut self, warning: impl AsRef<str>) { self.print(format!("{} {}\n", self.warning_intro, warning.as_ref())) ...
} else { println!("{:>width$}", "Validated", width = self.max_line_width) }
random_line_split
mod.rs
#![allow(clippy::pub_enum_variant_names)] use std::collections::HashMap; use serde::{Serialize, Serializer}; extern crate snowflake; pub use std::sync::Arc; use crate::ast::*; use crate::externals::{External, ArgumentType, EXTERNALS}; mod intexp; mod opexp; mod recordexp; mod seqexp; mod assignexp; mod ifexp; mod whi...
(ast : AST) -> Result<AST, TypeError> { let typed_ast = type_exp(ast, &initial_type_env(), &initial_value_env())?; if *typed_ast.typ == TigerType::TInt(R::RW) { Ok(typed_ast) } else { Err(TypeError::NonIntegerProgram(typed_ast.pos)) } }
typecheck
identifier_name
mod.rs
#![allow(clippy::pub_enum_variant_names)] use std::collections::HashMap; use serde::{Serialize, Serializer}; extern crate snowflake; pub use std::sync::Arc; use crate::ast::*; use crate::externals::{External, ArgumentType, EXTERNALS}; mod intexp; mod opexp; mod recordexp; mod seqexp; mod assignexp; mod ifexp; mod whi...
} else { false } } /// An entry in our `TypeEnviroment` table. #[derive(Clone, Debug)] pub enum EnvEntry { /// A declared varaible Var { /// The type of the variable ty: Arc<TigerType>, }, /// A declared function Func { /// The types of the arguments of the function ...
/// Returns true iif the type is an Int pub fn es_int(t: &TigerType) -> bool { if let TigerType::TInt(_) = *t { true
random_line_split
models.py
from enum import Enum from typing import List, Dict, Union, Tuple class UserAgents: def __init__(self, head: str, version: List[str]): self.head = head self.version = version self.index = -1 def get_next_user_agent(self): self.index = (self.index + 1) % len(self.version) ...
(self): body_repr_length = 100 body_repr = repr(self.body) print_body = body_repr[:body_repr_length] if body_repr[body_repr_length:]: print_body += '...' return 'Review(reviewer={}, reviewer_url={}, review_url={}, title={}, rating={}, helpful={}, body={})'.format( ...
__repr__
identifier_name
models.py
from enum import Enum from typing import List, Dict, Union, Tuple class UserAgents: def __init__(self, head: str, version: List[str]): self.head = head self.version = version self.index = -1 def get_next_user_agent(self): self.index = (self.index + 1) % len(self.version) ...
return 'ReviewList(reviews={}, asin={}, country={}, page={}, last_page={})'.format(print_reviews, repr(self.asin), self.country, ...
print_reviews += '...'
conditional_block
models.py
from enum import Enum from typing import List, Dict, Union, Tuple class UserAgents: def __init__(self, head: str, version: List[str]): self.head = head self.version = version self.index = -1 def get_next_user_agent(self): self.index = (self.index + 1) % len(self.version) ...
def __init__(self, sort_by: ReviewParameter.SortBy = ReviewParameter.SortBy.Helpful, reviewer_type: ReviewParameter.SortBy = ReviewParameter.ReviewerType.AllReviews, format_type: ReviewParameter.FormatType = ReviewParameter.FormatType.AllFormats, m...
class ReviewSettings:
random_line_split
models.py
from enum import Enum from typing import List, Dict, Union, Tuple class UserAgents: def __init__(self, head: str, version: List[str]): self.head = head self.version = version self.index = -1 def get_next_user_agent(self): self.index = (self.index + 1) % len(self.version) ...
class Review: def __init__(self, reviewer: str, reviewer_url: str, review_url: str, title: str, rating: int, helpful: int, body: str): self.reviewer = reviewer self.reviewer_url = reviewer_url self.review_url = review_url self.title = title self.rating = r...
def __init__(self, product_name: str, offer_count: int, offers: List[Offer], settings: Dict[str, bool]): self.product_name = product_name self.offer_count = offer_count self.offers = offers self.page = settings['page'] self.settings = settings def __repr__(self): off...
identifier_body
training.go
// training is a package for managing MXNet training jobs. package trainer import ( "fmt" "reflect" "github.com/deepinsight/mxnet-operator/pkg/spec" "github.com/deepinsight/mxnet-operator/pkg/util" "github.com/deepinsight/mxnet-operator/pkg/util/k8sutil" "github.com/deepinsight/mxnet-operator/pkg/util/retryuti...
err = j.job.Spec.Validate() if err != nil { return fmt.Errorf("invalid job spec: %v", err) } for _, t := range j.job.Spec.ReplicaSpecs { r, err := NewMXReplicaSet(j.KubeCli, *t, j) if err != nil { return err } j.Replicas = append(j.Replicas, r) } if err := j.job.Spec.ConfigureAccelerators(config....
{ return fmt.Errorf("there was a problem setting defaults for job spec: %v", err) }
conditional_block
training.go
// training is a package for managing MXNet training jobs. package trainer import ( "fmt" "reflect" "github.com/deepinsight/mxnet-operator/pkg/spec" "github.com/deepinsight/mxnet-operator/pkg/util" "github.com/deepinsight/mxnet-operator/pkg/util/k8sutil" "github.com/deepinsight/mxnet-operator/pkg/util/retryuti...
} log.Warningf("retry report status in %v: fail to get latest version: %v", retryInterval, err) return false, nil } j.job = cl return false, nil } retryutil.Retry(retryInterval, math.MaxInt64, f) } func (j *TrainingJob) name() string { return j.job.Metadata.GetName() }
// Because it will check UID first and return something like: // "Precondition failed: UID in precondition: 0xc42712c0f0, UID in object meta: ". if k8sutil.IsKubernetesResourceNotFoundError(err) { return true, nil
random_line_split
training.go
// training is a package for managing MXNet training jobs. package trainer import ( "fmt" "reflect" "github.com/deepinsight/mxnet-operator/pkg/spec" "github.com/deepinsight/mxnet-operator/pkg/util" "github.com/deepinsight/mxnet-operator/pkg/util/k8sutil" "github.com/deepinsight/mxnet-operator/pkg/util/retryuti...
// isRetryableTerminationState returns true if a container terminated in a state // that we consider retryable. func isRetryableTerminationState(s *v1.ContainerStateTerminated) bool { // TODO(jlewi): Need to match logic in // https://cs.corp.google.com/piper///depot/google3/cloud/ml/beta/job/training_job_state_util...
{ state := spec.StateUnknown replicaStatuses := make([]*spec.MxReplicaStatus, 0) // The state for each replica. // TODO(jlewi): We will need to modify this code if we want to allow multiples of a given type of replica. replicaSetStates := make(map[spec.MxReplicaType]spec.ReplicaState) for _, r := range j.Replic...
identifier_body
training.go
// training is a package for managing MXNet training jobs. package trainer import ( "fmt" "reflect" "github.com/deepinsight/mxnet-operator/pkg/spec" "github.com/deepinsight/mxnet-operator/pkg/util" "github.com/deepinsight/mxnet-operator/pkg/util/k8sutil" "github.com/deepinsight/mxnet-operator/pkg/util/retryuti...
() string { return fmt.Sprintf("master-%v-0", j.job.Spec.RuntimeId) } // setup the training job. func (j *TrainingJob) setup(config *spec.ControllerConfig) error { if j.job == nil { return fmt.Errorf("job.Spec can't be nil") } err := j.job.Spec.SetDefaults() if err != nil { return fmt.Errorf("there was a pro...
masterName
identifier_name
model_pki_patch_role_response.go
// Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 // // Code generated with OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package schema // PkiPatchRoleResponse struct for PkiPatchRoleResponse type PkiPatchRoleResponse struct { // If set, clients can request certificates for any...
() *PkiPatchRoleResponse { var this PkiPatchRoleResponse this.ServerFlag = true return &this }
NewPkiPatchRoleResponseWithDefaults
identifier_name
model_pki_patch_role_response.go
// Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 // // Code generated with OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package schema // PkiPatchRoleResponse struct for PkiPatchRoleResponse type PkiPatchRoleResponse struct { // If set, clients can request certificates for any...
{ var this PkiPatchRoleResponse this.ServerFlag = true return &this }
identifier_body
model_pki_patch_role_response.go
// Copyright (c) HashiCorp, Inc. // SPDX-License-Identifier: MPL-2.0 // // Code generated with OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. package schema // PkiPatchRoleResponse struct for PkiPatchRoleResponse type PkiPatchRoleResponse struct { // If set, clients can request certificates for any...
ClientFlag bool `json:"client_flag,omitempty"` // List of allowed validations to run against the Common Name field. Values can include 'email' to validate the CN is a email address, 'hostname' to validate the CN is a valid hostname (potentially including wildcards). When multiple validations are specified, these tak...
// Mark Basic Constraints valid when issuing non-CA certificates. BasicConstraintsValidForNonCa bool `json:"basic_constraints_valid_for_non_ca,omitempty"` // If set, certificates are flagged for client auth use. Defaults to true. See also RFC 5280 Section 4.2.1.12.
random_line_split
api_test.go
/* Copyright 2017 Continusec Pty Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
func testLog(ctx context.Context, t *testing.T, service pb.VerifiableDataStructuresServiceServer) { account := (&verifiable.Client{ Service: service, }).Account("999", "secret") log := account.VerifiableLog("smoketest") treeRoot, err := log.TreeHead(ctx, 0) if !(treeRoot == nil || (treeRoot.TreeSize == 0 && l...
{ account := (&verifiable.Client{ Service: service, }).Account("999", "secret") vmap := account.VerifiableMap("testmap") numToDo := 1000 var lastP verifiable.MapUpdatePromise var err error for i := 0; i < numToDo; i++ { lastP, err = vmap.Set(ctx, []byte(fmt.Sprintf("foo%d", i)), &pb.LeafData{LeafInput: []by...
identifier_body
api_test.go
/* Copyright 2017 Continusec Pty Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
(ctx context.Context, t *testing.T, service pb.VerifiableDataStructuresServiceServer) { account := (&verifiable.Client{ Service: service, }).Account("999", "secret") vmap := account.VerifiableMap("testmap") numToDo := 1000 var lastP verifiable.MapUpdatePromise var err error for i := 0; i < numToDo; i++ { la...
testMap
identifier_name
api_test.go
/* Copyright 2017 Continusec Pty Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
kw = &memory.TransientStorage{} kr = &bolt.Storage{} kw = &bolt.Storage{} kr = &badger.Storage{} kw = &badger.Storage{} m = &instant.Mutator{} m = (&batch.Mutator{}).MustCreate() o = policy.Open o = &policy.Static{} log.Println(kr, kw, m, o) // "use" these so that go compiler will be quiet }
random_line_split
api_test.go
/* Copyright 2017 Continusec Pty Ltd Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, soft...
if treeRoot.TreeSize != 205 { t.Fatal("Failure getting root hash") } cnt := 0 for entry := range log.Entries(context.Background(), 0, treeRoot.TreeSize) { err = log.VerifyInclusion(ctx, treeRoot, merkle.LeafHash(entry.LeafInput)) if err != nil { t.Fatal("Failure verifiying inclusion") } cnt++ } if...
{ t.Fatal(err) }
conditional_block
client.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
func GetClient() (*Client, error) { token := os.Getenv(apiTokenVarName) if token == "" { return nil, fmt.Errorf("%w: %s", ErrMissingEnvVar, apiTokenVarName) } return NewClient(token), nil } func (p *Client) GetDevice(ctx context.Context, deviceID string) (*metal.Device, *http.Response, error) { dev, resp, err...
{ token := strings.TrimSpace(packetAPIKey) if token != "" { configuration := metal.NewConfiguration() configuration.Debug = checkEnvForDebug() configuration.AddDefaultHeader("X-Auth-Token", token) configuration.AddDefaultHeader("X-Consumer-Token", clientName) configuration.UserAgent = fmt.Sprintf(clientUAF...
identifier_body
client.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
stringWriter := &strings.Builder{} userData := string(userDataRaw) userDataValues := map[string]interface{}{ "kubernetesVersion": pointer.StringPtrDerefOr(req.MachineScope.Machine.Spec.Version, ""), } tags := make([]string, 0, len(packetMachineSpec.Tags)+len(req.ExtraTags)) copy(tags, packetMachineSpec.Tags)...
{ return nil, fmt.Errorf("unable to retrieve bootstrap data from secret: %w", err) }
conditional_block
client.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
() (*Client, error) { token := os.Getenv(apiTokenVarName) if token == "" { return nil, fmt.Errorf("%w: %s", ErrMissingEnvVar, apiTokenVarName) } return NewClient(token), nil } func (p *Client) GetDevice(ctx context.Context, deviceID string) (*metal.Device, *http.Response, error) { dev, resp, err := p.DevicesApi...
GetClient
identifier_name
client.go
/* Copyright 2020 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
Facility: []string{facility}, BillingCycle: &req.MachineScope.PacketMachine.Spec.BillingCycle, Plan: req.MachineScope.PacketMachine.Spec.MachineType, OperatingSystem: req.MachineScope.PacketMachine.Spec.OS, IpxeScriptUrl: &req.MachineScope.PacketMachine.Spec.IPXEUrl, Tags: ...
serverCreateOpts := metal.CreateDeviceRequest{} if facility != "" { serverCreateOpts.DeviceCreateInFacilityInput = &metal.DeviceCreateInFacilityInput{ Hostname: &hostname,
random_line_split
main.rs
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>);...
let mut prover_transcript = Transcript::new(b"test"); let mut prover = Prover::new( &bp_gens, &pc_gens, &mut prover_transcript, ); let (in1_pt, in1_var) = prover.commit(x1.into(), Scalar::random(&mut rng)); l...
0u64 };
conditional_block
main.rs
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>);...
brackets: &TaxBrackets, total: u64) -> u64 { (0..brackets.0.len()) .map(|i| { let last_cutoff = if i == 0 { 0u64 } else { brackets.0[i-1].0 }; let (next_cutoff, rate) = brackets.0[i]; let amount = if total > next_cutoff { next_cutoff - last_cutoff ...
ompute_taxes(
identifier_name
main.rs
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>);...
) -> Result<LinearCombination, R1CSError> { let lhs_bits = scalar_to_bits_le(cs, n_bits, lhs)?; let rhs_bits = scalar_to_bits_le(cs, n_bits, rhs)?; let zero = LinearCombination::default(); // Iterate through bits from most significant to least, comparing each pair. let (lt, _) = lhs_bits.into_iter...
rhs: LinearCombination
random_line_split
main.rs
use bulletproofs::r1cs::{ ConstraintSystem, LinearCombination, Prover, R1CSError, Variable, Verifier, }; use bulletproofs::{ BulletproofGens, PedersenGens, }; use curve25519_dalek::scalar::Scalar; use merlin::Transcript; use rand::Rng; use std::u64; struct TaxBrackets(Vec<(u64, u64)>);...
fn synthesize<CS: ConstraintSystem>( cs: &mut CS, brackets: &TaxBrackets, values: &[Variable], expected: &Variable ) -> Result<(), R1CSError> { // Compute Σ values. let total = values.iter() .map(|val| (val.clone(), Scalar::one())) .collect::<LinearCombination>(); let mut ...
{ let lhs_bits = scalar_to_bits_le(cs, n_bits, lhs)?; let rhs_bits = scalar_to_bits_le(cs, n_bits, rhs)?; let zero = LinearCombination::default(); // Iterate through bits from most significant to least, comparing each pair. let (lt, _) = lhs_bits.into_iter().zip(rhs_bits.into_iter()) .rev(...
identifier_body
infer.py
# Copyright 2020 Tomas Hodan (hodantom@cmp.felk.cvut.cz). # Copyright 2018 The TensorFlow Authors All Rights Reserved. """A script for inference/visualization. Example: python infer.py --model=ycbv-bop20-xc65-f64 """ import os import os.path import time import numpy as np import cv2 import tensorflow as tf import py...
( sess, samples, predictions, im_ind, crop_size, output_scale, model_store, renderer, task_type, infer_name, infer_dir, vis_dir): """Estimates object poses from one image. Args: sess: TensorFlow session. samples: Dictionary with input data. predictions: Dictionary with predictions. im_i...
process_image
identifier_name
infer.py
# Copyright 2020 Tomas Hodan (hodantom@cmp.felk.cvut.cz). # Copyright 2018 The TensorFlow Authors All Rights Reserved. """A script for inference/visualization. Example: python infer.py --model=ycbv-bop20-xc65-f64 """ import os import os.path import time import numpy as np import cv2 import tensorflow as tf import py...
# Select correspondences with the highest confidence. if FLAGS.max_correspondences is not None \ and num_corrs > FLAGS.max_correspondences: # Sort the correspondences only if they have not been sorted for PROSAC. if FLAGS.use_prosac: keep_inds = np.arange(num_corrs) else: ...
obj_corr[key] = obj_corr[key][sorted_inds]
conditional_block
infer.py
# Copyright 2020 Tomas Hodan (hodantom@cmp.felk.cvut.cz). # Copyright 2018 The TensorFlow Authors All Rights Reserved. """A script for inference/visualization. Example: python infer.py --model=ycbv-bop20-xc65-f64 """ import os import os.path import time import numpy as np import cv2 import tensorflow as tf import py...
renderer=renderer, vis_dir=vis_dir) return poses, run_times def main(unused_argv): tf.logging.set_verbosity(tf.logging.INFO) # Model folder. model_dir = os.path.join(config.TF_MODELS_PATH, FLAGS.model) # Update flags with parameters loaded from the model folder. common.update_flags(os.path....
model_store=model_store,
random_line_split
infer.py
# Copyright 2020 Tomas Hodan (hodantom@cmp.felk.cvut.cz). # Copyright 2018 The TensorFlow Authors All Rights Reserved. """A script for inference/visualization. Example: python infer.py --model=ycbv-bop20-xc65-f64 """ import os import os.path import time import numpy as np import cv2 import tensorflow as tf import py...
def process_image( sess, samples, predictions, im_ind, crop_size, output_scale, model_store, renderer, task_type, infer_name, infer_dir, vis_dir): """Estimates object poses from one image. Args: sess: TensorFlow session. samples: Dictionary with input data. predictions: Dictionary with p...
txt = '# Corr format: u v x y z px_id frag_id conf conf_obj conf_frag\n' txt += '{}\n'.format(image_path) txt += '{} {} {} {}\n'.format(scene_id, im_id, obj_id, pred_time) # Add intrinsics. for i in range(3): txt += '{} {} {}\n'.format(K[i, 0], K[i, 1], K[i, 2]) # Add ground-truth poses. txt += '{}\n'...
identifier_body
main.rs
extern crate rand; extern crate palette; use std::fs::File; use std::io::prelude::*; use std::path::Path; extern crate clap; use std::thread; use std::sync::mpsc; extern crate rayon; use rayon::prelude::*; mod kohonen_neuron; //use kohonen_neuron::rgb_vector_neuron; mod kohonen; use kohonen::Kohonen; mod sphere_of_inf...
<T>( net: &Kohonen<T>, samples: &std::vec::Vec<T>, its: u32, associate: sphere_of_influence::AssociationKind) -> Kohonen<T> where T: kohonen_neuron::KohonenNeuron + Send + Sync + 'static { let mut rv = net.clone(); let width = net.cols as f64; // training with a large fixed radius for a bit ...
iter_train
identifier_name
main.rs
extern crate rand; extern crate palette; use std::fs::File; use std::io::prelude::*; use std::path::Path; extern crate clap; use std::thread; use std::sync::mpsc; extern crate rayon; use rayon::prelude::*; mod kohonen_neuron; //use kohonen_neuron::rgb_vector_neuron; mod kohonen; use kohonen::Kohonen; mod sphere_of_inf...
} let nets: Vec<Kohonen<T>> = descs .par_iter() .map(|(my_net, sample)| { let associate = associate.clone(); let mut net = my_net.clone(); feed_sample(&mut net, &sample, rate, radius, associate); net }) ...
Kohonen<T>: Send + Sync { let mut descs = Vec::new(); for i in 0..samples.len() { descs.push((net.clone(), samples[i].clone())); //feed_sample(net, &samples[i], rate, radius);
random_line_split
main.rs
extern crate rand; extern crate palette; use std::fs::File; use std::io::prelude::*; use std::path::Path; extern crate clap; use std::thread; use std::sync::mpsc; extern crate rayon; use rayon::prelude::*; mod kohonen_neuron; //use kohonen_neuron::rgb_vector_neuron; mod kohonen; use kohonen::Kohonen; mod sphere_of_inf...
pub fn show<T: kohonen_neuron::KohonenNeuron>(net: &Kohonen<T>, path: &str) { let rows = net.rows; let cols = net.cols; let path = Path::new(path); let mut os = match File::create(&path) { Err(why) => panic!("couldn't make file pls halp: {}", why), Ok(file) => file, }; let _ = ...
{ let mut rv = net.clone(); let width = net.cols as f64; // training with a large fixed radius for a bit should help things get into // the right general places /*for _i in 0..(its / 2) { let radius = width / 2.0; let rate = 0.5; rv = train(rv.clone(), samples, rate, radius a...
identifier_body
dis2py.py
import re from ast import literal_eval from dataclasses import dataclass from . import operations COMPREHENSION = 1 GEN_EXPR = 1 << 2 RAW_JUMPS = 1 << 3 @dataclass class Instruction: line_num: int offset: int opname: str arg: int argval: object def get_code_obj_name(s): match = re.match(r"<code object <?(.*?...
) ) else: push_invalid(instruction) elif opname == "MAP_ADD": #used in dict comprehensions if is_comp: key = pop() val = pop() push(operations.SubscriptAssign(key, operations.Value(temp_name), val)) else: push_invalid(instruction) elif opname == "UNPACK_SEQUENCE": push(oper...
push( operations.FunctionCall( operations.Attribute(operations.Value(temp_name), operations.Value(func)), [pop()]
random_line_split
dis2py.py
import re from ast import literal_eval from dataclasses import dataclass from . import operations COMPREHENSION = 1 GEN_EXPR = 1 << 2 RAW_JUMPS = 1 << 3 @dataclass class Instruction: line_num: int offset: int opname: str arg: int argval: object def get_code_obj_name(s): match = re.match(r"<code object <?(.*?...
def pretty_decompile(disasm,flags=0,tab_char="\t"): ret = [] for name, code, arg_names in decompile_all(disasm, flags, tab_char): ret.append( f"def {name}({','.join(arg_names)}):\n" + "\n".join(tab_char + line for line in code.split("\n")) ) return "\n".join(ret)
disasm = re.sub(r"^#.*\n?", "", disasm, re.MULTILINE).strip() # ignore comments for name, func in split_funcs(disasm): yield name, *decompile(func, get_flags(name)|flags, tab_char)
identifier_body
dis2py.py
import re from ast import literal_eval from dataclasses import dataclass from . import operations COMPREHENSION = 1 GEN_EXPR = 1 << 2 RAW_JUMPS = 1 << 3 @dataclass class Instruction: line_num: int offset: int opname: str arg: int argval: object def get_code_obj_name(s): match = re.match(r"<code object <?(.*?...
else: ast.append((indent, operation)) def pop(): return ast.pop()[1] def pop_n(n): nonlocal ast if n > 0: # ast[:-0] would be the empty list and ast[-0:] would be every element in ast if raw_jumps: ret = [x for _, x,_ in ast[-n:]] else: ret = [x for _, x in ast[-n:]] ast = ast[:-n] ...
ast.append((indent,operation,instruction.offset))
conditional_block
dis2py.py
import re from ast import literal_eval from dataclasses import dataclass from . import operations COMPREHENSION = 1 GEN_EXPR = 1 << 2 RAW_JUMPS = 1 << 3 @dataclass class Instruction: line_num: int offset: int opname: str arg: int argval: object def get_code_obj_name(s): match = re.match(r"<code object <?(.*?...
(operation): if raw_jumps: ast.append((indent,operation,instruction.offset)) else: ast.append((indent, operation)) def pop(): return ast.pop()[1] def pop_n(n): nonlocal ast if n > 0: # ast[:-0] would be the empty list and ast[-0:] would be every element in ast if raw_jumps: ret = [x for _,...
push
identifier_name
docker_image_dest.go
package docker import ( "bytes" "context" "crypto/rand" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "github.com/containers/image/docker/reference" "github.com/containers/image/manifest" "github.com/containers/image/types" "github.com/docker/distribution/registry/api...
.Body.Close() if res.StatusCode != http.StatusCreated { body, err := ioutil.ReadAll(res.Body) if err == nil { logrus.Debugf("Error body %s", string(body)) } logrus.Debugf("Error uploading signature, status %d, %#v", res.StatusCode, res) return errors.Wrapf(client.HandleErrorResponse(res), "Error up...
err } defer res
conditional_block
docker_image_dest.go
package docker import ( "bytes" "context" "crypto/rand" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "github.com/containers/image/docker/reference" "github.com/containers/image/manifest" "github.com/containers/image/types" "github.com/docker/distribution/registry/api...
// Reference returns the reference used to set up this destination. Note that this should directly correspond to user's intent, // e.g. it should use the public hostname instead of the result of resolving CNAMEs or following redirects. func (d *dockerImageDestination) Reference() types.ImageReference { return d.ref...
{ c, err := newDockerClientFromRef(sys, ref, true, "pull,push") if err != nil { return nil, err } return &dockerImageDestination{ ref: ref, c: c, }, nil }
identifier_body
docker_image_dest.go
package docker import ( "bytes" "context" "crypto/rand" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "github.com/containers/image/docker/reference" "github.com/containers/image/manifest" "github.com/containers/image/types" "github.com/docker/distribution/registry/api...
return false, errors.Errorf("Unsupported scheme when deleting signature from %s", url.String()) } } // putSignaturesToAPIExtension implements PutSignatures() using the X-Registry-Supports-Signatures API extension. func (d *dockerImageDestination) putSignaturesToAPIExtension(ctx context.Context, signatures [][]byte)...
default:
random_line_split
docker_image_dest.go
package docker import ( "bytes" "context" "crypto/rand" "encoding/json" "fmt" "io" "io/ioutil" "net/http" "net/url" "os" "path/filepath" "github.com/containers/image/docker/reference" "github.com/containers/image/manifest" "github.com/containers/image/types" "github.com/docker/distribution/registry/api...
() types.ImageReference { return d.ref } // Close removes resources associated with an initialized ImageDestination, if any. func (d *dockerImageDestination) Close() error { return nil } func (d *dockerImageDestination) SupportedManifestMIMETypes() []string { return []string{ imgspecv1.MediaTypeImageManifest, ...
Reference
identifier_name
factor_data_preprocess.py
# -*- coding: utf-8 -*- """ Created on Fri Feb 22 09:47:11 2019 @author: admin """ import numpy as np import pandas as pd import os from datetime import datetime from itertools import chain from functools import reduce from sklearn.linear_model import LinearRegression from utility.constant import info_cols, data_dair...
index_price_daily = index_price_daily.loc[tt, :] sf_beta = pd.DataFrame() for c, se in sf_close_daily.iterrows(): if 'IC' in c: tmp_i = index_price_daily['ZZ500'] elif 'IF' in c: tmp_i = index_price_daily['HS300'] elif 'IH' in c: tmp_i = index_pri...
sf_close_daily = sf_close_daily[tt]
random_line_split
factor_data_preprocess.py
# -*- coding: utf-8 -*- """ Created on Fri Feb 22 09:47:11 2019 @author: admin """ import numpy as np import pandas as pd import os from datetime import datetime from itertools import chain from functools import reduce from sklearn.linear_model import LinearRegression from utility.constant import info_cols, data_dair...
identifier_body
factor_data_preprocess.py
# -*- coding: utf-8 -*- """ Created on Fri Feb 22 09:47:11 2019 @author: admin """ import numpy as np import pandas as pd import os from datetime import datetime from itertools import chain from functools import reduce from sklearn.linear_model import LinearRegression from utility.constant import info_cols, data_dair...
use_dummies = 1 if not ind_neu: use_dummies = 0 # 市值中性行业不中性 if use_dummies == 0 and size_neu: X = lncap # 行业中性市值不中性 elif use_dummies == 1 and not size_neu: X = pd.get_dummies(datdf[f'Industry_{ind}']) else: # 使用 pd.get_dummies 生成行业哑变量 ind_dummy_matrix ...
生成行业哑变量
identifier_name
factor_data_preprocess.py
# -*- coding: utf-8 -*- """ Created on Fri Feb 22 09:47:11 2019 @author: admin """ import numpy as np import pandas as pd import os from datetime import datetime from itertools import chain from functools import reduce from sklearn.linear_model import LinearRegression from utility.constant import info_cols, data_dair...
eal_add_list = [col for col in columns_list if col not in panel_dat.columns] if len(real_add_list) == 0: continue # join_axes关键字为沿用那个的index,忽略另一个df的其余数据 panel_dat = pd.concat([panel_dat, toadded_dat[real_add_list]], axis=1, join_axes=[panel_dat.index]) panel_dat.to_csv(os.pa...
gbk', engine='python', index_col=['code']) r
conditional_block
pplot.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ "Post-plotting" utilities that take post-processed performance data (as provided by cocopf.pproc) and plot them in a variety of ways. Their counterpart are several scripts in the pptools/ directory, the goal here is to have these scripts as thin as possible to enable ...
for (kind, name, ds, style) in _pds_plot_iterator(pds, dim, funcId): #print name, ds budgets = ds.funvals[:, 0] funvals = groupby(ds.funvals[:, 1:], axis=1) # Throw away funvals after ftarget reached try: limit = np.nonzero(funvals < 10**-8)[0][0] + 1 e...
baseline_budgets = baseline_ds.funvals[:, 0] baseline_funvals = groupby(baseline_ds.funvals[:, 1:], axis=1) baseline_safefunvals = np.maximum(baseline_funvals, 10**-8) # eschew zeros # fvb is matrix with each row being [budget,funval] baseline_fvb = np.transpose(np.vstack([baseline_budge...
conditional_block
pplot.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ "Post-plotting" utilities that take post-processed performance data (as provided by cocopf.pproc) and plot them in a variety of ways. Their counterpart are several scripts in the pptools/ directory, the goal here is to have these scripts as thin as possible to enable ...
style = styles[i % len(styles)].copy() del style['linestyle'] style['markersize'] = 12. style['markeredgewidth'] = 1.5 style['markerfacecolor'] = 'None' style['markeredgecolor'] = style['color'] style['linestyle'] = 'solid' style['zorder'] = 1 style['linewidth'] = 2 return styl...
styles = bb.genericsettings.line_styles
random_line_split
pplot.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ "Post-plotting" utilities that take post-processed performance data (as provided by cocopf.pproc) and plot them in a variety of ways. Their counterpart are several scripts in the pptools/ directory, the goal here is to have these scripts as thin as possible to enable ...
(self, lst, **kwargs): return np.median(lst, **kwargs) def __str__(self): return 'median' def _style_thickline(xstyle): style = { 'linestyle': 'solid', 'zorder': -1, 'linewidth': 6 } style.update(xstyle) return style def _style_algorithm(name, i): # Automatic colors are fine, no m...
__call__
identifier_name
pplot.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ "Post-plotting" utilities that take post-processed performance data (as provided by cocopf.pproc) and plot them in a variety of ways. Their counterpart are several scripts in the pptools/ directory, the goal here is to have these scripts as thin as possible to enable ...
def legend(obj, ncol=3, **kwargs): """ Show a legend. obj can be an Axes or Figure (in that case, also pass handles and labels arguments). """ # Font size handling here is a bit weird. We specify fontsize=6 # in legend constructor since that affects spacing. However, we # need to manua...
""" An iterator that will in turn yield all drawable curves in the form of (kind, name, ds, style) tuples (where kind is one of 'algorithm', 'oracle', 'unifpf', 'strategy'). """ i = 0 for (algname, ds) in pds.algds_dimfunc((dim, funcId)): yield ('algorithm', algname, ds, _style_algorithm...
identifier_body
parser.go
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/transitional.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>Source file /src/pkg/exp/datafmt/parser.go</title> <link rel="stylesheet" type="text/css" href="../../../../do...
Do not delete this <div>. --> <div id="nav"></div> <!-- Content is HTML-escaped elsewhere --> <pre> <a id="L1"></a><span class="comment">// Copyright 2009 The Go Authors. All rights reserved.</span> <a id="L2"></a><span class="comment">// Use of this source code is governed by a BSD-style</span> <a id="L3...
<h1 id="generatedHeader">Source file /src/pkg/exp/datafmt/parser.go</h1> <!-- The Table of Contents is automatically inserted in this <div>.
random_line_split
capture_agents.py
"""Interfaces for capture agents. Champlain College CSI-480, Fall 2018 The following code was adapted by Joshua Auerbach (jauerbach@champlain.edu) from the UC Berkeley Pacman Projects (see license and attribution below). ---------------------- Licensing Information: You are free to use or extend these projects for e...
(self, index, time_for_computing=.1): """Initialize capture agent with several variables you can query. self.index = index for this agent self.red = true if you're on the red team, false otherwise self.agents_on_team = a list of agent objects that make up your team self.distance...
__init__
identifier_name
capture_agents.py
"""Interfaces for capture agents. Champlain College CSI-480, Fall 2018 The following code was adapted by Joshua Auerbach (jauerbach@champlain.edu) from the UC Berkeley Pacman Projects (see license and attribution below). ---------------------- Licensing Information: You are free to use or extend these projects for e...
score and the opponents score. This number is negative if you're losing. """ if self.red: return game_state.get_score() else: return game_state.get_score() * -1 def get_maze_distance(self, pos1, pos2): """Return the distance between two point...
def get_score(self, game_state): """Return how much you are beating the other team by. This is in the form of a number that is the difference between your
random_line_split
capture_agents.py
"""Interfaces for capture agents. Champlain College CSI-480, Fall 2018 The following code was adapted by Joshua Auerbach (jauerbach@champlain.edu) from the UC Berkeley Pacman Projects (see license and attribution below). ---------------------- Licensing Information: You are free to use or extend these projects for e...
def get_action(self, state): """Take too much time getting action.""" time.sleep(2.0) return random.choice(state.get_legal_actions(self.index))
"""Initialize agent with given index.""" self.index = index
identifier_body
capture_agents.py
"""Interfaces for capture agents. Champlain College CSI-480, Fall 2018 The following code was adapted by Joshua Auerbach (jauerbach@champlain.edu) from the UC Berkeley Pacman Projects (see license and attribution below). ---------------------- Licensing Information: You are free to use or extend these projects for e...
else: return self.choose_action(game_state) def choose_action(self, game_state): """Override this method to make a good agent. It should return a legal action within the time limit (otherwise a random legal action will be chosen for you). """ util.raise...
return game_state.get_legal_actions(self.index)[0]
conditional_block
mod.rs
//! A stateless, layered, multithread video system with OpenGL backends. //! //! # Overview and Goals //! //! The management of video effects has become an important topic and key feature of //! rendering engines. With the increasing number of effects it is not sufficient anymore //! to only support them, but also to i...
drop(Box::from_raw(CTX as *mut VideoSystem)); CTX = std::ptr::null(); } pub(crate) unsafe fn frames() -> Arc<DoubleBuf<Frame>> { ctx().frames() } /// Creates an surface with `SurfaceParams`. #[inline] pub fn create_surface(params: SurfaceParams) -> Result<SurfaceHandle> { ctx().create_surface(params...
{ return; }
conditional_block
mod.rs
//! A stateless, layered, multithread video system with OpenGL backends. //! //! # Overview and Goals //! //! The management of video effects has become an important topic and key feature of //! rendering engines. With the increasing number of effects it is not sufficient anymore //! to only support them, but also to i...
/// Gets the `ShaderParams` if available. #[inline] pub fn shader(handle: ShaderHandle) -> Option<ShaderParams> { ctx().shader(handle) } /// Get the resource state of specified shader. #[inline] pub fn shader_state(handle: ShaderHandle) -> ResourceState { ctx().shader_state(handle) } /// Delete shader state ...
#[inline] pub fn create_shader(params: ShaderParams, vs: String, fs: String) -> Result<ShaderHandle> { ctx().create_shader(params, vs, fs) }
random_line_split
mod.rs
//! A stateless, layered, multithread video system with OpenGL backends. //! //! # Overview and Goals //! //! The management of video effects has become an important topic and key feature of //! rendering engines. With the increasing number of effects it is not sufficient anymore //! to only support them, but also to i...
(params: SurfaceParams) -> Result<SurfaceHandle> { ctx().create_surface(params) } /// Gets the `SurfaceParams` if available. #[inline] pub fn surface(handle: SurfaceHandle) -> Option<SurfaceParams> { ctx().surface(handle) } /// Get the resource state of specified surface. #[inline] pub fn surface_state(handle...
create_surface
identifier_name
mod.rs
//! A stateless, layered, multithread video system with OpenGL backends. //! //! # Overview and Goals //! //! The management of video effects has become an important topic and key feature of //! rendering engines. With the increasing number of effects it is not sufficient anymore //! to only support them, but also to i...
mod ins { use super::system::VideoSystem; pub static mut CTX: *const VideoSystem = std::ptr::null(); #[inline] pub fn ctx() -> &'static VideoSystem { unsafe { debug_assert!( !CTX.is_null(), "video system has not been initialized properly." ...
{ ctx().delete_render_texture(handle) }
identifier_body
crystallography_frame_viewer.py
# This file is part of OnDA. # # OnDA is free software: you can redistribute it and/or modify it under the terms of # the GNU General Public License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # OnDA is distributed in the hope that it will be...
pen=self._ring_pen, pxMode=False, ) def _back_button_clicked(self): # Type () -> None # Manages clicks on the 'back' button. self._stop_stream() if self._current_frame_index > 0: self._current_frame_index -= 1 print("Showing frame ...
x=peak_x_list, y=peak_y_list, symbol="o", size=[5] * len(current_data[b"peak_list"][b"intensity"]), brush=(255, 255, 255, 0),
random_line_split
crystallography_frame_viewer.py
# This file is part of OnDA. # # OnDA is free software: you can redistribute it and/or modify it under the terms of # the GNU General Public License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # OnDA is distributed in the hope that it will be...
try: current_data = self._frame_list[self._current_frame_index] except IndexError: # If the framebuffer is empty, returns without drawing anything. return self._img[self._visual_pixel_map_y, self._visual_pixel_map_x] = ( current_data[b"detector_...
self._frame_list.append(copy.deepcopy(self.received_data[-1])) self._current_frame_index = len(self._frame_list) - 1 # Resets the 'received_data' attribute to None. One can then check if # data has been received simply by checking wether the attribute is not # None. ...
conditional_block
crystallography_frame_viewer.py
# This file is part of OnDA. # # OnDA is free software: you can redistribute it and/or modify it under the terms of # the GNU General Public License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # OnDA is distributed in the hope that it will be...
(geometry_file, hostname, port): # type: (Dict[str, Any], str, int) -> None """ OnDA frame viewer for crystallography. This program must connect to a running OnDA monitor for crystallography. If the monitor broadcasts detector frame data, this viewer will display it. The viewer will also show, overl...
main
identifier_name
crystallography_frame_viewer.py
# This file is part of OnDA. # # OnDA is free software: you can redistribute it and/or modify it under the terms of # the GNU General Public License as published by the Free Software Foundation, either # version 3 of the License, or (at your option) any later version. # # OnDA is distributed in the hope that it will be...
def _forward_button_clicked(self): # Type () -> None # Manages clicks on the 'forward' button. self._stop_stream() if (self._current_frame_index + 1) < len(self._frame_list): self._current_frame_index += 1 print("Showing frame {0} in the buffer".format(self._cur...
self._stop_stream() if self._current_frame_index > 0: self._current_frame_index -= 1 print("Showing frame {0} in the buffer".format(self._current_frame_index)) self._update_image()
identifier_body
run.py
import os import sys import argparse import functools from functools import partial import numpy as np import shutil import paddle import paddle.nn as nn from paddle.io import Dataset, BatchSampler, DataLoader from paddle.metric import Metric, Accuracy, Precision, Recall from paddlenlp.transformers import AutoModelForT...
return example['input_ids'], example['token_type_ids'], label else: return example['input_ids'], example['token_type_ids'] def create_data_holder(task_name): """ Define the input data holder for the glue task. """ input_ids = paddle.static.data( name="input_ids"...
text_pair=example['sentence2'], max_seq_len=max_seq_length) if not is_test:
random_line_split
run.py
import os import sys import argparse import functools from functools import partial import numpy as np import shutil import paddle import paddle.nn as nn from paddle.io import Dataset, BatchSampler, DataLoader from paddle.metric import Metric, Accuracy, Precision, Recall from paddlenlp.transformers import AutoModelForT...
(): devices = paddle.device.get_device().split(':')[0] places = paddle.device._convert_to_place(devices) exe = paddle.static.Executor(places) val_program, feed_target_names, fetch_targets = paddle.static.load_inference_model( global_config['model_dir'], exe, model_filename=global...
eval
identifier_name
run.py
import os import sys import argparse import functools from functools import partial import numpy as np import shutil import paddle import paddle.nn as nn from paddle.io import Dataset, BatchSampler, DataLoader from paddle.metric import Metric, Accuracy, Precision, Recall from paddlenlp.transformers import AutoModelForT...
def main(): all_config = load_config(args.config_path) global global_config assert "Global" in all_config, "Key Global not found in config file." global_config = all_config["Global"] if 'TrainConfig' in all_config: all_config['TrainConfig']['optimizer_builder'][ 'apply_deca...
if name.find("bias") > -1: return True elif name.find("b_0") > -1: return True elif name.find("norm") > -1: return True else: return False
identifier_body
run.py
import os import sys import argparse import functools from functools import partial import numpy as np import shutil import paddle import paddle.nn as nn from paddle.io import Dataset, BatchSampler, DataLoader from paddle.metric import Metric, Accuracy, Precision, Recall from paddlenlp.transformers import AutoModelForT...
else: return False def main(): all_config = load_config(args.config_path) global global_config assert "Global" in all_config, "Key Global not found in config file." global_config = all_config["Global"] if 'TrainConfig' in all_config: all_config['TrainConfig']['optimizer_bui...
return True
conditional_block
rt_threaded.rs
#![warn(rust_2018_idioms)] #![cfg(all(feature = "full", not(tokio_wasi)))] use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use tokio::runtime; use tokio::sync::oneshot; use tokio_test::{assert_err, assert_ok}; use futures::future::poll_fn; use std::future::Future; use std::pin:...
}); } rx.recv().unwrap(); // Wait for the pool to shutdown block.wait(); } } #[test] fn multi_threadpool() { use tokio::sync::oneshot; let rt1 = rt(); let rt2 = rt(); let (tx, rx) = oneshot::channel(); let (done_tx, done_rx) = mpsc::channel(); ...
{ tx.send(()).unwrap(); }
conditional_block
rt_threaded.rs
#![warn(rust_2018_idioms)] #![cfg(all(feature = "full", not(tokio_wasi)))] use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use tokio::runtime; use tokio::sync::oneshot; use tokio_test::{assert_err, assert_ok}; use futures::future::poll_fn; use std::future::Future; use std::pin:...
const TRACKS: usize = 50; for _ in 0..50 { let rt = rt(); let mut start_txs = Vec::with_capacity(TRACKS); let mut final_rxs = Vec::with_capacity(TRACKS); for _ in 0..TRACKS { let (start_tx, mut chain_rx) = tokio::sync::mpsc::channel(10); for _ in 0..CHA...
const CHAIN: usize = 200; const CYCLES: usize = 5;
random_line_split
rt_threaded.rs
#![warn(rust_2018_idioms)] #![cfg(all(feature = "full", not(tokio_wasi)))] use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; use tokio::runtime; use tokio::sync::oneshot; use tokio_test::{assert_err, assert_ok}; use futures::future::poll_fn; use std::future::Future; use std::pin:...
() { struct Shared { waker: Option<Waker>, } struct MyFuture { shared: Arc<Mutex<Shared>>, put_waker: bool, } impl MyFuture { fn new() -> (Self, Self) { let shared = Arc::new(Mutex::new(Shared { waker: None })); let f1 = MyFuture { ...
wake_during_shutdown
identifier_name
FormBaseInput.ts
/* tslint:disable:no-any */ import * as React from 'react'; import * as PropTypes from 'prop-types'; import { IFormBaseInputProps, IFormBaseInputState, DataStoreEntry, typesForInject, IDataProviderCollection, IDataProviderService } from './FormBaseInput.types'; export { IFormBaseInputProps }; import { BaseComponent, IC...
} /** * Loads the data from the Store async or sync. * If Async loading the return true * @param dataStoreKey The Key from the datastore * @param loadedFunction The funtion to call after data is loaded * @param waitText The Waiting Text for async loading controls. */ public loadDataFromStore(dataStoreK...
{ let entry = this.state.dataStores ? this.state.dataStores.find(e => e.key == configKey) : undefined; if (!entry) { let waitText = this.commonFormater.formatMessage(LocalsCommon.loadData); loadedFunction(configKey, undefined, waitText, true); } provider.retrieveFilteredListData(configKey,co...
conditional_block
FormBaseInput.ts
/* tslint:disable:no-any */ import * as React from 'react'; import * as PropTypes from 'prop-types'; import { IFormBaseInputProps, IFormBaseInputState, DataStoreEntry, typesForInject, IDataProviderCollection, IDataProviderService } from './FormBaseInput.types'; export { IFormBaseInputProps }; import { BaseComponent, IC...
(errorMessage?: string): void { this.setState((prevState: S) => { prevState.isValid = false; prevState.currentError = errorMessage; return prevState; }); } /** * Clear any errors from this input */ public clearError(): void { this.setState((prevState: S) => { prevState.i...
setError
identifier_name
FormBaseInput.ts
/* tslint:disable:no-any */ import * as React from 'react'; import * as PropTypes from 'prop-types'; import { IFormBaseInputProps, IFormBaseInputState, DataStoreEntry, typesForInject, IDataProviderCollection, IDataProviderService } from './FormBaseInput.types'; export { IFormBaseInputProps }; import { BaseComponent, IC...
* @param loadedFunction The funtion to call after data is loaded * @param waitText The Waiting Text for async loading controls. */ public loadDataFromStore(dataStoreKey:string, loadedFunction:DataLoadedFunction, waitText: string): boolean { let dataBinderAsync:Promise<any[]> = this.dataStore[dataStoreKey] as...
random_line_split
FormBaseInput.ts
/* tslint:disable:no-any */ import * as React from 'react'; import * as PropTypes from 'prop-types'; import { IFormBaseInputProps, IFormBaseInputState, DataStoreEntry, typesForInject, IDataProviderCollection, IDataProviderService } from './FormBaseInput.types'; export { IFormBaseInputProps }; import { BaseComponent, IC...
}
{ this.setState((prevState: S): S => { this.props.control.Value = value; prevState.currentValue = value; return prevState; }, () => { this.debouncedSubmitValue(this, validate, skipSendValue); } ); }
identifier_body
object-security-ui.js
if(!EURB.ObjSec) { EURB.ObjSec = {}; } EURB.ObjSec.getSharingWindows = function() { //var CheckBoxClass = Ext.ux.form.TriCheckbox; var CheckBoxClass = Ext.form.Checkbox; var groupStore = new Ext.data.Store({ reader:new Ext.data.JsonReader({ id:'id' ,totalProperty:'totalCount' ,root:'data' ,fields:[ ...
var sharingCheckColumn = new Ext.grid.CheckColumn({ header:EURB.ObjSec.authoritiesSharing ,id:'sharing' ,dataIndex:'sharing' ,editor:new CheckBoxClass() ,align:'center' }); var authoritiesColModel = new Ext.grid.ColumnModel({ defaults: { sortable: true ,width:20 }, columns: [{ header: EURB...
,width:20 ,editor:new CheckBoxClass() ,align:'center' });
random_line_split
object-security-ui.js
if(!EURB.ObjSec) { EURB.ObjSec = {}; } EURB.ObjSec.getSharingWindows = function() { //var CheckBoxClass = Ext.ux.form.TriCheckbox; var CheckBoxClass = Ext.form.Checkbox; var groupStore = new Ext.data.Store({ reader:new Ext.data.JsonReader({ id:'id' ,totalProperty:'totalCount' ,root:'data' ,fields:[ ...
else {//if(theId.get('type') == 1) { //group groupStore.each(function(r){ if(r.get('id') === theId) { groupsArr.push(r); } }); } }); userStore.remove(usersArr); groupStore.remove(groupsArr); } }); } }); } ...
{//user userStore.each(function(r){ if(r.get('id') === theId) { usersArr.push(r); } }); }
conditional_block
1_compute_MASTER.py
#!/bin/env python ###################################################################### ''' COMPUTE_MASTER.py ========================= AIM: Cycle through the observability maps and execute stray light computations Temporal resolution is 60 seconds and orbit step size is given by the max. error INPUT: files: - obse...
else : print 'Next adaptative step of :', current_step, 'orbit(s)' orbit_current += current_step former_step = current_step # if the test failed, reduce the step size else : current_step = int(former_step/2) if current_step < min_step: current_step = min_step if current_step == former_step and ...
current_step = orbit_step
conditional_block
1_compute_MASTER.py
#!/bin/env python ###################################################################### ''' COMPUTE_MASTER.py ========================= AIM: Cycle through the observability maps and execute stray light computations Temporal resolution is 60 seconds and orbit step size is given by the max. error INPUT: files: - obse...
# select only none zero value with resilience to rounding errors # See resources/routines.py map_obs = slice_map(map_obstot, minute) # Count the number of points for that particular minute total_targets += np.shape(map_obs)[0] if np.shape(map_obs)[0] > 0 : # Execute the stray light code only if there is...
np.savetxt('%s/INPUT/coord_sun.dat' % path,[xs,ys,zs,ra_sun,dec_sun,rs],delimiter='\n')
random_line_split
d3cap.rs
use std::thread::{self, JoinHandle}; use std::hash::{Hash}; use std::collections::hash_map::{Entry, HashMap}; use std::fs::File; use std::io::{self, Read}; use std::sync::{Arc,RwLock}; use std::sync::mpsc::{channel, Sender, SendError}; use toml; use multicast::Multicast; use json_serve::uiserver::UIServer; use util:...
} } Err(LoadMacError::TomlError(None)) } fn start_websocket(port: u16, mac_map: &MacMap, pg_ctl: &ProtoGraphController) -> io::Result<()> { let ui = UIServer::spawn(port, mac_map)?; pg_ctl.register_mac_listener(ui.create_sender()?); pg_ctl.register_ip4_listener(ui.create_sender()?); pg_...
.collect())
random_line_split
d3cap.rs
use std::thread::{self, JoinHandle}; use std::hash::{Hash}; use std::collections::hash_map::{Entry, HashMap}; use std::fs::File; use std::io::{self, Read}; use std::sync::{Arc,RwLock}; use std::sync::mpsc::{channel, Sender, SendError}; use toml; use multicast::Multicast; use json_serve::uiserver::UIServer; use util:...
let tap_hdr = unsafe { &*(pkt.pkt_ptr() as *const tap::RadiotapHeader) }; let base: &dot11::Dot11BaseHeader = magic(tap_hdr); let fc = &base.fr_ctrl; if fc.protocol_version() != 0 { // bogus packet, bail return Err(ParseErr::UnknownPacket); } m...
{ unsafe { skip_bytes_cast(pkt, pkt.it_len as isize) } }
identifier_body
d3cap.rs
use std::thread::{self, JoinHandle}; use std::hash::{Hash}; use std::collections::hash_map::{Entry, HashMap}; use std::fs::File; use std::io::{self, Read}; use std::sync::{Arc,RwLock}; use std::sync::mpsc::{channel, Sender, SendError}; use toml; use multicast::Multicast; use json_serve::uiserver::UIServer; use util:...
(conf: D3capConf, pkt_sender: Sender<Pkt>, pd_sender: Sender<PhysData>) -> io::Result<JoinHandle<()>> { thread::Builder::new().name("packet_capture".to_owned()).spawn(move || { let mut cap = init_capture(&conf, pkt_sender, pd_sender); loop { cap....
start_capture
identifier_name
d3cap.rs
use std::thread::{self, JoinHandle}; use std::hash::{Hash}; use std::collections::hash_map::{Entry, HashMap}; use std::fs::File; use std::io::{self, Read}; use std::sync::{Arc,RwLock}; use std::sync::mpsc::{channel, Sender, SendError}; use toml; use multicast::Multicast; use json_serve::uiserver::UIServer; use util:...
match pkt.unwrap() { Pkt::Mac(ref p) => phctl.mac.update(p), Pkt::IP4(ref p) => phctl.ip4.update(p), Pkt::IP6(ref p) => phctl.ip6.update(p), } } })?; Ok(ctl) } fn sender(&self) -> Sender<Pk...
{ break }
conditional_block
mod.rs
//! This module implements the global `Function` object as well as creates Native Functions. //! //! Objects wrap `Function`s and expose them via call/construct slots. //! //! `The `Function` object is used for matching text with a pattern. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN docum...
} #[derive(Debug, Trace, Finalize, PartialEq, Clone)] pub enum ConstructorKind { Base, Derived, } impl ConstructorKind { /// Returns `true` if the constructor kind is `Base`. pub fn is_base(&self) -> bool { matches!(self, Self::Base) } /// Returns `true` if the constructor kind is `D...
{ matches!(self, Self::Global) }
identifier_body
mod.rs
//! This module implements the global `Function` object as well as creates Native Functions. //! //! Objects wrap `Function`s and expose them via call/construct slots. //! //! `The `Function` object is used for matching text with a pattern. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN docum...
(_: &JsValue, _: &[JsValue], _: &mut Context) -> JsResult<JsValue> { Ok(JsValue::undefined()) } /// `Function.prototype.call` /// /// The call() method invokes self with the first argument as the `this` value. /// /// More information: /// - [MDN documentation][mdn] /// - [ECM...
prototype
identifier_name
mod.rs
//! This module implements the global `Function` object as well as creates Native Functions. //! //! Objects wrap `Function`s and expose them via call/construct slots. //! //! `The `Function` object is used for matching text with a pattern. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN docum...
} /// Boa representation of a Function Object. /// /// FunctionBody is specific to this interpreter, it will either be Rust code or JavaScript code (AST Node) /// /// <https://tc39.es/ecma262/#sec-ecmascript-function-objects> #[derive(Clone, Trace, Finalize)] pub enum Function { Native { #[unsafe_ignore_tr...
.deref_mut() .as_mut_any() .downcast_mut::<T>() .ok_or_else(|| context.construct_type_error("cannot downcast `Captures` to given type")) }
random_line_split
mod.rs
//! This module implements the global `Function` object as well as creates Native Functions. //! //! Objects wrap `Function`s and expose them via call/construct slots. //! //! `The `Function` object is used for matching text with a pattern. //! //! More information: //! - [ECMAScript reference][spec] //! - [MDN docum...
}; match (&function, name) { ( Function::Native { function: _, constructable: _, }, Some(name), ) => Ok(format!("function {}() {{\n [native Code]\n}}", &name).into()), (Function...
{ return context.throw_type_error("Not a function"); }
conditional_block
EncryptDecryptTextFile.py
import os import pprint import math import sys import datetime as dt from pathlib import Path import RotateCipher import ShiftCipher import TranspositionCipher def process_textfile( string_path: str, encryption_algorithm: str, algorithm_key: float, output_folderpath: str = str( ...
def manual_test(): dict_processedtext = process_textfile( string_path=r"C:\Users\Rives\Downloads\Quizzes\Quiz 0 Overwrite Number 1.txt", encryption_algorithm="rotate", algorithm_key=1, shift_left=True ) print("Encrypt ROT1 with default values....
encryption_algorithm = encryption_algorithm.lower() available_algorithms = ["rotate", "transposition"] if encryption_algorithm not in available_algorithms: pprint.pprint( ["Enter an algorithm from the list. Not case-sensitive.", available_algorithms] ) ...
identifier_body
EncryptDecryptTextFile.py
import os import pprint import math import sys import datetime as dt from pathlib import Path import RotateCipher import ShiftCipher import TranspositionCipher def
( string_path: str, encryption_algorithm: str, algorithm_key: float, output_folderpath: str = str( Path(os.path.expandvars("$HOME")).anchor ) + r"/EncryptDecrypt/", output_filename: str = r"EncryptDecrypt.txt", to_decrypt=False, **kwargs ): encryption_alg...
process_textfile
identifier_name
EncryptDecryptTextFile.py
import os import pprint import math import sys import datetime as dt from pathlib import Path import RotateCipher import ShiftCipher import TranspositionCipher def process_textfile( string_path: str, encryption_algorithm: str, algorithm_key: float, output_folderpath: str = str( ...
algorithm_key=1, output_folderpath=r"C:\Users\Rives\Downloads\Encryptions" ) print(dict_processedtext3a["output_file"]) dict_processedtext3b = process_textfile( string_path=dict_processedtext3a["output_file"], encryption...
for i in range(2): dict_processedtext3a = process_textfile( string_path=r"C:\Users\Rives\Downloads\Quizzes\Quiz 0 Overwrite Number 2.txt", encryption_algorithm="rotate",
random_line_split