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
SpatialGP.py
(lldda1, lldda2, params=None): import sigvisa.utils.geog as geog import numpy as np ll = geog.dist_km(tuple(lldda1[0:2]), tuple(lldda2[0:2])) depth = ( lldda1[2] - lldda2[2] ) * params[0] r = np.sqrt(ll ** 2 + depth ** 2) return r def lon_lat_depth_distfn_deriv(i, lldda1, lldda2, params=None): ...
lon_lat_depth_distfn
identifier_name
SpatialGP.py
0.0 def logdist_diff_distfn(lldda1, lldda2, params=None): import numpy as np dist = np.log(lldda1[3] + 1) - np.log(lldda2[3] + 1) return dist def azi_diff_distfn(lldda1, lldda2, params=None): import sigvisa.utils.geog as geog import numpy as np azi = np.abs ( geog.degdiff(lldda1[4], lldda2[4]...
return k """ def spatial_kernel_from_str(target=None, params=None): params = params if params is not None else start_params_lld[target] return params """ class SpatialGP(GaussianProcess, ParamModel): def init_hyperparams(self, hyperparams): (noise_var, signal_var, ll_scale, d_scale) = hype...
noise_kernel = kernels.DiagonalKernel(params=params[0:1], priors = priors[0:1]) distdiff_kernel = kernels.DistFNKernel(params=params[1:3], priors=priors[1:3], distfn = logdist_diff_distfn, deriv=None) azidiff_kernel = kernels.DistFNKernel(params=params[3:5], priors...
conditional_block
kubeconfig.go
("incorrect value of state parameter = %s", req.decodedState.Nonce) } oidcTokens, err := oidcIssuer.Exchange(ctx, req.code) if err != nil { return nil, kcerrors.NewBadRequest("error while exchaning oidc code for token = %v", err) } if len(oidcTokens.RefreshToken) == 0 { return nil, kcerrors.NewBa...
DecodeCreateOIDCKubeconfig
identifier_name
kubeconfig.go
cluster.Spec.OIDC.ExtraScopes } clientCmdAuth.AuthProvider = clientCmdAuthProvider adminClientCfg.AuthInfos = map[string]*clientcmdapi.AuthInfo{} adminClientCfg.AuthInfos["default"] = clientCmdAuth return &encodeKubeConifgResponse{clientCfg: adminClientCfg, filePrefix: "oidc"}, nil } } func CreateOIDCKub...
{ rsp := response.(createOIDCKubeconfigRsp) // handles kubeconfig Generated PHASE // it means that kubeconfig was generated and we need to properly encode it. if rsp.phase == kubeconfigGenerated { // clear cookie by setting MaxAge<0 err = setCookie(w, "", rsp.secureCookieMode, -1) if err != nil { return f...
identifier_body
kubeconfig.go
CreateOIDCKubeconfigEndpoint(projectProvider provider.ProjectProvider, oidcIssuerVerifier auth.OIDCIssuerVerifier, oidcCfg common.OIDCConfiguration) endpoint.Endpoint { return func(ctx context.Context, request interface{}) (interface{}, error) { oidcIssuer := oidcIssuerVerifier.(auth.OIDCIssuer) oidcVerifier := o...
{ return nil, err }
conditional_block
kubeconfig.go
.KubernetesErrorToHTTPError(err) } cluster, err := clusterProvider.Get(userInfo, req.ClusterID, &provider.ClusterGetOptions{}) if err != nil { return nil, common.KubernetesErrorToHTTPError(err) } adminClientCfg, err := clusterProvider.GetAdminKubeconfigForCustomerCluster(cluster) if err != nil { retu...
return rsp, nil } } type encodeKubeConifgResponse struct { clientCfg *clientcmdapi.Config filePrefix string } func EncodeKubeconfig(c context.Context, w http.ResponseWriter, response interface{}) (err error) { rsp := response.(*encodeKubeConifgResponse) cfg := rsp.clientCfg filename := "kubeconfig" if len(...
rsp.authCodeURL = oidcIssuer.AuthCodeURL(urlSafeState, oidcCfg.OfflineAccessAsScope, scopes...)
random_line_split
corrector.py
("decode_while_training", False, "Do test decode while training.") tf.app.flags.DEFINE_boolean("decode_whole", False, "decode whole code or just a set.") FLAGS = tf.app.flags.FLAGS # We use a number of buckets and pad to the closest one for efficiency. # See seq2seq_model.Seq2SeqModel for details of how they work. # ...
source_ids = [code[line_idx], code[line_idx + 1]] target_ids = [[]] target_ids[0].append(code_loader.EOS_ID) for bucket_id, (source_size, target_size) in enumerate(_buckets): if len(source_ids[0]) < source_size and len(source_ids[1]) < source_size and le...
n train_id_set: for line_idx in xrange(len(code) - 2): if max_size and counter >= max_size: break counter += 1 source_ids = [code[line_idx], code[line_idx + 2]] target_ids = [code[line_idx + 1]] target_ids[0].append(code_loader.EOS_ID)...
identifier_body
corrector.py
_boolean("decode_while_training", False, "Do test decode while training.") tf.app.flags.DEFINE_boolean("decode_whole", False, "decode whole code or just a set.") FLAGS = tf.app.flags.FLAGS # We use a number of buckets and pad to the closest one for efficiency. # See seq2seq_model.Seq2SeqModel for details of how they ...
_buckets, FLAGS.size, FLAGS.num_layers, FLAGS.max_gradient_norm, FLAGS.batch_size, FLAGS.learning_rate, FLAGS.learning_rate_decay_factor, forward_only=forward_only, dtype=dtype) ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir) if ckpt ...
dtype = tf.float16 if FLAGS.use_fp16 else tf.float32 model = code_model.CodeModel( vocab_size,
random_line_split
corrector.py
_boolean("decode_while_training", False, "Do test decode while training.") tf.app.flags.DEFINE_boolean("decode_whole", False, "decode whole code or just a set.") FLAGS = tf.app.flags.FLAGS # We use a number of buckets and pad to the closest one for efficiency. # See seq2seq_model.Seq2SeqModel for details of how they ...
with open(FLAGS.train_dir + "/" + os.path.basename(__file__) + ".ckpt.vb", mode="w") as vocab_size_file: pickle.dump(vocab_size, vocab_size_file) checkpoint_path = os.path.join(FLAGS.train_dir, FLAGS.data_path.split(".")[0] + ".ckpt.size." + str(FLAGS.size) + ".nl." + str...
and loss.
identifier_name
corrector.py
_step) def train(): train_id_data, id_to_vocab, vocab_to_id = code_loader.prepare_data(FLAGS.data_dir, FLAGS.vocab_size, data_path=FLAGS.data_path, cache=FLAGS.cache) vocab_size = FLAGS.vocab_size if FLAGS.vocab_size != 0 else len(id_to_vocab) # Create decode model # print("Creating %d layers of %d ...
[[]] target_ids[0].append(code_loader.EOS_ID) for idx, (source_size, target_size) in enumerate(_buckets): if len(source_ids[0]) < source_size and len(source_ids[1]) < source_size: data_set[idx].append([source_ids, target_ids]) ...
conditional_block
trajectory_multiple.py
_shape) # src_pt = np.float32(table) # dst_pt = np.float32([(0,0), (dst_shape[0],0), dst_shape, (0, dst_shape[1])]) # warp_matrix = cv.getPerspectiveTransform(src_pt, dst_pt) # img = cv.warpPerspective(img, warp_matrix, dst_shape) # 4. Correct known coordinates with the warp matrix. def transform_point(pt...
(pt1, pt2): return math.sqrt(math.pow(pt2[0]-pt1[0], 2)+math.pow(pt2[1]-pt1[1], 2)) def point_by_angle(pt, angle, distance): x = pt[0] + (distance * math.cos(angle)) y = pt[1] + (distance * math.sin(angle)) return tuple([round(x), round(...
point_distance
identifier_name
trajectory_multiple.py
_shape) # src_pt = np.float32(table) # dst_pt = np.float32([(0,0), (dst_shape[0],0), dst_shape, (0, dst_shape[1])]) # warp_matrix = cv.getPerspectiveTransform(src_pt, dst_pt) # img = cv.warpPerspective(img, warp_matrix, dst_shape) # 4. Correct known coordinates with the warp matrix. def transform_point(pt...
return [tuple(x[:2]) for x in squeezed] # table = transform_point(table, warp_matrix) table = [(0, 0), (1710, 0), (1710, 768), (0, 768)] cue_ball = transform_point(cue_ball, warp_matrix) cue_start = transform_point(cue_start, warp_matrix) cue_tip = transform_point(cue_tip, warp_matrix) balls = transform...
return tuple(squeezed[:2])
conditional_block
trajectory_multiple.py
_shape) # src_pt = np.float32(table) # dst_pt = np.float32([(0,0), (dst_shape[0],0), dst_shape, (0, dst_shape[1])]) # warp_matrix = cv.getPerspectiveTransform(src_pt, dst_pt) # img = cv.warpPerspective(img, warp_matrix, dst_shape) # 4. Correct known coordinates with the warp matrix. def transform_point(pt...
def update(): global img, table, cue_tip, cue_start, cue_ball, cue_ball_radius hit_balls = [] shown_image = img.copy() def points_to_angle(point1, point2): return math.atan2(point2[1] - point1[1], point2[0] - point1[0]) # 5. Draw the trajectory # 5.1 Get the cue angle based ...
random_line_split
trajectory_multiple.py
_shape) # src_pt = np.float32(table) # dst_pt = np.float32([(0,0), (dst_shape[0],0), dst_shape, (0, dst_shape[1])]) # warp_matrix = cv.getPerspectiveTransform(src_pt, dst_pt) # img = cv.warpPerspective(img, warp_matrix, dst_shape) # 4. Correct known coordinates with the warp matrix. def transform_point(pt...
if line_circle_collision(cue_start, cue_tip, cue_ball, cue_ball_radius): # 5.3 Get the angle of the cue ball trajectory. trj_angle = cue_angle start_point = cue_ball collisions = 1 while collisions <= 5: collisions += 1 # 5.4 Use the...
return (angle + math.pi) % (2 * math.pi)
identifier_body
lib.rs
([127, 0, 0, 1], 8000).into(); //! let svc = MitmProxyService::<MyMitm>::new(); //! let server = Server::bind(&addr) //! .serve(svc) //! .map_err(|e| eprintln!("server error: {}", e)); //! println!("noop mitm proxy listening on http://{}", addr); //! hyper::rt::run(server); //! } //! ``...
} impl<T: Mitm + Sync + Send + 'static> NewService for MitmProxyService<T> { type ReqBody = Body; type ResBody = Body; type Error = std::io::Error; type Service = MitmProxyService<T>; type InitError = std::io::Error; type Future = FutureResult<Self::Service, Self::InitError>; fn new_servi...
{ MitmProxyService::<T> { _phantom: std::marker::PhantomData, } }
identifier_body
lib.rs
. fn request_headers(&self, req: Request<Body>) -> Request<Body>; /// Observe and manipulate a chunk of the request payload. This function /// may be called zero or more times, depending on the size of the request /// payload. It will not be called at all in the common case of a GET /// request wit...
{ info!( "service_inner_requests() serve_connection: \ client closed connection" ); }
conditional_block
lib.rs
= ([127, 0, 0, 1], 8000).into(); //! let svc = MitmProxyService::<MyMitm>::new(); //! let server = Server::bind(&addr) //! .serve(svc) //! .map_err(|e| eprintln!("server error: {}", e)); //! println!("noop mitm proxy listening on http://{}", addr); //! hyper::rt::run(server); //! } //! ...
<T: Mitm + Sync + Send + 'static>( connect_req: Request<Body>, ) -> impl Future<Item = Response<Body>, Error = std::io::Error> { info!("proxy_connect() impersonating {:?}", connect_req.uri()); let authority = Authority::from_shared(Bytes::from(connect_req.uri().to_string())) .unwrap(); ...
proxy_connect
identifier_name
lib.rs
= ([127, 0, 0, 1], 8000).into(); //! let svc = MitmProxyService::<MyMitm>::new(); //! let server = Server::bind(&addr) //! .serve(svc) //! .map_err(|e| eprintln!("server error: {}", e)); //! println!("noop mitm proxy listening on http://{}", addr); //! hyper::rt::run(server); //! } //! ...
/// received "inside" the fake, tapped `CONNECT` tunnel. fn proxy_request<T: Mitm + Sync + Send + 'static>( req: Request<Body>, ) -> impl Future<Item = Response<Body>, Error = std::io::Error> { obtain_connection(req.uri().to_owned()) .map(|mut connection| { let mitm1 = Arc::new(T::new(req.ur...
/// /// This function is called for plain http requests, and for https requests
random_line_split
stereo_calibration.py
else: term = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_COUNT, 30, 0.1) cv2.cornerSubPix(img, corners, (5, 5), (-1, -1), term) if displayCorners is True: # print(filename) vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) cv2.drawChessboardCorners(vis, boardSize, corners, found) cv2.imshow(...
break
random_line_split
stereo_calibration.py
_FIX_INTRINSIC)) print("Rotation: ", R) r_vec, jac = cv2.Rodrigues(R) print("R_vec: ", np.multiply(r_vec, 180/math.pi)) print("Translation: ", T) print("Essential: ", E) print("Fundamental: ", F) print('Stereo calibration (DIY)...') topImagePointsConcat = topImagePoints[0] sideImagePointsConcat = sideImagePoi...
size = (9, 7) squareSize = 6 # millimeters sourcePath = '/home/jgschornak/NeedleGuidance/images_converging_cams/' top_img_mask = sourcePath + 'top*.jpg' top_img_names = glob(top_img_mask) side_img_mask = sourcePath + 'side*.jpg' side_img_names = glob(side_img_mask) # print(left_img_names) # print('\n') # pri...
identifier_body
stereo_calibration.py
(imageList, boardSize, squareSize, displayCorners = True, useCalibrated = True, showRectified = True): nImages = int(len(imageList)/2) goodImageList = [] imageSize = None fig = plt.figure() ax = fig.add_subplot(111, projection='3d') topImagePoints = [] sideImagePoints = [] imagePoints = [] imagePoints.appe...
StereoCalib
identifier_name
stereo_calibration.py
# Image from side camera goodImageList.append(imageList[i*2]) goodImageList.append(imageList[i*2+1]) j = j + 1 sideImagePoints.append(corners.reshape(-1,2)) topImagePoints.append(tempTop) objectPoints.append(pattern_points) print('Added left and right points') else: # I...
# print(imagePoints[1]) # print(objectPoints) print("Img count: " + str(len(topImagePoints))) print("Obj count: " + str(len(objectPoints))) # print(np.array(imagePoints[0])) top_calibration = np.load('top_calibration.npz') side_calibration = np.load('side_calibration.npz') top_rms = top_calibration['rms']...
print("Too few pairs to run calibration\n") return
conditional_block
block.rs
const ROW0_TABLE: LookupTable<u8, Block> = lookup_table![ (0x00, 0x7F, Basic), ]; const ROW0_LIMIT: char = '\u{80}'; const PLANE0_TABLE: LookupTable<u16, Block> = lookup_table![ (0x0080, 0x024F, Latin), (0x0250, 0x02AF, IPA), (0x02B0, 0x02FF, Spacing), (0x0300, 0x036F, Combining), (0x0370, 0x0...
{ use std::convert::TryInto; ROW0_TABLE.validate(); if let Ok(x) = (ROW0_LIMIT as u32).try_into() { assert!(!ROW0_TABLE.contains(&x)); } PLANE0_TABLE.validate(); if let Ok(x) = (PLANE0_LIMIT as u32).try_into() { assert!(!PLANE0_TABLE.contains(&x)); } SUPPLEMENTARY_TABLE.validate(); }
identifier_body
block.rs
, 0x197F, Tai), (0x1980, 0x19DF, New), (0x19E0, 0x19FF, Khmer), (0x1A00, 0x1A1F, Buginese), (0x1A20, 0x1AAF, Tai), (0x1AB0, 0x1AFF, Combining), (0x1B00, 0x1B7F, Balinese), (0x1B80, 0x1BBF, Sundanese), (0x1BC0, 0x1BFF, Batak), (0x1C00, 0x1C4F, Lepcha), (0x1C50, 0x1C7F, Ol),
(0x1CC0, 0x1CCF, Sundanese), (0x1CD0, 0x1CFF, Vedic), (0x1D00, 0x1DBF, Phonetic), (0x1DC0, 0x1DFF, Combining), (0x1E00, 0x1EFF, Latin), (0x1F00, 0x1FFF, Greek), (0x2000, 0x206F, General), (0x2070, 0x209F, Superscripts), (0x20A0, 0x20CF, Currency), (0x20D0, 0x20FF, Combining), ...
(0x1C80, 0x1C8F, Cyrillic), (0x1C90, 0x1CBF, Georgian),
random_line_split
block.rs
SUPPLEMENTARY_TABLE.validate(); } const ROW0_TABLE: LookupTable<u8, Block> = lookup_table![ (0x00, 0x7F, Basic), ]; const ROW0_LIMIT: char = '\u{80}'; const PLANE0_TABLE: LookupTable<u16, Block> = lookup_table![ (0x0080, 0x024F, Latin), (0x0250, 0x02AF, IPA), (0x02B0, 0x02FF, Spacing), (0x0300...
{ assert!(!PLANE0_TABLE.contains(&x)); }
conditional_block
block.rs
() { use std::convert::TryInto; ROW0_TABLE.validate(); if let Ok(x) = (ROW0_LIMIT as u32).try_into() { assert!(!ROW0_TABLE.contains(&x)); } PLANE0_TABLE.validate(); if let Ok(x) = (PLANE0_LIMIT as u32).try_into() { assert!(!PLANE0_TABLE.contains(&x)); } SUPPLEMENTARY_TABLE.validate(); } const R...
validate_tables
identifier_name
drawing.go
{c[0], a[1]}, f32.Vec2{a[0], c[1]} uvb, uvd := f32.Vec2{uvc[0], uva[1]}, f32.Vec2{uva[0], uvc[1]} dl.VtxWriter[0] = DrawVert{a, uva, color} dl.VtxWriter[1] = DrawVert{b, uvb, color} dl.VtxWriter[2] = DrawVert{c, uvc, color} dl.VtxWriter[3] = DrawVert{d, uvd, color} ii := dl.vtxIndex dl.IdxWriter[0] = DrawIdx(i...
32.Vec2{b[0]-br, a[1]+
conditional_block
drawing.go
ndex = 0 dl.vtxIndex = 0 } func (dl *DrawList) PathClear() { dl.pathUsed = 0 } func (dl *DrawList) PathLineTo(pos f32.Vec2) { if n := len(dl.path); dl.pathUsed < n-1 { dl.path[dl.pathUsed] = pos dl.pathUsed += 1 } } func (dl *DrawList) PathLineToMergeDuplicate(pos f32.Vec2) { //if (_Path.Size == 0 || memcmp...
.idxI
identifier_name
drawing.go
.Vec2 { return f32.Vec2{0, 0 } } func (dl *DrawList) GetClipRectMax() f32.Vec2 { return f32.Vec2{0, 0 } } func (dl *DrawList) PushTextureId(texId uint16) { dl.TextureIdStack = append(dl.TextureIdStack, texId) }
} } // primitive operation, auto scale by 1024 func (dl *DrawList) PrimReserve(idxCount, vtxCount int) { if sz, require := len(dl.VtxBuffer), dl.vtxIndex+vtxCount; require >= sz { vtxBuffer := make([]DrawVert, sz+1024) copy(vtxBuffer, dl.VtxBuffer) dl.VtxBuffer = vtxBuffer } if sz, require := len(dl.IdxBuffe...
func (dl *DrawList) PopTextureId() { if n := len(dl.TextureIdStack); n > 0 { dl.TextureIdStack = dl.TextureIdStack[:n-1]
random_line_split
drawing.go
ClipRect() (clip f32.Vec4) { if n := len(dl.ClipRectStack); n > 0 { clip = dl.ClipRectStack[n-1] } else { clip = dl.FullScreen } return } func (dl *DrawList) CurrentTextureId() (id uint16) { if n := len(dl.TextureIdStack); n > 0 { id = dl.TextureIdStack[n-1] } return } // will result in new draw-call fun...
pathUsed], color, thickness, closed) dl.PathClear() } func (dl *DrawList) Current
identifier_body
server.py
@app.route("/users") def user_list(): """Show list of users.""" users = User.query.all() return render_template("user_list.html", users=users) # This takes to each user's profile from user list @app.route("/users/<int:user_id>") def user_profile(user_id): """Show user information""" # Query ...
"""Homepage.""" # We want user profile link to show if user is logged in and clicks on homepage # Check if logged in and get the value or else return None # If there is a value, query to get user information so that user.user_id can be accessed in jinja # Else, pass None value through so that if state...
identifier_body
server.py
.""" # We want user profile link to show if user is logged in and clicks on homepage # Check if logged in and get the value or else return None # If there is a value, query to get user information so that user.user_id can be accessed in jinja # Else, pass None value through so that if statement in jin...
(): """Show list of users.""" users = User.query.all() return render_template("user_list.html", users=users) # This takes to each user's profile from user list @app.route("/users/<int:user_id>") def user_profile(user_id): """Show user information""" # Query by user id to return that record in d...
user_list
identifier_name
server.py
.""" # We want user profile link to show if user is logged in and clicks on homepage # Check if logged in and get the value or else return None # If there is a value, query to get user information so that user.user_id can be accessed in jinja # Else, pass None value through so that if statement in jin...
else: wizard_rating = wizard_rating.score if wizard_rating and effective_rating: difference = abs(wizard_rating - effective_rating) else: # We couldn't get a wizard rating, so we'll skip difference difference = None # Depending on how di...
wizard_rating = wizard.predict_rating(movie)
conditional_block
server.py
in jinja not executed user_email = session.get("logged_in_user_email", None) if user_email is not None: user = User.query.filter(User.email == user_email).one() return render_template("homepage.html", user=user) else: return render_template("homepage.html", user=None) @app.route(...
# get user id from log in email address user_email = session["logged_in_user_email"] user = User.query.filter(User.email == user_email).one()
random_line_split
broken_telephone.go
// randomSubstituteFor returns a semi-random but usually phonetically // close substitute for w. func (d metaphoneDict) randomSubstituteFor(w *metaphoneWord) *metaphoneWord { mp := w.metaphone if rand.Intn(2) == 0 { mp = w.secondary } match := d.matches(mp).randomNonEqual(w.literal) if match != nil { return ...
{ if len(d) == 0 { return nil } i := rand.Intn(len(d)) switch { case d[i].literal != w: case i > 0 && d[i-1].literal != w: i-- case i < len(d)-1 && d[i+1].literal != w: i++ case i == 0 && len(d) > 2 && d[i+2].literal != w: i += 2 case i == len(d)-1 && len(d) > 2 && d[i-2].literal != w: i -= 2 defaul...
identifier_body
broken_telephone.go
(i, j int) bool { return d[i].metaphone < d[j].metaphone } // phoneticLocation returns the index where metaphone is or would be sorted. func (d metaphoneDict) phoneticLocation(metaphone string) (i int) { left, right := 0, len(d) for left < right { i = left + ((right - left) / 2) if d[i].metaphone < metaphone { ...
Less
identifier_name
broken_telephone.go
(dict)+1, cap(dict)+dictCapacity) copy(dict, *d) } dict[len(dict)-1] = mp *d = dict } // readWords creates a metaphone dictionary from input of one word per line. // The dictionary is sorted by phonetic representation. func readWords(input io.Reader) metaphoneDict { dict := newMetaphoneDict() rd := bufio.NewRea...
// michael mp, ms = "K", "X" break } if (pos == 1 && (prev == 'M' || prev == 'S')) || n2 == 'T' || n2 == 'S' { // Mc, Sch, -cht, -chs mp = "K" break } if (prev == 'A' || prev == 'O' || prev == 'U' || prev == 'E') && (n2 == 'L' || n2 == 'R' || n2 == 'N'...
if pos > 0 { if n2 == 'A' && n3 == 'E' {
random_line_split
broken_telephone.go
} } if strings.Index(word, " ") != -1 || len(word) < minWordLength { continue } mp := *doubleMetaphone(word) dict.Push(mp) if mp.metaphone != mp.secondary { // Secondary phonetic representation dict.Push(metaphoneWord{word, mp.literal, mp.secondary, mp.metaphone}) } } else { ...
p = "F" } case
conditional_block
mod.rs
.read(); match peer_guard.control_channel.connection() { Some(connection) => connection.clone(), None => return, } }; let command_stream = connection.take_command_stream(); // Limit to 16 since that is the max number of transactions we can process at any one time p...
/// State observer task around a remote peer. Takes a change stream from the remote peer that wakes /// the task whenever some state has changed on the peer. Swaps tasks such as making outgoing /// connections, processing the incoming control messages, and registering for notifications on the /// remote peer. pub(supe...
) .map(|_| ()), ); handle }
random_line_split
mod.rs
.read(); match peer_guard.control_channel.connection() { Some(connection) => connection.clone(), None => return, } }; let command_stream = connection.take_command_stream(); // Limit to 16 since that is the max number of transactions we can process at any one time p...
NotificationEventId::EventTrackChanged => { let response = TrackChangedNotificationResponse::decode(data) .map_err(|e| Error::PacketError(e))?; peer.write().handle_new_controller_notification_event(ControllerEvent::TrackIdChanged( response.identifier(), ...
{ fx_vlog!(tag: "avrcp", 2, "received notification for {:?} {:?}", notif, data); let preamble = VendorDependentPreamble::decode(data).map_err(|e| Error::PacketError(e))?; let data = &data[preamble.encoded_len()..]; if data.len() < preamble.parameter_length as usize { return Err(Error::Unexpec...
identifier_body
mod.rs
.read(); match peer_guard.control_channel.connection() { Some(connection) => connection.clone(), None => return, } }; let command_stream = connection.take_command_stream(); // Limit to 16 since that is the max number of transactions we can process at any one time p...
(peer: Arc<RwLock<RemotePeer>>) { fx_vlog!(tag: "avrcp", 2, "state_watcher starting"); let mut change_stream = peer.read().state_change_listener.take_change_stream(); let peer_weak = Arc::downgrade(&peer); drop(peer); let mut channel_processor_abort_handle: Option<AbortHandle> = None; let mut n...
state_watcher
identifier_name
global.rs
this peer is a stuck node, and we will kick out such kind of stuck peers. pub const STUCK_PEER_KICK_TIME: i64 = 2 * 3600 * 1000; /// If a peer's last seen time is 2 weeks ago we will forget such kind of defunct peers. const PEER_EXPIRATION_DAYS: i64 = 7 * 2; /// Constant that expresses defunct peer timeout in second...
/// Set the global NRD feature flag using override. pub fn set_global_nrd_enabled(enabled: bool) { GLOBAL_NRD_FEATURE_ENABLED.set(enabled, true) } /// Explicitly enable the local NRD feature flag. pub fn set_local_nrd_enabled(enabled: bool) { NRD_FEATURE_ENABLED.with(|flag| flag.set(Some(enabled))) } /// Is the N...
{ GLOBAL_NRD_FEATURE_ENABLED.init(enabled) }
identifier_body
global.rs
this peer is a stuck node, and we will kick out such kind of stuck peers. pub const STUCK_PEER_KICK_TIME: i64 = 2 * 3600 * 1000; /// If a peer's last seen time is 2 weeks ago we will forget such kind of defunct peers. const PEER_EXPIRATION_DAYS: i64 = 7 * 2; /// Constant that expresses defunct peer timeout in second...
() -> ChainTypes { CHAIN_TYPE.with(|chain_type| match chain_type.get() { None => { if !GLOBAL_CHAIN_TYPE.is_init() { panic!("GLOBAL_CHAIN_TYPE and CHAIN_TYPE unset. Consider set_local_chain_type() in tests."); } let chain_type = GLOBAL_CHAIN_TYPE.borrow(); set_local_chain_type(chain_type); chain_t...
get_chain_type
identifier_name
global.rs
fn set_global_nrd_enabled(enabled: bool) { GLOBAL_NRD_FEATURE_ENABLED.set(enabled, true) } /// Explicitly enable the local NRD feature flag. pub fn set_local_nrd_enabled(enabled: bool) { NRD_FEATURE_ENABLED.with(|flag| flag.set(Some(enabled))) } /// Is the NRD feature flag enabled? /// Look at thread local config ...
/// Calculates the size of a header (in bytes) given a number of edge bits in the PoW #[inline] pub fn header_size_bytes(edge_bits: u8) -> usize { let size = 2 + 2 * 8 + 5 * 32 + 32 + 2 * 8; let proof_size = 8 + 4 + 8 + 1 + Proof::pack_len(edge_bits);
random_line_split
simple-filters.go
n *sam.Alignment) bool { return dictTable[aln.RNAME] } } } // ReplaceReferenceSequenceDictionaryFromSamFile returns a filter for // replacing the reference sequence dictionary in a Header with one // parsed from the given SAM/DICT file. func ReplaceReferenceSequenceDictionaryFromSamFile(samFile string) (f sam.Filter,...
if xg, ok := aln.TAGS.Get(XG); !ok || xg.(int32) != 0 { return false } return true } } // RemoveDuplicateReads is a filter for removing duplicate // sam-alignment instances, based on FLAG. func RemoveDuplicateReads(_ *sam.Header) sam.AlignmentFilter { return func(aln *sam.Alignment) bool { return (aln.FLAG...
{ return false }
conditional_block
simple-filters.go
(aln *sam.Alignment) bool { return dictTable[aln.RNAME] } } } // ReplaceReferenceSequenceDictionaryFromSamFile returns a filter for // replacing the reference sequence dictionary in a Header with one // parsed from the given SAM/DICT file. func ReplaceReferenceSequenceDictionaryFromSamFile(samFile string) (f sam.Filt...
(_ *sam.Header) sam.AlignmentFilter { return func(aln *sam.Alignment) bool { return ((aln.FLAG & sam.Unmapped) == 0) && (aln.POS != 0) && (aln.RNAME != "*") } } // RemoveNonExactMappingReads is a filter that removes all reads that // are not exact matches with the reference (soft-clipping ok), based // on CIGAR st...
RemoveUnmappedReadsStrict
identifier_name
simple-filters.go
n *sam.Alignment) bool { return dictTable[aln.RNAME] } } } // ReplaceReferenceSequenceDictionaryFromSamFile returns a filter for // replacing the reference sequence dictionary in a Header with one // parsed from the given SAM/DICT file. func ReplaceReferenceSequenceDictionaryFromSamFile(samFile string) (f sam.Filter,...
// RenameChromosomes is a filter for prepending "chr" to the reference // sequence names in a Header, and in RNAME and RNEXT in each // Alignment. func RenameChromosomes(header *sam.Header) sam.AlignmentFilter { for _, entry := range header.SQ { if sn, found := entry["SN"]; found { entry["SN"] = "chr" + sn } ...
{ return func(header *sam.Header) sam.AlignmentFilter { id := newPG["ID"] for utils.Find(header.PG, func(entry utils.StringMap) bool { return entry["ID"] == id }) >= 0 { id += " " id += strconv.FormatInt(rand.Int63n(0x10000), 16) } newPG["ID"] = id for _, PG := range header.PG { nextID := PG["ID"] ...
identifier_body
simple-filters.go
(aln *sam.Alignment) bool { return dictTable[aln.RNAME] } } } // ReplaceReferenceSequenceDictionaryFromSamFile returns a filter for // replacing the reference sequence dictionary in a Header with one // parsed from the given SAM/DICT file. func ReplaceReferenceSequenceDictionaryFromSamFile(samFile string) (f sam.Filt...
nerr := input.Close() if err == nil { err = nerr } }() header, _, err := sam.ParseHeader(input.Reader) if err != nil { return nil, err } return ReplaceReferenceSequenceDictionary(header.SQ), nil } // RemoveUnmappedReads is a filter for removing unmapped sam-alignment // instances, based on FLAG. func R...
return nil, err } defer func() {
random_line_split
scout.py
100 * res.score) label = '{}% {}'.format(percent, labels[res[0]]) cv2_im = cv2.putText(cv2_im, label, (600, 20+ii*30), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 255), 1) return cv2_im # define callbacks def human_callback(witch, arg_path, arg_name, arg_recfile, data_sens): # choosw from witch l...
t2 = time.time() nc_a, nc_b, data_sens = dual_detect(args.name, args.verbose) while True:
random_line_split
scout.py
) m_tb, arr_tb = read_sensor_pixels(sensor_b) na = len(list(filter(lambda x: (x - m_ta) >= MIN_TEMP_DIFF, arr_ta))) nb = len(list(filter(lambda x: (x - m_tb) >= MIN_TEMP_DIFF, arr_tb))) if verbose: print("\n") print ('[t1]:{0:.1f}\t[t2]:{1:.1f}'.format(m_tb, m_ta)) for ix in rang...
arg_path, arg_name, arg_recfile, data_sens): # choosw from witch label = "HUMAN" timetag = time.strftime("%Y%m%d_%H%M%S") # log to record file record_file = open(arg_recfile, 'a+') if (witch==1): record_file.write("[scout.detection]: <{0}> <{1}>\n".format(timetag, arg_name[0])) elif (witch==...
llback(witch,
identifier_name
scout.py
) m_tb, arr_tb = read_sensor_pixels(sensor_b) na = len(list(filter(lambda x: (x - m_ta) >= MIN_TEMP_DIFF, arr_ta))) nb = len(list(filter(lambda x: (x - m_tb) >= MIN_TEMP_DIFF, arr_tb))) if verbose: print(
eturn na, nb def dual_detect(arg_name, verbose=False): """ Llama a read_sensor_pixels una vez por cada sensor Devuelve el número de celdas ocupadas en cada sensor (mas los data_sens para log) Con verbose muestra paneles de detección """ m_ta, arr_ta = read_sensor_pixels(sensor_a) m_tb, ...
"\n") print ('[t1]:{0:.1f}\t[t2]:{1:.1f}'.format(m_tb, m_ta)) for ix in range(8): la = ''.join(['.' if (arr_ta[iy * 8 + ix] - m_ta) < MIN_TEMP_DIFF else '+' for iy in range(8)]) lb = ''.join(['.' if (arr_tb[iy * 8 + ix] - m_tb) < MIN_TEMP_DIFF else '+' for iy in range(8)]) ...
conditional_block
scout.py
) m_tb, arr_tb = read_sensor_pixels(sensor_b) na = len(list(filter(lambda x: (x - m_ta) >= MIN_TEMP_DIFF, arr_ta))) nb = len(list(filter(lambda x: (x - m_tb) >= MIN_TEMP_DIFF, arr_tb))) if verbose: print("\n") print ('[t1]:{0:.1f}\t[t2]:{1:.1f}'.format(m_tb, m_ta)) for ix in rang...
pend_results_to_img(cv2_im, results, labels): height, width, channels = cv2_im.shape for ii, res in enumerate(results): percent = int(100 * res.score) label = '{}% {}'.format(percent, labels[res[0]]) cv2_im = cv2.putText(cv2_im, label, (600, 20+ii*30), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0...
ns no more than top_k categories with score >= score_threshold.""" scores = cvtf.output_tensor(interpreter, 0) categories = [ Category(i, scores[i]) for i in np.argpartition(scores, -top_k)[-top_k:] if scores[i] >= score_threshold ] return sorted(categories, key=operator.itemgett...
identifier_body
mla_1c_v0.py
0.010741 #item_price 0.067416 -0.228345 1.000000 0.022186 #month_cnt 0.521578 -0.010741 0.022186 1.000000 # Transform it in a links data frame (3 columns only): links = C.stack().reset_index() links.columns =["var1","var2","corr_val"] # remove self correlation (cor(A,A)=1) links_filtered=links.l...
C=pd.merge(dataCtrl,dataCtrlHM,how="left",on=["date_block_num","item_id","shop_id"]) #target=dataCtrl["month_cnt"] #dataCtrl=dataCtrl.drop("month_cnt",axis=1) #predictions=poisson_fit.predict(exog=dataCtrl, transform=True)
random_line_split
mla_1c_v0.py
73820 0.067416 0.521578 #category_id -0.073820 1.000000 -0.228345 -0.010741 #item_price 0.067416 -0.228345 1.000000 0.022186 #month_cnt 0.521578 -0.010741 0.022186 1.000000 # Transform it in a links data frame (3 columns only): links = C.stack().reset_index() links.columns =["var1",...
# print("'%s' connects with '%s'" % (vertex,edge)) # Create positions of all nodes and save them #pos = nx.spring_layout(G) pos={"price": [1.5,1.5],"freq": [0.5,1.5],"count": [1,1]} labels ={('freq', 'price'): values[0], ('freq', 'count'): values[1], ('price', 'count'): values[2]} # Draw the graph acc...
G.add_node("%s" % vertex) # leng+=1 for edge in edges: G.add_node("%s" % edge) G.add_edge("%s" % vertex, "%s" % edge, weight = leng)
conditional_block
lib.rs
pub struct RequestHeader { pub method: Method, pub uri: Uri, pub version: Version, pub fields: HeaderMap, } #[derive(Debug)] pub struct ResponseHeader { pub status_code: StatusCode, pub fields: HeaderMap, } #[derive(Debug)] pub enum InvalidRequestHeader { Format, RequestLine(InvalidReq...
random_line_split
lib.rs
InvalidRequestHeader::Format); } line.truncate(line.len() - 2); if line == b"" { return Ok(RequestHeader { method, uri, version, fields }); } let (name, value) = parse_header_field(&line)?; // TODO: append is okay, right? No syntax issues because we haven't ...
{ let s = b"OPTIONS * HTTP/1.1"; let (m, u, v) = parse_request_line(s).unwrap(); assert_eq!(m, Method::OPTIONS); assert_eq!(u.path(), "*"); assert_eq!(v, Version::HTTP_11); let s = b"POST http://foo.example.com/bar?qux=19&qux=xyz HTTP/1.0"; let (m, u, v) = parse_...
identifier_body
lib.rs
pub fields: HeaderMap, } #[derive(Debug)] pub enum InvalidRequestHeader { Format, RequestLine(InvalidRequestLine), HeaderField(InvalidHeaderField), Io(io::Error), } impl From<InvalidRequestLine> for InvalidRequestHeader { fn from(e: InvalidRequestLine) -> Self { InvalidRequestHeader::Requ...
(e: InvalidHeaderField) -> Self { InvalidRequestHeader::HeaderField(e) } } impl From<io::Error> for InvalidRequestHeader { fn from(e: io::Error) -> Self { InvalidRequestHeader::Io(e) } } const LINE_CAP: usize = 16384; pub fn parse_request_header<B: BufRead>(mut stream: B) -> Result<Re...
from
identifier_name
api_export_tools.py
's xform :return True or False """ return bool(set(hxl_columns).intersection(set(dv_columns))) def _get_export_type(export_type): if export_type not in EXPORT_EXT or ( export_type == Export.GOOGLE_SHEETS_EXPORT and not getattr(settings, "GOOGLE_EXPORT", False) ): raise exc...
# get extension from file_path, exporter could modify to # xlsx if it exceeds limits _path, ext = os.path.splitext(export.filename) ext = ext[1:] show_date = True if filename is None and export.status == Export.SUCCESSFUL: filename = _generate_filename( request, xform, rem...
raise exceptions.ParseError(export.error_message)
conditional_block
api_export_tools.py
's xform :return True or False """ return bool(set(hxl_columns).intersection(set(dv_columns))) def _get_export_type(export_type): if export_type not in EXPORT_EXT or ( export_type == Export.GOOGLE_SHEETS_EXPORT and not getattr(settings, "GOOGLE_EXPORT", False) ): raise exc...
def _generate_filename(request, xform, remove_group_name=False, dataview_pk=False): if request.GET.get("raw"): filename = None else: # append group name removed flag otherwise use the form id_string if remove_group_name: filename = f"{xform.id_string}-{GROUPNAME_REMOVED_FL...
""" Redirects to export_url of XLSReports successful export. In case of a failure, returns a 400 HTTP JSON response with the error message. """ if isinstance(export, Export) and export.internal_status == Export.SUCCESSFUL: return HttpResponseRedirect(export.export_url) http_status = status.H...
identifier_body
api_export_tools.py
_columns))) def _get_export_type(export_type): if export_type not in EXPORT_EXT or ( export_type == Export.GOOGLE_SHEETS_EXPORT and not getattr(settings, "GOOGLE_EXPORT", False) ): raise exceptions.ParseError( _(f"'{export_type}' format not known or not implemented!") ...
elif export_type in [Export.CSV_ZIP_EXPORT, Export.SAV_ZIP_EXPORT]: extension = "zip" return extension
random_line_split
api_export_tools.py
iew's xform :return True or False """ return bool(set(hxl_columns).intersection(set(dv_columns))) def _get_export_type(export_type): if export_type not in EXPORT_EXT or ( export_type == Export.GOOGLE_SHEETS_EXPORT and not getattr(settings, "GOOGLE_EXPORT", False) ): raise ...
( # noqa: C0901 request, xform, query, export_type, dataview_pk=False, metadata=None ): query = _set_start_end_params(request, query) extension = _get_extension_from_export_type(export_type) options = { "extension": extension, "username": xform.user.username, "id_string": xform...
_generate_new_export
identifier_name
custom_widget.rs
the widget color depending on the current interaction. fn color(&self, color: Color) -> Color { match *self { /// The base color as defined in the Style struct, or a default provided /// by the current Theme if the Style has no color. Interaction::Nor...
// // Defaults can come from several places. Here, we define how certain defaults take // precedence over others. // // Most commonly, defaults are to be retrieved from the `Theme`, however in some cases // some other logic may need to be considere...
/// The default implementation is the same as below, but unwraps to an absolute scalar of /// `0.0` instead of `64.0`. fn default_x_dimension<C: CharacterCache>(&self, ui: &Ui<C>) -> Dimension { // If no width was given via the `Sizeable` (a trait implemented for all widgets) ...
random_line_split
custom_widget.rs
widget color depending on the current interaction. fn color(&self, color: Color) -> Color { match *self { /// The base color as defined in the Style struct, or a default provided /// by the current Theme if the Style has no color. Interaction::Normal ...
} // Here we check to see whether or not our button should capture the mouse. // // Widgets can "capture" user input. If the button captures the mouse, then mouse // events will only be seen by the button. Other widgets will not see mouse events ...
{ react(); }
conditional_block
custom_widget.rs
widget color depending on the current interaction. fn color(&self, color: Color) -> Color { match *self { /// The base color as defined in the Style struct, or a default provided /// by the current Theme if the Style has no color. Interaction::Normal ...
(&self) -> &CommonBuilder { &self.common } fn common_mut(&mut self) -> &mut CommonBuilder { &mut self.common } fn unique_kind(&self) -> &'static str { KIND } fn init_state(&self) -> State { State { interac...
common
identifier_name
handlers.go
"ASC" var queues []string var status []string if len(queuesStr) > 0 { queues = strings.Split(queuesStr, ",") } if len(statusStr) > 0 { status = strings.Split(statusStr, ",") } page, err := strconv.Atoi(c.QueryParam("page")) if err != nil { // if err, set default page = 0 } foundJobs, err := s.Stor...
DeactivateJobQueue
identifier_name
handlers.go
inish() c.QueryParams() search := c.QueryParam("q") queuesStr := c.QueryParam("queue") statusStr := c.QueryParam("status") column := c.QueryParam("sortColumn") sort := strings.ToUpper(c.QueryParam("sortDirection")) == "ASC" var queues []string var status []string if len(queuesStr) > 0 { queues = strings.Sp...
if err != nil { c.JSON(http.StatusInternalServerError, err) return err } for _, job_queue := range job_queues.JobQueues { name := job_queue.JobQueueName result = append(result, *name) } if input.NextToken != nil { next_token = input.NextToken } else { break } } c.JSON(http.StatusOK, ...
{ span := opentracing.StartSpan("API.ListAllJobQueues") defer span.Finish() // This function gets *all* job queues, even those not registered to // Batchiepatchie. Therefore, we must ask AWS about all the job // queues. (as opposed to looking in our data store). svc := awsclients.Batch result := make([]string,...
identifier_body
handlers.go
inish() c.QueryParams() search := c.QueryParam("q") queuesStr := c.QueryParam("queue") statusStr := c.QueryParam("status") column := c.QueryParam("sortColumn") sort := strings.ToUpper(c.QueryParam("sortDirection")) == "ASC" var queues []string var status []string if len(queuesStr) > 0 { queues = strings.Sp...
span := opentracing.StartSpan("API.ActivateJobQueue") defer span.Finish() job_queue_name := c.Param("name") err := s.Storage.ActivateJob
} func (s *Server) ActivateJobQueue(c echo.Context) error {
random_line_split
handlers.go
() c.QueryParams() search := c.QueryParam("q") queuesStr := c.QueryParam("queue") statusStr := c.QueryParam("status") column := c.QueryParam("sortColumn") sort := strings.ToUpper(c.QueryParam("sortDirection")) == "ASC" var queues []string var status []string if len(queuesStr) > 0 { queues = strings.Split(q...
c.JSON(http.StatusOK, task.ID) return nil } func (s *Server) ListActiveJobQueues(c echo.Context) error { span := opentracing.StartSpan("API.ListActiveJobQueues") defer span.Finish() active_job_queues, err := s.Storage.ListActiveJobQueues() if err != nil { log.Error(err) c.JSON(http.StatusInternalServerErr...
{ log.Error(err) c.JSON(http.StatusInternalServerError, err) return err }
conditional_block
wire.rs
: ToDname + ?Sized>( &mut self, name: &N, ) -> Result<(), Self::AppendError> { name.compose(self) } fn can_compress(&self) -> bool { false } } #[cfg(feature = "std")] impl Composer for std::vec::Vec<u8> {} impl<const N: usize> Composer for octseq::array::Array<N> {} #...
pl<'a, Octs: AsRef<[u8]> + ?Sized> Parse<'a, Octs> for i32 { fn parse(parser: &mut Parser<'a, Octs>) -> Result<Self, ParseError> { parser.parse_i32_be().map_err(Into::into) } } impl<'a, Octs: AsRef<[u8]> + ?Sized> Parse<'a, Octs> for u32 { fn parse(parser: &mut Parser<'a, Octs>) -> Result<Self, Par...
parser.parse_u16_be().map_err(Into::into) } } im
identifier_body
wire.rs
, ) -> Result<(), Target::AppendError>; } impl<'a, T: Compose + ?Sized> Compose for &'a T { const COMPOSE_LEN: u16 = T::COMPOSE_LEN; fn compose<Target: OctetsBuilder + ?Sized>( &self, target: &mut Target, ) -> Result<(), Target::AppendError> { (*self).compose(target) } } i...
impl From<FormError> for ParseError { fn from(err: FormError) -> Self { ParseError::Form(err)
random_line_split
wire.rs
: ToDname + ?Sized>( &mut self, name: &N, ) -> Result<(), Self::AppendError> { name.compose(self) } fn ca
self) -> bool { false } } #[cfg(feature = "std")] impl Composer for std::vec::Vec<u8> {} impl<const N: usize> Composer for octseq::array::Array<N> {} #[cfg(feature = "bytes")] impl Composer for bytes::BytesMut {} #[cfg(feature = "smallvec")] impl<A: smallvec::Array<Item = u8>> Composer for smallvec::Sma...
n_compress(&
identifier_name
add_manifest_deployitem.go
) *cobra.Command { opts := &addManifestDeployItemOptions{} cmd := &cobra.Command{ Use: addManifestDeployItemUse, Example: addManifestDeployItemExample, Short: addManifestDeployItemShort, Args: cobra.ExactArgs(1), Run: func(cmd *cobra.Command, args []string) { if err := opts.Complete(args); err ...
replaceParamsByUUIDs
identifier_name
add_manifest_deployitem.go
cli/pkg/logger" "github.com/gardener/landscapercli/pkg/util" ) const addManifestDeployItemUse = `deployitem \ [deployitem name] \ ` const addManifestDeployItemExample = ` landscaper-cli component add manifest deployitem \ nginx \ --component-directory ~/myComponent \ --manifest-file ./deployment.yaml \ ...
return err } if fileInfo.IsDir() { return fmt.Errorf("manifest file %s is a directory", path) } } err := o.checkIfDeployItemNotAlreadyAdded() if err != nil { return err } return nil } func (o *addManifestDeployItemOptions) run(ctx context.Context, log logr.Logger) error { err := o.createExecutio...
{ if !identityKeyValidationRegexp.Match([]byte(o.deployItemName)) { return fmt.Errorf("the deploy item name must consist of lower case alphanumeric characters, '-', '_' " + "or '+', and must start and end with an alphanumeric character") } if o.clusterParam == "" { return fmt.Errorf("cluster-param is missing...
identifier_body
add_manifest_deployitem.go
Example = ` landscaper-cli component add manifest deployitem \ nginx \ --component-directory ~/myComponent \ --manifest-file ./deployment.yaml \ --manifest-file ./service.yaml \ --import-param replicas:integer --cluster-param target-cluster ` const addManifestDeployItemShort = ` Command to add a deploy ite...
func (o *addManifestDeployItemOptions) readManifests() ([]managedresource.Manifest, error) { manifests := []managedresource.Manifest{} if o.files == nil {
random_line_split
add_manifest_deployitem.go
cli/pkg/logger" "github.com/gardener/landscapercli/pkg/util" ) const addManifestDeployItemUse = `deployitem \ [deployitem name] \ ` const addManifestDeployItemExample = ` landscaper-cli component add manifest deployitem \ nginx \ --component-directory ~/myComponent \ --manifest-file ./deployment.yaml \ ...
err := o.checkIfDeployItemNotAlreadyAdded() if err != nil { return err } return nil } func (o *addManifestDeployItemOptions) run(ctx context.Context, log logr.Logger) error { err := o.createExecutionFile() if err != nil { return err } blueprintPath := util.BlueprintDirectoryPath(o.componentPath) bluep...
{ fileInfo, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { return fmt.Errorf("manifest file %s does not exist", path) } return err } if fileInfo.IsDir() { return fmt.Errorf("manifest file %s is a directory", path) } }
conditional_block
WBSTree.js
NodeSelectForCopy:function(obj){}, oncreateCopyTask:function(obj){}, //cuando se crea una tarea usando copiar, @param obj es la tarea resultado de la copia onNodeSelectForCut:function(obj){}, onNodePaste:function(obj){}, onNodeCut:function(obj){}, onCancelClipoard:function(obj){}, onNoderequ...
this.algorithm ='basicWilliam'; return true; break; case 'ecotree': this.LayoutAlgoritm= new ECOTree(this); this.algorithm ='ecotree'; return true; break; } } } //---------------------------------------------------------------------------------------------------------------------------------------...
switch(algoritmo){ case 'basicWilliam': this.LayoutAlgoritm=new LayoutWilliam(this);
random_line_split
request.rs
: &'b Bucket, path: &'b str, command: Command<'b>) -> Request<'b> { Request { bucket, path, command, datetime: Utc::now(), async: false, } } fn url(&self) -> Url { let mut url_str = match self.command { Command::Get...
} fn string_to_sign(&self, request: &str) -> String { signing::string_to_sign(&self.datetime, &self.bucket.region(), request) } fn signing_key(&self) -> S3Result<Vec<u8>> { Ok(signing::signing_key( &self.datetime, &self.bucket.secret_key(), &self.buc...
self.command.http_verb().as_str(), &self.url(), headers, &self.sha256(), )
random_line_split
request.rs
: &'b Bucket, path: &'b str, command: Command<'b>) -> Request<'b> { Request { bucket, path, command, datetime: Utc::now(), async: false, } } fn url(&self) -> Url { let mut url_str = match self.command { Command::Get...
(&self) -> S3Result<(Vec<u8>, u16)> { let response_data = self.response_data_future().then(|result| match result { Ok((response_data, status_code)) => Ok((response_data, status_code)), Err(e) => Err(e), }); let mut runtime = Runtime::new().unwrap(); runtime.block_...
response_data
identifier_name
request.rs
: &'b Bucket, path: &'b str, command: Command<'b>) -> Request<'b> { Request { bucket, path, command, datetime: Utc::now(), async: false, } } fn url(&self) -> Url { let mut url_str = match self.command { Command::Get...
fn authorization(&self, headers: &HeaderMap) -> S3Result<String> { let canonical_request = self.canonical_request(headers); let string_to_sign = self.string_to_sign(&canonical_request); let mut hmac = signing::HmacSha256::new_varkey(&self.signing_key()?)?; hmac.input(string_to_sign...
{ Ok(signing::signing_key( &self.datetime, &self.bucket.secret_key(), &self.bucket.region(), "s3", )?) }
identifier_body
__init__.py
predict_des.strip().replace("-", "") return predict_des return predict_des # def detect_texts(img_path, ocr): # """Detects text in the file.""" # result = ocr.ocr(img_path, det=False, rec=True, cls=False) # for line in result: # # print(line[0]) # if line[1] > 0.7: # ...
def generate_subtitles( source_path, output=None, dst_language=DEFAULT_DST_LANGUAGE, debug=False, cloud=False, disable_time=False, min_height=80, max_height=100, l_v=240 ): """ Given an input audio/video file, generate subtitles in t...
"""Translates text into the target language. Target must be an ISO 639-1 language code. See https://g.co/cloud/translate/v2/translate-reference#supported_languages """ return text
identifier_body
__init__.py
(content): """Detects text in the file.""" image = vision.Image(content=content) response = client.text_detection(image=image, image_context={"language_hints": ["zh"]}) texts = response.text_annotations predict_des = "" for text in texts: predict_des = text.description predict_de...
detect_texts_google_cloud
identifier_name
__init__.py
utf-8") # Text can also be a sequence of strings, in which case this method # will return a sequence of results for each text. result = translate_client.translate(text, target_language=target) result = html.unescape(result["translatedText"]) # print(u"Text: {}".format(result["input"])) print("T...
random_line_split
__init__.py
use_angle_cls=True, rec_char_type='ch', drop_score=0.8, det_db_box_thresh=0.3, cls=True) cap = cv2.VideoCapture(source_path) # cap.set(3, 1280) # cap.set(4, 720) # cv2.createTrackbar("L - V", "Trackbars", 0...
"List of formats:") for subtitle_format in FORMATTERS: print("{format}".format(format=subtitle_format)) return 0
conditional_block
socketclient.go
nil } func (c *Client) disconnect() error { log.Debugf("Closing socket") // cleanup msg table c.setMsgTable(make(map[string]uint16), 0) if err := c.conn.Close(); err != nil { log.Debugln("Closing socket failed:", err) return err } return nil } const ( sockCreateMsgId = 15 // hard-coded sockclnt_create ...
{ n, err := io.ReadAtLeast(r, header, 16) if err != nil { return 0, err } if n == 0 { log.Debugln("zero bytes header") return 0, nil } else if n != 16 { log.Debugf("invalid header (%d bytes): % 0X", n, header[:n]) return 0, fmt.Errorf("invalid header (expected 16 bytes, got %d)", n) } dataLen := binar...
identifier_body
socketclient.go
// SetClientName sets a client name used for identification. func (c *Client) SetClientName(name string) { c.clientName = name } // SetConnectTimeout sets timeout used during connecting. func (c *Client) SetConnectTimeout(t time.Duration) { c.connectTimeout = t } // SetDisconnectTimeout sets timeout used during dis...
func (c *Client) open() error { var msgCodec = codec.DefaultCodec // Request socket client create req := &memclnt.SockclntCreate{ Name: c.clientName, } msg, err := msgCodec.EncodeMsg(req, sockCreateMsgId) if err != nil { log.Debugln("Encode error:", err) return err } // set non-0 context msg[5] = crea...
)
random_line_split
socketclient.go
(logger logrus.FieldLogger) { log = logger } func init() { logger := logrus.New() if debug { logger.Level = logrus.DebugLevel logger.Debug("govpp: debug level enabled for socketclient") } log = logger.WithField("logger", "govpp/socketclient") } type Client struct { socketPath string clientName string con...
SetLogger
identifier_name
socketclient.go
// SetClientName sets a client name used for identification. func (c *Client) SetClientName(name string) { c.clientName = name } // SetConnectTimeout sets timeout used during connecting. func (c *Client) SetConnectTimeout(t time.Duration) { c.connectTimeout = t } // SetDisconnectTimeout sets timeout used during dis...
log.Debugf("SockclntCreateReply: Response=%v Index=%v Count=%v", reply.Response, reply.Index, reply.Count) c.clientIndex = reply.Index msgTable := make(map[string]uint16, reply.Count) var sockDelMsgId uint16 for _, x := range reply.MessageTable { msgName := strings.Split(x.Name, "\x00")[0] name := strings...
{ return fmt.Errorf("sockclnt_create_reply: response error (%d)", reply.Response) }
conditional_block
tx.go
(now time.Time) { tx.now = now } // CreateMappers will create a set of mappers that need to be run to execute the map phase of a MapReduceJob. func (tx *tx) CreateMapReduceJobs(stmt *influxql.SelectStatement, tagKeys []string) ([]*influxql.MapReduceJob, error) { jobs := []*influxql.MapReduceJob{} for _, src := range...
SetNow
identifier_name
tx.go
MRJob this mapper belongs to mapFunc influxql.MapFunc // the map func fieldID uint8 // the field ID associated with the mapFunc curently being run fieldName string // the field name associated with the mapFunc currently being run keyBuffer []in...
} } // return if there is no more data in this group by interval
random_line_split
tx.go
// SetNow sets the current time for the transaction. func (tx *tx) SetNow(now time.Time) { tx.now = now } // CreateMappers will create a set of mappers that need to be run to execute the map phase of a MapReduceJob. func (tx *tx) CreateMapReduceJobs(stmt *influxql.SelectStatement, tagKeys []string) ([]*influxql.MapR...
{ return &tx{ meta: meta, store: store, now: time.Now(), } }
identifier_body
tx.go
if !m.HasTagKey(n) { return nil, fmt.Errorf("unknown field or tag name in select clause: %s", n) } selectTags = append(selectTags, n) tagKeys = append(tagKeys, n) } for _, n := range stmt.NamesInWhere() { if n == "time" { continue } if m.HasField(n) { whereFields = append(whereFiel...
{ selectFields = append(selectFields, n) continue }
conditional_block
testing.py
bslash", "|": "pipe", "?": "qmark", "*": "asterisk", } def _response_to_json(resp: Response, ip_dict: Dict[str, int]) -> str: """Converts a Response object into json string readable by the responses mocking library Args: resp: Response from a Tamr API call ip_dict: Mapping of previ...
response_log_path: Location of saved API responses test_function: The function to test **kwargs: Keyword arguments for the test function """ with response_log_path.open(encoding="utf-8") as f: for line in f: response = json.loads(line) ...
random_line_split
testing.py
lash", "|": "pipe", "?": "qmark", "*": "asterisk", } def _response_to_json(resp: Response, ip_dict: Dict[str, int]) -> str: """Converts a Response object into json string readable by the responses mocking library Args: resp: Response from a Tamr API call ip_dict: Mapping of previou...
) if response_log_path.exists() and enforce_online_test: # Delete the file to enforce an online test response_log_path.unlink() if response_log_path.exists(): try: LOGGER.info(f"Running offline test based on file a...
"""Decorator for `pytest` tests that mocks API requests by reading a file of pre-generated responses. Will generate responses file based on a real connection if pre-generated responses are not found. Args: response_logs_dir: Directory to read/write response logs enforce_online_test: Whether...
identifier_body
testing.py
lash", "|": "pipe", "?": "qmark", "*": "asterisk", } def _response_to_json(resp: Response, ip_dict: Dict[str, int]) -> str: """Converts a Response object into json string readable by the responses mocking library Args: resp: Response from a Tamr API call ip_dict: Mapping of previou...
(**kwargs): response_log_path = _build_response_log_path( test_func=test_function, response_logs_dir=response_logs_dir, **kwargs, ) if response_log_path.exists() and enforce_online_test: # Delete the file to enforce an online test res...
wrapped
identifier_name
testing.py
lash", "|": "pipe", "?": "qmark", "*": "asterisk", } def _response_to_json(resp: Response, ip_dict: Dict[str, int]) -> str: """Converts a Response object into json string readable by the responses mocking library Args: resp: Response from a Tamr API call ip_dict: Mapping of previou...
ip_lookup = {} def _find_anonymized_match(self, request): """Allows responses library to match requests for an ip address to match to an anonymized ip address """ request.url = _anonymize_url(request.url, ip_lookup) return _BASE_FIND_MATCH(s...
response = json.loads(line) responses.add(**response)
conditional_block
current_models.py
6)) minf = alpha_m/(alpha_m + beta_m) mtau = 1/(alpha_m + beta_m) alpha_h = 0.011 + 1.39/(1 + np.exp((v+78.04)/11.32)) beta_h = 0.56 - 0.56/(1 + np.exp((v-21.82)/20.03)) hinf = alpha_h/(alpha_h + beta_h) htau = 1/(alpha_h + beta_h) dm = (minf-m)/mtau dh = (hinf-h)/htau retur...
h = Y[1] v = voltage_clamp_func(t,voltage_clamp_params) vhalf = -43.0 a_m = 0.182*(v-vhalf)/(1-np.exp((vhalf-v)/6.)) b_m = 0.124*(-v+vhalf)/(1-np.exp((-vhalf+v)/6.)) m_inf = a_m/(a_m + b_m) m_tau = 1./(a_m + b_m) vhalf_ha = -50.0 vhalf_hb = -75.0 q_h = 5.0 ...
random_line_split
current_models.py
376/(1 + np.exp(-(v+60.92)/15.79)) sinf = alpha_s/(alpha_s + beta_s) stau = 1/(alpha_s + beta_s) dm = (minf-m)/mtau dh = (hinf-h)/htau ds = (sinf-s)/stau return [dm, dh, ds] def nav19md(Y,t,voltage_clamp_func,voltage_clamp_params): " Nav 1.9 model from Maingret 2008" m...
can_mi
identifier_name
current_models.py
np.exp((v+46.463)/8.8289)) minf = alpha_m/(alpha_m + beta_m) mtau = 1/(alpha_m + beta_m) hinf = 1/(1+np.exp((v+32.2)/4)) htau = 1.218 + 42.043*np.exp(-((v+38.1)**2)/(2*15.19**2)) alpha_s = 0.001 * 5.4203 / (1 + np.exp((v+79.816)/16.269)) beta_s = 0.001 * 5.0757 / (1 + np.exp(-(v+15.968)/11....
""" Tigerholm version of the IM current. Current is from multiple sources: The voltage dependence of steady-state activation forthe KM current is from Maingret et al. (2008), which was derived from Passmore 2003. The KM channel activation has a fast and a slow time constant as described by Passmore et al. ...
identifier_body
current_models.py
_params) n = Y[0] q10 = 1.0#3.3 # Preserved in case it is useful but disabled if v > -31.0: tau = 0.16+0.8*np.exp(-0.0267*(v+11)) else: tau = 1000*(0.000688 + 1/(np.exp((v+75.2)/6.5) + np.exp(-(v-131.5)/(34.8)))) ninf = 1/(1 + np.exp(-(v+45)/15.4)) ntau = tau/q10 ...
tau_ns = 2500.0 + 100.0 * np.exp((v+240.0)/50.0) tau_nf = 250.0 + 12.0 * np.exp((v+240.0)/50.0)
conditional_block
keyword_plan.pb.go
func (m *KeywordPlan) XXX_DiscardUnknown() { xxx_messageInfo_KeywordPlan.DiscardUnknown(m) } var xxx_messageInfo_KeywordPlan proto.InternalMessageInfo func (m *KeywordPlan) GetResourceName() string { if m != nil { return m.ResourceName } return "" } func (m *KeywordPlan) GetId() *wrappers.Int64V...
{ return xxx_messageInfo_KeywordPlan.Size(m) }
identifier_body