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
process_node.go
if manual == nil && len(parentNodeRuns) == 1 && parentNodeRuns[0].Manual != nil { n := wr.Workflow.WorkflowData.NodeByID(parentNodeRuns[0].WorkflowNodeID) // If fork or JOIN and No run conditions if (n.Type == sdk.NodeTypeJoin || n.Type == sdk.NodeTypeFork) && (n.Context == nil || (n.Context.Conditions.LuaScr...
{ report := new(ProcessorReport) exist, errN := nodeRunExist(db, wr.ID, n.ID, wr.Number, subNumber) if errN != nil { return nil, false, sdk.WrapError(errN, "processNodeRun> unable to check if node run exist") } if exist { return nil, false, nil } var end func() ctx, end = observability.Span(ctx, "workflow....
identifier_body
process_node.go
(ctx context.Context, db gorp.SqlExecutor, store cache.Store, proj *sdk.Project, wr *sdk.WorkflowRun, mapNodes map[int64]*sdk.Node, n *sdk.Node, subNumber int, parentNodeRuns []*sdk.WorkflowNodeRun, hookEvent *sdk.WorkflowNodeRunHookEvent, manual *sdk.WorkflowNodeRunManual) (*ProcessorReport, bool, error) { report := ...
processNodeRun
identifier_name
process_node.go
if (n.Type == sdk.NodeTypeJoin || n.Type == sdk.NodeTypeFork) && (n.Context == nil || (n.Context.Conditions.LuaScript == "" && len(n.Context.Conditions.PlainConditions) == 0)) { manual = parentNodeRuns[0].Manual } } switch n.Type { case sdk.NodeTypeFork, sdk.NodeTypePipeline, sdk.NodeTypeJoin: r1, condi...
random_line_split
client.go
// resource is already deleted (or never existsed) // so we're done here return nil } else if err != nil { // failed to get stack status return err } if *state.StackStatus == DeleteComplete { // resource already deleted return nil } // trigger a delete unless we're already in a deleting state if *sta...
{ return false }
conditional_block
client.go
var Ref = goformation.Ref var Sub = goformation.Sub const CreateInProgress = cloudformation.StackStatusCreateInProgress const DeleteInProgress = cloudformation.StackStatusDeleteInProgress const UpdateInProgress = cloudformation.StackStatusUpdateInProgress const ReviewInProgress = cloudformation.StackStatusReviewInPro...
(ctx context.Context, stack Stack) (Outputs, error) { state, err := r.get(ctx, stack) if err != nil { return nil, err } return r.resolveOutputs(ctx, state.Outputs) } // resolveOutputs returns cloudformation outputs in a map format and resolves // any values that are stored in AWS Secrets Manager func (r *Client)...
Outputs
identifier_name
client.go
return nil, err } } _, err = r.waitUntilCompleteState(ctx, stack) if err != nil { return nil, err } err = r.update(ctx, stack, params...) if err != nil { return nil, err } state, err := r.waitUntilCompleteState(ctx, stack) if err != nil { return nil, err } return r.resolveOutputs(ctx, state.Output...
{ // use a fresh context or we might not be able to update status after // deadline is hit, but this feels a little wrong ctx := context.Background() state, _ := r.get(ctx, stack) events, _ := r.events(ctx, stack) s := stack.GetStatus() // update aws specific state if state != nil { if state.StackId != nil { ...
identifier_body
client.go
var Ref = goformation.Ref var Sub = goformation.Sub const CreateInProgress = cloudformation.StackStatusCreateInProgress const DeleteInProgress = cloudformation.StackStatusDeleteInProgress const UpdateInProgress = cloudformation.StackStatusUpdateInProgress const ReviewInProgress = cloudformation.StackStatusReviewInPro...
if err != nil { return nil, err } subval, haveSubkey
return nil, fmt.Errorf("unexpected nil value in SecretString of %s", arn) } secrets := map[string]interface{}{} err = json.Unmarshal([]byte(*v.SecretString), &secrets)
random_line_split
runtime.rs
dpListen`]) use this to make sure they have a runtime to handle the sockets /// on. /// /// If you prefer to specify configuration of the runtime to use, instead of the default one, you /// can create an instance of this extension yourself and register it *before registering any socket /// pipelines*, which will take p...
{ /// Use the threadpool runtime. /// /// The threadpool runtime is the default (both in tokio and spirit). /// /// This allows you to modify the builder prior to starting it, specifying custom options like /// number of threads. ThreadPool(Box<dyn FnMut(&mut runtime::Builder) + Send>), ...
Runtime
identifier_name
runtime.rs
dpListen`]) use this to make sure they have a runtime to handle the sockets /// on. /// /// If you prefer to specify configuration of the runtime to use, instead of the default one, you /// can create an instance of this extension yourself and register it *before registering any socket /// pipelines*, which will take p...
runtime.block_on(fut)?; runtime.run().map_err(Error::from) } Runtime::Custom(mut callback) => callback(Box::new(fut)), Runtime::__NonExhaustive__ => unreachable!(), } } } impl<E> Extension<E> for Runtime where E: Extensible<Ok = E>, ...
{ let spirit = Arc::clone(spirit); let fut = future::lazy(move || { inner.run().map_err(move |e| { spirit.terminate(); e }) }); match self { Runtime::ThreadPool(mut mod_builder) => { let mut builder = run...
identifier_body
runtime.rs
dpListen`]) use this to make sure they have a runtime to handle the sockets /// on. /// /// If you prefer to specify configuration of the runtime to use, instead of the default one, you /// can create an instance of this extension yourself and register it *before registering any socket /// pipelines*, which will take p...
/// Maximum number of blocking worker threads. /// /// These do tasks that take longer time. This includes file IO and CPU intensive tasks. /// /// If not set, defaults to 100. /// /// Often, the application doesn't start these threads as they might not always be needed. #[serde(skip_se...
/// it may make sense to set it lower. /// /// If not set, the application will start with number of CPUs available in the system. #[serde(skip_serializing_if = "Option::is_none")] pub async_threads: Option<usize>,
random_line_split
init.rs
, Service>, } impl InitServer { fn new(hostname: &str) -> Result<InitServer> { Self::check_pid1()?; let hostname = hostname.to_string(); let cmdline = CmdLine::load()?; let homedir = cmdline.lookup("phinit.home") .unwrap_or("/home/user".to_string()); let rootfs =...
fn write_xauth(&self) -> io::Result<()> { let xauth_path = format!("{}/.Xauthority", self.homedir()); let mut randbuf = [0; 16]; let mut file = fs::File::open("/dev/urandom")?; file.read_exact(&mut randbuf)?; let mut v: Vec<u8> = Vec::new(); // ??? v.exte...
{ let mut octets = ip.octets(); octets[3] = 1; let gw = Ipv4Addr::from(octets); let nl = NetlinkSocket::open()?; if !nl.interface_exists("eth0") { } nl.add_ip_address("eth0", ip, 24)?; nl.set_interface_up("eth0")?; nl.add_default_route(gw)?; ...
identifier_body
init.rs
, Service>, } impl InitServer { fn new(hostname: &str) -> Result<InitServer> { Self::check_pid1()?; let hostname = hostname.to_string(); let cmdline = CmdLine::load()?; let homedir = cmdline.lookup("phinit.home") .unwrap_or("/home/user".to_string()); let rootfs =...
} pub fn setup_filesystem(&self) -> Result<()> { sys::set_umask(0o022); //mount_devtmpfs()?; mount_tmpfs("/tmp")?; mkdir("/tmp/sysroot")?; if self.rootfs.read_only() { self.setup_readonly_root()?; } else { self.setup_writeable_root()?; ...
{ Logger::set_log_level(LogLevel::Info); }
conditional_block
init.rs
Service>, } impl InitServer { fn new(hostname: &str) -> Result<InitServer> { Self::check_pid1()?; let hostname = hostname.to_string(); let cmdline = CmdLine::load()?; let homedir = cmdline.lookup("phinit.home") .unwrap_or("/home/user".to_string()); let rootfs = ...
chmod("/dev/wl0", 0o666)?; let dbus = ServiceLaunch::new("dbus-daemon", "/usr/bin/dbus-daemon") .base_environment() .uidgid(1000,1000) .env("HOME", self.homedir()) .env("NO_AT_BRIDGE", "1") .env("QT_ACCESSIBILITY", "1") .env("SHEL...
}
random_line_split
init.rs
, Service>, } impl InitServer { fn new(hostname: &str) -> Result<InitServer> { Self::check_pid1()?; let hostname = hostname.to_string(); let cmdline = CmdLine::load()?; let homedir = cmdline.lookup("phinit.home") .unwrap_or("/home/user".to_string()); let rootfs =...
(&self) -> Result<()> { sys::set_umask(0o022); //mount_devtmpfs()?; mount_tmpfs("/tmp")?; mkdir("/tmp/sysroot")?; if self.rootfs.read_only() { self.setup_readonly_root()?; } else { self.setup_writeable_root()?; } fs::write("/etc/hos...
setup_filesystem
identifier_name
main.go
add channel error") } } common.Band = bandConfig common.BandName = band.Name(c.String("band")) return nil } func setDeduplicationDelay(c *cli.Context) error { common.DeduplicationDelay = c.Duration("deduplication-delay") return nil } func setGetDownlinkDataDelay(c *cli.Context) error { common.GetDownlinkDa...
gs := grpc.NewServer(opts...) nsAPI := api.NewNetworkServerAPI() ns.RegisterNetworkServerServer(gs, nsAPI) ln, err := net.Listen("tcp", c.String("bind")) if err != nil { return errors.Wrap(err, "start api listener error") } go gs.Serve(ln) return nil } func startGatewayAPIServer(c *cli.Context) error { lo...
{ creds := mustGetTransportCredentials(c.String("tls-cert"), c.String("tls-key"), c.String("ca-cert"), false) opts = append(opts, grpc.Creds(creds)) }
conditional_block
main.go
"github.com/brocaar/lorawan" "github.com/brocaar/lorawan/band" ) func init() { grpclog.SetLogger(log.StandardLogger()) } var version string // set by the compiler var bands = []string{ string(band.AS_923), string(band.AU_915_928), string(band.CN_470_510), string(band.CN_779_787), string(band.EU_433), string(...
"github.com/brocaar/loraserver/internal/common" "github.com/brocaar/loraserver/internal/migrations" // TODO: merge backend/gateway into internal/gateway? "github.com/brocaar/loraserver/internal/gateway" "github.com/brocaar/loraserver/internal/uplink"
random_line_split
main.go
func setBandConfig(c *cli.Context) error { if c.String("band") == "" { return fmt.Errorf("--band is undefined, valid options are: %s", strings.Join(bands, ", ")) } dwellTime := lorawan.DwellTimeNoLimit if c.Bool("band-dwell-time-400ms") { dwellTime = lorawan.DwellTime400ms } bandConfig, err := band.GetConfi...
{ var netID lorawan.NetID if err := netID.UnmarshalText([]byte(c.String("net-id"))); err != nil { return errors.Wrap(err, "NetID parse error") } common.NetID = netID return nil }
identifier_body
main.go
add channel error") } } common.Band = bandConfig common.BandName = band.Name(c.String("band")) return nil } func setDeduplicationDelay(c *cli.Context) error { common.DeduplicationDelay = c.Duration("deduplication-delay") return nil } func setGetDownlinkDataDelay(c *cli.Context) error { common.GetDownlinkDa...
(c *cli.Context) error { log.Info("connecting to postgresql") db, err := common.OpenDatabase(c.String("postgres-dsn")) if err != nil { return errors.Wrap(err, "database connection error") } common.DB = db return nil } func setGatewayBackend(c *cli.Context) error { gw, err := gwBackend.NewBackend(c.String("gw-...
setPostgreSQLConnection
identifier_name
SVD_getMatrixCompletion.py
gram return " ".join(new_tokens) def iter_folder(folder, extension, ngrams=[1]): for subdir, dirs, files in os.walk(folder): for file in sorted(files): if not file.endswith(extension): continue print file document = open(file).readlines...
return True def getSVD(prefix, np, corpusname, ngrams, rank_max, softImpute_lambda, binary_matrix, output, types = ['POI', 'MP', 'LP']): #types = ['POI', 'MP', 'LP'] path = prefix sheets = range(0,26) dictname = output + "_".join(types) + '_' + corpusnam...
row = [] for j in range(n): if A[i][j] != 0 and A[i][j] != 1: return False
conditional_block
SVD_getMatrixCompletion.py
gram return " ".join(new_tokens) def iter_folder(folder, extension, ngrams=[1]): for subdir, dirs, files in os.walk(folder): for file in sorted(files): if not file.endswith(extension): continue print file document = open(file).readlines...
Process one document at a time using generators, never load the entire corpus into RAM. """ def __init__(self, top_dir, types=['POI', 'MP', 'LP'], sheets = range(0,25), np='syntax', ngrams=[1]): self.types = types self.top_dir = top_dir self.np = np self.ngrams = ngrams...
random_line_split
SVD_getMatrixCompletion.py
gram return " ".join(new_tokens) def iter_folder(folder, extension, ngrams=[1]): for subdir, dirs, files in os.walk(folder): for file in sorted(files): if not file.endswith(extension): continue print file document = open(file).readlines...
class TxtSubdirsCorpus(object): """ Iterable: on each iteration, return bag-of-words vectors, one vector for each document. Process one document at a time using generators, never load the entire corpus into RAM. """ def __init__(self, top_dir, types=['POI', 'MP', 'LP'], sheets = r...
document = open(path).readlines() for line in document: line = re.sub( '\s+', ' ', line).strip() if len(line) == 0: continue line = ProcessLine(line, ngrams) # break document into utf8 tokens yield gensim.utils.tokenize(line, lower=True, errors='ignore'...
identifier_body
SVD_getMatrixCompletion.py
gram return " ".join(new_tokens) def iter_folder(folder, extension, ngrams=[1]): for subdir, dirs, files in os.walk(folder): for file in sorted(files): if not file.endswith(extension): continue print file document = open(file).readlines...
(prefix, np, corpusname, ngrams, rank_max, softImpute_lambda, binary_matrix, output, types = ['POI', 'MP', 'LP']): #types = ['POI', 'MP', 'LP'] path = prefix sheets = range(0,26) dictname = output + "_".join(types) + '_' + corpusname + corpusdictexe # # that's it! the streamed corpus...
getSVD
identifier_name
get.go
return status, nil } // GetDiscoveredResources ... loops through all specified resourceTypes // Lists all resources by Type (Will need to loop over all cfg.ResourceType* types) // https://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html#supported-resources func (c *CfgSvc) GetDiscover...
{ params.NextToken = result.NextToken result, err = c.Client.DescribeConfigRuleEvaluationStatus(&params) if err != nil { return nil, err } status = append(status, result.ConfigRulesEvaluationStatus...) }
conditional_block
get.go
", "AWS::EFS::AccessPoint", "AWS::EKS::Cluster", "AWS::EKS::FargateProfile", "AWS::EKS::IdentityProviderConfig", "AWS::EKS::Addon", "AWS::EMR::SecurityConfiguration", "AWS::Events::EventBus", "AWS::Events::ApiDestination", "AWS::Events::Archive", "AWS::Events::Endpoint", "AWS::Events::Connection",...
"AWS::DataSync::LocationObjectStorage", "AWS::DataSync::Task",
random_line_split
get.go
// GetLastExecution ... gets the time of the most recent execution of all config services func (c *CfgSvc) GetLastExecution() (time.Time, error) { t := time.Time{} stats, err := c.GetStatus() if err != nil { return t, err } if len(stats) == 0 { return t, errors.New("empty config rule evaluation status arra...
{ for _, v := range i { e := v.RelatedEvents r := v.Relationships sort.SliceStable(e, func(i, j int) bool { return sliceSorter(e[i], e[j]) }) sort.SliceStable(r, func(i, j int) bool { return sliceSorter(r[i], r[j]) }) v.RelatedEvents = e v.Relationships = r } }
identifier_body
get.go
essment", "AWS::AutoScaling::AutoScalingGroup", "AWS::AutoScaling::LaunchConfiguration", "AWS::AutoScaling::ScalingPolicy", "AWS::AutoScaling::ScheduledAction", "AWS::AutoScaling::WarmPool", "AWS::Backup::BackupPlan", "AWS::Backup::BackupSelection", "AWS::Backup::BackupVault", "AWS::Backup::RecoveryPo...
getPreviousSnapshot
identifier_name
Server.py
: # process the login of the client self.process_login(msg) else: # process command if self.process_command(msg): # if the client exited, break the loop break except socket.error: pass # close the connection self.connection.close(...
self.port = port # {client address -> client threads} self.clients = {} # {username -> password} self.passwords = {} # {username -> last login time} self.logins = {} # {ip -> blocked time} self.blocked_ips = {} # {username -> [messages]} self.offline_messages = {} # starts...
# server port
random_line_split
Server.py
# process the login of the client self.process_login(msg) else: # process command if self.process_command(msg): # if the client exited, break the loop break except socket.error: pass # close the connection self.connection.close() ...
# loads usernames and passwords from the password file # return True if success or False otherwise. def load_passwords(self): print 'load users' try: # open the file f = open(Constants.PASSWORD_FILE) # for each line in the file for line in f: # remove leading and trailing...
self.blocked_ips[address[0]] = time.time()
identifier_body
Server.py
# process the login of the client self.process_login(msg) else: # process command if self.process_command(msg): # if the client exited, break the loop break except socket.error: pass # close the connection self.connection.close() ...
else: # increment the failed times self.failed_login_attempts += 1 # if it exceeds the maximum retry times, if self.failed_login_attempts >= Constants.MAX_LOGIN_ATTEMPTS: # tell the client self.connection.send(Constants.MSG_LOGIN_EXCEED_MAX_TIMES) # b...
self.connection.send(Constants.MSG_USER_ALREADY_LOGINED)
conditional_block
Server.py
# process the login of the client self.process_login(msg) else: # process command if self.process_command(msg): # if the client exited, break the loop break except socket.error: pass # close the connection self.connection.close() ...
(self): print 'Stop server...' # disconnect all the clients for address in self.clients.keys(): self.disconnect(address) # disconnect a client def disconnect(self, address): # if the address is present, if address in self.clients: # get the client thread t = self.clients[addre...
stop_server
identifier_name
train_stage1.py
cluded.type(torch.cuda.FloatTensor), requires_grad=False).cuda() img = Variable(img.type(torch.cuda.FloatTensor), requires_grad=False).cuda() lmk = Variable(lmk.type(torch.cuda.FloatTensor), requires_grad=False).cuda() flag = Variable(flag.type(torch.cuda.FloatTensor), requires_grad=False).cuda(...
(args): if args.seed is not None: random.seed(args.seed) torch.manual_seed(args.seed) cudnn.deterministic = True warnings.warn('You have chosen to seed training. ' 'This will turn on the CUDNN deterministic setting, ' 'which can slow down ...
main
identifier_name
train_stage1.py
cluded.type(torch.cuda.FloatTensor), requires_grad=False).cuda() img = Variable(img.type(torch.cuda.FloatTensor), requires_grad=False).cuda() lmk = Variable(lmk.type(torch.cuda.FloatTensor), requires_grad=False).cuda() flag = Variable(flag.type(torch.cuda.FloatTensor), requires_grad=False).cuda(...
def main_worker(gpu, ngpus_per_node, args): args.gpu = gpu if args.gpu is not None: print("Use GPU: {} for training".format(args.gpu)) if args.distributed: if args.dist_url == "env://" and args.rank == -1: args.rank = int(os.environ["RANK"]) if args.multiprocessing_...
random_line_split
train_stage1.py
Synthesize background rendered = img*(1.-vector) + rendered*vector # Perceptual loss affined_r = F.interpolate(rendered[:,:,15:-40,15:-15], (112,112), mode='bilinear', align_corners=True) affined_i = F.interpolate(img[:,:,15:-40,15:-15], (112,112), mode='bilinear', align_corners=True) ...
error = validate(models, val_loader, epoch, args) logger.log_validation(error, epoch) torch.save(estimator3d.regressor.module.state_dict(), args.save_path+"/reg_ep%d_%.4f_stage1.pth" % (epoch+1, error))
conditional_block
train_stage1.py
cluded.type(torch.cuda.FloatTensor), requires_grad=False).cuda() img = Variable(img.type(torch.cuda.FloatTensor), requires_grad=False).cuda() lmk = Variable(lmk.type(torch.cuda.FloatTensor), requires_grad=False).cuda() flag = Variable(flag.type(torch.cuda.FloatTensor), requires_grad=False).cuda(...
estimator3d.regressor.cuda(args.gpu) parsing_net = BiSeNet(n_classes=19) parsing_net.cuda(args.gpu) parsing_net.load_state_dict(torch.load('faceParsing/model_final_diss.pth', map_location='cuda:'+str(args.gpu))) parsing_net.eval() face_encoder = IR_SE_50([112,112]) face_encoder.load_state_di...
args.gpu = gpu if args.gpu is not None: print("Use GPU: {} for training".format(args.gpu)) if args.distributed: if args.dist_url == "env://" and args.rank == -1: args.rank = int(os.environ["RANK"]) if args.multiprocessing_distributed: # For multiprocessing d...
identifier_body
atariclip.py
, self).__init__() self.conv1 = nn.Conv2d(3, 10, kernel_size=5) self.conv2 = nn.Conv2d(10, 20, kernel_size=5) self.conv2_drop = nn.Dropout2d() self.fc1 = nn.Linear(400, 6) for layer in self.parameters(): layer.requires_grad = False def forward(self, x): x...
return self._init_state class Clip(object): def __init__(self, shape, model_name): from clipper_admin import ClipperConnection, DockerContainerManager from clipper_admin.deployers import python as python_deployer from clipper_admin.deployers import pytorch as pytorch_deployer ...
def initial_state(self):
random_line_split
atariclip.py
x = x.view(-1, 400) x = F.relu(self.fc1(x)) return F.log_softmax(x, dim=1) class ModelSimple(nn.Module): def __init__(self): super(ModelSimple, self).__init__() #self.conv1 = nn.Conv2d(3, 10, kernel_size=5) #self.conv2 = nn.Conv2d(10, 20, kernel_size=5) #self.conv2...
RemoteClipperRunner = ray.remote(ClipperRunner) simulators = [RemoteClipperRunner.remote(args) for i in range(args.num_sims)] c = Clip(ray.get(simulators[0].initial_state.remote()).shape, args.model) start = time.time() ray.get([sim.run.remote(args.iters) for sim in simulators]) print("Took %f sec.....
identifier_body
atariclip.py
(self.conv2_drop(self.conv2(x)), 2)) #x = F.max_pool2d(x, 3, 3) #x = F.max_pool2d(x, 3, 3) x = x.view(-1, 100800) x = F.relu(self.fc1(x)) #x = F.dropout(x, training=self.training) #x = self.fc2(x) return F.log_softmax(x, dim=1) class ModelDummy(nn.Module): d...
import ray ray.init() eval_ray_batch(args)
conditional_block
atariclip.py
) for layer in self.parameters(): layer.requires_grad = False def forward(self, x): x = F.relu(F.max_pool2d(self.conv1(x), 2)) x = F.relu(F.max_pool2d(self.conv2_drop(self.conv2(x)), 2)) x = F.max_pool2d(x, 3, 3) x = F.max_pool2d(x, 3, 3) x = x.view(-1, 4...
eval_clipper
identifier_name
olm_parser.rs
] } fn sub_images(image: RgbImage, chunk_size: usize) -> impl Iterator<Item=RgbImage> { let chunk_size_32: u32 = TryFrom::try_from(chunk_size) .expect("chunk_size too large, cannot convert to u32"); let height_iter = 0..(image.dimensions().1) - (chunk_size_32 - 1); let width_iter = 0..(image.d...
( image: RgbImage, chunk_size: usize, pixel_aliases: &PixelKeys, rotate: bool, reflect_vertical: bool, reflect_horizontal: bool, reflect_diagonal: bool, ) -> IndexMap<Chunk, u16> { sub_images(image, chunk_size) .map(|sub_image| alias_sub_image(sub_image, pixel_aliases)) ....
chunk_image
identifier_name
olm_parser.rs
] } fn sub_images(image: RgbImage, chunk_size: usize) -> impl Iterator<Item=RgbImage> { let chunk_size_32: u32 = TryFrom::try_from(chunk_size) .expect("chunk_size too large, cannot convert to u32"); let height_iter = 0..(image.dimensions().1) - (chunk_size_32 - 1); let width_iter = 0..(image.d...
}) }); rules }) } // Create a raw graph for pruning fn create_raw_graph(all_labels: &MSu16xNU, chunk_size: usize, (height, width): (usize, usize)) -> Graph { // pixel based graph dimensions let v_dim_x = (width * chunk_size) - (chunk_size - 1); l...
{ let mut set = MSu16xNU::empty(); set.insert(other_label, 1); rules .entry((*direction, label)) .and_modify(|l| l.add_assign(set)) ...
conditional_block
olm_parser.rs
] } fn sub_images(image: RgbImage, chunk_size: usize) -> impl Iterator<Item=RgbImage> { let chunk_size_32: u32 = TryFrom::try_from(chunk_size) .expect("chunk_size too large, cannot convert to u32"); let height_iter = 0..(image.dimensions().1) - (chunk_size_32 - 1); let width_iter = 0..(image....
}) } // Create a raw graph for pruning fn create_raw_graph(all_labels: &MSu16xNU, chunk_size: usize, (height, width): (usize, usize)) -> Graph { // pixel based graph dimensions let v_dim_x = (width * chunk_size) - (chunk_size - 1); let v_dim_y = (height * chunk_size) - (chunk_size - 1); let ver...
.or_insert(set); } }) }); rules
random_line_split
olm_parser.rs
height_iter = 0..(image.dimensions().1) - (chunk_size_32 - 1); let width_iter = 0..(image.dimensions().0) - (chunk_size_32 - 1); height_iter .cartesian_product(width_iter) .map(move |(y, x)| { imageops::crop_imm(&image, x, y, chunk_size_32, chunk_size_32).to_image() }) } f...
{ let img = image::open("resources/test/chunk_image_test.png").unwrap().to_rgb8(); let mut pixel_aliases: PixelKeys = BiMap::new(); pixel_aliases.insert(0, Rgb::from([255, 255, 255])); pixel_aliases.insert(1, Rgb::from([0, 0, 0])); let chunk_map = chunk_image(img, 2, &pixel_alia...
identifier_body
wasm.rs
v: InternalValue::from(v), } } } impl From<f32> for Value { fn from(v: f32) -> Self { Self { t: PrimitiveType::from(v), v: InternalValue::from(v), } } } impl From<f64> for Value { fn from(v: f64) -> Self { Self { t: Primit...
num_params
identifier_name
wasm.rs
} } } impl std::fmt::Display for Value { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { unsafe { match self.t { PrimitiveType::I32 => { write!(f, "(i32:{})", self.v.i32) } PrimitiveType::I6...
pub fn add_function_type(&mut self, ft: FunctionType) {
random_line_split
wasm.rs
InternalValue { f32: x } } } impl From<f64> for InternalValue { fn from(x: f64) -> InternalValue { InternalValue { f64: x } } } /// Representation of all wasm values #[derive(Copy, Clone)] pub struct Value { t: PrimitiveType, v: InternalValue, } impl Value { pub fn new<T: Into<Intern...
#[inline] pub fn as_i64_unchecked(&self) -> i64 { unsafe { self.v.i64 } } #[inline] pub fn as_f32_unchecked(&self) -> f32 { unsafe { self.v.f32 } } #[inline] pub fn as_f64_unchecked(&self) -> f64 { unsafe { self.v.f64 } } } impl From<i32> for Value { fn ...
{ unsafe { self.v.i32 } }
identifier_body
main.go
()) if len(m) < 2 { continue } acc = m[1] if len(acc) == 0 { continue } p.accounts = append(p.accounts, acc) assignForAccount(acc) } } func (p *parser) generateClasses() { p.classes = make([]bayesian.Class, 0, 10) tomap := make(map[string]bool) for _, t := range p.txns { if t.skipClassificati...
score float64 pos int } type byScore []pair func (b byScore) Len() int { return len(b) } func (b byScore) Less(i int, j int) bool { return b[i].score > b[j].score } func (b byScore) Swap(i int, j int) { b[i], b[j] = b[j], b[i] } var trimWhitespace = regexp.MustCompile(`^[\s]+|[\s}]+$`) var dedupWhitespace = r...
type pair struct {
random_line_split
main.go
() int { return len(b) } func (b byScore) Less(i int, j int) bool { return b[i].score > b[j].score } func (b byScore) Swap(i int, j int) { b[i], b[j] = b[j], b[i] } var trimWhitespace = regexp.MustCompile(`^[\s]+|[\s}]+$`) var dedupWhitespace = regexp.MustCompile(`[\s]{2,}`) func (t *txn) isFromJournal() bool { r...
getCategory
identifier_name
main.go
return currentUser.HomeDir } var ( debug = flag.Bool("debug", false, "Additional debug information if set.") journal = flag.String("j", "", "Existing journal to learn from.") output = flag.String("o", "out.ldg", "Journal file to write to.") csvFile = flag.String("csv", "", "File path of CSV fi...
{ return "" }
conditional_block
main.go
categories. Found none.") if *tfidf { p.cl = bayesian.NewClassifierTfIdf(p.classes...) } else { p.cl = bayesian.NewClassifier(p.classes...) } assertf(p.cl != nil, "Expected a valid classifier. Found nil.") for _, t := range p.txns { if _, has := tomap[t.To]; !has { continue } p.cl.Learn(t.getTerms()...
{ return len(b) }
identifier_body
cargo_test.rs
, CargoTestError, Config, Test}; use cargo_util::{ProcessBuilder, ProcessError}; use std::ffi::OsString; use std::path::{Path, PathBuf}; pub struct TestOptions { pub compile_opts: ops::CompileOptions, pub no_run: bool, pub no_fail_fast: bool, } pub fn run_tests( ws: &Workspace<'_>, options: &TestO...
else { doctest }; errors.extend(docerrors); if errors.is_empty() { Ok(None) } else { Ok(Some(CargoTestError::new(test, errors))) } } pub fn run_benches( ws: &Workspace<'_>, options: &TestOptions, args: &[&str], ) -> CargoResult<Option<CargoTestError>> { let compilation ...
{ test }
conditional_block
cargo_test.rs
, CargoTestError, Config, Test}; use cargo_util::{ProcessBuilder, ProcessError}; use std::ffi::OsString; use std::path::{Path, PathBuf}; pub struct TestOptions { pub compile_opts: ops::CompileOptions, pub no_run: bool, pub no_fail_fast: bool, } pub fn run_tests( ws: &Workspace<'_>, options: &TestO...
_ => Ok(Some(CargoTestError::new(test, errors))), } } fn compile_tests<'a>(ws: &Workspace<'a>, options: &TestOptions) -> CargoResult<Compilation<'a>> { let mut compilation = ops::compile(ws, &options.compile_opts)?; compilation.tests.sort(); Ok(compilation) } /// Runs the unit and integration ...
0 => Ok(None),
random_line_split
cargo_test.rs
, CargoTestError, Config, Test}; use cargo_util::{ProcessBuilder, ProcessError}; use std::ffi::OsString; use std::path::{Path, PathBuf}; pub struct TestOptions { pub compile_opts: ops::CompileOptions, pub no_run: bool, pub no_fail_fast: bool, } pub fn run_tests( ws: &Workspace<'_>, options: &TestO...
( ws: &Workspace<'_>, options: &TestOptions, test_args: &[&str], compilation: &Compilation<'_>, ) -> CargoResult<(Test, Vec<ProcessError>)> { let config = ws.config(); let mut errors = Vec::new(); let doctest_xcompile = config.cli_unstable().doctest_xcompile; let doctest_in_workspace = c...
run_doc_tests
identifier_name
lib.rs
where R: Read, F: Facade { // building the freetype library // FIXME: call FT_Done_Library let library = unsafe { // taken from https://github.com/PistonDevelopers/freetype-rs/blob/master/src/library.rs extern "C" fn alloc_library(_memory: freetype::FT_Memory, size: ...
texture: texture, character_infos: chr_infos, em_pixels: em_pixels, }) } /// Return the size of an em-unit for the generated font texture. /// This is needed for a pixel-perfect display: the text geometry is scaled so that /// 1em == 1 unit. We must scale the...
Ok(FontTexture {
random_line_split
lib.rs
where R: Read, F: Facade { // building the freetype library // FIXME: call FT_Done_Library let library = unsafe { // taken from https://github.com/PistonDevelopers/freetype-rs/blob/master/src/library.rs extern "C" fn alloc_library(_memory: freetype::FT_Memory, size: ...
/// Return the x-positions (in em-units) of the breaks between characters. /// When a character starts at n-th byte, then get_char_pos_x()[n] is the x-pos of the character. /// The last value of the array is the x-pos of the end of the string pub fn get_char_pos_x(&self) -> &[f32] { &self.char...
{ let mut text_display = TextDisplay { context: system.context.clone(), texture: texture, vertex_buffer: None, index_buffer: None, char_pos_x: vec![], is_empty: true, }; text_display.set_text(text); text_display ...
identifier_body
lib.rs
realloc: realloc_library, }; let mut raw = ::std::ptr::null_mut(); if freetype::FT_New_Library(&mut MEMORY, &mut raw) != freetype::FT_Err_Ok { return Err(()); } freetype::FT_Add_Default_Modules(raw); raw };...
draw
identifier_name
lib.rs
new_size: libc::c_long, block: *mut libc::c_void) -> *mut libc::c_void { unsafe { libc::realloc(block, new_size as libc::size_t) } } static mut MEMORY: freetype...
{ // building the vertex buffer self.vertex_buffer = Some(glium::VertexBuffer::new(&self.context, &vertex_buffer_data).unwrap()); // building the index buffer self.index_buffer = Some(glium::IndexBuffer::new(...
conditional_block
hf2.ts
uint32_t data[flash_page_size]; }; */ // no result export const HF2_CMD_CHKSUM_PAGES = 0x0007
/* struct HF2_CHKSUM_PAGES_Command { uint32_t target_addr; uint32_t num_pages; }; struct HF2_CHKSUM_PAGES_Result { uint16_t chksums[num_pages]; }; */ export const HF2_CMD_READ_WORDS = 0x0008 /* struct HF2_READ_WORDS_Command { uint32_t target_addr; uint32_t num_words; }; struct HF2_READ_WORDS_Result...
random_line_split
hf2.ts
32_t data[flash_page_size]; }; */ // no result export const HF2_CMD_CHKSUM_PAGES = 0x0007 /* struct HF2_CHKSUM_PAGES_Command { uint32_t target_addr; uint32_t num_pages; }; struct HF2_CHKSUM_PAGES_Result { uint16_t chksums[num_pages]; }; */ export const HF2_CMD_READ_WORDS = 0x0008 /* struct HF2_READ_WORDS_...
private recvPacketAsync(): Promise<Uint8Array> { let final = (res: USBInTransferResult) => { if (res.status != "ok") this.error("USB IN transfer failed") let arr = new Uint8Array(res.data.buffer) if (arr.length == 0) return this.recvPacke...
{ this.ready = false if (!this.dev) return Promise.resolve() this.log("close device") return this.dev.close() .catch(e => { // just ignore errors closing, most likely device just disconnected }) .then(() => { this.clearD...
identifier_body
hf2.ts
32_t data[flash_page_size]; }; */ // no result export const HF2_CMD_CHKSUM_PAGES = 0x0007 /* struct HF2_CHKSUM_PAGES_Command { uint32_t target_addr; uint32_t num_pages; }; struct HF2_CHKSUM_PAGES_Result { uint16_t chksums[num_pages]; }; */ export const HF2_CMD_READ_WORDS = 0x0008 /* struct HF2_READ_WORDS_...
} } } error(m: string) { return this.io.error(m) } talkAsync(cmd: number, data?: Uint8Array) { let len = 8 if (data) len += data.length let pkt = new Uint8Array(len) let seq = ++this.cmdSeq & 0xffff U.write32(pkt, 0, cmd); U...
{ this.msgs.push(r) }
conditional_block
hf2.ts
32_t data[flash_page_size]; }; */ // no result export const HF2_CMD_CHKSUM_PAGES = 0x0007 /* struct HF2_CHKSUM_PAGES_Command { uint32_t target_addr; uint32_t num_pages; }; struct HF2_CHKSUM_PAGES_Result { uint16_t chksums[num_pages]; }; */ export const HF2_CMD_READ_WORDS = 0x0008 /* struct HF2_READ_WORDS_...
(msg: string) { throw new Error(`USB error on device ${this.dev ? this.dev.productName : "n/a"} (${msg})`) } private async readLoop() { if (this.readLoopStarted) return this.readLoopStarted = true this.log("start read loop") while (true) { if (!t...
error
identifier_name
lib.rs
_TLS` | enable secure connection using AMQPS (default: `false`, enable with `true` or `1` or `TRUE` or `True`) | //! | `AMQP_USERNAME` | Username used to connect to AMQP server (default: `guest`) | //! | `AMQP_PASSWORD` | Password used to connect to AMQP server (default: `guest`) | //! | `AMQP_VHOST` | AMQP vir...
{ job_result.update_execution_duration(); info!(target: &job_result.get_job_id().to_string(), "Process succeeded: {:?}", job_result) }
conditional_block
lib.rs
//! // fn main() {
//! // } //! ``` //! //! ## Runtime configuration //! //! ### AMQP connection //! //! | Variable | Description | //! |-----------------|-------------| //! | `AMQP_HOSTNAME` | IP or host of AMQP server (default: `localhost`) | //! | `AMQP_PORT` | AMQP server port (default: `5672`) | //! | `AMQP_TLS` | en...
//! // mcai_worker_sdk::start_worker(&WORKER_NAME_EVENT);
random_line_split
lib.rs
//! // fn main() { //! // mcai_worker_sdk::start_worker(&WORKER_NAME_EVENT); //! // } //! ``` //! //! ## Runtime configuration //! //! ### AMQP connection //! //! | Variable | Description | //! |-----------------|-------------| //! | `AMQP_HOSTNAME` | IP or host of AMQP server (default: `localhost`) | //! | `...
( &mut self, _job_result: JobResult, _stream_index: usize, _frame: ProcessFrame, ) -> Result<ProcessResult> { Err(MessageError::NotImplemented()) } #[cfg(feature = "media")] fn ending_process(&mut self) -> Result<()> { Ok(()) } /// Not called when the "media" feature is enabled f...
process_frame
identifier_name
lib.rs
message::publish_job_progression; pub use parameter::container::ParametersContainer; pub use parameter::{Parameter, ParameterValue, Requirement}; #[cfg(feature = "media")] pub use stainless_ffmpeg::{format_context::FormatContext, frame::Frame}; use crate::worker::docker; use chrono::prelude::*; use config::*; use env...
{ "long description".to_string() }
identifier_body
esp.py
(len(ridge_list)): r = ridge_list[i] L.append(Ridge_Facet(r.E_r, r.ar, r.br, E_0, af, bf)) G = af.T g = bf if verbose > 0: print("\nStarting eq set " + str(E_0) + "\nStarting ridges ") for rr in L: print(str(rr.E_r)) E.append(E_0) while len(L) > 0: ...
continue
conditional_block
esp.py
class Ridge_Facet(object): """A ridge facet. Attributes: - `E_r`: Equality set of a ridge - `ar,br`: Affine hull of the ridge s.t. P_{E_f} intersection {x | ar x = br} defines the ridge, where E_f is the equality set of the facet. - `E_0`: Equal...
self.E_r = E self.ar = a self.br = b
identifier_body
esp.py
abs_tol) return E_adj, af_adj, bf_adj def proj_aff(Ce, De, be, expected_dim=None, abs_tol=1e-7): """Affine projection. Compute the set aff = {x | Ce x + De y = be} on the form aff = ({x | a x = b} intersection {Ce x + De y < be}). Input: Polytope parameters Ce, De and be Output: Constants a...
normalize
identifier_name
esp.py
_tol=abs_tol) if verbose > 0: print("found neighbor " + str(E_adj) + ". \n\nLooking for ridges of neighbor..") ridge_list = ridge( C, D, b, E_adj, a_adj, b_adj, abs_tol=abs_tol, verbose=verbose) if verbose > 0: print("found " + st...
Q = np.nonzero(test < abs_tol)[0] X = np.setdiff1d(X, Q) # Have Q_i Sq = S[Q_i, :] tq = t[Q_i]
random_line_split
learnPython.py
数据量。flag提供有关消息的其他信息,通常可以忽略。 # s.send() 发送TCP数据,将string中的数据发送到连接的套接字。返回值是要发送的字节数量,该数量可能小于string的字节大小。 # s.sendall() 完整发送TCP数据,完整发送TCP数据。将string中的数据发送到连接的套接字,但在返回之前会尝试发送所有数据。成功返回None,失败则抛出异常。 # s.recvfrom() 接收UDP数据,与recv()类似,但返回值是(data,address)。其中data是包含接收数据的字符串,address是发送数据的套接字地址。 # s.sendto() 发送UDP数据,将数据发送到...
random_line_split
main.rs
127.0.0.1:8080 > User-Agent: curl/7.64.1 > Accept: * / * > < HTTP/1.1 302 Found < content-length: 51 < location: https://linkedin.com/in/tsauvajon < date: Wed, 19 May 2021 17:36:49 GMT < * Connection #0 to host 127.0.0.1 left intact redirecting to https://linkedin.com/in/tsauvajon...* Closing connection 0 ``` */ use a...
#[post("/{id}")] async fn create_with_id( db: web::Data<Db>, payload: web::Payload, web::Path(id): web::Path<String>, ) -> impl Responder { let target = match read_target(payload).await { Ok(target) => target, Err(err) => return Err(error::ErrorBadRequest(err)), }; create_shor...
{ if let Err(err) = Url::parse(&target) { return Err(format!("malformed URL: {}", err)); }; let id = match id { Some(id) => id, None => hash(&target), }; let mut db = db.write().unwrap(); if db.contains_key(&id) { Err("already registered".to_string()) } else...
identifier_body
main.rs
Host: 127.0.0.1:8080 > User-Agent: curl/7.64.1 > Accept: * / * > < HTTP/1.1 302 Found < content-length: 51 < location: https://linkedin.com/in/tsauvajon < date: Wed, 19 May 2021 17:36:49 GMT < * Connection #0 to host 127.0.0.1 left intact
*/ use actix_web::{error, get, post, web, App, HttpResponse, HttpServer, Responder}; use futures::StreamExt; use std::collections::HashMap; use std::sync::RwLock; use url::Url; const MAX_SIZE: usize = 1_024; // max payload size is 1k const RANDOM_URL_SIZE: usize = 5; // ramdomly generated URLs are 5 characters long t...
redirecting to https://linkedin.com/in/tsauvajon...* Closing connection 0 ```
random_line_split
main.rs
: 127.0.0.1:8080 > User-Agent: curl/7.64.1 > Accept: * / * > < HTTP/1.1 302 Found < content-length: 51 < location: https://linkedin.com/in/tsauvajon < date: Wed, 19 May 2021 17:36:49 GMT < * Connection #0 to host 127.0.0.1 left intact redirecting to https://linkedin.com/in/tsauvajon...* Closing connection 0 ``` */ use ...
(db: web::Data<Db>, web::Path(id): web::Path<String>) -> impl Responder { match db.read() { Ok(db) => match db.get(&id) { None => Err(error::ErrorNotFound("not found")), Some(url) => Ok(HttpResponse::Found() .header("Location", url.clone()) .body(forma...
browse
identifier_name
gateway.go
ListenerProtocol: listenerType, Env: env, Node: node, ProxyInstances: workloadInstances, Push: push, ServiceInstance: si, Port: &model.Port{ Name: servers[0].Port.Name, Port: int(portNumber), Protocol: protocol, }, } if err...
listeners = append(listeners, mutable.Listener) } // We'll try to return any listeners we successfully marshaled; if we have none, we'll emit the error we built up err = errs.ErrorOrNil() if err != nil { // we have some listeners to return, but we also have some errors; log them log.Info(err.Error()) } if ...
}
random_line_split
gateway.go
Protocol: listenerType, Env: env, Node: node, ProxyInstances: workloadInstances, Push: push, ServiceInstance: si, Port: &model.Port{ Name: servers[0].Port.Name, Port: int(portNumber), Protocol: protocol, }, } if err = p.OnO...
return routeCfg, nil } // to process HTTP and HTTPS servers along with virtualService.HTTP rules func (configgen *ConfigGeneratorImpl) createGatewayHTTPFilterChainOpts( node *model.Proxy, env *model.Environment, push *model.PushContext, servers []*networking.Server, gatewaysForWorkload map[string]bool) []*filterCh...
{ in := &plugin.InputParams{ ListenerProtocol: plugin.ListenerProtocolHTTP, Env: env, Node: node, Push: push, } p.OnOutboundRouteConfiguration(in, routeCfg) }
conditional_block
gateway.go
if len(server.Tls.CaCertificates) != 0 { trustedCa = &core.DataSource{ Specifier: &core.DataSource_Filename{ Filename: server.Tls.CaCertificates, }, } } if trustedCa != nil || len(server.Tls.SubjectAltNames) > 0 { certValidationContext = &auth.CertificateValidationContext{ TrustedCa: tr...
{ return &networking.L4MatchAttributes{ DestinationSubnets: tlsMatch.DestinationSubnets, Port: tlsMatch.Port, SourceSubnet: tlsMatch.SourceSubnet, SourceLabels: tlsMatch.SourceLabels, Gateways: tlsMatch.Gateways, } }
identifier_body
gateway.go
name]bool) for _, server := range servers { for _, host := range server.Hosts { gatewayHosts[model.Hostname(host)] = true if server.Tls != nil && server.Tls.HttpsRedirect { tlsRedirect[model.Hostname(host)] = true } } } port := int(servers[0].Port.Number) // NOTE: WE DO NOT SUPPORT two gateways o...
convertTLSProtocol
identifier_name
mod.rs
empty, which the scoring library doesn't handle println!(); println!("An empty password puts your wallet at risk against an attacker with access to this device."); println!("Use this only if you are sure that your device is safe from prying eyes!"); println!(); true } else ...
let master_seed = read_or_create_master_seed(recovery_seed.clone(),
random_line_split
mod.rs
let (wallet_backend, transaction_backend, output_manager_backend, contacts_backend, key_manager_backend) = initialize_sqlite_database_backends(db_path, arg_password, config.wallet.db_connection_pool_size)?; let wallet_db = WalletDatabase::new(wallet_backend); let output_db = OutputManagerDatabase:...
tari_splash_screen
identifier_name
mod.rs
.map(|r| r.map(Peer::from)) .collect::<Result<Vec<_>, _>>() .map_err(|err| ExitError::new(ExitCode::ConfigError, format!("Malformed seed peer: {}", err)))?; let peer_config = PeerConfig::new(selected_base_node, base_node_peers, peer_seeds); debug!(target: LOG_TARGET, "base node peer con...
{ debug!(target: LOG_TARGET, "Setting base node peer"); let net_address = base_node .addresses .best() .ok_or_else(|| ExitError::new(ExitCode::ConfigError, "Configured base node has no address!"))?; wallet .set_base_node_peer(base_node.public_key.clone(), net_address.addres...
identifier_body
mod.rs
, which the scoring library doesn't handle println!(); println!("An empty password puts your wallet at risk against an attacker with access to this device."); println!("Use this only if you are sure that your device is safe from prying eyes!"); println!(); true } else if let...
, _ => ExitError::new(ExitCode::DatabaseError, "Your password was not changed."), }) } /// Populates the PeerConfig struct from: /// 1. The custom peer in the wallet config if it exists /// 2. The custom peer in the wallet db if it exists /// 3. The detected local base node if any /// 4. The service peers ...
{ ExitError::new(ExitCode::IncorrectOrEmptyPassword, "Your password was not changed.") }
conditional_block
ChatEventCtrl.ts
iliang.huang * @Date: 2019-03-22 13:32:05 * @Last Modified by: jiangping * @Last Modified time: 2021-10-13 16:43:36 */ const { ccclass, property } = cc._decorator; @ccclass export default class ChatEventCtrl extends cc.Component { testFunc(event, param) { // console.log("testFunc", param) } ...
gdk.panel.hide(PanelId.HelpTipsPanel); JumpUtils.openRechargeView([0]) } scoreSysClick() { gdk.panel.open(PanelId.ScoreSytemView); } adventureClick() { JumpUtils.openActivityMain([9]) } shareHeroClick(event, param) { let msg = new icmsg.ShareInfoReq() ...
; } goToTQStore() {
conditional_block
ChatEventCtrl.ts
weiliang.huang * @Date: 2019-03-22 13:32:05 * @Last Modified by: jiangping * @Last Modified time: 2021-10-13 16:43:36 */ const { ccclass, property } = cc._decorator; @ccclass export default class ChatEventCtrl extends cc.Component { testFunc(event, param) { // console.log("testFunc", param) } ...
// roleModel.guildId = data.guildId // roleModel.guildName = data.camp.guild.name // gdk.panel.open(PanelId.GuildMain) // } // } else { // gdk.gui.showMessage(ErrorManager.get(data.error, [data.minLv])) /...
// gdk.panel.hide(PanelId.Friend) // gdk.panel.hide(PanelId.Chat) // gdk.gui.showMessage(`成功加入${data.camp.guild.name}公会`)
random_line_split
ChatEventCtrl.ts
weiliang.huang * @Date: 2019-03-22 13:32:05 * @Last Modified by: jiangping * @Last Modified time: 2021-10-13 16:43:36 */ const { ccclass, property } = cc._decorator; @ccclass export default class ChatEventCtrl extends cc.Component { testFunc(event, param) { // console.log("testFunc", param) } ...
// gdk.panel.open(PanelId.GuildMain) // } // } else { // gdk.gui.showMessage(ErrorManager.get(data.error, [data.minLv])) // } }, this) } /**打开赏金板 */ bountyClick(event, param) { gdk.panel.hide(PanelId.Chat) ...
anager.get(RoleModel) let joinLv = ConfigManager.getItemById(SystemCfg, 2400).openLv if (roleModel.level < joinLv) { gdk.gui.showMessage(`指挥官${joinLv}级才可加入`) return } let guildId = parseInt(param) let msg = new icmsg.GuildJoinReq() msg.guildId = gu...
identifier_body
ChatEventCtrl.ts
iliang.huang * @Date: 2019-03-22 13:32:05 * @Last Modified by: jiangping * @Last Modified time: 2021-10-13 16:43:36 */ const { ccclass, property } = cc._decorator; @ccclass export default class ChatEventCtrl extends cc.Component { testFunc(event, param) { // console.log("testFunc", param) } ...
eInfoReq() msg.shareId = param NetManager.send(msg, (data: icmsg.ShareInfoRsp) => { gdk.panel.open(PanelId.LookHeroView, (node: cc.Node) => { let model = ModelManager.get(HeroModel) model.heroImage = data.info let comp = node.getComponent(LookH...
new icmsg.Shar
identifier_name
goldenFile.go
init() { // gfc.AddUpdateFlag() // } // ... // gfc.Check(t, "my value test", t.Name(), val) // // Then to update the golden files you would invoke the test command as follows: // // go test -upd-gf // // Similarly with the KeepBadResultsFlag. // // Give the -v argument to go test to see what is being updated. // /...
{ t.Helper() origVal, err := os.ReadFile(gfName) // nolint: gosec if err == nil { if bytes.Equal(val, origVal) { return true } origFileName := gfName + ".orig" writeFile(t, origFileName, "original contents", origVal) } else if !os.IsNotExist(err) { t.Log("Couldn't preserve the original contents") t...
identifier_body
goldenFile.go
to have a long // string in the body of a test. // // DirNames is a slice of strings holding the parts of the directory path // to the file // // Pfx is an optional prefix - leave it as an empty string to exclude it // // Sfx is an optional suffix - as for the prefix // // UpdFlagName is the name of a flag that will s...
if actEqualsExp(t, id, gfName, val, expVal) { return true
random_line_split
goldenFile.go
report the flag name to use if any is // available. func (gfc *GoldenFileCfg) AddKeepBadResultsFlag() { if gfc.keepBadResultsFlagAdded { return } gfGlob := gfc.PathName("*") if gfc.KeepBadResultsFlagName == "" { panic(errors.New( "AddKeepBadResultsFlag has been called for files in " + gfGlob + " but th...
(t *testing.T, testID string, val []byte, gfName string, updGF bool) bool { t.Helper() return checkFile(t, testID, gfName, val, updGF) } // getExpVal reads the contents of the golden file. If the updGF flag is set // then if will write the contents of the file before reading it. It returns // the contents and true ...
CheckAgainstGoldenFile
identifier_name
goldenFile.go
report the flag name to use if any is // available. func (gfc *GoldenFileCfg) AddKeepBadResultsFlag() { if gfc.keepBadResultsFlagAdded { return } gfGlob := gfc.PathName("*") if gfc.KeepBadResultsFlagName == "" { panic(errors.New( "AddKeepBadResultsFlag has been called for files in " + gfGlob + " but th...
return expVal, true } // checkFile confirms that the value given matches the contents of the golden // file and returns true if it does, false otherwise. It will report any // errors it finds including any problems reading from or writing to the // golden file itself. If the updGF flag is set to true then the golden...
{ t.Log(id) t.Logf("\t: Problem with the golden file: %q", gfName) t.Errorf("\t: Couldn't read the expected value. Error: %s", err) return nil, false }
conditional_block
record_io.py
.FLAGS try: FLAGS.__delattr__('output_path') FLAGS.__delattr__('f') except: pass tf.app.flags.DEFINE_string('f', '', 'kernel') flags.DEFINE_string('output_path', path, '') FLAGS = flags.FLAGS print("New record file : {}".format(flags.FLAGS.output_path)) return tf...
height = result.context.feature['image/height'].int64_list.value[0] xmins = np.array(result.context.feature['image/object/bbox/xmin'].float_list.value) ymins = np.array(result.context.feature['image/object/bbox/ymin'].float_list.value) xmaxs = np.array(result.context.feature['image/objec...
objects = dict() obj_per_img = [] obj_shapes = [] img_shapes = [] total_images = 0 for result in load_tf_record_file(path): total_images += 1 names = result.context.feature['image/object/class/text'].bytes_list.value for name in names: if name not in objects: ...
identifier_body
record_io.py
.FLAGS try: FLAGS.__delattr__('output_path') FLAGS.__delattr__('f') except: pass tf.app.flags.DEFINE_string('f', '', 'kernel') flags.DEFINE_string('output_path', path, '') FLAGS = flags.FLAGS print("New record file : {}".format(flags.FLAGS.output_path)) return tf...
(path, index_to_class, return_dict=True, plot=True, **plot_kwargs): record = dict() for result in load_tf_record_file(path): fname = str(result.context.feature['image/filename'].bytes_list.value[0], "utf-8") width = result.context.feature['image/width'].int64_list.value...
read_record_file
identifier_name
record_io.py
.FLAGS try: FLAGS.__delattr__('output_path') FLAGS.__delattr__('f') except: pass tf.app.flags.DEFINE_string('f', '', 'kernel') flags.DEFINE_string('output_path', path, '') FLAGS = flags.FLAGS print("New record file : {}".format(flags.FLAGS.output_path)) return tf...
if plot: fig, ax = plt.subplots(1,1,figsize=plot_kwargs.get
record[fname] = dict() record[fname]["width"] = width record[fname]["height"] = height record[fname]["image"] = img record[fname]["xmins"] = xmins record[fname]["xmaxs"] = xmaxs record[fname]["ymins"] = ymins record[fname]["ymaxs"]...
conditional_block
record_io.py
.FLAGS try: FLAGS.__delattr__('output_path') FLAGS.__delattr__('f') except: pass tf.app.flags.DEFINE_string('f', '', 'kernel') flags.DEFINE_string('output_path', path, '') FLAGS = flags.FLAGS print("New record file : {}".format(flags.FLAGS.output_path)) return tf...
def peek_in_record(path, plot=True): objects = dict() obj_per_img = [] obj_shapes = [] img_shapes = [] total_images = 0 for result in load_tf_record_file(path): total_images += 1 names = result.context.feature['image/object/class/text'].bytes_list.value for name in na...
random_line_split
data_tools.py
_gen, y_enf_gen, y_enf_gen_pixl, idx_IN_X_and_y, idx_enf_gen def get_TRAIN_relevant(TRAIN, words): # IMPORTANT: we preserve the ORDER of TRAIN (so that we can recover information afterwards) TRAIN_relevant, rel_ids, OBJ_ctr_sd = {}, [], [] print('Getting *relevant* instances, from a total of: ' + str(le...
EMB_dict = {} for i in range(len(words)): EMB_dict[words[i]] = EMB[i,:] return EMB_dict
identifier_body
data_tools.py
_enf_gen['subj'].append(subj_list.index(TRAIN_relevant['subj'][i])) X_enf_gen['pred'].append(pred_list.index(TRAIN_relevant['rel'][i])) X_enf_gen['obj'].append(obj_list.index(TRAIN_relevant['obj'][i])) else: # if either the triplet/word is not generalized or we aren't enforcing general...
:param n_side_pixl: number of pixels as output (hyperparameter) :return y_pixl: matrix of pixels, i.e., a 2D tensor (n_side_pixl, n_side_pixl) ''' # continuous bounding box corners (prevent problems of predictions outside [0,1]) A_left_x, A_right_x = max((obj_ctr_x - obj_sd_x), 0), min((obj_ctr_x +...
def coord2pixel_indiv(obj_sd_x, obj_sd_y, obj_ctr_x, obj_ctr_y, n_side_pixl): ''' This function works with an individual example (extending it to many examples, where e.g., obj_sd_x is a vector, is easy) :param obj_sd_x (and the rest): real number (not vectors!)
random_line_split
data_tools.py
f_gen['subj'].append(subj_list.index(TRAIN_relevant['subj'][i])) X_enf_gen['pred'].append(pred_list.index(TRAIN_relevant['rel'][i])) X_enf_gen['obj'].append(obj_list.index(TRAIN_relevant['obj'][i])) else: # if either the triplet/word is not generalized or we aren't enforcing generaliza...
y = np.array(y) y_enf_gen = np.array(y_enf_gen) if y_enf_gen != [] else None if model_type == 'PIX': y_pixl = np.array(y_pixl) y_enf_gen_pixl = np.array(y_enf_gen_pixl) if y_enf_gen_pixl != [] else None else: y_pixl = [[[]]] # necessary because we get the index 0 of y_pixl (i...
y.append(y_new_row) if model_type == 'PIX': y_pixl.append(y_pixl_new_row) idx_IN_X_and_y.append(i)
conditional_block
data_tools.py
_enf_gen_pixl, idx_IN_X_and_y, idx_enf_gen def get_TRAIN_relevant(TRAIN, words): # IMPORTANT: we preserve the ORDER of TRAIN (so that we can recover information afterwards) TRAIN_relevant, rel_ids, OBJ_ctr_sd = {}, [], [] print('Getting *relevant* instances, from a total of: ' + str(len(TRAIN['subj'])))...
wordlist2emb_matrix
identifier_name
optimizer-output.component.ts
.dots('Loading...'); this.apiServices.scenario_planner_listdetails(this.valueSelected).subscribe((res:any)=>{ console.log(res,"listDetails"); Notiflix.Loading.remove(); let response=res; if(res.code==200 && res.status=='success'){ this.resetFilter(); let filterD...
random_line_split
optimizer-output.component.ts
text: 'Incremental Revenue by Placements', display: true } }; dataSetLabel1:any=[]; saveList:any=[{'name':'SELECT','id':0}, {'name':'Load1','id':1}] selectedplacementTypes=''; dataSet1:any={ data: [], label: 'Expected Lift by Pack type' }; //'total_activation_cost','total_incremental_sales','proc...
{ this.TATS_ARRAY=[]; for(let [key,value] of Object.entries(this.activationLIB)){ this.TATS_ARRAY.push({'name':value,'value':this.TATS[key]}) } this.TATSPack_ARRAY=[]; if(this.packTypeList){ for(let [key,value] of Object.entries(this.packTypeList)){ let values:any...
identifier_body
optimizer-output.component.ts
@Input() dataSet:any={ data: [0, 0, 0, 0, 0], title: { text: 'Incremental Revenue by Placements', display: true } }; dataSetLabel1:any=[]; saveList:any=[{'name':'SELECT','id':0}, {'name':'Load1','id':1}] selectedplacementTypes=''; dataSet1:any={ data: [], label: 'Expected Lift by Pack typ...
let payload={ "name":this.FileName, "json_data":this.filterData, "planner_type":planner_type } if(this.FileName.trim()!=''){ this.apiServices.scenario_planner_simulate_save(payload).subscribe((res:any)=>{ console.log(res,"res") if(res.code==200){ this.modalService.dismissAll(); ...
{ planner_type='simulation' }
conditional_block
optimizer-output.component.ts
(private modalService: NgbModal, private dataservice:DataControllerService, private routes:Router,private apiServices:ScenarioPlannerService) { // console.log(this.route.getCurrentNavigation()?.extras.state); this.datastream=this.routes.getCurrentNavigation()?.extras.state; this.currencySymbol=enviro...
constructor
identifier_name