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
main.rs
::convert::TryInto; use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use std::str; use uuid::Uuid; static mut USER_TOKEN: Vec<(String, String)> = Vec::new(); static mut USER_CHALLENGE: Vec<(String, u64)> = Vec::new(); #[derive(Debug)] struct User { username: String, salt: Salt, passw...
oad, req: HttpRequest) -> HttpResponse { // lire et vérifier le Token if !check_token(&req) { return HttpResponse::NonAuthoritativeInformation().finish(); } // lire le body let mut bytes = web::BytesMut::new(); while let Some(item) = body.next().await { let item = item.unwrap();...
::Payl
identifier_name
main.rs
OPSLIMIT_SENSITIVE, argon2id13::MEMLIMIT_SENSITIVE, ) .unwrap(); map.insert( "jerome", User { username: "jerome".to_string(), salt: salt, password_kdf: key, secret: auth.create_secret(32), ...
} } } return false;
conditional_block
main.rs
::convert::TryInto; use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use std::str; use uuid::Uuid; static mut USER_TOKEN: Vec<(String, String)> = Vec::new(); static mut USER_CHALLENGE: Vec<(String, u64)> = Vec::new(); #[derive(Debug)] struct User { username: String, salt: Salt, passw...
let mut contents = String::new(); current_file .read_to_string(&mut contents) .expect("Unable to read the file"); let meta: Metadata = serde_json::from_str(&contents).unwrap(); if meta.username.contains(&user_name.to_string()) { ...
r le Token if !check_token(&req) { return HttpResponse::NonAuthoritativeInformation().finish(); } let user_name: &str = req.headers().get("Username").unwrap().to_str().unwrap(); // préparation des clés pour AES-GCM et du nonce let key_aes = Key::from_slice(b"an example very very secret key....
identifier_body
4_orient_grasping.py
print "============ Generating plan 1" pose_target = Pose() pose_target.position.x = x pose_target.position.y = y pose_target.position.z = z pose_target.orientation.x = Ox pose_target.orientation.y = Oy pose_target.orientation.z = Oz pose_target.orientation.w = Ow move_group.set_pose_target(pose_tar...
def cartesian_path_planner(a,b,c): waypoints = [] wpose = move_group.get_current_pose().pose wpose.position.z += a # First move up (z) waypoints.append(copy.deepcopy (wpose)) wpose = move_group.get_current_pose().pose wpose.position.x += b # First move up (z) waypoints.append(copy.deepc...
if abs(angle_to_goal - theta) > 2*pi/180: speed.linear.x = 0.0 speed.angular.z = 0.3 if abs(angle_to_goal - theta) < 5*pi/180: # 0.5이내로 들어오면 속도를 매우 줄여서 목표점을 지나쳐버리는 일이 없도록함. speed.angular.z = 0.03 speed.linear.x = 0.0 else: ...
conditional_block
4_orient_grasping.py
_goal = atan2(inc_y,inc_x) if abs(angle_to_goal - theta) > 2*pi/180: speed.linear.x = 0.0 speed.angular.z = 0.3 if abs(angle_to_goal - theta) < 5*pi/180: # 0.5이내로 들어오면 속도를 매우 줄여서 목표점을 지나쳐버리는 일이 없도록함. speed.angular.z = 0.03 speed.linear....
#move_Joint(1.65163641729639 ,0.202937041530315 ,-1.05397766677144 ,-2.29055198297394 ,3.05995622779418 ,1.57079637373908) #move_Joint(1.63317874347654 ,-0.210429202660752 ,-1.10151162936461 ,-0.0669323613463442 ,-2.82134998229054 ,-2.93965974902066)
random_line_split
4_orient_grasping.py
print "============ Generating plan 1" pose_target = Pose() pose_target.position.x = x pose_target.position.y = y pose_target.position.z = z pose_target.orientation.x = Ox pose_target.orientation.y = Oy pose_target.orientation.z = Oz pose_target.orientation.w = Ow move_group.set_pose_target(pose_tar...
#move_Joint(1.38187901932325 ,0.594965748224829 ,-1.84587120888068 ,-0.259201159280024 ,1.87922844334536 ,-2.94403460825812) #move_Joint(1.49234992746732 ,0.505575183819339 ,-1.77749928330972 ,-0.242572378864612 ,2.19692733555951 ,-3.04571339173395) #move_Joint(1.5788...
"go more right..!" y_path_planner(0.2) rospy.sleep(2) print "right demo complete!, Go to home pose..!" move_Joint(1.57,-2.27,1.93,-1.19,-1.57,0) #home pose if __name__=='__main__': down_demo() up_demo() left_demo() right_demo() #move_Joint(1.57079632679490 ,-1.57079632679...
identifier_body
4_orient_grasping.py
print "============ Generating plan 1" pose_target = Pose() pose_target.position.x = x pose_target.position.y = y pose_target.position.z = z pose_target.orientation.x = Ox pose_target.orientation.y = Oy pose_target.orientation.z = Oz pose_target.orientation.w = Ow move_group.set_pose_target(pose_tar...
anner(-0.05) print "go down..!" z_path_planner(0.1) rospy.sleep(1) print "up demo complete!, Go to home pose..!" move_Joint(1.57,-2.27,1.93,-1.19,-1.57,0) #home pose def left_demo(): #move_Joint(1.57,-2.27,1.93,-1.19,1.57,0) #up pose move_Joint(1.57,-2.27,1.93,-1.19,3.14,0) #left pose...
path_pl
identifier_name
lib.register_lints.rs
comparison_chain::COMPARISON_CHAIN, copies::BRANCHES_SHARING_CODE, copies::IFS_SAME_COND, copies::IF_SAME_THEN_ELSE, copies::SAME_FUNCTIONS_IN_IF_CONDITION, copy_iterator::COPY_ITERATOR, create_dir::CREATE_DIR, dbg_macro::DBG_MACRO, default::DEFAULT_TRAIT_ACCESS, default::FIELD_R...
collapsible_if::COLLAPSIBLE_ELSE_IF, collapsible_if::COLLAPSIBLE_IF, collapsible_match::COLLAPSIBLE_MATCH,
random_line_split
tracesegment.go
indicates that the type of the `cause` // field is an object CauseTypeObject ) // Segment schema is documented in xray-segmentdocument-schema-v1.0.0 listed // on https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html type Segment struct { // Required fields for both segment and subsegments...
(data []byte) error { err := json.Unmarshal(data, &c.CauseObject) if err == nil { c.Type = CauseTypeObject return nil } rawStr := string(data) if len(rawStr) > 0 && (rawStr[0] != '"' || rawStr[len(rawStr)-1] != '"') { return fmt.Errorf("the value assigned to the `cause` field does not appear to be a string: ...
UnmarshalJSON
identifier_name
tracesegment.go
indicates that the type of the `cause` // field is an object CauseTypeObject ) // Segment schema is documented in xray-segmentdocument-schema-v1.0.0 listed // on https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html type Segment struct { // Required fields for both segment and subsegments...
// it's ok for embedded subsegments to not have trace_id // but the root segment and independent subsegments must all // have trace_id. if s.TraceID == nil { return errors.New(`segment "trace_id" can not be nil`) } return nil } // AWSData represents the aws resource that this segment // originates from type...
{ return errors.New(`segment "start_time" can not be nil`) }
conditional_block
tracesegment.go
indicates that the type of the `cause` // field is an object CauseTypeObject ) // Segment schema is documented in xray-segmentdocument-schema-v1.0.0 listed // on https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html type Segment struct { // Required fields for both segment and subsegments...
} // BeanstalkMetadata represents the Elastic Beanstalk environment metadata field type BeanstalkMetadata struct { Environment *string `json:"environment_name"` VersionLabel *string `json:"version_label"` DeploymentID *int64 `json:"deployment_id"` } // EKSMetadata represents the EKS metadata field type EKSMetada...
random_line_split
tracesegment.go
indicates that the type of the `cause` // field is an object CauseTypeObject ) // Segment schema is documented in xray-segmentdocument-schema-v1.0.0 listed // on https://docs.aws.amazon.com/xray/latest/devguide/xray-api-segmentdocuments.html type Segment struct { // Required fields for both segment and subsegments...
// Exception represents an exception occurred type Exception struct { ID *string `json:"id,omitempty"` Message *string `json:"message,omitempty"` Type *string `json:"type,omitempty"` Remote *bool `json:"remote,omitempty"` Truncated *int64 `json:"truncated,omitempty"` ...
{ err := json.Unmarshal(data, &c.CauseObject) if err == nil { c.Type = CauseTypeObject return nil } rawStr := string(data) if len(rawStr) > 0 && (rawStr[0] != '"' || rawStr[len(rawStr)-1] != '"') { return fmt.Errorf("the value assigned to the `cause` field does not appear to be a string: %v", data) } excep...
identifier_body
gateway.go
statusUpdater k8s.StatusUpdater log logrus.FieldLogger // gatewayClassControllerName is the configured controller of managed gatewayclasses. gatewayClassControllerName gatewayapi_v1beta1.GatewayController eventSource chan event.GenericEvent } // RegisterGatewayController creates the gatew...
{ if gw == oldest { continue } if r.statusUpdater != nil { r.statusUpdater.Send(k8s.StatusUpdate{ NamespacedName: k8s.NamespacedNameOf(gw), Resource: &gatewayapi_v1beta1.Gateway{}, Mutator: k8s.StatusMutatorFunc(func(obj client.Object) client.Object { gw, ok := obj.(*gatewayapi_v1bet...
conditional_block
gateway.go
" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" gatewayapi_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" ) type gatewayReconciler struct { client client.Client eventHa...
(obj client.Object) bool { log := r.log.WithFields(logrus.Fields{ "namespace": obj.GetNamespace(), "name": obj.GetName(), }) gw, ok := obj.(*gatewayapi_v1beta1.Gateway) if !ok { log.Debugf("unexpected object type %T, bypassing reconciliation.", obj) return false } gc := &gatewayapi_v1beta1.GatewayC...
hasMatchingController
identifier_name
gateway.go
ClassControllerName), // Set up a source.Channel that will trigger reconciles // for all GatewayClasses when this Contour process is // elected leader, to ensure that their statuses are up // to date. eventSource: make(chan event.GenericEvent), } c, err := controller.NewUnmanaged("gateway-controller", mgr, ...
func isAccepted(gatewayClass *gatewayapi_v1beta1.GatewayClass) bool { for _, cond := range gatewayClass.Status.Conditions {
random_line_split
gateway.go
" "sigs.k8s.io/controller-runtime/pkg/manager" "sigs.k8s.io/controller-runtime/pkg/predicate" "sigs.k8s.io/controller-runtime/pkg/reconcile" "sigs.k8s.io/controller-runtime/pkg/source" gatewayapi_v1beta1 "sigs.k8s.io/gateway-api/apis/v1beta1" ) type gatewayReconciler struct { client client.Client eventHa...
if err := c.Watch( source.Kind(mgr.GetCache(), &gatewayapi_v1beta1.Gateway{}), &handler.EnqueueRequestForObject{}, predicate.NewPredicateFuncs(r.hasMatchingController), ); err != nil { return nil, err } // Watch GatewayClasses and reconcile their associated Gateways // to handle changes in the GatewayCla...
{ r := &gatewayReconciler{ log: log, client: mgr.GetClient(), eventHandler: eventHandler, statusUpdater: statusUpdater, gatewayClassControllerName: gatewayapi_v1beta1.GatewayController(gatewayClassControllerName), // Set up a source.Chan...
identifier_body
FieldClassifierAndKeywords.py
', "input.txt"] pos_file = open("output.txt", 'w') p = subprocess.Popen(command, stdout=pos_file, shell=False) p.wait() ##s就是pos后的question pos_file.close() f = codecs.open("output.txt","r") s = f.readline().strip() Keywords = self.extract(s) #KeywordsW...
while True: s = f.readline() if len(s) ==0: break else: s= s.strip("\r\n") stopWord[s] = 1 for word in question.split(): sep = word.split('#') word = sep[0].decode("utf-8") tag = sep[1] ...
if tag[0] == 'N': keywords.add(word) return keywords def keywordWeight(self,question): keyword = [] f = codecs.open("chinese_stopwords.txt","r","utf-8") stopWord ={}
identifier_body
FieldClassifierAndKeywords.py
agger', "input.txt"] pos_file = open("output.txt", 'w') p = subprocess.Popen(command, stdout=pos_file, shell=False) p.wait() ##s就是pos后的question pos_file.close() f = codecs.open("output.txt","r") s = f.readline().strip() Keywords = self.extract(s) #Keyw...
else: wordSet[w] = [0, 0, 1, 0] elif type == "名词": for w in l1: c4 = c4 +1 if wordSet.has_key(w): wordSet[w][3] = wordSet[w][3] + 1 ...
random_line_split
FieldClassifierAndKeywords.py
', "input.txt"] pos_file = open("output.txt", 'w') p = subprocess.Popen(command, stdout=pos_file, shell=False) p.wait() ##s就是pos后的question pos_file.close() f = codecs.open("output.txt","r") s = f.readline().strip() Keywords = self.extract(s) #KeywordsW...
urn "loc" elif classifyArray[2] == max(classifyArray): return "time" elif classifyArray[3] == max(classifyArray): return "other" def extract(self,question): keywords = set() for word in question.split(): sep = word.split('#') word = se...
ion/4 for x in classifyArray] if classifyArray[0] == max(classifyArray): return "person" elif classifyArray[1] == max(classifyArray): ret
conditional_block
FieldClassifierAndKeywords.py
: def __init__(self): words = jieba.cut("我是谁", cut_all=False) def FieldClassifierAndKeywords(self,question): ##读入问题,调用分词工具分词,同时去除标点符号 delset = string.punctuation question = question.translate(None, delset) questionTag = self.typeClassify(question) f = open("input.t...
FieldClassifierAndKeywords
identifier_name
index.js
+"\" ,\"nick_name\":\""+nickname+"\" ,\"im_sign\":\""+resapp.data.im_sig+"\" ,\"user_icon_url\":\""+bbs_icon+"\" ,\"txy_sign\":\""+resapp.data.file_sig+"\" ,\"im_identifier\":\""+resapp.data.im_id+"\"}"); }); this.getlist(); window.scrollTo(0,0); } componentWillUnmou
entStatus = false; document.removeEventListener('scroll',this.scroll); } appzhibocallback=()=>{ this.page = 1; this.getlist(); } getlist=()=>{ this.page==1 ? this.setState({ "liststatus" : "pending" ,"list" : [] }) : this.setState({ "liststatus" : "pending" }); setTimeout(()=>{ if(this.dataty...
nt(){ this.compon
identifier_name
index.js
mobile+"\" ,\"nick_name\":\""+nickname+"\" ,\"im_sign\":\""+resapp.data.im_sig+"\" ,\"user_icon_url\":\""+bbs_icon+"\" ,\"txy_sign\":\""+resapp.data.file_sig+"\" ,\"im_identifier\":\""+resapp.data.im_id+"\"}"); }); this.getlist(); window.scrollTo(0,0); } componentWillUnmount(){ this.componentStatus = fa...
} },400); } scroll=( event)=>{ let scrolltop = document.documentElement.scrollTop || document.body.scrollTop; let el = ''; if(this.datatype==2){ el = document.querySelectorAll('ul.livelist li:last-child')[0]; } if(this.datatype==1){ el = document.querySelectorAll('.box2:last-child')[0];...
hPost('/hyb-stu/stu_talk/list',{ UserKey : this.props.userstate.userKey, token : this.token, body : JSON.stringify({ page : this.page ,size : 10 }) }).then(({res})=>{ this.total = res.data.total; if(this.page==1){ if(res.data.list.length){ this.componentStatus && this.s...
conditional_block
index.js
this.page = 1; this.create_time = ''; this.getlist(); } } actionzan=(event)=>{ const el = api.closest(event.target ,'span') ,el_i = el.querySelectorAll('i')[0] ,div = api.closest(event.target ,'div.box'); let praise_type = 0; if(el_i.classList.contains('on')){ praise_type = 1; } a...
userstate : state.UserState
random_line_split
manager.go
Len() int { return len(*q) } func (q *PriorityQueue) Less(i, j int) bool { return (*q)[i].NextExecutionTime.Before((*q)[j].NextExecutionTime) } func (q *PriorityQueue) Pop() interface{} { old := *q n := len(*q) item := (*q)[n-1] *q = old[0 : n-1] return item } func (q *PriorityQueue) Push(x interface{}) { *...
{ log4go.Warn("unknown task source :%v", task.Source) continue }
conditional_block
manager.go
click"` Reach int `gorm:"column:reach"` ClickRate float32 `gorm:"column:click_rate"` Retry int `gorm:"-"` RetryInterval int `gorm:"-"` Timeout int `gorm:"-"` Handler TaskHandler `gorm:"-" json:"-"` Context interface{} `gorm:"-"` } type TaskLog struct { TaskId int Status int Start tim...
(x interface{}) { *q = append(*q, x.(*Task)) } func (taskManager *TaskManager) RegisterTaskSourceHandler(source TaskSource, handler TaskHandler) { taskManager.handlers[source] = handler } func (taskManager *TaskManager) internalRemoveTask(task *Task) error { var ok bool key := TaskKey{ Source: task.Source, Ui...
Push
identifier_name
manager.go
([]*Task, 0) for len(taskManager.PendingQueue.inner) > 0 { next := taskManager.PendingQueue.inner[0].NextExecutionTime if next.Before(deadline) || next.Equal(deadline) { p := heap.Pop(&taskManager.PendingQueue.inner) ret = append(ret, p.(*Task)) } else { break } } return ret } func (*TaskManager)...
{ var err error if err = taskManager.wdb.Create(task).Error; err != nil { return err } log4go.Info("saved task %d to db", task.ID) return nil }
identifier_body
manager.go
type TaskKey struct { Source TaskSource Uid string } type Task struct { ID uint `gorm:"column:id;primary_key"` CreatedAt time.Time `gorm:"column:created_at"` UpdatedAt time.Time `gorm:"column:updated_at"` CanceledAt time.Time `gorm:"column:canceled_at"` UserIdentifier string `gorm:"co...
DoTask(identifier string, context interface{}) error Sync(uid string) (interface{}, error) }
random_line_split
retrieval_eval_bleu.py
" ) parser.add_argument("--name", type=str, help="Part of name of response output file") parser.add_argument("--no-cuda", action="store_true", help="Use CPU only") parser.add_argument( "--normalize-cands", action="store_true", help="Normalize encoded candidates" ) parser.add_argument( "--output-folder", type=st...
iwords = net_dictionary["iwords"] assert tensor.squeeze().dim() == 1, "Wrong tensor size!" return " ".join( iwords[i] for i in tensor.squeeze().cpu().numpy() if i != NET_PAD_IDX ).replace("@@ ", "") # Remove any BPE tokenization
identifier_body
retrieval_eval_bleu.py
parser.add_argument( "--model", "--pretrained", type=str, default=None, help="Path to model to use" ) parser.add_argument( "--n-candidates", type=int, default=int(1e6), help="Max number of candidates" ) parser.add_argument("--name", type=str, help="Part of name of response output file") parser.add_argument("--n...
)
random_line_split
retrieval_eval_bleu.py
default=int(1e6), help="Max number of candidates" ) parser.add_argument("--name", type=str, help="Part of name of response output file") parser.add_argument("--no-cuda", action="store_true", help="Use CPU only") parser.add_argument( "--normalize-cands", action="store_true", help="Normalize encoded candidates" ) pa...
def _has_lts(sentence_) -> bool: if "bert_tokenizer" in net_dictionary: tokens = net_dictionary["bert_tokenizer"].convert_ids_to_tokens( sentence_.tolist() ) return "& l ##t" in " ".join(tokens) else: return torch.sum(sentence_ == lt_...
all_sent = set()
conditional_block
retrieval_eval_bleu.py
default=int(1e6), help="Max number of candidates" ) parser.add_argument("--name", type=str, help="Part of name of response output file") parser.add_argument("--no-cuda", action="store_true", help="Use CPU only") parser.add_argument( "--normalize-cands", action="store_true", help="Normalize encoded candidates" ) pa...
(sentence_) -> bool: if "bert_tokenizer" in net_dictionary: if sentence_.size(0) < 3: return False else: return torch.eq(sentence_[:3], gt_tokens).all() else: return sentence_[0].item == gt_index parlai_dict = ParlAIDictionary.crea...
_starts_with_gt
identifier_name
debugger-script.js
return null; var location = generatorMirror.sourceLocation() || funcMirror.sourceLocation(); var script = funcMirror.script(); if (script && location) { return { scriptId: "" + script.id(), lineNumber: location.line, columnNumber: location.column }...
endLine += 1; endColumn = 0; } else { if (lineCount === 1) endColumn = script.source.length + script.column_offset; else endColumn = script.source.length - (lineEnds[lineCount - 2] + 1); } return { id: script.id, name: script.nameOrSour...
// V8 will not count last line if script source ends with \n. if (script.source[script.source.length - 1] === '\n') {
random_line_split
debugger-script.js
Script.stepIntoStatement = function(execState) { execState.prepareStep(Debug.StepAction.StepIn); } /** * @param {!ExecutionState} execState */ DebuggerScript.stepFrameStatement = function(execState) { execState.prepareStep(Debug.StepAction.StepFrame); } /** * @param {!ExecutionState} execState */ Debugger...
{ if (!location) { var script = ensureFuncMirror().script(); if (script) location = script.locationFromPosition(sourcePosition, true); if (!location) location = { line: 0, column: 0 }; } return location; }
identifier_body
debugger-script.js
(execState) { execState.prepareStep(Debug.StepAction.StepFrame); } /** * @param {!ExecutionState} execState */ DebuggerScript.stepOverStatement = function(execState) { execState.prepareStep(Debug.StepAction.StepNext); } /** * @param {!ExecutionState} execState */ DebuggerScript.stepOutOfFunction = functio...
column
identifier_name
main.rs
TreeViewColumn, Type, Window, WindowType}; use gtk::{BuilderExt, ButtonExt, CellLayoutExt, DialogExt, EntryExt, FileChooserExt, GtkWindowExt, ListStoreExt, ListStoreExtManual, TreeModelExt, TreeSelectionExt, TreeSortableExtManual, TreeViewColumnExt, TreeViewExt, WidgetExt}; #[derive(Debu...
( title: &str, window_type: gtk::WindowType, action: gtk::FileChooserAction, ) -> Option<PathBuf> { let dialog = FileChooserDialog::new(Some(title), Some(&Window::new(window_type)), action); dialog.add_button("_Cancel", gtk::ResponseType::Cancel.into()); match action { gtk::FileChooserA...
select_dir_dialog
identifier_name
main.rs
TreeViewColumn, Type, Window, WindowType}; use gtk::{BuilderExt, ButtonExt, CellLayoutExt, DialogExt, EntryExt, FileChooserExt, GtkWindowExt, ListStoreExt, ListStoreExtManual, TreeModelExt, TreeSelectionExt, TreeSortableExtManual, TreeViewColumnExt, TreeViewExt, WidgetExt}; #[derive(Debu...
let count_str = if selected_count == 0 || selected_count == store_len { "all".into() } else { format!("({})", selected_count) }; extract_button.set_label(&format!("Extract {}", count_str)) }); } fn select_dir_dialog( title: &str, window_type: gtk::Wi...
random_line_split
main.rs
TreeViewColumn, Type, Window, WindowType}; use gtk::{BuilderExt, ButtonExt, CellLayoutExt, DialogExt, EntryExt, FileChooserExt, GtkWindowExt, ListStoreExt, ListStoreExtManual, TreeModelExt, TreeSelectionExt, TreeSortableExtManual, TreeViewColumnExt, TreeViewExt, WidgetExt}; #[derive(Debu...
fn convert_size(s: String) -> u32 { let v = s.split(' ').collect::<Vec<&str>>(); let exp = match v.get(1) { Some(&"B") => 0, Some(&"KiB") => 1, Some(&"MiB") => 2, Some(&"GiB") => 3, _ => panic!("Unable to convert size: `{}`", s), ...
{ s }
identifier_body
block.rs
(&Data::from_bytes(test_bytes)); assert!(metrics::has_repeated_blocks(&output, block_size)); // Keep track of the suffix bytes that we have decrypted so far. let mut suffix = Vec::new(); // Decrypt the suffix one byte at a time. 'outer: loop { // Pad the known suffix with null bytes until...
craft_cbc_admin_token
identifier_name
block.rs
(&input); metrics::has_repeated_blocks(&encrypted, block_size) } /// Decrypt an unknown suffix encrypted under ECB mode. /// /// Given a black box which adds an unknown suffix to input data before encrypting under ECB mode /// with the given block size, determine the suffix. pub fn find_ecb_suffix(ecb_suffix_box: ...
test_block.push(byte as u8); let output = ecb_affixes_box.encrypt(&Data::from_bytes(test_block)); if &output.bytes()[output_start..output_start + block_size] == block { suffix.push(byte as u8); continue 'outer; } } } Data::...
let output_start = prefix_len + extra_padding; for byte in 0..256 { let mut test_block = vec![0; block_size - (prefix_len % block_size)]; test_block.extend_from_slice(partial_block);
random_line_split
block.rs
input); metrics::has_repeated_blocks(&encrypted, block_size) } /// Decrypt an unknown suffix encrypted under ECB mode. /// /// Given a black box which adds an unknown suffix to input data before encrypting under ECB mode /// with the given block size, determine the suffix. pub fn find_ecb_suffix(ecb_suffix_box: &E...
let output = ecb_suffix_box.encrypt(&Data::from_bytes(test_bytes)); assert!(metrics::has_repeated_blocks(&output, block_size)); // Keep track of the suffix bytes that we have decrypted so far. let mut suffix = Vec::new(); // Decrypt the suffix one byte at a time. 'outer: loop { // Pad...
{ // Determine the block size by repeatedly encrypting larger chunks of data until the output // jumps in length. let block_size; let base_len = ecb_suffix_box.encrypt(&Data::new()).len(); let mut cnt = 1; loop { let bytes = vec![0; cnt]; let input = Data::from_bytes(bytes); ...
identifier_body
block.rs
input); metrics::has_repeated_blocks(&encrypted, block_size) } /// Decrypt an unknown suffix encrypted under ECB mode. /// /// Given a black box which adds an unknown suffix to input data before encrypting under ECB mode /// with the given block size, determine the suffix. pub fn find_ecb_suffix(ecb_suffix_box: &E...
} } Data::from_bytes(suffix) } /// Find the length of an unknown prefix which is appended to ECB-encrypted messages. fn find_ecb_prefix_len(ecb_affixes_box: &EcbWithAffixes, block_size: usize) -> usize { // Find the block in which the prefix ends, by finding the first block which is different up...
{ suffix.push(byte as u8); continue 'outer; }
conditional_block
emoji-picker-qt.py
font.setPointSize(emojiFontSize) # quits without a lag def
(): mainWindow.hide() quit() # gets mouse position from Xlib def mousePosition(): pointerData = display.Display().screen().root.query_pointer()._data return pointerData["root_x"], pointerData["root_y"] # copies and pastes selected emoji def execute_emoji(char): add_char_to_history(char) global...
quitNicely
identifier_name
emoji-picker-qt.py
font.setPointSize(emojiFontSize) # quits without a lag def quitNicely(): mainWindow.hide() quit() # gets mouse position from Xlib def mousePosition(): pointerData = display.Display().screen().root.query_pointer()._data return pointerData["root_x"], pointerData["root_y"] # copies and pastes selected e...
# clear grid global emojiGridLayout for i in reversed(range(emojiGridLayout.count())): emojiGridLayout.itemAt(i).widget().setParent(None) # fill with new chars rowIdx = 0 colIdx = 0 for emoji in charList: if rowIdx>emojiGridRowCount-1: break; label =...
foundAnyEmoji = False layoutStack.setCurrentIndex(1)
conditional_block
emoji-picker-qt.py
font.setPointSize(emojiFontSize) # quits without a lag def quitNicely(): mainWindow.hide() quit() # gets mouse position from Xlib def mousePosition(): pointerData = display.Display().screen().root.query_pointer()._data return pointerData["root_x"], pointerData["root_y"] # copies and pastes selected e...
# handles what to do after hovering over a given label def emoji_hovered(hoveredLabel): parentGrid = hoveredLabel.parentWidget().layout() hoveredIndex = parentGrid.indexOf(hoveredLabel) hoveredRow, hoveredColumn, _, _ = parentGrid.getItemPosition(hoveredIndex) highlight_emoji([hoveredRow,hoveredColumn...
selectedEmoji = (0,0) if not text or text.isspace(): fill_grid_with_history() return foundEmoji = edp.find_by_name(text) charList = [emoji.char for emoji in foundEmoji] fill_grid_with_char_list(charList)
identifier_body
emoji-picker-qt.py
font.setPointSize(emojiFontSize) # quits without a lag def quitNicely(): mainWindow.hide() quit()
return pointerData["root_x"], pointerData["root_y"] # copies and pastes selected emoji def execute_emoji(char): add_char_to_history(char) global willExitOnItsOwn willExitOnItsOwn = True mainWindow.hide() QApplication.clipboard().setText(char) pyautogui.hotkey("ctrl","v") QtTest.QTest.qW...
# gets mouse position from Xlib def mousePosition(): pointerData = display.Display().screen().root.query_pointer()._data
random_line_split
qasync.py
by default `eos_marker` is passed through to output queue, but you can disable that. Calls `task_done()` method on input queue after result was copied to output queue. Assumption is that mapping function doesn't raise exceptions, instead it should return some sort of error object. ...
return xx wk_pool = ThreadPoolExecutor(max_workers=2) src = queue.Queue(3) dst = queue.Queue(3) # first do self test of consumer/producer N = 100 wk_pool.submit(run_producer, N, src, EOS_MARKER) xx = wk_pool.submit(run_consumer, src, EOS_MARKER) xx = xx.result() assert ...
x = q.get() q.task_done() xx.append(x) if x is eos_marker: break
conditional_block
qasync.py
by default `eos_marker` is passed through to output queue, but you can disable that. Calls `task_done()` method on input queue after result was copied to output queue. Assumption is that mapping function doesn't raise exceptions, instead it should return some sort of error object. ...
(func, N, nconcurrent): wk_pool.submit(run_producer, N, src, EOS_MARKER) xx = wk_pool.submit(run_consumer, dst, EOS_MARKER) await q2q_nmap(func, src, dst, nconcurrent, eos_passthrough=eos_passthrough) if eos_passthrough is False: dst.put(EOS_MARKER) ...
run_test
identifier_name
qasync.py
by default `eos_marker` is passed through to output queue, but you can disable that. Calls `task_done()` method on input queue after result was copied to output queue. Assumption is that mapping function doesn't raise exceptions, instead it should return some sort of error object. ...
loop = asyncio.new_event_loop() def run(N, nconcurrent, delay, eos_passthrough=True): async def run_test(func, N, nconcurrent): wk_pool.submit(run_producer, N, src, EOS_MARKER) xx = wk_pool.submit(run_consumer, dst, EOS_MARKER) await q2q_nmap(func, src, dst, nconcurr...
random_line_split
qasync.py
by default `eos_marker` is passed through to output queue, but you can disable that. Calls `task_done()` method on input queue after result was copied to output queue. Assumption is that mapping function doesn't raise exceptions, instead it should return some sort of error object. ...
while True: x = await src.get() if x is eos_marker: if eos_passthrough: await push_to_dst(x, dst, dt) src.task_done() break await push_to_dst(x, dst, dt) src.task_done() async def q2q_nmap(func, q_in, ...
while not safe_put(x, dst): await asyncio.sleep(dt)
identifier_body
prxlistcache.go
aleTime = 5 * time.Minute } listCache = newListObjectsCache(p) hk.Reg(hkListObjectName, func() time.Duration { return housekeepListCache(p) }, bucketPrefixStaleTime) } // TODO: Remove old entries, or those which take a lot of memory // until MemPressure/PctMemUsed falls below some level. func housekeepListCache(p ...
(cacheID string) (*locReq, bool) { c.mtx.Lock() req, ok := c.reqs[cacheID] c.mtx.Unlock() return req, ok } // Gathers init results for each target on `resultCh` func (c *listObjCache) initAllTargets(entries []*locTarget, smsg cmn.SelectMsg, size uint, newUUID string) (resultCh chan *locTargetResp) { resultCh = ma...
getRequestEntry
identifier_name
prxlistcache.go
smsg) } // fetchAll returns next `size` object names from each target. It include additional information // if all calls to targets succeeded and if there were any errors. It cache has buffered object names // it might return results without making any API calls. func (c *listObjCache) fetchAll(entries []*locTarget, s...
{ res := c.parent.parent.p.call(*args) return res.status, res.err }
identifier_body
prxlistcache.go
} entry, ok := tce[targetEntry.t.ID()] if !ok { entry = &locTarget{parent: targetEntry.parent, t: targetEntry.t, buff: make([]*cmn.BucketEntry, 0)} tce[targetEntry.t.ID()] = entry } // First case: the entire page was unused if !cmn.PageMarkerIncludesObject(smsg.PageMarker, targetEntry.buff[0].Name) { ...
// Target prepare the final result.
random_line_split
prxlistcache.go
.buff, targetEntry.buff...) targetEntry.mtx.Unlock() continue } // Seconds case: partially used page cond := func(i int) bool { return !cmn.PageMarkerIncludesObject(smsg.PageMarker, targetEntry.buff[i].Name) } idx := sort.Search(len(targetEntry.buff), cond) entry.buff = append(entry.buff, targetEntry.bu...
{ s = len(c.buff) }
conditional_block
lib.rs
{ /// The note column. /// /// - 0: Nothing. /// - 1 to 127 inclusive: A normal note. /// - 128+: See the `NOTECMD` constants. pub note: c_uchar, /// The velocity column (note velocity). /// /// - 0: Empty (default). /// - 1 to 129 inclusive: The specified velocity + 1. pu...
sunvox_note
identifier_name
lib.rs
/// A single note cell in a pattern. #[repr(C)] #[derive(Clone, Debug)] pub struct sunvox_note { /// The note column. /// /// - 0: Nothing. /// - 1 to 127 inclusive: A normal note. /// - 128+: See the `NOTECMD` constants. pub note: c_uchar, /// The velocity column (note velocity). ///...
random_line_split
beacon.py
(self, server, type_, name): # method is required, but can be ignored if you don't care about updates. We don't. if self.logger is not None: # ex. WARNING:pyTivo.beacon:ZCListener.update_service name='Movies._tivo-videos._tcp.local.' type_='_tivo-videos._tcp.local.' # WARNING...
""" Exchange beacons, and extract the machine name. """ our_beacon = self.format_beacon('connected', False)
random_line_split
beacon.py
n {address}:{port} {name}\n" log_fmt = log_hdr if debugging: log_level = logging.DEBUG if info.server != info.name: log_info['server'] = info.server log_fmt += " server: {server}\n" for (k, v) in info.properties.items(): ...
add = sock.recv(length - len(block)) if not add: break block += add
conditional_block
beacon.py
/ log level INFO, if the log level is DEBUG more the basic info plus more (all properties) is written w/ log level DEBUG. """ try: debugging = logger.isEnabledFor(logging.DEBUG) log_level = logging.INFO log_info = {'name': info.name, 'address': socket.inet_n...
start
identifier_name
beacon.py
data) return data def log_serviceinfo(logger, info): """ Write interesting attributes from a ServiceInfo to the log. Information written depends on the log level, basic info is written w/ log level INFO, if the log level is DEBUG more the basic info plus more (all properties) is written w/...
def format_beacon(self, conntype, services=True): beacon = ['tivoconnect=1', 'method=%s' % conntype, 'identity={%s}' % config.getGUID(), 'machine=%s' % socket.gethostname(), 'platform=%s' % self.platform] if services: ...
return ';'.join(self.services)
identifier_body
ctap.rs
romiumos/platform2/+/master/u2fd/u2fhid.cc static REPORT_DESCRIPTOR: &'static [u8] = &[ 0x06, 0xD0, 0xF1, // HID_UsagePage ( FIDO_USAGE_PAGE ), 0x09, 0x01, // HID_Usage ( FIDO_USAGE_CTAPHID ), 0xA1, 0x01, // HID_Collection ( HID_Application ), 0x09, 0x20, // HID_Usage ( FIDO_USAGE_DATA_IN ), 0x15, 0...
fn enable(&'a self) { // Set up the default control endpoint self.client_ctrl.enable(); // Setup buffers for IN and OUT data transfer. self.controller() .endpoint_set_out_buffer(ENDPOINT_NUM, &self.buffers[OUT_BUFFER].buf); self.controller() .endpoint...
} impl<'a, U: hil::usb::UsbController<'a>> hil::usb::Client<'a> for CtapHid<'a, U> {
random_line_split
ctap.rs
..InterfaceDescriptor::default() }]; let endpoints: &[&[EndpointDescriptor]] = &[&[ EndpointDescriptor { endpoint_address: EndpointAddress::new_const( ENDPOINT_NUM, TransferDirection::DeviceToHost, ), ...
{ // We can't receive data. Record that we have data to send later // and apply back pressure to USB self.saved_endpoint.set(endpoint); self.recv_buffer.replace(buf); ...
conditional_block
ctap.rs
os/platform2/+/master/u2fd/u2fhid.cc static REPORT_DESCRIPTOR: &'static [u8] = &[ 0x06, 0xD0, 0xF1, // HID_UsagePage ( FIDO_USAGE_PAGE ), 0x09, 0x01, // HID_Usage ( FIDO_USAGE_CTAPHID ), 0xA1, 0x01, // HID_Collection ( HID_Application ), 0x09, 0x20, // HID_Usage ( FIDO_USAGE_DATA_IN ), 0x15, 0x00, /...
} fn receive_cancel(&'a self) -> Result<&'static mut [u8; 64], ErrorCode> { self.saved_endpoint.take(); match self.recv_buffer.take() { Some(buf) => Ok(buf), None => Err(ErrorCode::BUSY), } } } impl<'a, U: hil::usb::UsbController<'a>> hil::usb::Client<'a> f...
{ self.recv_buffer.replace(recv); if self.saved_endpoint.is_some() { // We have saved data from before, let's pass it. if self.can_receive() { self.recv_buffer.take().map(|buf| { self.client.map(move |client| { client.p...
identifier_body
ctap.rs
x09, 0x01, // HID_Usage ( FIDO_USAGE_CTAPHID ), 0xA1, 0x01, // HID_Collection ( HID_Application ), 0x09, 0x20, // HID_Usage ( FIDO_USAGE_DATA_IN ), 0x15, 0x00, // HID_LogicalMin ( 0 ), 0x26, 0xFF, 0x00, // HID_LogicalMaxS ( 0xff ), 0x75, 0x08, // HID_ReportSize ( 8 ), 0x95, 0x40, // HID_ReportCo...
ctrl_status
identifier_name
oracle.py
_transformation_config["prediction_market_minute"] = self.scheduling.prediction_frequency.minutes_offset data_transformation_config["features_start_market_minute"] = self.scheduling.training_frequency.minutes_offset data_transformation_config["target_delta_ndays"] = int(self.scheduling.prediction_horizo...
def predict_classification(self, data, current_timestamp): """ Returns the raw pdf from the network. """ latest_train_file = self._train_file_manager.latest_train_filename(current_timestamp) predict_x, symbols, prediction_timestamp, target_timestamp = self._data_transformation.create_pre...
return TRAIN_FILE_NAME_TEMPLATE
identifier_body
oracle.py
_transformation_config["prediction_market_minute"] = self.scheduling.prediction_frequency.minutes_offset data_transformation_config["features_start_market_minute"] = self.scheduling.training_frequency.minutes_offset data_transformation_config["target_delta_ndays"] = int(self.scheduling.prediction_horizo...
logger.info('Initialised network topology: {}.'.format(self._topology.layers)) logger.info('Training features of shape: {}.'.format( train_x.shape, )) logger.info('Training labels of shape: {}.'.format( train_y.shape, )) resume_train_path = Non...
n_timesteps = train_x.shape[2] self.initialise_topology(n_timesteps)
conditional_block
oracle.py
def predict_classification(self, data, current_timestamp): """ Returns the raw pdf from the network. """ latest_train_file = self._train_file_manager.latest_train_filename(current_timestamp) predict_x, symbols, prediction_timestamp, target_timestamp = self._data_transformation.create_predi...
reorder_input_dimensions
identifier_name
oracle.py
self._topology = None def _init_train_file_manager(self): self._train_file_manager = TrainFileManager( self._train_path, TRAIN_FILE_NAME_TEMPLATE, DATETIME_FORMAT_COMPACT ) self._train_file_manager.ensure_path_exists() def _init_data_transfo...
self._n_forecasts = 1 else: self._n_input_series = self.config['n_series'] self._n_forecasts = self.config['n_forecasts']
random_line_split
context.ts
governing permissions and * limitations under the License. */ /// <reference path="../../../typings/globals/node/index.d.ts" /> import {action_set_state_data, action_set_state_user} from "./actions"; const GLOBAL_CONSTANTS = require('../../global/constants').GLOBAL_CONSTANTS; const LOGGING_ENABLED = require('../.....
return socketURL; } /** * this sets up the socket object for use by this context */ initSocket() { let io = require("socket.io-client"); this.socket = new io.connect(this.getSocketURL()); } /** * to access the socket for this context use this method ... you can emit() * using it...
{ socketURL = "/"; }
conditional_block
context.ts
language governing permissions and * limitations under the License. */ /// <reference path="../../../typings/globals/node/index.d.ts" /> import {action_set_state_data, action_set_state_user} from "./actions"; const GLOBAL_CONSTANTS = require('../../global/constants').GLOBAL_CONSTANTS; const LOGGING_ENABLED = requi...
() { try { return this.getReduxState().user; } catch (err) { return null; } } /** gets the uid field of the userObject */ getUserId() { try { return this.getUser().uid; } catch (err) { return null; } } /** * get a reference to the saved data object *...
getUser
identifier_name
context.ts
language governing permissions and * limitations under the License. */ /// <reference path="../../../typings/globals/node/index.d.ts" /> import {action_set_state_data, action_set_state_user} from "./actions"; const GLOBAL_CONSTANTS = require('../../global/constants').GLOBAL_CONSTANTS; const LOGGING_ENABLED = requi...
* @returns {string} */ getSocketURL() { let socketURL = "http://localhost:8080"; if (this.isProduction()) { socketURL = "/"; } return socketURL; } /** * this sets up the socket object for use by this context */ initSocket() { let io = require("socket.io-client"); thi...
* DEV - If it's running in localhost, then it understands this to be * the dev environment and it tries to connect to "localhost:8080". * PROD - If it's NOT running in localhost, then it understands this to be the * production environment and tries to connect to "/".
random_line_split
block.rs
size_of::<u32>(); coding::decode_fixed32(&data[offset..]) as usize } fn iter_slice<'a, T: SliceComparator>(&'a self, comparator: T, slice: Slice<'a>) -> BlockIterator<'a, T> { if self.get_size() < mem::size_of::<u32>() { BlockIterator::new(comparator, &[], 0, 0) ...
impl<'a> SliceBlock<'a> { fn get_size(&self) -> usize { self.data.len() } } struct DecodedEntry<'a> { new_slice: Slice<'a>, shared: u32, non_shared: u32, value_length: u32, } /// Helper routine: decode the next block entry starting at "p", /// storing the number of shared key bytes, non_shared key...
random_line_split
block.rs
_of::<u32>(); coding::decode_fixed32(&data[offset..]) as usize } fn iter_slice<'a, T: SliceComparator>(&'a self, comparator: T, slice: Slice<'a>) -> BlockIterator<'a, T> { if self.get_size() < mem::size_of::<u32>() { BlockIterator::new(comparator, &[], 0, 0) .wit...
fn get_restart_point(&self, index: usize) -> usize { assert!(index < self.num_restarts); let offset = self.restarts + index * mem::size_of::<u32>(); coding::decode_fixed32(&self.data[offset..]) as usize } pub fn seek_to_restart_point(&mut self, index: usize) { self...
{ self.value_offset + self.value_len }
identifier_body
block.rs
_of::<u32>(); coding::decode_fixed32(&data[offset..]) as usize } fn iter_slice<'a, T: SliceComparator>(&'a self, comparator: T, slice: Slice<'a>) -> BlockIterator<'a, T> { if self.get_size() < mem::size_of::<u32>() { BlockIterator::new(comparator, &[], 0, 0) .wit...
(&self, a: Slice, b: Slice) -> i32 { self.comparator.compare(a, b) } /// Return the offset in data_ just past the end of the current entry. fn next_entry_offset(&self) -> usize { self.value_offset + self.value_len } fn get_restart_point(&self, index: usize) -> usize { ...
compare
identifier_name
generator.rs
and saved /// for possible later use. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GeneratorArgs { /// magic_number helps to identify that the block was written /// by the app. magic_number: u64, /// process_id helps to differentiate this run from other runs process_id: u64, ///...
active_command_block_test
identifier_name
generator.rs
command_count: Arc<(Mutex<u64>, Condvar)>, } impl ActiveCommands { pub fn new() -> ActiveCommands { ActiveCommands { command_count: Arc::new((Mutex::new(0), Condvar::new())) } } /// Decrements number of active commands. Waits on the condition variable if /// command_count is zero. Returns ...
random_line_split
generator.rs
is zero. Returns true if command_count was zero and call /// was blocked. /// ``` /// let mut count = ActiveCommands::new(); /// /// Thread 1 /// command_count.remove(); /// cmd = receiver.try_recv(); /// assert_eq!(cmd.is_ok()); /// /// Thread 2 /// sender.send(cmd); //...
/// Based on the input args this returns a generator that can generate requested /// IO load.For now we only allow sequential io. fn pick_generator_type(args: &GeneratorArgs, target_id: u64) -> Box<dyn Generator> { if !args.sequential { panic!("Only sequential io generator is implemented at the moment"); ...
{ let mut operations: Vec<OperationType> = vec![]; if args.operations.write { operations.push(OperationType::Write); } else { assert!(false); } return operations; }
identifier_body
generator.rs
is zero. Returns true if command_count was zero and call /// was blocked. /// ``` /// let mut count = ActiveCommands::new(); /// /// Thread 1 /// command_count.remove(); /// cmd = receiver.try_recv(); /// assert_eq!(cmd.is_ok()); /// /// Thread 2 /// sender.send(cmd); //...
else { assert!(false); } return operations; } /// Based on the input args this returns a generator that can generate requested /// IO load.For now we only allow sequential io. fn pick_generator_type(args: &GeneratorArgs, target_id: u64) -> Box<dyn Generator> { if !args.sequential { panic!(...
{ operations.push(OperationType::Write); }
conditional_block
main.rs
From<&'a mut ES> for Option<&'a mut Ant> { fn from(entity_state: &'a mut ES) -> Self { match entity_state { &mut ES::Ant(ref mut ant) => Some(ant), } } } #[derive(Clone, Debug)] enum ES { Ant(Ant), } impl EntityState<CS> for ES {} impl From<Ant> for ES { fn from(ant: Ant)...
} match process_action_buffers(
random_line_split
main.rs
.add_named_value("UNIVERSE_SIZE", UNIVERSE_SIZE.into()); return Rc::new(global_scope) } fn get_ant_default_context() -> ketos::Context { let scope = get_ant_global_scope(); let restrictions = get_ant_restrictions(); let context = ketos::Context::new(scope, restrictions); // Fill the context with d...
(context: &Context, universe_index: usize) { let scope: &GlobalScope = context.scope(); scope.add_named_value("__CELL_ACTIONS", Value::Unit); scope.add_named_value("__SELF_ACTIONS", Value::Unit); scope.add_named_value("__ENTITY_ACTIONS", Value::Unit); scope.add_named_value("UNIVERSE_INDEX", Value::I...
reset_action_buffers
identifier_name
main.rs
type of {} provided to argument 1 of translate action!", list[1].type_name() )); }, }; let arg2: isize = match &list[2] { &Value::Integer(ref int)...
{ match cell.state.contents { CellContents::Anthill => [222, 233, 244, 255], CellContents::Empty => [12, 12, 12, 255], CellContents::Food(_) => [200, 30, 40, 255], // TODO: Different colors for different food amounts CellContents::Filled(_) => [230, 230, 230, 255]...
conditional_block
main.rs
.add_named_value("UNIVERSE_SIZE", UNIVERSE_SIZE.into()); return Rc::new(global_scope) } fn get_ant_default_context() -> ketos::Context { let scope = get_ant_global_scope(); let restrictions = get_ant_restrictions(); let context = ketos::Context::new(scope, restrictions); // Fill the context with d...
} #[derive(Clone)] struct MES(ketos::Value); impl Default for MES { fn default() -> Self { MES(ketos::Value::Unit) } } impl MutEntityState for MES {} enum CA { } impl CellAction<CS> for CA {} #[derive(Debug)] enum EA { } type U = Universe2D<CS, ES, MES>; fn map_value_to_self_action(val: &Valu...
{ ES::Ant(ant) }
identifier_body
test_utils.go
TestLeaderIP = "10.10.10.10" ) const KubeConfigData = ` apiVersion: v1 clusters: [] contexts: [] kind: Config preferences: {} users: [] ` type ClustersKubeConfig struct { APIVersion string `yaml:"apiVersion"` Clusters []ClusterData `yaml:"clusters"` Contexts []KubeContextData `yaml:...
VerifyTestAMKOClusterStatus
identifier_name
test_utils.go
/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" ) var testEnv1 *envtest.Environment var testEnv2 *envtest.Environment const ( Cluster1 = "cluster1" Cluster2 ...
func getTestAMKOClusterStatusReason(status amkovmwarecomv1alpha1.AMKOClusterStatus, statusType string) map[string]string { for _, condition := range status.Conditions { if condition.Type == statusType { return map[string]string{ "reason": condition.Reason, "status": condition.Status, } } } retur...
{ return amkovmwarecomv1alpha1.AMKOCluster{ ObjectMeta: metav1.ObjectMeta{ Name: TestAMKOClusterName, Namespace: AviSystemNS, }, Spec: amkovmwarecomv1alpha1.AMKOClusterSpec{ ClusterContext: currentContext, IsLeader: isLeader, Clusters: []string{Cluster1, Cluster2}, Version: ...
identifier_body
test_utils.go
/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" ) var testEnv1 *envtest.Environment var testEnv2 *envtest.Environment const ( Cluster1 = "cluster1" Cluster2 ...
Expect(err).ToNot(HaveOccurred()) err = k8sClient.Delete(ctx, gdp) if err != nil && k8serrors.IsNotFound(err) { return } Expect(err).ToNot(HaveOccurred()) } func TestGCGDPNotFederated(k8sClient client.Client) { var gcList gslbalphav1.GSLBConfigList ctx := context.Background() Expect(k8sClient.List(ctx, &gcL...
{ return }
conditional_block
test_utils.go
/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/envtest" ) var testEnv1 *envtest.Environment var testEnv2 *envtest.Environment const ( Cluster1 = "cluster1"...
Expect(k8sClient1.Create(context.TODO(), &nsObj)).Should(Succeed()) Expect(os.Setenv("GSLB_CONFIG", string(kubeCfgData))).Should(Succeed()) // create "avi-system" namespace on the other cluster as well nsObj.ObjectMeta.ResourceVersion = "" Expect(k8sClient2.Create(context.TODO(), &nsObj)).Should(Succeed()) } fun...
}
random_line_split
main-v2.js
let displayRow = renderElement('div', 'row'); let display = renderElement('div', 'col bg-light text-right display-4'); display.id = 'displayWindow'; display.setAttribute('style', 'height: 80px;'); display.innerHTML = 0; let bottom = renderElement('div', 'p-5'); // Append Elements centerC...
} // Key "=/+" without Shift --> "=" if (e.keyCode === 187 && !e.shiftKey) { symPress('='); } // Can use * for multiply if (e.keyCode === 56 && e.shiftKey) { symPress('X'); } if (e.keyCode === 56 && !e.shiftKey) { numPress('8'); } switch (e.keyCode) { ...
// Keys: Shift and "=/+" --> "+" if (e.keyCode === 187 && e.shiftKey) { symPress('+');
random_line_split
main-v2.js
67: symPress('C'); break; // Delete key also --> Clear case 8: symPress('C'); break; case 191: symPress('/'); break; case 88: symPress('X'); break; case 189: symPress('-')...
{ num1 = ''; num2 = ''; operand = ''; displayWindow.innerHTML = 0; equalTemp = undefined; eqPress = false; }
identifier_body
main-v2.js
let displayRow = renderElement('div', 'row'); let display = renderElement('div', 'col bg-light text-right display-4'); display.id = 'displayWindow'; display.setAttribute('style', 'height: 80px;'); display.innerHTML = 0; let bottom = renderElement('div', 'p-5'); // Append Elements centerC...
else { numPress(this.id); } // If NaN (for example, from 0/0) clears the calc and displays a message) if (displayWindow.innerHTML === 'NaN') { clear(); displayWindow.innerHTML = '-Undefined-'; } // Debugging Logs: console.log(`Equation: ${num1} ${operand} ${num2}`); ...
{ symPress(this.id); }
conditional_block
main-v2.js
() { // Create Elements let container = renderElement('div', 'container-fluid'); let row = renderElement('div', 'row'); let leftCol = renderElement('div', 'col-0 col-sm-0 col-md-1 col-lg-2'); let centerCol = renderElement('div', 'col-12 col-sm-12 col-md-10 col-lg-8 text-center'); let rightCol =...
loadCalc
identifier_name
proc.py
self.props['suffix'] = utils.uid(signature) return self.suffix def _tidyBeforeRun (self): """ Do some preparation before running jobs """ self._buildProps () self._buildInput () self._buildProcVars () self._buildJobs () def _tidyAfterRun (self): """ Do some cleaning after running jobs """ f...
""" Read the configuration @params: `config`: The configuration """ conf = { key:val for key, val in config.iteritems() if key not in self.sets } self.config.update (conf) for key, val in conf.iteritems(): self.props[key] = val
identifier_body
proc.py
raise Exception ('Failed to run afterCmd: %s' % self.afterCmd) self._tidyAfterRun () self.log ('Done (time: %s).' % utils.formatTime(time() - timer), 'info') def _buildProps (self): """ Compute some properties """ if isinstance (self.retcodes, int): self.props['retcodes'] = [self.retcodes] ...
_runJobs
identifier_name
proc.py
ValueError('Property "%s" of proc is not found' % name) if proc.ALIAS.has_key(name): name = proc.ALIAS[name] return self.props[name] def __setattr__ (self, name, value): if not self.config.has_key(name) and not proc.ALIAS.has_key(name) and not name.endswith ('Runner'): raise ValueError('Cannot set...
# set cached to False, then my nexts will access it self.props['cached'] = False self.log (self.workdir, 'info', 'RUNNING') self._runJobs() if self._runCmd('afterCmd') != 0:
random_line_split
proc.py
'): depends = config['depends'] pickable_depends = [] if isinstance(depends, proc): depends = [depends] elif isinstance(depends, aggr): depends = depends.procs for depend in depends: pickable_depends.append(depend.id + '.' + depend.tag) config['depends'] = pickable_depends # lambda no...
val = self.props[prop] if not prop in ['id', 'tag', 'tmpdir', 'forks', 'cache', 'workdir', 'echo', 'runner', 'errorhow', 'errorntry', 'defaultSh', 'exportdir', 'exporthow', 'exportow', 'indir', 'outdir', 'length', 'args']: continue if prop == 'args': self.props['procvars']['proc.args'] =...
conditional_block
madlibs.py
1) * 10) msg.reply("======= Starting Round {0}/{1} =======".format( int(state['round']), state['options']['numrounds'] )) log.info("======= Starting Round {0}/{1} =======".format( int(state['round']), state['options']['numrounds'] )) if state['options']['hidesentence']: ...
"End a round of Mad Libs." state['round'] += 0.25 state['doc'] = None state['text'] = "" state['textshape'] = [] shame = [] for nick, vote in state['votes'].items(): if vote == -1: shame.append(nick) else: ent = state['entries'][vote] state['...
identifier_body
madlibs.py
t2 if not state['options']['botplays']: return t3 = threading.Thread( target=botentry, args=(msg, state) ) t3.start() state['threads'][t3.ident] = t3 def processentry(msg, state): "Process a submitted Mad Lib word list entry." try: if msg.text.strip(...
winners = [slist[0]] for player in slist[1:]:
random_line_split
madlibs.py
pus open failed: " + str(e)) killgame(state) # give 10s more time for each add'l 80-char line entrytime = int(state['options']['entrytime'] + \ (floor(len(state['text']) / 80) - 1) * 10) msg.reply("======= Starting Round {0}/{1} =======".format( int(state['round']), state['...
(msg, state): """Generate a response based on the original text. Warning, may take 30-60s to complete. Do not set entrytime very low!""" if 'words' not in state: # expensive initialization, do ALAP log.info("Loading word corpus...") state['words'] = [w for w in nlp.nlp.vocab if w...
botentry
identifier_name
madlibs.py
else: name = state['options']['corpus'] if state['options']['corporaset'] == "None": set = None else: set = state['options']['corporaset'] # will raise IOError if corpus invalid if name: sta...
name = None
conditional_block
gru_model.py
"] unique_intent = list(set(intent)) sentences = list(df["Sentence"]) return (intent, unique_intent, sentences) intent, unique_intent, sentences = load_dataset("Dataset.csv") intent sentences print(sentences[:10]) nltk.download("stopwords") nltk.download("punkt") #define stemmer stemmer = LancasterStemme...
(words): return(len(max(words, key = len))) word_tokenizer = create_tokenizer(cleaned_words) vocab_size = len(word_tokenizer.word_index) + 1 max_length = max_length(cleaned_words) print("Vocab Size = %d and Maximum length = %d" % (vocab_size, max_length)) """### 3.2 One Hot Encoding for Model Fed""" def encoding_...
max_length
identifier_name
gru_model.py
"] unique_intent = list(set(intent)) sentences = list(df["Sentence"]) return (intent, unique_intent, sentences) intent, unique_intent, sentences = load_dataset("Dataset.csv") intent sentences print(sentences[:10]) nltk.download("stopwords") nltk.download("punkt") #define stemmer stemmer = LancasterStemme...
"""# 7. Testing""" text = "Can you help me?" pred = predictions(text) get_final_output(pred, unique_intent) """# 8. Save/Load Pickle""" # from sklearn.externals import joblib # joblib.dump(model, 'modelnlp.pkl') # nlp_model = open('modelnlp.pkl','rb') # nlp = joblib.load(nlp_model) # !pip install git+https://git...
print("%s has confidence = %s" % (classes[i], (predictions[i])))
conditional_block
gru_model.py
"] unique_intent = list(set(intent)) sentences = list(df["Sentence"]) return (intent, unique_intent, sentences) intent, unique_intent, sentences = load_dataset("Dataset.csv") intent sentences print(sentences[:10]) nltk.download("stopwords") nltk.download("punkt") #define stemmer stemmer = LancasterStemme...
return input_ids def create_single_input(self,sentence,maxlen): stokens = self.tokenizer.tokenize(sentence) stokens = stokens[:maxlen] stokens = ["[CLS]"] + stokens + ["[SEP]"] ids = self.get_ids(stokens, self.tokenizer, self.max_len) masks = self.get_masks
random_line_split