file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.rs | use crate::argon2id13::Salt;
use actix_web::{get, post, web, HttpRequest, HttpResponse};
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use futures::StreamExt;
use google_authenticator::{ErrorCorrectionLevel, GoogleAuthenticator};
use hmac::{Hmac, Mac, NewMac};
use lazy_static::lazy_static;
u... |
// récupère le code dans le header
let input_code: &str = req.headers().get("Code").unwrap().to_str().unwrap();
if !auth.verify_code(&user.secret, &input_code, 0, 0) {
println!("Mauvais code.");
return HttpResponse::Unauthorized().finish();
}
// si ok, un token est envoyé à l'utili... | }
}; | random_line_split |
main.rs | use crate::argon2id13::Salt;
use actix_web::{get, post, web, HttpRequest, HttpResponse};
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use futures::StreamExt;
use google_authenticator::{ErrorCorrectionLevel, GoogleAuthenticator};
use hmac::{Hmac, Mac, NewMac};
use lazy_static::lazy_static;
u... | 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 | use crate::argon2id13::Salt;
use actix_web::{get, post, web, HttpRequest, HttpResponse};
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use futures::StreamExt;
use google_authenticator::{ErrorCorrectionLevel, GoogleAuthenticator};
use hmac::{Hmac, Mac, NewMac};
use lazy_static::lazy_static;
u... |
}
| }
}
}
return false; | conditional_block |
main.rs | use crate::argon2id13::Salt;
use actix_web::{get, post, web, HttpRequest, HttpResponse};
use aes_gcm::aead::{Aead, NewAead};
use aes_gcm::{Aes256Gcm, Key, Nonce};
use futures::StreamExt;
use google_authenticator::{ErrorCorrectionLevel, GoogleAuthenticator};
use hmac::{Hmac, Mac, NewMac};
use lazy_static::lazy_static;
u... | main() -> std::io::Result<()> {
println!("Le serveur est prêt à recevoir des requêtes");
use actix_web::{App, HttpServer};
HttpServer::new(|| {
App::new()
.service(username)
.service(username_post)
.service(get_code)
.service(validate_code)
... | 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 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
import sys
import rospy
import copy, math
import threading
import time
import tf
from math import pi, radians, degrees, atan2, sqrt
from moveit_commander import MoveGroupCommander, RobotCommander
from moveit_commander import PlanningSceneInterface, roscpp_initia... | (wpose))
wpose = move_group.get_current_pose().pose
wpose.position.x += b # First move up (z)
waypoints.append(copy.deepcopy(wpose))
wpose = move_group.get_current_pose().pose
wpose.position.y += c # First move up (z)
waypoints.append(copy.deepcopy(wpose))
# We want the Cartesian ... | 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 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
import sys
import rospy
import copy, math
import threading
import time
import tf
from math import pi, radians, degrees, atan2, sqrt
from moveit_commander import MoveGroupCommander, RobotCommander
from moveit_commander import PlanningSceneInterface, roscpp_initia... | #move_Joint(1.57882340096811 ,-0.312808525716150 ,-1.00858459420407 ,-0.237259591096372 ,-2.51322054719748 ,-3.12658213005787)
#move_Joint(1.49234990741608 ,-1.25023043364197 ,0.884986270249331 ,-1.26185202847346 ,-2.19692733997135 ,3.04571337230654)
#move_Joint(1.38187898379176 ,-1.24138218321594 ,0.770320... | #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 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
import sys
import rospy
import copy, math
import threading
import time
import tf
from math import pi, radians, degrees, atan2, sqrt
from moveit_commander import MoveGroupCommander, RobotCommander
from moveit_commander import PlanningSceneInterface, roscpp_initia... |
#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 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
"""
import sys
import rospy
import copy, math
import threading
import time
import tf
from math import pi, radians, degrees, atan2, sqrt
from moveit_commander import MoveGroupCommander, RobotCommander
from moveit_commander import PlanningSceneInterface, roscpp_initia... | 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 | // This file was generated by `cargo dev update_lints`.
// Use that command to update this file and do not edit by hand.
// Manual edits will be overwritten.
store.register_lints(&[
#[cfg(feature = "internal")]
utils::internal_lints::CLIPPY_LINTS_INTERNAL,
#[cfg(feature = "internal")]
utils::internal_l... | 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 | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package awsxray // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/xray"
import (
"encoding/json"
"errors"
"fmt"
)
type CauseType int
const (
// CauseTypeExceptionID indicates that the type of the `cause... | (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 | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package awsxray // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/xray"
import (
"encoding/json"
"errors"
"fmt"
)
type CauseType int
const (
// CauseTypeExceptionID indicates that the type of the `cause... |
// 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 | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package awsxray // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/xray"
import (
"encoding/json"
"errors"
"fmt"
)
type CauseType int
const (
// CauseTypeExceptionID indicates that the type of the `cause... | }
// 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 | // Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package awsxray // import "github.com/open-telemetry/opentelemetry-collector-contrib/internal/aws/xray"
import (
"encoding/json"
"errors"
"fmt"
)
type CauseType int
const (
// CauseTypeExceptionID indicates that the type of the `cause... |
// 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 | // Copyright Project Contour Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
// TODO: Ensure the gateway by creating manage infrastructure, i.e. the Envoy service.
// xref: https://github.com/projectcontour/contour/issues/3545
r.log.WithField("namespace", oldest.Namespace).WithField("name", oldest.Name).Info("assigning gateway to DAG")
r.eventHandler.OnAdd(oldest, false)
return reconcil... | {
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 | // Copyright Project Contour Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | (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 | // Copyright Project Contour Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... | if cond.Type == string(gatewayapi_v1beta1.GatewayClassConditionStatusAccepted) && cond.Status == metav1.ConditionTrue {
return true
}
}
return false
}
func setGatewayNotAccepted(gateway *gatewayapi_v1beta1.Gateway) *gatewayapi_v1beta1.Gateway {
newCond := metav1.Condition{
Type: string(gatew... | func isAccepted(gatewayClass *gatewayapi_v1beta1.GatewayClass) bool {
for _, cond := range gatewayClass.Status.Conditions { | random_line_split |
gateway.go | // Copyright Project Contour Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to... |
func (r *gatewayReconciler) OnElectedLeader() {
r.log.Info("elected leader, triggering reconciles for all gateways")
var gateways gatewayapi_v1beta1.GatewayList
if err := r.client.List(context.Background(), &gateways); err != nil {
r.log.WithError(err).Error("error listing gateways")
return
}
for i := rang... | {
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 | #coding=utf-8
import sys
import os
import subprocess
import jieba
import string
import re
import math
import codecs
import time
import json
class FieldClassifierAndKeywords:
def __init__(self):
words = jieba.cut("我是谁", cut_all=False)
def FieldClassifierAndKeywords(self,question):
##读入问题,调用分词工具分词... | 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 | #coding=utf-8
import sys
import os
import subprocess
import jieba
import string
import re
import math
import codecs
import time
import json
class FieldClassifierAndKeywords:
def __init__(self):
words = jieba.cut("我是谁", cut_all=False)
def FieldClassifierAndKeywords(self,question):
##读入问题,调用分词工具分词... | 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 | #coding=utf-8
import sys
import os
import subprocess
import jieba
import string
import re
import math
import codecs
import time
import json
class FieldClassifierAndKeywords:
def __init__(self):
words = jieba.cut("我是谁", cut_all=False)
def FieldClassifierAndKeywords(self,question):
##读入问题,调用分词工具分词... | 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 | #coding=utf-8
import sys
import os
import subprocess
import jieba
import string
import re
import math
import codecs
import time
import json
class | :
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 | import React, { Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import api from 'api/api'
import Tip from 'component/pagemsg/tip'
import Tipshowend from 'component/pagemsg/tipshowend'
import css from 'css/indexpage'
import companylogo from 'images/companylogo.pn... | 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 | import React, { Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import api from 'api/api'
import Tip from 'component/pagemsg/tip'
import Tipshowend from 'component/pagemsg/tipshowend'
import css from 'css/indexpage'
import companylogo from 'images/companylogo.pn... | 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];
}
if(!el){
return;... | 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 | import React, { Component } from 'react'
import { Link } from 'react-router'
import { connect } from 'react-redux'
import api from 'api/api'
import Tip from 'component/pagemsg/tip'
import Tipshowend from 'component/pagemsg/tipshowend'
import css from 'css/indexpage'
import companylogo from 'images/companylogo.pn... | }
}
IndexPage = connect(mapStateToProps)(IndexPage)
export default IndexPage | userstate : state.UserState
| random_line_split |
manager.go | package task
import (
"container/heap"
"fmt"
"sync"
"time"
"github.com/alecthomas/log4go"
"github.com/jinzhu/gorm"
)
const (
TASK_TYPE_PERIODIC = TaskType(1)
TASK_TYPE_ONESHOT = TaskType(2)
TASK_SOURCE_PUSH = TaskSource(0)
STATUS_UNKNOWN = TaskStatus(-1)
STATUS_INIT = TaskStatus(0) //init but may ed... | else {
task.Handler = taskManager.handlers[task.Source]
context, err = task.Handler.Sync(task.UserIdentifier)
if err != nil {
log4go.Warn("task context sync error: %v", err)
continue
} else {
task.Context = context
}
}
now := time.Now()
if task.NextExecutionTime.Before(now) {
log4... | {
log4go.Warn("unknown task source :%v", task.Source)
continue
} | conditional_block |
manager.go | package task
import (
"container/heap"
"fmt"
"sync"
"time"
"github.com/alecthomas/log4go"
"github.com/jinzhu/gorm"
)
const (
TASK_TYPE_PERIODIC = TaskType(1)
TASK_TYPE_ONESHOT = TaskType(2)
TASK_SOURCE_PUSH = TaskSource(0)
STATUS_UNKNOWN = TaskStatus(-1)
STATUS_INIT = TaskStatus(0) //init but may ed... | (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 | package task
import (
"container/heap"
"fmt"
"sync"
"time"
"github.com/alecthomas/log4go"
"github.com/jinzhu/gorm"
)
const (
TASK_TYPE_PERIODIC = TaskType(1)
TASK_TYPE_ONESHOT = TaskType(2)
TASK_SOURCE_PUSH = TaskSource(0)
STATUS_UNKNOWN = TaskStatus(-1)
STATUS_INIT = TaskStatus(0) //init but may ed... | {
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 | package task
import (
"container/heap"
"fmt"
"sync"
"time"
"github.com/alecthomas/log4go"
"github.com/jinzhu/gorm"
)
const (
TASK_TYPE_PERIODIC = TaskType(1)
TASK_TYPE_ONESHOT = TaskType(2)
TASK_SOURCE_PUSH = TaskSource(0)
STATUS_UNKNOWN = TaskStatus(-1)
STATUS_INIT = TaskStatus(0) //init but may ed... |
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 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import logging
import os
import torch
from fairseq import bleu
from tqdm import ... |
if args.candidates:
fixed_candidates = torch.load(args.candidates)
if args.n_candidates < fixed_candidates.size(0):
logging.warning(
f"Keeping only {args.n_candidates} / {fixed_candidates.size(0)} candidates"
)
fixed_candidates = fixed_candidates[: args.n_candidates]
else:... | 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 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import logging
import os
import torch
from fairseq import bleu
from tqdm import ... | 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 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import logging
import os
import torch
from fairseq import bleu
from tqdm import ... |
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 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import argparse
import logging
import os
import torch
from fairseq import bleu
from tqdm import ... | (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 | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditio... | 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 | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditio... |
/**
* @return {number}
*/
function line()
{
return ensureLocation().line;
}
/**
* @return {number}
*/
function column()
{
return ensureLocation().column;
}
/**
* @return {number}
*/
function contextId()
{
var mirror = ... | {
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 | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditio... | ()
{
return ensureLocation().column;
}
/**
* @return {number}
*/
function contextId()
{
var mirror = ensureFuncMirror();
// Old V8 do not have context() function on these objects
if (!mirror.context)
return DebuggerScript._executionContextId(mir... | column | identifier_name |
main.rs | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::rc::Rc;
use std::cell::Cell;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::u32;
extern crate chariot_drs as lib;
use lib::DrsFile as Archive;
extern crate number_prefix;
use number_prefix::{binary_pre... | (
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 | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::rc::Rc;
use std::cell::Cell;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::u32;
extern crate chariot_drs as lib;
use lib::DrsFile as Archive;
extern crate number_prefix;
use number_prefix::{binary_pre... | 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 | #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::rc::Rc;
use std::cell::Cell;
use std::fs::{self, OpenOptions};
use std::io::Write;
use std::path::PathBuf;
use std::u32;
extern crate chariot_drs as lib;
use lib::DrsFile as Archive;
extern crate number_prefix;
use number_prefix::{binary_pre... |
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 | //! Implementations of cryptographic attacks against block ciphers.
use utils::data::Data;
use utils::metrics;
use victims::block::{EcbOrCbc, EcbWithSuffix, EcbWithAffixes, EcbUserProfile, CbcCookie};
/// Determine whether a block cipher is using ECB or CBC mode.
///
/// Given a black box which encrypts (padded) user... | (cbc_cookie_box: &CbcCookie) -> Data {
// First, provide the user data "aaaaaaaaaaaaaaaa:admin<true:aa<a" and get the
// resulting token as raw bytes.
let token = cbc_cookie_box.make_token("aaaaaaaaaaaaaaaa:admin<true:aa<a");
let mut bytes = token.bytes().to_vec();
// Now, by flipping some of the ... | craft_cbc_admin_token | identifier_name |
block.rs | //! Implementations of cryptographic attacks against block ciphers.
use utils::data::Data;
use utils::metrics;
use victims::block::{EcbOrCbc, EcbWithSuffix, EcbWithAffixes, EcbUserProfile, CbcCookie};
/// Determine whether a block cipher is using ECB or CBC mode.
///
/// Given a black box which encrypts (padded) user... | 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 | //! Implementations of cryptographic attacks against block ciphers.
use utils::data::Data;
use utils::metrics;
use victims::block::{EcbOrCbc, EcbWithSuffix, EcbWithAffixes, EcbUserProfile, CbcCookie};
/// Determine whether a block cipher is using ECB or CBC mode.
///
/// Given a black box which encrypts (padded) user... |
/// 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 upon
// inserting a null byte.
let empty =... | {
// 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 | //! Implementations of cryptographic attacks against block ciphers.
use utils::data::Data;
use utils::metrics;
use victims::block::{EcbOrCbc, EcbWithSuffix, EcbWithAffixes, EcbUserProfile, CbcCookie};
/// Determine whether a block cipher is using ECB or CBC mode.
///
/// Given a black box which encrypts (padded) user... |
}
}
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 | #!/usr/bin/python
# Copyright (c) 2020 Maryushi3
import emoji_data_python as edp
import sys
import pyautogui
from Xlib import display
from PyQt5.QtWidgets import QApplication, QGridLayout, QLabel, QLineEdit, QScrollArea, QSizePolicy, QStackedLayout, QVBoxLayout, QWidget
from PyQt5.QtCore import QEvent, QSettings, Qt, ... | ():
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 | #!/usr/bin/python
# Copyright (c) 2020 Maryushi3
import emoji_data_python as edp
import sys
import pyautogui
from Xlib import display
from PyQt5.QtWidgets import QApplication, QGridLayout, QLabel, QLineEdit, QScrollArea, QSizePolicy, QStackedLayout, QVBoxLayout, QWidget
from PyQt5.QtCore import QEvent, QSettings, Qt, ... |
# 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 | #!/usr/bin/python
# Copyright (c) 2020 Maryushi3
import emoji_data_python as edp
import sys
import pyautogui
from Xlib import display
from PyQt5.QtWidgets import QApplication, QGridLayout, QLabel, QLineEdit, QScrollArea, QSizePolicy, QStackedLayout, QVBoxLayout, QWidget
from PyQt5.QtCore import QEvent, QSettings, Qt, ... |
# 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 | #!/usr/bin/python
# Copyright (c) 2020 Maryushi3
import emoji_data_python as edp
import sys
import pyautogui
from Xlib import display
from PyQt5.QtWidgets import QApplication, QGridLayout, QLabel, QLineEdit, QScrollArea, QSizePolicy, QStackedLayout, QVBoxLayout, QWidget
from PyQt5.QtCore import QEvent, QSettings, Qt, ... | 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 | """ Tools for working with async queues and tasks.
These are mostly failed experiments, too much complexity. Futures based
techniques compose better and are only slightly more expensive in terms of
overheads. I'm keeping these for now, but probably they will be deleted.
"""
import asyncio
import queue
import logging
f... |
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 | """ Tools for working with async queues and tasks.
These are mostly failed experiments, too much complexity. Futures based
techniques compose better and are only slightly more expensive in terms of
overheads. I'm keeping these for now, but probably they will be deleted.
"""
import asyncio
import queue
import logging
f... | (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 | """ Tools for working with async queues and tasks.
These are mostly failed experiments, too much complexity. Futures based
techniques compose better and are only slightly more expensive in terms of
overheads. I'm keeping these for now, but probably they will be deleted.
"""
import asyncio
import queue
import logging
f... | 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 | """ Tools for working with async queues and tasks.
These are mostly failed experiments, too much complexity. Futures based
techniques compose better and are only slightly more expensive in terms of
overheads. I'm keeping these for now, but probably they will be deleted.
"""
import asyncio
import queue
import logging
f... |
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 | // Package ais provides core functionality for the AIStore object storage.
/*
* Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
*/
package ais
import (
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"time"
"github.com/NVIDIA/aistore/3rdparty/glog"
"github.com/NVIDIA/aistore/cluster"
... | (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 | // Package ais provides core functionality for the AIStore object storage.
/*
* Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
*/
package ais
import (
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"time"
"github.com/NVIDIA/aistore/3rdparty/glog"
"github.com/NVIDIA/aistore/cluster"
... |
func gatherTargetListObjsResults(uuid string, ch chan *locTargetResp, expectedListsSize int, smsg *cmn.SelectMsg) (result fetchResult) {
result.allOK = true
allNotFound := true
result.lists = make([]*cmn.BucketList, 0, expectedListsSize)
requestedProps := smsg.PropsSet()
for singleResult := range ch {
result.... | {
res := c.parent.parent.p.call(*args)
return res.status, res.err
} | identifier_body |
prxlistcache.go | // Package ais provides core functionality for the AIStore object storage.
/*
* Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
*/
package ais
import (
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"time"
"github.com/NVIDIA/aistore/3rdparty/glog"
"github.com/NVIDIA/aistore/cluster"
... | res := p.call(*args)
preallocSize := cmn.DefaultListPageSize
if smsg.PageSize != 0 {
preallocSize = smsg.PageSize
}
if res.err != nil {
return &locTargetResp{list: nil, status: res.status, err: res.err}
}
if len(res.outjson) == 0 {
s := cmn.Min(int(size), len(c.buff))
if s == 0 {
s = len(c.buff)
}... |
// Target prepare the final result. | random_line_split |
prxlistcache.go | // Package ais provides core functionality for the AIStore object storage.
/*
* Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
*/
package ais
import (
"fmt"
"net/http"
"net/url"
"sort"
"strings"
"sync"
"time"
"github.com/NVIDIA/aistore/3rdparty/glog"
"github.com/NVIDIA/aistore/cluster"
... |
return &locTargetResp{list: &cmn.BucketList{Entries: c.buff[:s]}, status: res.status, err: res.err}
}
bucketList := &cmn.BucketList{Entries: make([]*cmn.BucketEntry, 0, preallocSize)}
if err := jsoniter.Unmarshal(res.outjson, &bucketList); err != nil {
return &locTargetResp{list: nil, status: http.StatusIntern... | {
s = len(c.buff)
} | conditional_block |
lib.rs | //! # sunvox-sys
//!
//! FFI bindings to the Sunvox library (http://warmplace.ru/soft/sunvox).
// --- Crate attributes --- //
#![allow(non_camel_case_types)]
// --- ==== --- //
// --- External crates --- //
extern crate libc;
// --- ==== --- //
// --- Use --- //
use libc::{c_void, c_int, c_uint, c_char, c_uchar, ... | {
/// 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 | //! # sunvox-sys
//!
//! FFI bindings to the Sunvox library (http://warmplace.ru/soft/sunvox).
// --- Crate attributes --- //
#![allow(non_camel_case_types)]
// --- ==== --- //
// --- External crates --- //
extern crate libc;
// --- ==== --- //
// --- Use --- //
use libc::{c_void, c_int, c_uint, c_char, c_uchar, ... |
/// 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 | import logging
import re
import socket
import struct
import time
import uuid
from threading import Timer
from urllib.parse import quote
import zeroconf
import config
from plugin import GetPlugin
SHARE_TEMPLATE = '/TiVoConnect?Command=QueryContainer&Container=%s'
PLATFORM_MAIN = 'pyTivo'
PLATFORM_VIDEO = 'pc/pyTivo' ... | machine_name = re.compile('machine=(.*)\n').search
try:
tsock = socket.socket()
tsock.connect((address, 2190))
self.send_packet(tsock, our_beacon)
tivo_beacon = self.recv_packet(tsock)
tsock.close()
name = machine_name(tivo_beacon)... | """ Exchange beacons, and extract the machine name. """
our_beacon = self.format_beacon('connected', False) | random_line_split |
beacon.py | import logging
import re
import socket
import struct
import time
import uuid
from threading import Timer
from urllib.parse import quote
import zeroconf
import config
from plugin import GetPlugin
SHARE_TEMPLATE = '/TiVoConnect?Command=QueryContainer&Container=%s'
PLATFORM_MAIN = 'pyTivo'
PLATFORM_VIDEO = 'pc/pyTivo' ... |
return block
@staticmethod
def recv_packet(sock):
length = struct.unpack('!I', Beacon.recv_bytes(sock, 4))[0]
return Beacon.recv_bytes(sock, length)
@staticmethod
def send_packet(sock, packet):
sock.sendall(struct.pack('!I', len(packet)) + packet)
def listen(self)... | add = sock.recv(length - len(block))
if not add:
break
block += add | conditional_block |
beacon.py | import logging
import re
import socket
import struct
import time
import uuid
from threading import Timer
from urllib.parse import quote
import zeroconf
import config
from plugin import GetPlugin
SHARE_TEMPLATE = '/TiVoConnect?Command=QueryContainer&Container=%s'
PLATFORM_MAIN = 'pyTivo'
PLATFORM_VIDEO = 'pc/pyTivo' ... | (self):
self.send_beacon()
self.timer = Timer(60, self.start)
self.timer.start()
def stop(self):
self.timer.cancel()
if self.bd:
self.bd.shutdown()
@staticmethod
def recv_bytes(sock, length):
block = ''
while len(block) < length:
... | start | identifier_name |
beacon.py | import logging
import re
import socket
import struct
import time
import uuid
from threading import Timer
from urllib.parse import quote
import zeroconf
import config
from plugin import GetPlugin
SHARE_TEMPLATE = '/TiVoConnect?Command=QueryContainer&Container=%s'
PLATFORM_MAIN = 'pyTivo'
PLATFORM_VIDEO = 'pc/pyTivo' ... |
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 | // Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Client to Authenticator Protocol CTAPv2 over USB HID
//!
//! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-... | 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 | // Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Client to Authenticator Protocol CTAPv2 over USB HID
//!
//! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-... |
} else {
// Make sure to put the RX buffer back.
self.recv_buffer.replace(buf);
hil::usb::OutResult::Ok
}
})
}
TransferType::Bulk | TransferTyp... | {
// 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 | // Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Client to Authenticator Protocol CTAPv2 over USB HID
//!
//! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-... |
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> for Cta... | {
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 | // Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.
//! Client to Authenticator Protocol CTAPv2 over USB HID
//!
//! Based on the spec avaliable at: <https://fidoalliance.org/specs/fido-v2.0-id-20180227/fido-client-to-... | (&'a self, endpoint: usize) {
self.client_ctrl.ctrl_status(endpoint)
}
/// Handle the completion of a Control transfer
fn ctrl_status_complete(&'a self, endpoint: usize) {
if self.send_buffer.is_some() {
self.controller().endpoint_resume_in(ENDPOINT_NUM);
}
self... | ctrl_status | identifier_name |
oracle.py | # Trains the network then uses it to make predictions
# Also transforms the data before and after the predictions are made
# A fairly generic interface, in that it can easily applied to other models
import logging
from timeit import default_timer as timer
from copy import deepcopy
from datetime import timedelta
impo... |
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 | # Trains the network then uses it to make predictions
# Also transforms the data before and after the predictions are made
# A fairly generic interface, in that it can easily applied to other models
import logging
from timeit import default_timer as timer
from copy import deepcopy
from datetime import timedelta
impo... |
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 | # Trains the network then uses it to make predictions
# Also transforms the data before and after the predictions are made
# A fairly generic interface, in that it can easily applied to other models
import logging
from timeit import default_timer as timer
from copy import deepcopy
from datetime import timedelta
impo... | (self, train_x):
""" Reassign ordering of dimensions.
:param train_x: Enters with dimensions [features; samples; timesteps; series]
:return: train_x Now with dimensions [samples; series ; time; features]
"""
source = [0, 1, 2, 3]
destination = [3, 0, 2, 1]
re... | reorder_input_dimensions | identifier_name |
oracle.py | # Trains the network then uses it to make predictions
# Also transforms the data before and after the predictions are made
# A fairly generic interface, in that it can easily applied to other models
import logging
from timeit import default_timer as timer
from copy import deepcopy
from datetime import timedelta
impo... |
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 | /*
* Copyright 2018 Nazmul Idris All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... |
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 | /*
* Copyright 2018 Nazmul Idris All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | () {
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 | /*
* Copyright 2018 Nazmul Idris All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applic... | * @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 | use ::slice::Slice;
use ::errors::RubbleResult;
use ::util::coding;
use ::status::Status;
use ::comparator::SliceComparator;
use std::mem;
use std::str;
pub struct OwnedBlock {
data: Vec<u8>,
restart_offset: usize,
}
pub struct SliceBlock<'a> {
data: Slice<'a>,
restart_offset: usize,
}
pub trait Bloc... | 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 | use ::slice::Slice;
use ::errors::RubbleResult;
use ::util::coding;
use ::status::Status;
use ::comparator::SliceComparator;
use std::mem;
use std::str;
pub struct OwnedBlock {
data: Vec<u8>,
restart_offset: usize,
}
pub struct SliceBlock<'a> {
data: Slice<'a>,
restart_offset: usize,
}
pub trait Bloc... |
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 | use ::slice::Slice;
use ::errors::RubbleResult;
use ::util::coding;
use ::status::Status;
use ::comparator::SliceComparator;
use std::mem;
use std::str;
pub struct OwnedBlock {
data: Vec<u8>,
restart_offset: usize,
}
pub struct SliceBlock<'a> {
data: Slice<'a>,
restart_offset: usize,
}
pub trait Bloc... | (&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 | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Implementation of Generator thread and Generator trait.
//!
//! Generator thread accept a set of serializable arguments.
use {
crate::common_operat... | () {
let mut command_count = ActiveCommands::new();
assert_eq!(command_count.count(), 0);
let mut command_count_copy = command_count.clone();
command_count.increment();
let thd = thread::spawn(move || {
sleep(time::Duration::from_secs(1));
// First repay... | active_command_block_test | identifier_name |
generator.rs | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Implementation of Generator thread and Generator trait.
//!
//! Generator thread accept a set of serializable arguments.
use {
crate::common_operat... | 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 | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Implementation of Generator thread and Generator trait.
//!
//! Generator thread accept a set of serializable arguments.
use {
crate::common_operat... |
/// 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 | // Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//! Implementation of Generator thread and Generator trait.
//!
//! Generator thread accept a set of serializable arguments.
use {
crate::common_operat... | 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 | #![feature(try_from)]
extern crate itertools;
extern crate ketos;
extern crate minutiae;
extern crate pcg;
extern crate rand;
extern crate uuid;
use std::fmt::{self, Debug, Formatter};
use std::rc::Rc;
use ketos::{Context, GlobalScope, Scope, Value};
use ketos::compile::compile;
use ketos::bytecode::Code;
use ketos:... | context,
cell_action_executor,
self_action_executor,
entity_action_executor
) {
Ok(()) => (),
Err(err) => println!("Error while retrieving action buffers from context: {}", err),
... | }
match process_action_buffers( | random_line_split |
main.rs | #![feature(try_from)]
extern crate itertools;
extern crate ketos;
extern crate minutiae;
extern crate pcg;
extern crate rand;
extern crate uuid;
use std::fmt::{self, Debug, Formatter};
use std::rc::Rc;
use ketos::{Context, GlobalScope, Scope, Value};
use ketos::compile::compile;
use ketos::bytecode::Code;
use ketos:... | (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 | #![feature(try_from)]
extern crate itertools;
extern crate ketos;
extern crate minutiae;
extern crate pcg;
extern crate rand;
extern crate uuid;
use std::fmt::{self, Debug, Formatter};
use std::rc::Rc;
use ketos::{Context, GlobalScope, Scope, Value};
use ketos::compile::compile;
use ketos::bytecode::Code;
use ketos:... |
}
#[cfg(feature = "wasm")]
fn init(
universe: U,
engine: OurSerialEngine
) {
use minutiae::emscripten::{EmscriptenDriver, CanvasRenderer};
let driver = EmscriptenDriver;
driver.init(universe, engine, &mut [
Box::new(MinDelay::from_tps(59.99)),
Box::new(CanvasRenderer::new(UNIVERS... | {
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 | #![feature(try_from)]
extern crate itertools;
extern crate ketos;
extern crate minutiae;
extern crate pcg;
extern crate rand;
extern crate uuid;
use std::fmt::{self, Debug, Formatter};
use std::rc::Rc;
use ketos::{Context, GlobalScope, Scope, Value};
use ketos::compile::compile;
use ketos::bytecode::Code;
use ketos:... |
}
#[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 | /*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed un... | (k8sClient client.Client, statusType, statusMsg, failureMsg string) {
Eventually(func() map[string]string {
var obj amkovmwarecomv1alpha1.AMKOCluster
Expect(k8sClient.Get(context.TODO(),
types.NamespacedName{
Name: TestAMKOClusterName,
Namespace: AviSystemNS},
&obj)).Should(Succeed())
fmt.Pr... | VerifyTestAMKOClusterStatus | identifier_name |
test_utils.go | /*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed un... |
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 | /*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed un... |
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 | /*
Copyright 2021.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed un... | 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 | // Array with all the button values
let calcBtns = ['C', '', '', '/', '7', '8', '9', 'X', '4', '5', '6', '-', '1', '2', '3', '+', '0', '', '.', '='];
// Default Values
let num1 = '';
let num2 = '';
let operand = '';
// Values for multiple equal sign press
let equalTemp = undefined;
let eqPress = false;
// Function t... | }
// 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 | // Array with all the button values
let calcBtns = ['C', '', '', '/', '7', '8', '9', 'X', '4', '5', '6', '-', '1', '2', '3', '+', '0', '', '.', '='];
// Default Values
let num1 = '';
let num2 = '';
let operand = '';
// Values for multiple equal sign press
let equalTemp = undefined;
let eqPress = false;
// Function t... |
// Cases I tested for:
// [] + [] =
// [] + [] + []... =
// [] + [] =, [] + [] = --> Should reset after first equal sign
// [] + [] =, + [] = --> Shouldn't reset, should add the new value to the first answer
// [] + = = =... --> Should keep adding the first number to the running sum
// [] + [] = = =... --> Should co... | {
num1 = '';
num2 = '';
operand = '';
displayWindow.innerHTML = 0;
equalTemp = undefined;
eqPress = false;
} | identifier_body |
main-v2.js | // Array with all the button values
let calcBtns = ['C', '', '', '/', '7', '8', '9', 'X', '4', '5', '6', '-', '1', '2', '3', '+', '0', '', '.', '='];
// Default Values
let num1 = '';
let num2 = '';
let operand = '';
// Values for multiple equal sign press
let equalTemp = undefined;
let eqPress = false;
// Function t... | 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 | // Array with all the button values
let calcBtns = ['C', '', '', '/', '7', '8', '9', 'X', '4', '5', '6', '-', '1', '2', '3', '+', '0', '', '.', '='];
// Default Values
let num1 = '';
let num2 = '';
let operand = '';
// Values for multiple equal sign press
let equalTemp = undefined;
let eqPress = false;
// Function t... | () {
// 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 | """
proc module for pyppl
"""
import copy as pycopy
import os
import pickle
import sys
import threading
from Queue import Queue
from random import randint
from subprocess import PIPE, Popen
from time import sleep, time
from . import utils
from .aggr import aggr
from .channel import channel
from .job import job as pjob... |
def _isCached (self):
"""
Tell whether the jobs are cached
@returns:
True if all jobs are cached, otherwise False
"""
self.props['ncjobids'] = range(self.length)
if self.cache == False:
self.log ('Not cached, because proc.cache is False', 'debug')
return False
if self.cache == True:
for ... | """
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 | """
proc module for pyppl
"""
import copy as pycopy
import os
import pickle
import sys
import threading
from Queue import Queue
from random import randint
from subprocess import PIPE, Popen
from time import sleep, time
from . import utils
from .aggr import aggr
from .channel import channel
from .job import job as pjob... | (self):
"""
Submit and run the jobs
"""
# submit jobs
def sworker (q):
"""
The worker to run jobs
"""
while True:
(run, i) = q.get()
sleep (i)
if run.isRunning():
self.log ("Job #%s is already running, skip submitting." % run.job.index, 'info')
else:
run.submit()
run... | _runJobs | identifier_name |
proc.py | """
proc module for pyppl
"""
import copy as pycopy
import os
import pickle
import sys
import threading
from Queue import Queue
from random import randint
from subprocess import PIPE, Popen
from time import sleep, time
from . import utils
from .aggr import aggr
from .channel import channel
from .job import job as pjob... | 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]
... | # 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 | """
proc module for pyppl
"""
import copy as pycopy
import os
import pickle
import sys
import threading
from Queue import Queue
from random import randint
from subprocess import PIPE, Popen
from time import sleep, time
from . import utils
from .aggr import aggr
from .channel import channel
from .job import job as pjob... |
def _buildJobs (self):
rptjob = randint(0, self.length-1)
for i in range(self.length):
job = pjob (i, self)
self.jobs[i] = job
job.init ()
row = [x['data'] for x in job.output.values()]
self.channel.rbind (row)
self.jobs[rptjob].report()
def _readConfig (self, config):
"""
Read the co... | 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 | """\
The Mad Libs gaming bot.
"""
from __future__ import unicode_literals
import os
import random
import sys
import threading
from collections import defaultdict
from gizzylib import nlp
from itertools import repeat
from math import ceil, floor
from numpy import dot
from numpy.linalg import norm
bold = irc.style("bo... |
def endgame(msg, state):
"End a game of Mad Libs."
slist = sorted(iter(state['scores'].items()),
key=lambda k: k[1],
reverse=True
)
winners = [slist[0]]
for player in slist[1:]:
if player[1] == slist[0][1]:
winners.append(player[0])
else:
... | "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 | """\
The Mad Libs gaming bot.
"""
from __future__ import unicode_literals
import os
import random
import sys
import threading
from collections import defaultdict
from gizzylib import nlp
from itertools import repeat
from math import ceil, floor
from numpy import dot
from numpy.linalg import norm
bold = irc.style("bo... | if player[1] == slist[0][1]:
winners.append(player[0])
else:
break
msg.reply(bold + "======= GAME OVER! =======" + bold)
log.info(bold + "======= GAME OVER! =======" + bold)
msg.reply("Winner" + ("s" if len(winners) > 1 else "") + \
" with... | winners = [slist[0]]
for player in slist[1:]: | random_line_split |
madlibs.py | """\
The Mad Libs gaming bot.
"""
from __future__ import unicode_literals
import os
import random
import sys
import threading
from collections import defaultdict
from gizzylib import nlp
from itertools import repeat
from math import ceil, floor
from numpy import dot
from numpy.linalg import norm
bold = irc.style("bo... | (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 | """\
The Mad Libs gaming bot.
"""
from __future__ import unicode_literals
import os
import random
import sys
import threading
from collections import defaultdict
from gizzylib import nlp
from itertools import repeat
from math import ceil, floor
from numpy import dot
from numpy.linalg import norm
bold = irc.style("bo... |
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 | # -*- coding: utf-8 -*-
"""Intent GRU Model 90+.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1zH4GNqFS_Z4PxGEueU5Y6g_qOevCl-6d
<a href="https://colab.research.google.com/github/Dark-Sied/Intent_Classification/blob/master/Intent_classification_... | (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 | # -*- coding: utf-8 -*-
"""Intent GRU Model 90+.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1zH4GNqFS_Z4PxGEueU5Y6g_qOevCl-6d
<a href="https://colab.research.google.com/github/Dark-Sied/Intent_Classification/blob/master/Intent_classification_... |
"""# 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.