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 |
|---|---|---|---|---|
cartesian.rs | !(combinations.next(), None);
/// ```
///
/// Note that if any one of the passed containers is empty, the product
/// as a whole is empty, too.
///
/// ```rust
/// extern crate scenarios;
///
/// use scenarios::cartesian;
///
/// let vectors = [vec![1, 2], vec![11, 22], vec![]];
/// let combinations = cartesian::produc... | 1 + self
.iterators
.iter()
.enumerate()
.map(|(i, iterator)| {
iterator.len()
* self.collections[i + 1..]
.iter()
.map(|c| c.into_iter().len())
.product::<usize>(... | return 0;
}
| conditional_block |
cartesian.rs | /// ```
pub fn product<'a, C: 'a, T: 'a>(collections: &'a [C]) -> Product<'a, C, T>
where
&'a C: IntoIterator<Item = &'a T>,
{
// We start with fresh iterators and a `next_item` full of `None`s.
let mut iterators = collections.iter().map(<&C>::into_iter).collect::<Vec<_>>();
let next_item = iterators.it... | let lower = self.0 * other.0;
let upper = match (self.1, other.1) {
(Some(left), Some(right)) => Some(left * right),
_ => None,
};
SizeHint(lower, upper)
}
}
impl | identifier_body | |
cartesian.rs | ///
/// let combinations = cartesian::product(&[]);
/// assert_eq!(combinations.next(), Some(Vec::new()));
/// assert_eq!(combinations.next(), None);
/// ```
pub fn product<'a, C: 'a, T: 'a>(collections: &'a [C]) -> Product<'a, C, T>
where
&'a C: IntoIterator<Item = &'a T>,
{
// We start with fresh iterators an... | type Output = Self;
fn mul(self, other: Self) -> Self {
let lower = self.0 * other.0;
let upper = match (self.1, other.1) { | random_line_split | |
dnn1.py | #detector.setModelTypeAsTinyYOLOv3()
if localdir:
detector.setModelPath(os.path.join(execution_path , yolo_path))
else:
detector.setModelPath(yolo_path)
#dir(detector)
detector.loadModel()
#loaded_model = tf.keras.models.load_model("./src/mood-saved-models/"model + ".h5")
... | Detect | identifier_name | |
dnn1.py | -Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAIWNJYAX4CSVEH53A%2F20210812%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20210812T232641Z&X-Amz-Expires=300&X-Amz-Signature=a5b91876c83b83a6aafba333c63c5f4a880bea9a937b30e52e92bbb0ac784018&X-Amz-SignedHeaders=host&actor_id=23367640&key_id=0&repo_id=125932201&response-c... | # My experiments results: disappointingly bad pose estimation on the images I tested. Sometimes good, sometimes terrible.
import cv2
import tensorflow.compat.v1 as tf
from imageai.Detection import ObjectDetection
import os
boxes = []
def yolo():
#name = "k.jpg"
root = "Z:\\"
name = "23367640.png" #t.jpg"... | # I tried with yolo-tiny, but the accuracy of the bounding boxes didn't seem acceptable.
#tf 1.15 for older versions of ImageAI - but tf doesn't support Py 3.8
#ImageAI: older versions require tf 1.x
#tf 2.4 - required by ImageAI 2.1.6 -- no GPU supported on Win 7, tf requires CUDA 11.0 (Win10). Win7: CUDA 10.x. CPU: w... | random_line_split |
dnn1.py | path = "pose1.webp" #E:\\capture_046_29092020_150628.jpg"
pathOut = "yolo_out_2.jpg"
path = root + name
pathOut = root + name + "yolo_out" + ".jpg"
detections = detector.detectObjectsFromImage(input_image=os.path.join(execution_path , path), output_image_path=os.path.join(execution_path , pathO... | frameHeight, frameWidth, ch = image.shape
# Prepare the image to be fed to the network
inpBlob = cv2.dnn.blobFromImage(image, 1.0 / 255, (inWidth, inHeight), (0, 0, 0), swapRB=False, crop=False)
#cv2.imshow("G", inpBlob) #unsupported
#cv2.waitKey(0)
# Set the prepared object as the input blob of t... | identifier_body | |
dnn1.py | 53, 397]}
{'name': 'person', 'percentage_probability': 53.89136075973511, 'box_points': [3
86, 93, 428, 171]}
{'name': 'person', 'percentage_probability': 11.339860409498215, 'box_points': [
585, 99, 641, 180]}
{'name': 'person', 'percentage_probability': 10.276197642087936, 'box_points': [
126, 178, 164, 290]}
{'name'... | probMap = output[0, i, :, :]
# Find global maxima of the probMap.
minVal, prob, minLoc, point = cv2.minMaxLoc(probMap)
# Scale the point to fit on the original image
x = (frameWidth * point[0]) / W
y = (frameHeight * point[1]) / H
if prob > threshold :
cv2.... | conditional_block | |
manifest.go | and makes it easy to ensure we are never processing the same item
// simultaneously in two different workers.
workqueue workqueue.RateLimitingInterface
manifestLister applisters.ManifestLister
manifestSynced cache.InformerSynced
}
//NewController new controller
func NewController(clusternetClient clusternetclien... | // more up to date that when the item was initially put onto the
// workqueue.
if key, ok = obj.(string); !ok {
// As the item in the workqueue is actually invalid, we call
// Forget here else we'd go into a loop of attempting to
// process a work item that is invalid.
c.workqueue.Forget(obj)
utilr... | eue.Get()
if shutdown {
return false
}
// We wrap this block in a func so we can defer c.workqueue.Done.
err := func(obj interface{}) error {
// We call Done here so the workqueue knows we have finished
// processing this item. We also must remember to call Forget if we
// do not want this work item being... | identifier_body |
manifest.go | , and makes it easy to ensure we are never processing the same item
// simultaneously in two different workers.
workqueue workqueue.RateLimitingInterface
manifestLister applisters.ManifestLister
manifestSynced cache.InformerSynced
}
//NewController new controller
func NewController(clusternetClient clusternetclie... | // workqueue.
func (c *Controller) runWorker() {
for c.processNextWorkItem() {
}
}
// processNextWorkItem will read a single work item off the workqueue and
// attempt to process it, by calling the syncHandler.
func (c *Controller) processNextWorkItem() bool {
obj, shutdown := c.workqueue.Get()
if shutdown {
re... | random_line_split | |
manifest.go | , and makes it easy to ensure we are never processing the same item
// simultaneously in two different workers.
workqueue workqueue.RateLimitingInterface
manifestLister applisters.ManifestLister
manifestSynced cache.InformerSynced
}
//NewController new controller
func NewController(clusternetClient clusternetclie... | (workers int, stopCh <-chan struct{}) {
defer utilruntime.HandleCrash()
defer c.workqueue.ShutDown()
klog.Info("starting manifest controller...")
defer klog.Info("shutting down manifest controller")
// Wait for the caches to be synced before starting workers
if !cache.WaitForNamedCacheSync("manifest-controller"... | Run | identifier_name |
manifest.go | , and makes it easy to ensure we are never processing the same item
// simultaneously in two different workers.
workqueue workqueue.RateLimitingInterface
manifestLister applisters.ManifestLister
manifestSynced cache.InformerSynced
}
//NewController new controller
func NewController(clusternetClient clusternetclie... |
//过滤没有annotation的
annotations := utd.GetAnnotations()
if ok := util.MatchAnnotationsKeyPrefix(annotations); !ok {
klog.V(5).Infof("addManifest but manifest %s:%s does not find match annotation", manifest.Namespace, manifest.Name)
return
}
c.enqueue(manifest)
}
func (c *Controller) updateManifest(old, cur int... | {
klog.Errorf("unmarshal error, %q, err=%v", klog.KObj(manifest), err)
return
} | conditional_block |
rsqf.rs | struct Metadata {
n: usize,
qbits: usize,
rbits: usize,
nblocks: usize,
nelements: usize,
ndistinct_elements: usize,
nslots: usize,
noccupied_slots: usize,
max_slots: usize,
}
/// Standard filter result type, on success returns a count on error returns a message
/// This should prob... | #[derive(Default, PartialEq)] | random_line_split | |
rsqf.rs | rbits))
}
/// Creates an instance of the filter given the description of the filter parameters stored in
/// a `Metadata` structure
fn from_metadata(meta: Metadata) -> RSQF {
let logical = logical::LogicalData::new(meta.nslots, meta.rbits);
return RSQF { meta, logical };
}
//... | () {
RSQF::new(10000, 8);
}
#[test]
fn computes_valid_metadata() {
let filter = RSQF::new(10000, 9);
assert_eq!(filter.meta.n, 10000);
assert_eq!(filter.meta.rbits, 9);
assert_eq!(filter.meta.qbits, 14);
assert_eq!(filter.meta.nslots, 1usize << 14);
... | panics_on_invalid_r | identifier_name |
rsqf.rs | 3Hash) -> FilterResult {
return self.add_count(hash, 1);
}
/// Subtracts `count` from the total count for `hash` in the filter.
///
/// If `hash` is not present in the filter, an error is returned
/// If `hash` is present, `count` is subtracted from the existing count. The resulting count
... | {
// Test data data values were computed from a Google Sheet using formulae from the RSQF
// paper
let test_data = [
// (n, r, expected_q)
(100_000_usize, 6_usize, 17),
(1_000_000_usize, 6_usize, 20),
(10_000_000_usize, 6_usize, 24),
(1... | identifier_body | |
chekcPermission.go | .Userid)
} else {
log.Debugf("success GetUserByUserid(%d), user:[%+v]", input.Userid, user)
}
args := map[string]interface{}{}
if input.Args == "" {
//log.Debugf("Not args input")
} else if err := json.Unmarshal([]byte(input.Args), &args); err == nil {
//log.Debugf("args input is json")
} else if values, er... | ogicexp)
if err != nil {
return false, err
}
//step 2. get all token value
for token, value := range args {
tokens[token] = value
}
for token, _ := range tokens {
switch token {
case "alluser":
tokens["alluser"] = true
case "inneruser":
inneruser, err := EnvIsInnerUser(user)
if err != nil {
... | = append(roleids, node.Id.Id)
cached[node.Id.Id] = node.Id.Id
}
}
}
return
}
func CheckPrivilege(logicexp string, user t_user.User, args map[string]interface{}) (ok bool, err error) {
if len(logicexp) == 0 {
return true, nil
}
//Step 1. get need tokens
tokens, expression, err := GetLogicexpTokensAndE... | identifier_body |
chekcPermission.go | .Userid)
} else {
log.Debugf("success GetUserByUserid(%d), user:[%+v]", input.Userid, user)
}
args := map[string]interface{}{}
if input.Args == "" {
//log.Debugf("Not args input")
} else if err := json.Unmarshal([]byte(input.Args), &args); err == nil {
//log.Debugf("args input is json")
} else if values, er... | 获取用户角色树
roletree, err := GetUserRoleTreeFromDb(c.Mysql(), input.Userid)
if err != nil {
return c.RESULT_ERROR(ERR_PERMISSION_DENIED, "获取用户角色树错误")
}
log.PrintPreety("roletree", roletree)
//Step 5. 获取所有权限
privilegeids := GetPrivilegeIds(roletree)
if len(privilegeids) == 0 {
return c.RESULT_ERROR(ERR_PERMISSI... | bugf("args input is querystring")
for k, varray := range values {
if varray != nil {
args[k] = varray[0]
}
}
}
//Step 4. | conditional_block |
chekcPermission.go | .RESULT_ERROR(ERR_PERMISSION_DENIED, "用户无任何权限")
}
privileges, err := t_rbac_privilege.FindPrivilegeByIds(c.Mysql(), privilegeids)
if err != nil {
return c.RESULT_ERROR(ERR_PERMISSION_DENIED, "获取权限列表失败")
}
//Step 6. 判断用户有权限
pass := false
for _, privilege := range privileges {
if privilege.F_uri == input.Uri ... | (logicexp)
if err != nil {
| identifier_name | |
chekcPermission.go | input.Userid)
} else {
log.Debugf("success GetUserByUserid(%d), user:[%+v]", input.Userid, user)
}
args := map[string]interface{}{}
if input.Args == "" {
//log.Debugf("Not args input")
} else if err := json.Unmarshal([]byte(input.Args), &args); err == nil {
//log.Debugf("args input is json")
} else if valu... | //子节点不存在,新建添加
roletree[cnid] = &NodeInfo{
Id: cnid,
Name: getName(db, cnid),
Children: RoleTree{},
Parents: RoleTree{},
}
roletree[pnid].Children[cnid] = roletree[cnid]
roletree[cnid].Parents[pnid] = roletree[pnid]
}
//获取下一层级的节点信息
if rolemap.F_target_type == ... | } else { | random_line_split |
myds_retrain.py | _argument(
'-d',
'--data_path',
help='path to HDF5 file containing own dataset',
default='data/phaseI-dataset.hdf5')
argparser.add_argument(
'-a',
'--anchors_path',
help='path to anchors file, defaults to yolo_anchors.txt',
default='model_data/yolo_anchors.txt')
argparser.add_argument(... | image = image.resize((416,416), PIL.Image.BICUBIC)
image_data = np.array(image, dtype=np.float)
image_data /= 255.0
image_data.resize((image_data.shape[0], image_data.shape[1], 1))
image_data = np.repeat(image_data, 3, 2)
image_list.append(image)
image_data_list.a... | '''
function to preprocess hdf5 data
borrowed code from train_overfit and retrain_yolo and modified to suit my input dataset type (hdf5)
'''
image_list = []
boxes_list = []
image_data_list = []
processed_box_data = []
# boxes processing
box_dataset = data['train/boxes']
proc... | identifier_body |
myds_retrain.py | anchors = np.array(anchors).reshape(-1, 2)
else:
anchors = YOLO_ANCHORS
data = h5py.File(data_path, 'r')
#Pre-processing data
boxes_list, image_data_list = get_preprocessed_data(data)
detectors_mask, matching_true_boxes = get_detector_mask(boxes_list, anchors)
#Creat... | for image in image_data[int(len(image_data)*.9):]])
elif image_set == 'all':
image_data = np.array([np.expand_dims(image, axis=0) | random_line_split | |
myds_retrain.py | 5py.File(data_path, 'r')
#Pre-processing data
boxes_list, image_data_list = get_preprocessed_data(data)
detectors_mask, matching_true_boxes = get_detector_mask(boxes_list, anchors)
#Create model
model_body, model = create_model(anchors, class_names, load_pretrained=True, freeze_body=False... | ValueError("draw argument image_set must be 'train', 'val', or 'all'") | conditional_block | |
myds_retrain.py | (
'-d',
'--data_path',
help='path to HDF5 file containing own dataset',
default='data/phaseI-dataset.hdf5')
argparser.add_argument(
'-a',
'--anchors_path',
help='path to anchors file, defaults to yolo_anchors.txt',
default='model_data/yolo_anchors.txt')
argparser.add_argument(
'-c'... | (boxes_list, anchors):
'''
Precompute detectors_mask and matching_true_boxes for training.
Detectors mask is 1 for each spatial position in the final conv layer and
anchor that should be active for the given boxes and 0 otherwise.
Matching true boxes gives the regression targets for the ground truth... | get_detector_mask | identifier_name |
server.ts | != WebSocket.OPEN || this.webSocket.url.indexOf(server.address) == -1) {
console.log('[S]: not connected or new server selected, creating a new WS connection...');
this.wsConnect(server, skipQueue);
} else if (this.webSocket.readyState == WebSocket.OPEN) {
console.log('[S]: already connected to a... |
private isTransitioningState() {
return this.webSocket && (this.webSocket.readyState == WebSocket.CLOSING || this.webSocket.readyState == WebSocket.CONNECTING);
}
private wsConnect(server: ServerModel, skipQueue: boolean = false) {
//console.log('[S]: wsConnect(' + server.address + ')', new Date())
... | {
console.log('[S]: wsDisconnect(reconnect=' + reconnect + ')', this.webSocket);
if (this.webSocket) {
if (this.everConnected && !this.reconnecting) {
this.lastToast.present('Connection lost');
this.connected = false;
this.wsEventObservable.next({ name: wsEvent.EVENT_ERROR, ws: th... | identifier_body |
server.ts | .readyState != WebSocket.OPEN || this.webSocket.url.indexOf(server.address) == -1) {
console.log('[S]: not connected or new server selected, creating a new WS connection...');
this.wsConnect(server, skipQueue);
} else if (this.webSocket.readyState == WebSocket.OPEN) {
console.log('[S]: already con... | //console.log('[S]: queue: ', this.serverQueue);
}
disconnect() {
this.wsDisconnect(false);
}
isConnected() {
return this.connected;
}
isReconnecting() {
return this.reconnecting;
}
private wsDisconnect(reconnect = false) {
console.log('[S]: wsDisconnect(reconnect=' + reconnect +... | random_line_split | |
server.ts | this.popup.present();
} else if (messageData.action == responseModel.ACTION_ENABLE_QUANTITY) {
let responseModelEnableQuantity: responseModelEnableQuantity = messageData;
this.settings.setQuantityEnabled(responseModelEnableQuantity.enable);
} else if (messageData.action == responseModel.ACT... | etContinuoslyWatchForServers( | identifier_name | |
server.ts | .readyState != WebSocket.OPEN || this.webSocket.url.indexOf(server.address) == -1) {
console.log('[S]: not connected or new server selected, creating a new WS connection...');
this.wsConnect(server, skipQueue);
} else if (this.webSocket.readyState == WebSocket.OPEN) {
console.log('[S]: already con... | else {
//console.log('[S]: WS: the server is already in the connections queue');
}
setTimeout(() => {
if (this.isTransitioningState()/* && this.webSocket.url.indexOf(server.address) != -1*/) {
//console.log('[S]: the server ' + server.address + ' is still in transitiong state aft... | {
this.serverQueue.push(server);
//console.log('[S]: WS: the server has been added to the connections list')
} | conditional_block |
ash-v3_8h.js | [ "ASH_FLAG", "ash-v3_8h.html#a35d6a5603fa48cc59eb18417e4376ace", null ],
[ "ASH_FRAME_COUNTER_ROLLOVER", "ash-v3_8h.html#a3898f887b8d025d7b9b58ed70ca31a9c", null ],
[ "ASH_PAYLOAD_LENGTH_BYTE_ESCAPED", "ash-v3_8h.html#acdbd78ad666c177bb3111175b6b20c97", null ],
[ "ASH_STATE_STRINGS", "ash-v3_8h.html#aa... | random_line_split | ||
lpc55_flash.rs | , clap::ValueEnum)]
enum CfpaChoice {
Scratch,
Ping,
Pong,
}
#[derive(Debug, Parser)]
#[clap(name = "isp")]
struct Isp {
/// UART port
#[clap(name = "port")]
port: String,
/// How fast to run the UART. 57,600 baud seems very reliable but is rather
/// slow. In certain test setups we've ... | (prop: BootloaderProperty, params: Vec<u32>) {
match prop {
BootloaderProperty::BootloaderVersion => {
println!("Version {:x}", params[1]);
}
BootloaderProperty::AvailablePeripherals => {
println!("Bitmask of peripherals {:x}", params[1]);
}
Bootloader... | pretty_print_bootloader_prop | identifier_name |
lpc55_flash.rs | , clap::ValueEnum)]
enum CfpaChoice {
Scratch,
Ping,
Pong,
}
#[derive(Debug, Parser)]
#[clap(name = "isp")]
struct Isp {
/// UART port
#[clap(name = "port")]
port: String,
/// How fast to run the UART. 57,600 baud seems very reliable but is rather
/// slow. In certain test setups we've ... | BootloaderProperty::CRCStatus => {
println!("CRC status = {}", params[1]);
}
BootloaderProperty::VerifyWrites => {
println!("Verify Writes (bool) {}", params[1]);
}
BootloaderProperty::MaxPacketSize => {
println!("Max Packet Size = {}", params[... | {
match prop {
BootloaderProperty::BootloaderVersion => {
println!("Version {:x}", params[1]);
}
BootloaderProperty::AvailablePeripherals => {
println!("Bitmask of peripherals {:x}", params[1]);
}
BootloaderProperty::FlashStart => {
println... | identifier_body |
lpc55_flash.rs | , clap::ValueEnum)]
enum CfpaChoice {
Scratch,
Ping,
Pong,
}
#[derive(Debug, Parser)]
#[clap(name = "isp")]
struct Isp {
/// UART port
#[clap(name = "port")]
port: String,
/// How fast to run the UART. 57,600 baud seems very reliable but is rather
/// slow. In certain test setups we've ... |
0x0b38f300 => {
println!("DICE failure. Check:");
println!("- Key store is set up properly (UDS)");
}
0x0d70f300 => {
println!("Trying to boot a TZ image on a device that doesn't have TZ!");
}
0x0d71f300 => {
... | {
println!("Application entry point and/or stack is invalid");
} | conditional_block |
lpc55_flash.rs | file: PathBuf,
},
/// Erase the CMPA region (use to boot non-secure binaries again)
#[clap(name = "erase-cmpa")]
EraseCMPA,
/// Save the CMPA region to a file
ReadCMPA {
/// Write to FILE, or stdout if omitted
file: Option<PathBuf>,
},
/// Save the CFPA region to ... | },
/// Write a file to the CMPA region
#[clap(name = "write-cmpa")]
WriteCMPA { | random_line_split | |
main.js | websocket.onmessage = function (evt) { onMessage(evt) };
websocket.onerror = function (evt) { onError(evt) };
}
function onOpen(evt) {
state.className = "success";
addMessage(127, '');
// state.innerHTML = "Connected to server";
}
function onClose(evt) {
state.className = "fail";... |
function onRTPMessage(evt) {
var cad = evt.data;
var message = cad.slice(1, cad.length);
messageSplitted = message.split("|");
if (messageSplitted[0] === "$POSE_VEL") {
showPositionVel(messageSplitted[1]);
if(svg_first_sector_load){
drawDorisPosition(messageSplitte... |
var obj = JSON.parse(message);
var errorStatus = parseInt(obj.streaming.error);
if (errorStatus === 0) {
var port = obj.streaming.port;
var rtpURL = 'ws://192.168.1.101:' + port;
rtPackages = new WebSocket(rtpURL);
rtPackages.onmessage = function (evt) { onRTPMessag... | identifier_body |
main.js | websocket.onmessage = function (evt) { onMessage(evt) };
websocket.onerror = function (evt) { onError(evt) };
}
function onOpen(evt) {
state.className = "success";
addMessage(127, '');
// state.innerHTML = "Connected to server";
}
function onClose(evt) {
state.className = "fail";... | /*case 27:
siteAdded(message);
break;*/
case 34:
// MakeMenuRooms();
loadMenuMap(0);
break;
case 124:
notifyMe(message);
break;
case 125:
changeControlStatus(message);
... | random_line_split | |
main.js | websocket.onmessage = function (evt) { onMessage(evt) };
websocket.onerror = function (evt) { onError(evt) };
}
function onOpen(evt) {
state.className = "success";
addMessage(127, '');
// state.innerHTML = "Connected to server";
}
function onClose(evt) {
state.className = "fail";... | evt){
console.log("2 websocket se ha cerrado");
}
function onRTPError(evt){
console.log("2 websocket ha tenido un error");
}
/*
function siteAdded(message){
var obj = JSON.parse(message);
alert("Added at index: " + obj.robot.index);
}
*/
function requestReleaseControl() {
... | nRTPClose( | identifier_name |
main.js | websocket.onmessage = function (evt) { onMessage(evt) };
websocket.onerror = function (evt) { onError(evt) };
}
function onOpen(evt) {
state.className = "success";
addMessage(127, '');
// state.innerHTML = "Connected to server";
}
function onClose(evt) {
state.className = "fail";... |
else if (obj.robot.error === "None.") {
alert(selected_map.nameSector.concat(" cargado con éxito."));
}
/// Cargar o no cargar todos las caracteristicas del mapa dependiendo de si tenemos el control ///
///Si es positivo llamamos a features/... | {
alert("Tiene que tener el control.");
var room_number = parseInt(room_selected, 10); //Cogemos la escala aqui tambien aunque no tengamos el control, para asi dibujar donde se encuentra DOris
scaleSVG.x = document.getElementById("mySVG").getBBox().width / parseInt(ro... | conditional_block |
handler.go | // 星号相关:有几种情况要特殊处理,核心是要分清在标点内部还是外部
// -------------------------- 情况一 -------------------------
// 当前是中文,后面是星号或反引号对开头
// -----------------------------------------------------------
// 粗体中文**abc**
// 斜体中文*abc*
// 点中文`abc`
if isZh(currentRune) {
switch nextRune {
case '*':
doZhS... | filepath.Dir(in | identifier_name | |
handler.go | 块中,连续多个空行只保留一个
if strings.TrimSpace(newLine) == "" {
if emptyLineFlag {
continue
}
outputLines = append(outputLines, "")
emptyLineFlag = true
} else {
emptyLineFlag = false
outputLines = append(outputLines, newLine)
}
}
return strings.Join(outputLines, "\n")
}
func formatLine(line strin... | neFlag = false
outputLines = append(outputLines, newLine)
continue
}
// 位于非代码 | conditional_block | |
handler.go | .WriteString(doFormat([]rune(line[prevEndIdx:pair.startIdx])))
prevEndIdx = pair.endIdx
// 处理 link 数据
buf.WriteString(handleLinks(line[pair.startIdx:pair.endIdx]))
// 处理最后的 link 与文本直接的数据
if i == len(pairs)-1 {
buf.WriteString(doFormat([]rune(line[pair.endIdx:])))
prevEndIdx = pair.endIdx
}
result... | OutputSuffix, MarkdownSuffix)
}
// 其他情况 outPath 不处理
}
bf, err := os.Open(inPath)
if err != nil {
return err
}
// 内容处理
inContentBytes, err := ioutil.ReadAll(bf)
if err != nil {
return err
}
inContent := string(inContentBytes)
// 手动关闭输入文件(因为可能后面是覆盖该文件,要写入)
bf.Close()
// 备份 | identifier_body | |
handler.go | '*' {
boldCnt++
italicCnt--
} else {
italicCnt++
}
case '`':
backQuoteCnt++
}
// 判断当前字符后是否要加空格
if idx < length-1 {
nextRune := line[idx+1]
// 注:泛用英文不包括 Markdown 中的特殊符号 * ` [ ] ( )
if isZh(currentRune) && isGeneralEn(nextRune) {
// 中文 + 泛用英文 -> 加空格
buffer.WriteString(" ")... | // step2. 遍历 inPath,逐个替换文件 | random_line_split | |
manage-hospital.component.ts | : any;
public collect_email_array: any = [];
public collect_phone_array: any = [];
public id: any;
public btn_text: string = "SUBMIT";
public condition: any;
public message: string;
public salesrepname: string;
public ErrCode: boolean;
public action: string;
public defaultData: any;
pub... | {
if (this.configData.files.length > 1) { this.ErrCode = true; return; }
this.manageHospitalForm.value.mpimage =
{
"basepath": this.configData.files[0].upload.data.basepath + '/' + this.configData.path + '/',
"image": this.configData.files[0].upload.data.data.fileservernam... | conditional_block | |
manage-hospital.component.ts | ManageHospitalComponent implements OnInit {
/** declarations **/
public manageHospitalForm: FormGroup;
public imgMedical:any;
public states: string;
public allCities: any;
public cities: string;
public userData: any;
public collect_email_array: any = [];
public collect_phone_array: any = ... |
ngOnInit() {
/** generating the form **/
this.generateForm();
/** calling all state **/
this.allStateCityData();
/** switch case **/
switch (this.action) {
case 'add':
/* Button text */
this.btn_text = "SUBMIT";
//Generating the form on ... | /** fetching the current date **/
if (this.action == 'add')
this.date = moment(this.myDate).format('MM/DD/YYYY');
}
| random_line_split |
manage-hospital.component.ts | ManageHospitalComponent implements OnInit {
/** declarations **/
public manageHospitalForm: FormGroup;
public imgMedical:any;
public states: string;
public allCities: any;
public cities: string;
public userData: any;
public collect_email_array: any = [];
public collect_phone_array: any = ... | (index) {
this.collect_email_array.splice(index, 1);
}
/** collecting the phone numbers **/
collect_phones(event: any) {
if (event.keyCode == 32 || event.keyCode == 13) {
this.collect_phone_array.push(event.target.value);
this.manageHospitalForm.controls['contactphones'].patchValue(""... | clearEmail | identifier_name |
manage-hospital.component.ts | ManageHospitalComponent implements OnInit {
/** declarations **/
public manageHospitalForm: FormGroup;
public imgMedical:any;
public states: string;
public allCities: any;
public cities: string;
public userData: any;
public collect_email_array: any = [];
public collect_phone_array: any = ... |
/** clearing the phones **/
clearPhones(index) {
this.collect_phone_array.splice(index, 1);
}
/** --------------------------submit------------------------**/
onSubmit() {
this.manageHospitalForm.value.user_id = this.manageHospitalForm.controls['user_id'].value;
this.manageHospit... | {
if (event.keyCode == 32 || event.keyCode == 13) {
this.collect_phone_array.push(event.target.value);
this.manageHospitalForm.controls['contactphones'].patchValue("");
return;
}
} | identifier_body |
option_definition.py | ForDictionary(tokens)
if tokens == -1:
print '''ERROR: found in definition of %s:\n
Please check your tokens and settings again''' %(name)
self.parents = parents
self.non_parents = non_parents
self.non_parent_exceptions = non_parent_exceptions
self.childs = childs
self.name = name
self.help = he... | (self):
self.valid_range = ["1d","3d"]
def get_valid_range(self):
return self.valid_range
class ProfileType():
"""
Options which can take several profile files as argument (e.g. 1D, 3D, moments, ipa_files)
"""
def __init__(self):
self.valid_range = ["1d","3d","ipa_files","moments"]
def get_valid_range(self... | __init__ | identifier_name |
option_definition.py | checkForDictionary(tokens)
if tokens == -1:
print '''ERROR: found in definition of %s:\n
Please check your tokens and settings again''' %(name)
self.parents = parents
self.non_parents = non_parents
self.non_parent_exceptions = non_parent_exceptions
self.childs = childs
self.name = name
self.help... |
if extra_dependencies:
self.isMandatory = self._isMandatoryMixedOption
# Pretend to be a dictionary to avoid breaking old code
def __getitem__(self, *args, **kwargs):
return self.dict.__getitem__(*args, **kwargs)
def __setitem__(self, *args, **kwargs):
return self.dict.__setitem__(*args, **kwargs)
def... | self._speaker = speaker
assert not isinstance(enable_values, basestring), "Missing comma in one-item-tuple?"
self._enable_values = enable_values
self.canEnable = self._canEnableContinousOption | conditional_block |
option_definition.py | checkForDictionary(tokens)
if tokens == -1:
print '''ERROR: found in definition of %s:\n
Please check your tokens and settings again''' %(name)
self.parents = parents
self.non_parents = non_parents
self.non_parent_exceptions = non_parent_exceptions
self.childs = childs
self.name = name
self.help... | if not vr: vr = (-1e99, 1e99)
gui_inp = (FloatInput(name=name,optional=inp.get('optional'),valid_range=vr,default=inp.get('default')),)
elif dtype == int:
if not vr: vr = (-1e99, 1e99)
gui_inp = (IntegerInput(name=name,valid_range=vr,optional=inp.get('optional'),default=inp.get('default')),)
... | if not self.showInGui:
return gui_inputs
for inp in tokens:
try:
name = inp.gui_name
except KeyError:
pass
if not name: name = inp.get('name')
try:
vr = inp.get('valid_range')
except KeyError:
vr = None
if isinstance(inp, addSetting):
continue
elif isinstance(inp, addLogic... | identifier_body |
option_definition.py | ForDictionary(tokens)
if tokens == -1:
print '''ERROR: found in definition of %s:\n
Please check your tokens and settings again''' %(name)
self.parents = parents
self.non_parents = non_parents
self.non_parent_exceptions = non_parent_exceptions
self.childs = childs
self.name = name
self.help = he... | if not vr: vr = (-1e99, 1e99)
gui_inp = (FloatInput(name=name,optional=inp.get('optional'),valid_range=vr,default=inp.get('default')),)
elif dtype == int:
if not vr: vr = (-1e99, 1e99)
gui_inp = (IntegerInput(name=name,valid_range=vr,optional=inp.get('optional'),default=inp.get('default')),)
... | if dtype == float or dtype==Double: | random_line_split |
mod.rs | of changes to files under `path` from external sources, it
/// expects to have sole maintence of the contents.
pub fn new<T>(path: T, size: u64) -> Result<Self>
where
PathBuf: From<T>,
{
LruDiskCache {
lru: LruCache::with_meter(size, FileSize),
root: PathBuf::fro... | }
fn insert_by<K: AsRef<OsStr>, F: FnOnce(&Path) -> io::Result<()>>(
&mut self,
key: K,
size: Option<u64>,
by: F,
) -> Result<()> {
if let Some(size) = size {
if !self.can_store(size) {
return Err(Error::FileTooLarge);
}
... | {
if !self.can_store(size) {
return Err(Error::FileTooLarge);
}
let rel_path = match addfile_path {
AddFile::AbsPath(ref p) => p.strip_prefix(&self.root).expect("Bad path?").as_os_str(),
AddFile::RelPath(p) => p,
};
//TODO: ideally LRUCache::in... | identifier_body |
mod.rs | <Q: ?Sized>(&self, _: &Q, v: &u64) -> usize
where
K: Borrow<Q>,
{
*v as usize
}
}
/// Return an iterator of `(path, size)` of files under `path` sorted by ascending last-modified
/// time, such that the oldest modified file is returned first.
fn get_all_files<P: AsRef<Path>>(path: P) -> Box... | measure | identifier_name | |
mod.rs | : u64) -> Result<()> {
if !self.can_store(size) {
return Err(Error::FileTooLarge);
}
let rel_path = match addfile_path {
AddFile::AbsPath(ref p) => p.strip_prefix(&self.root).expect("Bad path?").as_os_str(),
AddFile::RelPath(p) => p,
};
//TODO:... | let f = TestFixture::new();
// Create files explicitly in the past. | random_line_split | |
utils.py | 'XXXII': 27, 'IX': 28, 'L': 29, 'XXXI': 30, 'XXXVI': 31,
'XIII': 32, 'XXVII': 33, 'XXXIII': 34, 'VI': 35, 'XV': 36, 'XLI': 37, 'LI': 38, 'XLII': 39,
'XXVI': 40, 'XLV': 41, 'XVI': 42, 'LIII': 43, 'XX': 44, 'LII': 45, 'XL': 46, 'XLIII': 47, 'XXX': 48,
'XLVII': 49, 'XXXIV': 50, 'XLVI':... |
Args:
state: (dict) contains model's state_dict, may contain other keys such as epoch, optimizer state_dict
is_best: (bool) True if it is the best model seen till now
checkpoint: (string) folder where parameters are to be saved
"""
filepath = os.path.join(checkpoint, 'last.pth.tar')... | 'best.pth.tar'
| identifier_name |
utils.py | 2, 'XXVII': 33, 'XXXIII': 34, 'VI': 35, 'XV': 36, 'XLI': 37, 'LI': 38, 'XLII': 39,
'XXVI': 40, 'XLV': 41, 'XVI': 42, 'LIII': 43, 'XX': 44, 'LII': 45, 'XL': 46, 'XLIII': 47, 'XXX': 48,
'XLVII': 49, 'XXXIV': 50, 'XLVI': 51, 'XXV': 52, 'XLVIII': 53, 'II': 54, 'XXVIII': 55}
ID2TAG = {v: k for k, v i... | """
#
for name, param | identifier_body | |
utils.py | , 'XXXII': 27, 'IX': 28, 'L': 29, 'XXXI': 30, 'XXXVI': 31,
'XIII': 32, 'XXVII': 33, 'XXXIII': 34, 'VI': 35, 'XV': 36, 'XLI': 37, 'LI': 38, 'XLII': 39,
'XXVI': 40, 'XLV': 41, 'XVI': 42, 'LIII': 43, 'XX': 44, 'LII': 45, 'XL': 46, 'XLIII': 47, 'XXX': 48,
'XLVII': 49, 'XXXIV': 50, 'XLVI'... | self.data_cache = True
self.train_batch_size = 256
self.dev_batch_size = 128
self.test_batch_size = 128
# 最小训练次数
self.min_epoch_num = 5
# 容纳的提高量(f1-score)
self.patience = 0.001
# 容纳多少次未提高
self.patience_num = 5
self.seed = 2020
... | self.tags = list(MAP_DICT.values())
self.n_gpu = torch.cuda.device_count()
# 读取保存的data | random_line_split |
utils.py | 'XXXII': 27, 'IX': 28, 'L': 29, 'XXXI': 30, 'XXXVI': 31,
'XIII': 32, 'XXVII': 33, 'XXXIII': 34, 'VI': 35, 'XV': 36, 'XLI': 37, 'LI': 38, 'XLII': 39,
'XXVI': 40, 'XLV': 41, 'XVI': 42, 'LIII': 43, 'XX': 44, 'LII': 45, 'XL': 46, 'XLIII': 47, 'XXX': 48,
'XLVII': 49, 'XXXIV': 50, 'XLVI':... | init.normal_(w.data) # bias
elif m is not None and hasattr(m, 'weight') and \
hasattr(m.weight, "requires_grad"):
if len(m.weight.size()) > 1:
init_method(m.weight.data)
else:
init.normal_(m.weight.data)
else:
... | isinstance(m, nn.LSTM):
for w in m.parameters():
if len(w.data.size()) > 1:
init_method(w.data) # weight
else:
| conditional_block |
Unity_K144.py | .get()
NR5G.NR_ChBW = int(entryCol.entry6_enum.get())
NR5G.NR_SubSp = int(entryCol.entry7_enum.get())
NR5G.NR_RB = int(entryCol.entry8.get())
NR5G.NR_RBO = int(entryCol.entry9.get())
NR5G.NR_Mod = entryCol.entry10_enum.get()
NR5G.NR_CC = int(entryCol.entry11.get())
NR5... |
if 'DMRS Config'in K144Data[0][i]:
K144Data[1][i] = K144Data[1][i].replace('T','')
if 'L_PTRS' in K144Data[0][i]:
K144Data[1][i] = K144Data[1][i].replace('TD','')
if 'K_PTRS' in K144Data[0][i]:
K144Data[1][i] = K144Data[1][i].r... | K144Data[1][i] = K144Data[1][i].replace('N','')
K144Data[2][i] = K144Data[2][i].replace('SS','') | conditional_block |
Unity_K144.py | ---+---+---|')
topWind.writeN('|0 015kHz|052 106 270 N/A| |0 015kHz|N/A N/A N/A N/A|')
topWind.writeN('|1 030kHz|024 051 133 273| |1 030kHz|N/A N/A N/A N/A|')
topWind.writeN('|2 060kHz|011 024 065 135| |2 060kHz|066 132 264 N/A|')
topWind.writeN('|3 120kHz|N/A N/A N/A N/A| |3 120kHz|032 066 ... | entryCol.entry3.delete(0,END)
entryCol.entry3.insert(0,data[3])
botWind.writeN("DataLoad: File") | random_line_split | |
Unity_K144.py | 9.get())
NR5G.NR_Mod = entryCol.entry10_enum.get()
NR5G.NR_CC = int(entryCol.entry11.get())
NR5G.NR_TF = 'OFF'
return NR5G
def btn1():
"""*IDN Query"""
NR5G = VST().jav_Open(entryCol.entry0.get(),entryCol.entry1.get())
print(NR5G.SMW.query('*IDN?'))
print(NR5G.FSW.query('*... | """Set RB Offset"""
botWind.writeN('FSW:Signal Description-->RadioFrame-->BWP Config-->RB Offset')
botWind.writeN('SMW:User/BWP-->UL BWP-->RB Offset') | identifier_body | |
Unity_K144.py | (self):
self.List1 = ['- Utility does not validate settings against 3GPP 5G',
'- Click *IDN? to validate IP Addresses',
'- Frequency & SMW Power labels are clickable',
'']
def gui_reader():
"""Read values from GUI"""
SMW_IP = en... | __init__ | identifier_name | |
lab1e.py | 30]
for i in range(5030):
unigram[uni[i][0]] = i
#The below chunk of code makes sure all words from table RG65 are included
#instead of just the 5030 most frequently occuring words. it ends up being the most
#frequently occuring 5000 words plus the other 30 words in table RG65 that were not
#already in the top 5030.... | Mw3[len(Mw3)-1] = M2_100[unigram[ww[0].lower()]] - M2_100[unigram[ww[1].lower()]] + M2_100[unigram[ww[3].lower()]]
SMw3 = cosine_similarity(Mw3)
max = -10
maxind = -1
for index, i in enumerate(SMw3[len(Mw3)-1], start=0):
if i > max and index < 5030 and uni[index][0] != ww[3].lower():
... | conditional_block | |
lab1e.py | 3.66,
3.68,
3.82,
3.84,
3.88,
3.92,
3.94,
3.94]
#STEP 2 5030 most frequent words stored using uni and unigram
#unigram['example'] returns the index of the tuple ('example', count) in
#the uni list, where count is the unigram count of 'example'.
unigram = dict()
bigram = dict()
... | #instances in rel_words. It counts how many times LSA pick the right word for the analogy.
#(Note: picks the word from the pool of 5030 whose vector is closest in cosine distance to the
#added vectors)
Mw3 = np.zeros(shape=(5031,100)) | random_line_split | |
serializers.py | а в виде int приходит). По ТЗ нам нужно принимать только
целые числа.
Поэтому наследуемся от сериализатора IntegerField и переопределяем первичную валидацию.
Если входные данные str, то возвращаем bad request 400.
"""
def to_internal_value(self, data):
if isinstance(data, int):
r... | if birth_date > current_date:
raise serializers.ValidationError("Birth_date can't be "
"after current date")
return value
def to_representation(self, instance):
"""
Корректируем отображение данных из БД.
m2m отображен... | """
birth_date = value
current_date = datetime.now().date() | random_line_split |
serializers.py | в виде int приходит). По ТЗ нам нужно принимать только
целые числа.
Поэтому наследуемся от сериализатора IntegerField и переопределяем первичную валидацию.
Если входные данные str, то возвращаем bad request 400.
"""
def to_internal_value(self, data):
if isinstance(data, int):
re... |
def save_citizens(citizen_data, new_import):
"""Логика полного сохранения гражданина"""
new_citizen = CitizenInfo(import_id=new_import,
citizen_id=citizen_data.get('citizen_id'),
town=citizen_data.get('town'),
street=ci... | "name": instance.name,
"birth_date": JSON_birth_date,
"gender": instance.gender,
"relatives": relatives_id_list
} | conditional_block |
serializers.py | в виде int приходит). По ТЗ нам нужно принимать только
целые числа.
Поэтому наследуемся от сериализатора IntegerField и переопределяем первичную валидацию.
Если входные данные str, то возвращаем bad request 400.
"""
def to_internal_value(self, data):
if isinstance(data, int):
re... | elatives_id_list.sort()
# Нужный формат дня рождения
JSON_birth_date = datetime.strptime(str(instance.birth_date),
'%Y-%m-%d').strftime('%d.%m.%Y')
# Составляем ответ вручную
return {
"citizen_id": instance.citizen_id,
"... | ражении
r | identifier_name |
serializers.py | в виде int приходит). По ТЗ нам нужно принимать только
целые числа.
Поэтому наследуемся от сериализатора IntegerField и переопределяем первичную валидацию.
Если входные данные str, то возвращаем bad request 400.
"""
def to_internal_value(self, data):
if isinstance(data, int):
re... | """
Сериализатор для POST запроса. Логика сохранения в BulkCitizensSerializer
"""
def run_validation(self, data=empty):
"""
Помимо родительской логики здесь подготовка к общей валидации relatives,
которая будет проходить с данными из глобального
словаря relatives_dict, в... | твенников" его родственника,
# Что бы не проверять по два раза. Сохранению не помешает.
relatives_dict[relative_id].remove(citizen_id)
# Если находим несовпадение, то сразу отдаем 400 BAD_REQUEST
elif citizen_id not in relatives_dict[relative_id]:
... | identifier_body |
server.go | , reader)
return err
}
func (server *Server) putApp(w http.ResponseWriter, r *http.Request) error {
runID := mux.Vars(r)["id"]
err := server.app.PutApp(runID, r.Body, r.ContentLength)
if errors.Is(err, commands.ErrArchiveFormat) {
return newHTTPError(err, http.StatusBadRequest, err.Error())
}
return err
}
fun... | if !created {
err = newHTTPError(err, http.StatusNotFound, fmt.Sprintf("run %v: not found", runID))
logAndReturnError(err, w)
return
}
next.ServeHTTP(w, r)
})
}
func logAndReturnError(err error, w http.ResponseWriter) {
log.Println(err)
err2, ok := err.(clientError)
if !ok {
// TODO: Factor out c... | logAndReturnError(err, w)
return
} | random_line_split |
server.go | (w http.ResponseWriter, r *http.Request) error {
createResult, err := server.app.CreateRun(protocol.CreateRunOptions{APIKey: r.URL.Query().Get("api_key")})
if err != nil {
if errors.Is(err, integrationclient.ErrNotAllowed) {
return newHTTPError(err, http.StatusUnauthorized, err.Error())
}
return err
}
w.H... | createRun | identifier_name | |
server.go | , reader)
return err
}
func (server *Server) putApp(w http.ResponseWriter, r *http.Request) error |
func (server *Server) getCache(w http.ResponseWriter, r *http.Request) error {
runID := mux.Vars(r)["id"]
reader, err := server.app.GetCache(runID)
if err != nil {
// Returns 404 if there is no cache
if errors.Is(err, commands.ErrNotFound) {
return newHTTPError(err, http.StatusNotFound, err.Error())
}
r... | {
runID := mux.Vars(r)["id"]
err := server.app.PutApp(runID, r.Body, r.ContentLength)
if errors.Is(err, commands.ErrArchiveFormat) {
return newHTTPError(err, http.StatusBadRequest, err.Error())
}
return err
} | identifier_body |
server.go | , reader)
return err
}
func (server *Server) putApp(w http.ResponseWriter, r *http.Request) error {
runID := mux.Vars(r)["id"]
err := server.app.PutApp(runID, r.Body, r.ContentLength)
if errors.Is(err, commands.ErrArchiveFormat) {
return newHTTPError(err, http.StatusBadRequest, err.Error())
}
return err
}
fun... |
}
})
}
// Middleware function, which will be called for each request
// TODO: Refactor checkRunCreated method to return an error
func (server *Server) checkRunCreated(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
runID := mux.Vars(r)["id"]
created, e... | {
// TODO: Will this actually work here
logAndReturnError(err, w)
return
} | conditional_block |
saga.ts | import {
call,
cancel,
delay,
fork,
join,
put,
race,
select,
spawn,
takeLeading,
} from 'redux-saga/effects'
import { Task } from '@redux-saga/types'
import { setBackupCompleted } from 'src/account/actions'
import { uploadNameAndPicture } from 'src/account/profileInfo'
import { recoveringFromStoreWi... |
// If the given mnemonic phrase is invalid, spend up to 5 seconds trying to correct it.
// A balance check happens before the phrase is returned, so if the phrase was autocorrected,
// we do not need to check the balance again later in this method.
// If useEmptyWallet is true, skip this step. It only... | {
ValoraAnalytics.track(OnboardingEvents.wallet_import_phrase_invalid, {
wordCount: countMnemonicWords(normalizedPhrase),
invalidWordCount: invalidWords?.length,
})
} | conditional_block |
saga.ts | '
import {
call,
cancel,
delay,
fork,
join,
put,
race,
select,
spawn,
takeLeading,
} from 'redux-saga/effects'
import { Task } from '@redux-saga/types'
import { setBackupCompleted } from 'src/account/actions'
import { uploadNameAndPicture } from 'src/account/profileInfo'
import { recoveringFromStore... | mnemonic = correctedPhrase
checkedBalance = true
} else {
Logger.info(
TAG + '@importBackupPhraseSaga',
`Backup phrase autocorrection ${timeout ? 'timed out' : 'failed'}`
)
ValoraAnalytics.track(OnboardingEvents.wallet_import_phrase_corre... | correctedPhrase: call(attemptBackupPhraseCorrection, normalizedPhrase),
timeout: delay(MNEMONIC_AUTOCORRECT_TIMEOUT),
})
if (correctedPhrase) {
Logger.info(TAG + '@importBackupPhraseSaga', 'Using suggested mnemonic autocorrection') | random_line_split |
agent.py | = use_frozen_net
if net_path is not None:
self.load_net(net_path, use_frozen_net)
else:
self.net = None
self.net_input_placeholder = None
self.sess = None
def act(self, obz, reward, done):
if obz is not None:
log.debug('steering %... | (self, obz, y):
log.debug('getting next action')
if y is None:
log.debug('net out is None')
return self.previous_action or Action()
desired_spin, desired_direction, desired_speed, desired_speed_change, desired_steering, desired_throttle = y[0]
desired_spin = des... | get_next_action | identifier_name |
agent.py | = use_frozen_net
if net_path is not None:
self.load_net(net_path, use_frozen_net)
else:
self.net = None
self.net_input_placeholder = None
self.sess = None
def act(self, obz, reward, done):
if obz is not None:
log.debug('steering %... |
elif 0.67 <= rand < 0.85:
self.random_action_count = 4
self.non_random_action_count = 5
elif 0.85 <= rand < 0.95:
self.random_action_count = 8
self.non_random_action_count = 10
else:
self.random_action_c... | self.random_action_count = 0
self.non_random_action_count = 10 | conditional_block |
agent.py | import glob
import gym
import tensorflow as tf
import numpy as np
import config as c
import deepdrive
from gym_deepdrive.envs.deepdrive_gym_env import Action
from tensorflow_agent.net import Net
from utils import save_hdf5, download
import logs
log = logs.get_log(__name__)
class Agent(object):
def __init__(sel... | import time
from datetime import datetime
import math | random_line_split | |
agent.py | z['cameras'][0]['image'], obz['cameras'][0]['depth'],
# os.path.join(self.sess_dir, str(self.total_obz).zfill(10)))
self.recorded_obz_count += 1
else:
log.debug('Not recording frame')
self.maybe_save()
action = action.as_gym()
retur... | gym_env.close()
agent.close() | identifier_body | |
AddSlotModal.js | import ModalDropdown from 'react-native-modal-dropdown';
import DateTimePickerModal from "react-native-modal-datetime-picker";
import RNFetchBlob from 'rn-fetch-blob';
import Toast from 'react-native-simple-toast';
class AddSlotModal extends React.Component {
state = {
datePickerMode:'',
isDatePickerVisibl... | onBackdropPress={this.props.closeModal}>
<ScrollView style={styles.scrollView}>
<View style={styles.container}>
<View style={styles.sectionHeader}>
<View style={styles.sectionHeading}>
<Text style={styles.sectio... | onSwipe={this.props.closeModal} | random_line_split |
AddSlotModal.js | import ModalDropdown from 'react-native-modal-dropdown';
import DateTimePickerModal from "react-native-modal-datetime-picker";
import RNFetchBlob from 'rn-fetch-blob';
import Toast from 'react-native-simple-toast';
class | extends React.Component {
state = {
datePickerMode:'',
isDatePickerVisible:false,
startTime:'',
endTime:'',
weekDay: '',
isLoading:false,
errors:[]
};
weekDays = ['Mon', 'Tues','Wed','Thur','Fri', 'Sat', 'Sun'];
getCurrentTime = (date) => {
let hours = date.getHour... | AddSlotModal | identifier_name |
Home.js | // import Storage from '../../tools/storage'
import Storage from '../../libs/storage';
import VTouch from '../Live/Refresh';
import Tracker from '../../tracker';
import { browserHistory, hashHistory} from 'react-router';
const history = window.config.hashHistory ? hashHistory : browserHistory
import './home.css';
c... | import { getChannels } from '../../actions/compile';
import Immutable from 'immutable';
import ToolKit from '../../tools/tools' | random_line_split | |
Home.js | .state.index || !Storage.get(Storage.KEYS.HOME_LOCALS.EPISODE_DATA)) ?
// Storage.set(Storage.KEYS.HOME_LOCALS.EPISODE_DATA, newPropsData) : Storage.get(Storage.KEYS.HOME_LOCALS.EPISODE_DATA).length < 40 ?
// Storage.set(Storage.KEYS.HOME_LOCALS.EPISODE_DATA, this.state.mainSource.concat(newPropsData)) : Storag... | 'up';
t | identifier_name | |
Home.js | (Storage.KEYS.HOME_LOCALS.CURRENT_CHANNEL_ID) && Storage.set(Storage.KEYS.HOME_LOCALS.CURRENT_CHANNEL_ID, userShowLists[0].id);
if (!Storage.s_get(Storage.KEYS.PLAY_PAGE_KEY) && !Storage.s_get(Storage.KEYS.LIVE_PAGE_KEY) && !Storage.s_get(Storage.KEYS.ME_PAGE_KEY) && !Storage.s_get(Storage.KEYS.SEARCH_PAGE_KEY) && ... | his.lastDownKey : this.end;
this.context.store.dispatch(getHomeList(this.state.index, firstDownKey, lastDownKey, this.handle));
Tracker.track('send', 'event', 'app', 'pull', 'down', 1);
console.log('=========下拉刷新==========');
}
}
navHandleClick(i, index) {
//index表示当前元素在nav中的index位数
let linkageKey;
... | identifier_body | |
Home.js | _PAGE_KEY) || Storage.s_get(Storage.KEYS.LIVE_PAGE_KEY) || Storage.s_get(Storage.KEYS.ME_PAGE_KEY)) && this.context.store.dispatch(clearHomeData());
}
componentDidMount() {
//pull-down init
this.Touch = new VTouch(this.refs.homeList, "y", this.showRefresh, this.pullUp)
this.Touch.init()
document.addEventL... | .s_remove(Storage.KEYS.HOME_SCROLL_KEY);
}
if ( nextProps.getHomeData.data && nextProps.getHomeData.data.data.length > 0) {
this.refreshKey = false;
let newPropsObj = nextProps.getHomeData.data;
let newPropsData = newPropsObj.data;
this.handle === 'up' ? this.isUpLoading = newPropsObj.loadMore : this.i... | = Storage.s_get(Storage.KEYS.HOME_SCROLL_KEY)
this.Touch.init();
Storage | conditional_block |
word_module_trials07.py | currentPage_font_count
currentPage_font_count = 0
def my_add_paragraph(text, bold_or_not,change_font, underlined, fontSize=None):
#global document
p = document.add_paragraph()
run = p.add_run(text)
if(bold_or_not):
run.bold=True
if(change_font):
font = run.font
font.size = Pt(fontSize)
if(u... | #write the multiple choice questions
myAddPageBreak()
for x in range(len(question_header)):
| random_line_split | |
word_module_trials07.py | was able to draw the attention of the salesmen who thought him rich and likely to make heavy purchases. He was shown the superior varieties of suit lengths and sarees. But after casually examining them, he kept moving to the next section, where readymade goods were being sold and further on to another section. By then... |
row = table_merge.rows[3].cells
row[0].text = '\nID: '
paragraphs = row[0].paragraphs
for paragraph in paragraphs:
for run in paragraph.runs:
font = run.font
font.size= Pt(14)
a = table_merge.cell(0, 0)
b = table_merge.cell(5, 1)
A = a.merge(b)
#add notes
my_add_paragraph("\n\n\t\t\t\tImpor... | font = run.font
font.size= Pt(14) | conditional_block |
word_module_trials07.py | ():
#we get the following list from DB test ----------------------------------------------
question_header = ["there is very little .... from the factory, so it's nor bad for the environment", \
"here is your ticket for the museum , the ticket is ....... for two days." , \
... | get_mcq | identifier_name | |
word_module_trials07.py |
def get_choices():
#we get the following list from DB test ----------------------------------------------
#split choices using ",,__,,"
question_choices = ["waste,,__,,wave,,__,,wildlife,,__,,weight" , "virtual,,__,,valid,,__,,vinegar,,__,,vapour" , \
"child,,__,,childhood,,__,,ch... | question_header = ["there is very little .... from the factory, so it's nor bad for the environment", \
"here is your ticket for the museum , the ticket is ....... for two days." , \
"ola spent most of her ..... living on a farm , but she moved to cairo when she was sixteen",\
... | identifier_body | |
displayTopology.js | 884567890','9884567890','9884567890','9884567890'],
apstatus :['1','1','0','0','1','1','1','0']
}
*/
var apsdata = newdata;
DATA.count = apsdata.apcount;
DATA.width = (apsdata.apcount == 0?230:apsdata.apcount*230);
/* 自适应外框*/
var $div = $('<div id="ap_page_cover_all"></div>');
$d... | 'left' :'308px'
})
aparr.push($noap);
}
*/
return aparr;
}
function getAPDom(index,ip,ssid,ssid5,cnl,cnl5,serial,apstatus,clienCt,mac){
var $ap = $('<div class="ap_signle_cover_div"></div>');
$ap.css({
// 'opacity':'0.2',
'transition':'all 0.3s',
'color' :'#000000'... | random_line_split | |
displayTopology.js | :20px;padding:3px 0">信道(2.4G)</td><td> :'+cnl+'</td></tr>'))+
(ssid == ''?'':('<tr><td style="width:20px;padding:3px 0">用户(2.4G)</td><td> :'+cnum24+'</td></tr>'))+
(ssid5 == ''?'':('<tr><td style="width:20px;padding:3px 0">SSID(5G)</td><td> :'+ssid5+'</td></tr>'))+
(ssid5 == ''?'':('<tr><td styl... |
};
va | identifier_name | |
displayTopology.js | 884567890','9884567890','9884567890','9884567890'],
apstatus :['1','1','0','0','1','1','1','0']
}
*/
var apsdata = newdata;
DATA.count = apsdata.apcount;
DATA.width = (apsdata.apcount == 0?230:apsdata.apcount*230);
/* 自适应外框*/
var $div = $('<div id="ap_page_cover_all"></div>');
$d... | lse if(apsdata.apcount == 3){
aparr[0].css({
top:'250px',
left:'45px'
});
aparr[1].css({
top:'250px',
left:'300px'
});
aparr[2].css({
top:'250px',
left:'565px'
});
}else if(apsdata.apcount == 2){
aparr[0].css({
top:'250px',
left:'100px'
});
... | .css({
top:'250px',
left:'10px'
});
aparr[1].css({
top:'250px',
left:'215px'
});
aparr[2].css({
top:'250px',
left:'420px'
});
aparr[3].css({
top:'250px',
left:'630px'
});
}e | conditional_block |
displayTopology.js | :3px 0">信道(5G)</td><td> :'+cnl5+'</td></tr>'))+
(ssid5 == ''?'':('<tr><td style="width:20px;padding:3px 0">用户(5G)</td><td> :'+num5+'</td></tr>'))+
'<tr><td style="width:20px;padding:0 0" colspan="2" > <a class="u-inputLink link-forUser" data-mac="'+mac+'">查看在线用户</a></td></tr>'+
'</tbody>'+
... | require('Modal');
var modalObj = Modal.getModalObj(modallist);
var TableContainer = require('P_template/common/TableContainer');
var conhtml = TableContainer.getHTML({}),
$tableCon = $(conhtml);
modalObj.insert($tableCon);
var headData = {
"btns" : []
};
// 表格配置数据
... | identifier_body | |
step3-twist.py | init_para_list.append([np.round(a,1),np.round(b,1),theta,A1,A2,np.round(c[0],1),np.round(c[1],1),np.round(c[2],1),'NotYet'])
df_init_params = pd.DataFrame(np.array(init_para_list),columns = ['a','b','theta','A1','A2','cx','cy','cz','status'])
df_init_params.to_csv(init_params_csv... | nit_params.csvとstep3-twist.csvがauto_dirの下にある
"""
init_params_csv=os.path.join(auto_dir, 'step3-twist_init_params.csv')
df_init_params = pd.read_csv(init_params_csv)
df_cur = pd.read_csv(os.path.join(auto_dir, 'step3-twist.csv'))
df_init_params_inprogress = df_init_params[df_init_params['status'... | (df_E, params_dict)
df_E_filtered = df_E_filtered.reset_index(drop=True)
try:
status = get_values_from_df(df_E_filtered,0,'status')
return status=='Done'
except KeyError:
return False
def get_params_dict(auto_dir, num_nodes, fixed_param_keys, opt_param_keys, monomer_name):
... | identifier_body |
step3-twist.py | init_para_list.append([np.round(a,1),np.round(b,1),theta,A1,A2,np.round(c[0],1),np.round(c[1],1),np.round(c[2],1),'NotYet'])
df_init_params = pd.DataFrame(np.array(init_para_list),columns = ['a','b','theta','A1','A2','cx','cy','cz','status'])
df_init_params.to_csv(init_params_csv,index=Fals... | param_keys].to_dict()
fixed_params_dict = df_init_params.loc[index,fixed_param_keys].to_dict()
isDone, opt_params_dict = get_opt_params_dict(df_cur, init_params_dict,fixed_params_dict, monomer_name)
if isDone:
# df_init_paramsのstatusをupdate
df_init_params = update_va... | n_df(df_init_params,index,'status','InProgress')
df_init_params.to_csv(init_params_csv,index=False)
params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()
return params_dict
for index in df_init_params.index:
df_init_params = pd.read_csv(in... | conditional_block |
step3-twist.py | ,Eip2,Eit1,Eit2=map(float,E_list)
Eit3 = Eit2; Eit4 = Eit1
try:
Ep, Et = df_step2[(df_step2['A1']==A1)&(df_step2['A2']==A2)&(df_step2['theta']==theta)&(df_step2['a']==a)&(df_step2['b']==b)][['E_p','E_t']].values[0]
except IndexError:
inner_params_... | if type(v) | identifier_name | |
step3-twist.py | init_para_list.append([np.round(a,1),np.round(b,1),theta,A1,A2,np.round(c[0],1),np.round(c[1],1),np.round(c[2],1),'NotYet'])
df_init_params = pd.DataFrame(np.array(init_para_list),columns = ['a','b','theta','A1','A2','cx','cy','cz','status'])
df_init_params.to_csv(init_params_csv... | for index in df_init_params.index:
df_init_params = pd.read_csv(init_params_csv)
init_params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()
fixed_params_dict = df_init_params.loc[index,fixed_param_keys].to_dict()
isDone, opt_params_dict = get_opt_param... | df_init_params = update_value_in_df(df_init_params,index,'status','InProgress')
df_init_params.to_csv(init_params_csv,index=False)
params_dict = df_init_params.loc[index,fixed_param_keys+opt_param_keys].to_dict()
return params_dict
| random_line_split |
lib.rs |
}
impl Default for PickState {
fn default() -> Self {
PickState {
cursor_event_reader: EventReader::default(),
ordered_pick_list: Vec::new(),
topmost_pick: None,
}
}
}
/// Holds the entity associated with a mesh as well as it's computed intersection from a ... | {
&self.topmost_pick
} | identifier_body | |
lib.rs | Some(pick_depth) = pick_state.topmost_pick {
if let Ok(mut top_mesh) = query.get_mut::<SelectablePickMesh>(pick_depth.entity) {
top_mesh.selected = true;
}
}
}
}
/// Casts a ray into the scene from the cursor position, tracking pickable meshes that are hit.
fn pick_... | fn triangle_behind_cam(triangle: [Vec3; 3]) -> bool { | random_line_split | |
lib.rs | (&self) -> &Vec<PickIntersection> {
&self.ordered_pick_list
}
pub fn top(&self) -> &Option<PickIntersection> {
&self.topmost_pick
}
}
impl Default for PickState {
fn default() -> Self {
PickState {
cursor_event_reader: EventReader::default(),
ordered_pick... | list | identifier_name | |
lib.rs | /// Marks an entity as pickable
#[derive(Debug)]
pub struct PickableMesh {
camera_entity: Entity,
bounding_sphere: Option<BoundSphere>,
pick_coord_ndc: Option<Vec3>,
}
impl PickableMesh {
pub fn new(camera_entity: Entity) -> Self {
PickableMesh {
camera_entity,
bounding_... | else {
*current_color = initial_color;
}
}
// Query highlightable entities that have changed
for (mut highlightable, _pickable, material_handle, entity) in &mut query_picked.iter() {
let current_color = &mut materials.get_mut(material_handle).unwrap().albedo;
let initia... | {
*current_color = highlight_params.selection_color;
} | conditional_block |
lib.rs |
}
/// A per-relay-parent job for the provisioning subsystem.
pub struct ProvisioningJob {
relay_parent: Hash,
receiver: mpsc::Receiver<ProvisionerMessage>,
backed_candidates: Vec<CandidateReceipt>,
signed_bitfields: Vec<SignedAvailabilityBitfield>,
metrics: Metrics,
inherent_after: InherentAfter,
awaiting_inhe... | {
match *self {
InherentAfter::Ready => {
// Make sure we never end the returned future.
// This is required because the `select!` that calls this future will end in a busy loop.
futures::pending!()
},
InherentAfter::Wait(ref mut d) => {
d.await;
*self = InherentAfter::Ready;
},
}
} | identifier_body | |
lib.rs | is a set of
/// non-conflicting candidates and the appropriate bitfields. Non-conflicting
/// means that there are never two distinct parachain candidates included for
/// the same parachain and that new parachain candidates cannot be included
/// until the previous one either gets declared available or expired.
///
/... | ) -> bool {
let mut availability = availability.clone();
let availability_len = availability.len();
| random_line_split | |
lib.rs | source] oneshot::Canceled),
#[error(transparent)]
ChainApi(#[from] ChainApiError),
#[error(transparent)]
Runtime(#[from] RuntimeApiError),
#[error("failed to send message to ChainAPI")]
ChainApiMessageSend(#[source] mpsc::SendError),
#[error("failed to send message to CandidateBacking to get backed candidate... | (
relay_parent: Hash,
metrics: Metrics,
receiver: mpsc::Receiver<ProvisionerMessage>,
) -> Self {
Self {
relay_parent,
receiver,
backed_candidates: Vec::new(),
signed_bitfields: Vec::new(),
metrics,
inherent_after: InherentAfter::new_from_now(),
awaiting_inherent: Vec::new(),
}
}
asyn... | new | identifier_name |
lib.rs | ] oneshot::Canceled),
#[error(transparent)]
ChainApi(#[from] ChainApiError),
#[error(transparent)]
Runtime(#[from] RuntimeApiError),
#[error("failed to send message to ChainAPI")]
ChainApiMessageSend(#[source] mpsc::SendError),
#[error("failed to send message to CandidateBacking to get backed candidates")]
... |
}
#[tracing::instrument(level = "trace", skip(self), fields(subsystem = LOG_TARGET))]
fn note_provisionable_data(&mut self, span: &jaeger::Span, provisionable_data: ProvisionableData) {
match provisionable_data {
ProvisionableData::Bitfield(_, signed_bitfield) => {
self.signed_bitfields.push(signed_bitfie... | {
self.metrics.on_inherent_data_request(Ok(()));
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.