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
demo.py
#!/usr/bin/env python ######################################## # Mario Rosasco, 2017 ######################################## from Model import * from Visualization import * from scipy.optimize import minimize from allensdk.ephys.ephys_features import detect_putative_spikes import numpy as np import sys ...
(modelID): print "Loading parameters for model", modelID selection=raw_input('Would you like to download NWB data for model? [Y/N] ') if selection[0] == 'y' or selection[0] == 'Y': currModel = Model(modelID, cache_stim = True) if selection[0] == 'n' or selection[0] == 'N': currMo...
main
identifier_name
demo.py
#!/usr/bin/env python ######################################## # Mario Rosasco, 2017 ######################################## from Model import * from Visualization import * from scipy.optimize import minimize from allensdk.ephys.ephys_features import detect_putative_spikes import numpy as np import sys ...
# if at a branch point or an end of a section, set up a vector to monitor that segment's voltage type = compartmentNames[n['type']] sec_index = sectionIndices[n['type']] if not (len(morphology.children_of(n)) == 1): #either branch pt or end sec_nam...
tempCol[offset+col_i] = cval col_i += 1
conditional_block
fs.rs
use core_collections::borrow::ToOwned; use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom}; use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use mem; use path::{PathBuf, Path}; use string::String; use sys_common::AsInner; use vec::Vec; use syscall::{open, dup, close, fpath, fstat, f...
} remove_dir(path) } /// Removes a file from the filesystem pub fn remove_file<P: AsRef<Path>>(path: P) -> Result<()> { let path_str = path.as_ref().as_os_str().as_inner(); unlink(path_str).and(Ok(())).map_err(|x| Error::from_sys(x)) }
{ try!(remove_file(&child.path())); }
conditional_block
fs.rs
use core_collections::borrow::ToOwned; use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom}; use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use mem; use path::{PathBuf, Path}; use string::String; use sys_common::AsInner; use vec::Vec; use syscall::{open, dup, close, fpath, fstat, f...
self.mode = mode as u16; } fn from_mode(mode: u32) -> Self { Permissions { mode: mode as u16 } } } pub struct DirEntry { path: PathBuf, } impl DirEntry { pub fn file_name(&self) -> &Path { unsafe { mem::transmute(self.path.file_name().unwrap().to_str()....
random_line_split
fs.rs
use core_collections::borrow::ToOwned; use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom}; use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use mem; use path::{PathBuf, Path}; use string::String; use sys_common::AsInner; use vec::Vec; use syscall::{open, dup, close, fpath, fstat, f...
} impl FromRawFd for File { unsafe fn from_raw_fd(fd: RawFd) -> Self { File { fd: fd } } } impl IntoRawFd for File { fn into_raw_fd(self) -> RawFd { let fd = self.fd; mem::forget(self); fd } } impl Read for File { fn read(&mut self, buf: &mut [...
{ self.fd }
identifier_body
fs.rs
use core_collections::borrow::ToOwned; use io::{self, BufRead, BufReader, Read, Error, Result, Write, Seek, SeekFrom}; use os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use mem; use path::{PathBuf, Path}; use string::String; use sys_common::AsInner; use vec::Vec; use syscall::{open, dup, close, fpath, fstat, f...
<P: AsRef<Path>>(path: P) -> Result<()> { if let Some(parent) = path.as_ref().parent() { try!(create_dir_all(&parent)); } if let Err(_err) = metadata(&path) { try!(create_dir(&path)); } Ok(()) } /// Copy the contents of one file to another pub fn copy<P: AsRef<Path>, Q: AsRef<Path>>...
create_dir_all
identifier_name
dnp3.go
// Copyright 2019, The GoPacket Authors, All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. // //****************************************************************************** package layers import ( "encod...
case FirstOfMulti01: return false case NotFirstNotLast00: return false case FinalFrame10: return true case OneFrame11: return true } return false } // Contains tells whether a contains x. // func (d *DNP3) contains(a []byte, x int) bool { // for _, n := range a { // if x == n { // return true // ...
var FinalFrame10 byte = 0x80 var OneFrame11 byte = 0xC0 TpFinFir := bytesRead[10] & 0xC0 switch TpFinFir {
random_line_split
dnp3.go
// Copyright 2019, The GoPacket Authors, All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. // //****************************************************************************** package layers import ( "encod...
() gopacket.LayerType { return gopacket.LayerTypePayload } // Payload returns nil, since TLS encrypted payload is inside TLSAppDataRecord func (d *DNP3) Payload() []byte { return nil } func appObject(bytesRead []byte) { object := bytesRead[22:] // indexSize := uint(object[2] & 0x70 >> 4) // QualifierCode := ui...
NextLayerType
identifier_name
dnp3.go
// Copyright 2019, The GoPacket Authors, All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. // //****************************************************************************** package layers import ( "encod...
func (d *DNP3) DecodeFromBytes(data []byte, df gopacket.DecodeFeedback) error { // If the data block is too short to be a DNP3 layer, then return an error. if len(data) < 10 { df.SetTruncated() return errDNP3PacketTooShort } d.linkLayer(data) d.transportLayer(data) d.applicationLayer(data) return nil } ...
{ return d.restOfData }
identifier_body
dnp3.go
// Copyright 2019, The GoPacket Authors, All rights reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the LICENSE file in the root of the source // tree. // //****************************************************************************** package layers import ( "encod...
ctlFUNC = ctlFUNC + " (" + ctlFUNCCODE + ")" d.DNP3DataLinkLayer.Control.FUNC = ctlFUNC // TODO: make sure 0 to 65535 destination := fmt.Sprintf("%x%x", data[5], data[4]) destinationInt, _ := strconv.Atoi(destination) d.DNP3DataLinkLayer.Destination = destinationInt // TODO: make sure 0 to 65535 source := f...
{ ctlFUNC = PfCodes[FUNCCODE] }
conditional_block
config.js
'use strict'; // load modules const path = require('path'); const { flow, reduce } = require('lodash'); const { map, max } = require('lodash/fp'); const moment = require('moment-timezone'); const PUSH_NOTIFICATION_STAGING_URL = ''; // TODO(michael.kuk@ubnt.com) const PUSH_NOTIFICATION_PRODUCTION_URL = ''; // TODO(mic...
publicDir: './public', imagesUrl: 'site-images', imagesDir: './public/site-images', // images directory is mapped to /data/images in docker maxBytes: 20000000, // 20MB maxResolution: 10000 ** 2, // limit in pixels thumb: { width: 700, // px height: 700, // px }, }; internals.Config.nmsBackup = { ...
random_line_split
packet.go
package minq import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/hex" "fmt" ) // Encode a QUIC packet. /* Long header 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+ |1| Type (7) | +-+-+-+-+-+-+-+-+-+-+-+-+-...
buf = dup(buf[:pat.length]) buf[0] &= ^pat.mask return uintDecodeIntBuf(buf), pat.length, nil }
{ return 0, 0, fmt.Errorf("Buffer too short for packet number (%v < %v)", len(buf), pat.length) }
conditional_block
packet.go
package minq import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/hex" "fmt" ) // Encode a QUIC packet. /* Long header 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+ |1| Type (7) | +-+-+-+-+-+-+-+-+-+-+-+-+-...
logf(logTypePacket, "Packet too short") return nil } // Now compute the offset sample_offset := hdrlen + 4 if sample_offset+sample_length > len(p) { sample_offset = len(p) - sample_length } sample := p[sample_offset : sample_offset+sample_length] logf(logTypeTrace, "PNE sample_offset=%d sample=%x", sampl...
sample_length := 16 if sample_length > len(p)-(hdrlen+1) {
random_line_split
packet.go
package minq import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/hex" "fmt" ) // Encode a QUIC packet. /* Long header 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+ |1| Type (7) | +-+-+-+-+-+-+-+-+-+-+-+-+-...
(versions []VersionNumber) *versionNegotiationPacket { var buf bytes.Buffer for _, v := range versions { buf.Write(encodeArgs(v)) } return &versionNegotiationPacket{buf.Bytes()} } /* We don't use these. func encodePacket(c ConnectionState, aead Aead, p *Packet) ([]byte, error) { hdr, err := encode(&p.packetH...
newVersionNegotiationPacket
identifier_name
packet.go
package minq import ( "bytes" "crypto/aes" "crypto/cipher" "encoding/hex" "fmt" ) // Encode a QUIC packet. /* Long header 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+ |1| Type (7) | +-+-+-+-+-+-+-+-+-+-+-+-+-...
func (pt packetType) String() string { switch pt { case packetTypeInitial: return "Initial" case packetTypeRetry: return "Retry" case packetTypeHandshake: return "Handshake" case packetType0RTTProtected: return "0-RTT" case packetTypeProtectedShort: return "1-RTT" default: return fmt.Sprintf("%x", ...
{ if !pt.isLongHeader() { return true } switch pt & 0x7f { case packetTypeInitial, packetTypeHandshake, packetTypeRetry: return false } return true }
identifier_body
TCP_echo_server.py
import asyncio import hashlib import re import os import random import json import ssl import sqlite3 import concurrent.futures from config.config import * from xmlrpc.server import SimpleXMLRPCServer user_list = {} # 存储已连接上的用户 server_list = {} rules = [] def create_sqlite_db(): con = sqlite3.connect("user.db")...
identifier_body
TCP_echo_server.py
import asyncio import hashlib import re import os import random import json import ssl import sqlite3 import concurrent.futures from config.config import * from xmlrpc.server import SimpleXMLRPCServer user_list = {} # 存储已连接上的用户 server_list = {} rules = [] def create_sqlite_db(): con = sqlite3.connect("user.db")...
print('正在请求:' + str(client_addr) + '请求目的ip:' + str(dest_ip)) find_dest = await connect_dest_server(dest_ip, reader, writer, l_reader, l_writer) if find_dest: config_rule['ident'] = 'hi' config_rule_json = json.dumps(config_rule) writer.write(config_rule_jso...
random_line_split
TCP_echo_server.py
import asyncio import hashlib import re import os import random import json import ssl import sqlite3 import concurrent.futures from config.config import * from xmlrpc.server import SimpleXMLRPCServer user_list = {} # 存储已连接上的用户 server_list = {} rules = [] def create_sqlite_db(): con = sqlite3.connect("user.db")...
account['password']) cur.execute(sql) search_result = cur.fetchall() except sqlite3.OperationalError: search_result = False except ssl.SSLError: search_result = False if search_result: print('\n用户' + account['usern...
identifier_name
TCP_echo_server.py
import asyncio import hashlib import re import os import random import json import ssl import sqlite3 import concurrent.futures from config.config import * from xmlrpc.server import SimpleXMLRPCServer user_list = {} # 存储已连接上的用户 server_list = {} rules = [] def create_sqlite_db(): con = sqlite3.connect("user.db")...
riter.close() break else: pass s_writer.write(data) await s_writer.drain() print(str(client_addr) + '正在给' + str(server_addr) + '发送信息:' + data.decode()) try: re_msg = aw...
print('用户已断开连接:', client_addr) writer.close() s_w
conditional_block
localization.rs
// Copyright 2019 The xi-editor 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 ag...
} } /* //// impl<T> std::fmt::Debug for ArgSource<T> { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "Arg Resolver {:p}", self.0) } } /// Helper to impl display for slices of displayable things. struct PrintLocales<'a, T>(&'a [T]); imp...
{ false }
conditional_block
localization.rs
// Copyright 2019 The xi-editor 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 ag...
( mut self, key: &'static str, f: fn(&T, &Env) -> ArgValue, //// ////f: impl Fn(&T, &Env) -> FluentValue<'static> + 'static, ) -> Self { self.args .get_or_insert(Vec::new()) .push((key, ArgSource(f))) .expect("with arg failed"); //// ...
with_arg
identifier_name
localization.rs
// Copyright 2019 The xi-editor 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 ag...
} } impl<T: Data> LocalizedString<T> { /// Add a named argument and a corresponding [`ArgClosure`]. This closure /// is a function that will return a value for the given key from the current /// environment and data. /// /// [`ArgClosure`]: type.ArgClosure.html pub fn with_arg( mut ...
*/ ////
random_line_split
localization.rs
// Copyright 2019 The xi-editor 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 ag...
}
{ // TODO Ok(()) }
identifier_body
cardano_wallet.d.ts
/* tslint:disable */ /** * @param {Entropy} entropy * @param {Uint8Array} iv * @param {string} password * @returns {any} */ export function paper_wallet_scramble(entropy: Entropy, iv: Uint8Array, password: string): any; /** * @param {Uint8Array} paper * @param {string} password * @returns {Entropy} */ export fun...
{ free(): void; static from_hex(hex: string): PublicRedeemKey; to_hex(): string; verify(data: Uint8Array, signature: RedeemSignature): boolean; address(settings: BlockchainSettings): Address; } /** */ export class RedeemSignature { free(): void; static from_hex(hex: string): RedeemSignature; to_hex(): ...
PublicRedeemKey
identifier_name
cardano_wallet.d.ts
/* tslint:disable */ /** * @param {Entropy} entropy * @param {Uint8Array} iv * @param {string} password * @returns {any} */ export function paper_wallet_scramble(entropy: Entropy, iv: Uint8Array, password: string): any; /** * @param {Uint8Array} paper * @param {string} password * @returns {Entropy} */ export fun...
export class Entropy { free(): void; static from_english_mnemonics(mnemonics: string): Entropy; to_english_mnemonics(): string; to_array(): any; } /** */ export class InputSelectionBuilder { free(): void; static first_match_first(): InputSelectionBuilder; static largest_first(): InputSelectionBuilder; s...
*/
random_line_split
Upload.js
const UI = window.classes.UI; const AppIcon = require('../../icons/AppIcon.js'); const Button = window.classes.Button; const UIInput = window.classes.UIInput; const Layouter = require('../utils/Layouter.js'); class Upload extends UI { constructor(params) { super(params); this._components.CloseIcon = this.newC(A...
} this.$('#uploadPreviewAlbum').style.height = this._layouter._height+'px'; this.initScrollBarOn(this.$('.uploadPreview')); } swapItems(id1, id2) { if (id1 == id2) { return; } id1 = id1.split('uploadPreviewItem_').join(''); id2 = id2.split('uploadPreviewItem_').join(''); let toMove1 = null; ...
{ el.style.left = '' + file.pos.left + 'px'; el.style.top = '' + file.pos.top + 'px'; el.style.width = '' + file.pos.width + 'px'; el.style.height = '' + file.pos.height + 'px'; }
conditional_block
Upload.js
const UI = window.classes.UI; const AppIcon = require('../../icons/AppIcon.js'); const Button = window.classes.Button; const UIInput = window.classes.UIInput; const Layouter = require('../utils/Layouter.js'); class Upload extends UI { constructor(params) { super(params); this._components.CloseIcon = this.newC(A...
let title = 'Send '+( (this._files.length > 1) ? this._files.length : '' ) + ' ' + suffix[this._files[0].type] + ( (this._files.length > 1) ? 's' : '' ); this.$('.uploadTitle').innerHTML = title; } onAlbumClick(e) { const base = this.$(); let closest = event.target.closest('.upiRemove'); if (closest && bas...
};
random_line_split
Upload.js
const UI = window.classes.UI; const AppIcon = require('../../icons/AppIcon.js'); const Button = window.classes.Button; const UIInput = window.classes.UIInput; const Layouter = require('../utils/Layouter.js'); class Upload extends UI { constructor(params) { super(params); this._components.CloseIcon = this.newC(A...
() { this.$('#uploadTop').style.display = 'block'; this.$('.popupOverlay').classList.add('active'); this.loaded(); this.initScrollBarOn(this.$('.uploadPreview')); } hide() { this.$('.popupOverlay').classList.remove('active'); this.$('.popupOverlay').classList.add('fading'); setTimeout(()=>{ this.$('...
show
identifier_name
image_utils.py
# coding=utf-8 # Copyright 2019 The Tensor2Tensor 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...
class Image2TextProblem(ImageProblem): """Base class for image-to-text problems.""" @property def is_character_level(self): raise NotImplementedError() @property def vocab_problem(self): raise NotImplementedError() # Not needed if self.is_character_level. @property def target_space_id(self)...
yield { "image/encoded": [enc_image], "image/format": ["png"], "image/class/label": [int(label)], "image/height": [height], "image/width": [width] }
conditional_block
image_utils.py
# coding=utf-8 # Copyright 2019 The Tensor2Tensor 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...
(self): raise NotImplementedError() @property def train_shards(self): raise NotImplementedError() @property def dev_shards(self): raise NotImplementedError() def generator(self, data_dir, tmp_dir, is_training): raise NotImplementedError() def example_reading_spec(self): label_key = "...
target_space_id
identifier_name
image_utils.py
# coding=utf-8 # Copyright 2019 The Tensor2Tensor 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...
assumes VALID padding, so the original image's height must be divisible by each resolution's height to return the exact resolution size. num_channels: Number of channels in image. Returns: List of Tensors, one for each resolution with shape given by [resolutions[i], resolutions[i], num_channe...
image: Tensor of shape [height, height, num_channels]. resolutions: List of heights that image's height is resized to. The function
random_line_split
image_utils.py
# coding=utf-8 # Copyright 2019 The Tensor2Tensor 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...
def image_generator(images, labels): """Generator for images that takes image and labels lists and creates pngs. Args: images: list of images given as [width x height x channels] numpy arrays. labels: list of ints, same length as images. Yields: A dictionary representing the images with the follo...
"""Yield images encoded as pngs.""" if tf.executing_eagerly(): for image in images: yield tf.image.encode_png(image).numpy() else: (height, width, channels) = images[0].shape with tf.Graph().as_default(): image_t = tf.placeholder(dtype=tf.uint8, shape=(height, width, channels)) encoded...
identifier_body
congestion.go
/* Package minq is a minimal implementation of QUIC, as documented at https://quicwg.github.io/. Minq partly implements draft-04. */ package minq import ( "math" "time" // "fmt" ) // congestion control related constants const ( kDefaultMss = 1460 // bytes kInitalWindow = 10 * kDefaultMss kMinim...
} else { rttDelta := cc.smoothedRtt - latestRtt if rttDelta < 0 { rttDelta = -rttDelta } cc.rttVar = time.Duration(int64(cc.rttVar)*3/4 + int64(rttDelta)*1/4) cc.smoothedRtt = time.Duration(int64(cc.smoothedRtt)*7/8 + int64(latestRtt)*1/8) } cc.conn.log(logTypeCongestion, "New RTT estimate: %v, variance...
random_line_split
congestion.go
/* Package minq is a minimal implementation of QUIC, as documented at https://quicwg.github.io/. Minq partly implements draft-04. */ package minq import ( "math" "time" // "fmt" ) // congestion control related constants const ( kDefaultMss = 1460 // bytes kInitalWindow = 10 * kDefaultMss kMinim...
/* * draft-ietf-quic-recovery congestion controller */ type CongestionControllerIetf struct { // Congestion control related bytesInFlight int congestionWindow int endOfRecovery uint64 sstresh int // Loss detection related lossDetectionAlarm int //TODO(ekr@rtfm.com) set this to the right ty...
{ return kMinRTOTimeout }
identifier_body
congestion.go
/* Package minq is a minimal implementation of QUIC, as documented at https://quicwg.github.io/. Minq partly implements draft-04. */ package minq import ( "math" "time" // "fmt" ) // congestion control related constants const ( kDefaultMss = 1460 // bytes kInitalWindow = 10 * kDefaultMss kMinim...
() { //TODO(ekr@rtfm.com) } func (cc *CongestionControllerIetf) detectLostPackets() { var lostPackets []packetEntry //TODO(ekr@rtfm.com) implement loss detection different from reorderingThreshold for _, packet := range cc.sentPackets { if (cc.largestAckedPacket > packet.pn) && (cc.largestAckedPacket-packet.p...
onLossDetectionAlarm
identifier_name
congestion.go
/* Package minq is a minimal implementation of QUIC, as documented at https://quicwg.github.io/. Minq partly implements draft-04. */ package minq import ( "math" "time" // "fmt" ) // congestion control related constants const ( kDefaultMss = 1460 // bytes kInitalWindow = 10 * kDefaultMss kMinim...
else { rttDelta := cc.smoothedRtt - latestRtt if rttDelta < 0 { rttDelta = -rttDelta } cc.rttVar = time.Duration(int64(cc.rttVar)*3/4 + int64(rttDelta)*1/4) cc.smoothedRtt = time.Duration(int64(cc.smoothedRtt)*7/8 + int64(latestRtt)*1/8) } cc.conn.log(logTypeCongestion, "New RTT estimate: %v, variance: ...
{ cc.smoothedRtt = latestRtt cc.rttVar = time.Duration(int64(latestRtt) / 2) }
conditional_block
Leanote4MD.py
#!/usr/bin/env python #encoding: utf8 # # author: goodbest <lovegoodbest@gmail.com> # github: github.com/goodbest import requests import json import os import sys from datetime import datetime import dateutil.parser from dateutil import tz from PIL import Image from StringIO import StringIO from requests_toolbelt imp...
def getNoteDetail(noteId): param = { 'noteId': noteId, } return req_get('note/getNoteAndContent', param) def getImage(fileId): param = { 'fileId': fileId, } return req_get('file/getImage', param, type = 'image') def addNotebook(title='Import', parentId='', seq=-1): param ...
return req_get('note/getNotes', param) #ret type.NoteContent
random_line_split
Leanote4MD.py
#!/usr/bin/env python #encoding: utf8 # # author: goodbest <lovegoodbest@gmail.com> # github: github.com/goodbest import requests import json import os import sys from datetime import datetime import dateutil.parser from dateutil import tz from PIL import Image from StringIO import StringIO from requests_toolbelt imp...
if not meta_flag: file_content = file_meta file_meta = '' if meta_flag: meta = yaml.load(file_meta) else: meta = {} return file_content, meta def saveToFile(notes, noteBooks, path = '.'): unique_noteTitle = set() for note in not...
if meta_flag: file_content += line else: if line.find('---')>-1: meta_flag = True else: file_meta += line #print meta
conditional_block
Leanote4MD.py
#!/usr/bin/env python #encoding: utf8 # # author: goodbest <lovegoodbest@gmail.com> # github: github.com/goodbest import requests import json import os import sys from datetime import datetime import dateutil.parser from dateutil import tz from PIL import Image from StringIO import StringIO from requests_toolbelt imp...
def addNote(NotebookId, Title, Content, Tags=[], IsMarkdown = True, Abstract= '', Files=[]): param = { 'NotebookId': NotebookId, 'Title': Title, 'Content': Content, 'Tags[]': Tags, 'IsMarkdown': IsMarkdown, 'Abstract': Abstract, #'Files' : seq } ret...
param = { 'title': title, 'parentNotebookId': parentId, 'seq' : seq } return req_post('notebook/addNotebook', param)
identifier_body
Leanote4MD.py
#!/usr/bin/env python #encoding: utf8 # # author: goodbest <lovegoodbest@gmail.com> # github: github.com/goodbest import requests import json import os import sys from datetime import datetime import dateutil.parser from dateutil import tz from PIL import Image from StringIO import StringIO from requests_toolbelt imp...
(fileId): param = { 'fileId': fileId, } return req_get('file/getImage', param, type = 'image') def addNotebook(title='Import', parentId='', seq=-1): param = { 'title': title, 'parentNotebookId': parentId, 'seq' : seq } return req_post('notebook/addNotebook', par...
getImage
identifier_name
AddDoctorForm.js
import { ToastProvider, useToasts } from 'react-toast-notifications' import LoaderComponent from "./LoaderComponent" import Select from "../Select" import React, { useRef, useState, useEffect } from "react" import { is_positive_whole_number, get_url_params } from "../../utils/common_utilities" const AddDoctorForm= (p...
props.loadingImageOff() props.uploadRetClr() } if(!!props.addDoctorRet){ if(!!props.addDoctorRet.success){ addToast(props.addDoctorRet.message, {appearance: 'success', autoDismiss:true}) console.log(props.addDoctorRet,"props.addDoctorRet") props.set_user_info({ ...pro...
{ addToast(props.uploadRet.message, {appearance: 'success', autoDismiss:true}) }
conditional_block
AddDoctorForm.js
import { ToastProvider, useToasts } from 'react-toast-notifications' import LoaderComponent from "./LoaderComponent" import Select from "../Select" import React, { useRef, useState, useEffect } from "react" import { is_positive_whole_number, get_url_params } from "../../utils/common_utilities" const AddDoctorForm= (p...
<div onClick = {(e)=>props.handleCloseDay(item,i,e)} className='circul_rund'> <label className={item.closed?'green-background ':''} for="checkbox"></label></div></div> {/* <div classNa...
random_line_split
io_file_browser_search.py
# file_brower_search.py Copyright (C) 2012, Jakub Zolcik # # Relaxes selected vertices while retaining the shape as much as possible # # ***** BEGIN GPL LICENSE BLOCK ***** # # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by...
class FilteredFileSelectOperator(bpy.types.Operator): bl_idname = "file.filtered_file_select" bl_label = "Select File" fname = bpy.props.StringProperty() fexec = bpy.props.BoolProperty() def execute(self, context): context.space_data.params.filename = self.fname if self.fexec: ...
return fileSearch(self, context)
random_line_split
io_file_browser_search.py
# file_brower_search.py Copyright (C) 2012, Jakub Zolcik # # Relaxes selected vertices while retaining the shape as much as possible # # ***** BEGIN GPL LICENSE BLOCK ***** # # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by...
(bpy.types.Operator): bl_idname = "file.filtered_file_select" bl_label = "Select File" fname = bpy.props.StringProperty() fexec = bpy.props.BoolProperty() def execute(self, context): context.space_data.params.filename = self.fname if self.fexec: bpy.ops.file.execute('IN...
FilteredFileSelectOperator
identifier_name
io_file_browser_search.py
# file_brower_search.py Copyright (C) 2012, Jakub Zolcik # # Relaxes selected vertices while retaining the shape as much as possible # # ***** BEGIN GPL LICENSE BLOCK ***** # # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by...
def unregister(): del bpy.types.WindowManager.filtered_search_prop del bpy.types.WindowManager.last_directory_prop del bpy.types.Scene.file_autoexecute del bpy.types.WindowManager.filtered_files_prop del bpy.types.WindowManager.file_searchtree del bpy.types.Scene.file_hideextensions del ...
bpy.utils.register_module(__name__) bpy.types.WindowManager.filtered_search_prop = bpy.props.StringProperty(update=filteredSearchFunc) bpy.types.WindowManager.last_directory_prop = bpy.props.StringProperty() bpy.types.Scene.file_autoexecute = bpy.props.BoolProperty(name="Open Automatically", default=True) ...
identifier_body
io_file_browser_search.py
# file_brower_search.py Copyright (C) 2012, Jakub Zolcik # # Relaxes selected vertices while retaining the shape as much as possible # # ***** BEGIN GPL LICENSE BLOCK ***** # # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by...
if(cf >= maxf): break else: filesList = os.listdir(directory) for filename in filesList: if prog.match(filename.lower()) != None: p = context.window_manager.filtered_files_prop.add() p.name = filename if contex...
break
conditional_block
node_dir_ops.go
package fusefrontend import ( "context" "fmt" "io" "runtime" "syscall" "golang.org/x/sys/unix" "github.com/hanwen/go-fuse/v2/fs" "github.com/hanwen/go-fuse/v2/fuse" "github.com/rfjakob/gocryptfs/v2/internal/configfile" "github.com/rfjakob/gocryptfs/v2/internal/cryptocore" "github.com/rfjakob/gocryptfs/v2...
defer syscall.Close(parentDirFd) if rn.args.PlaintextNames { // Unlinkat with AT_REMOVEDIR is equivalent to Rmdir err := unix.Unlinkat(parentDirFd, cName, unix.AT_REMOVEDIR) return fs.ToErrno(err) } if rn.args.DeterministicNames { if err := unix.Unlinkat(parentDirFd, cName, unix.AT_REMOVEDIR); err != nil {...
{ return errno }
conditional_block
node_dir_ops.go
package fusefrontend import ( "context" "fmt" "io" "runtime" "syscall" "golang.org/x/sys/unix" "github.com/hanwen/go-fuse/v2/fs" "github.com/hanwen/go-fuse/v2/fuse" "github.com/rfjakob/gocryptfs/v2/internal/configfile" "github.com/rfjakob/gocryptfs/v2/internal/cryptocore" "github.com/rfjakob/gocryptfs/v2...
// Opendir is a FUSE call to check if the directory can be opened. func (n *Node) Opendir(ctx context.Context) (errno syscall.Errno) { dirfd, cName, errno := n.prepareAtSyscallMyself() if errno != 0 { return } defer syscall.Close(dirfd) // Open backing directory fd, err := syscallcompat.Openat(dirfd, cName, ...
{ rn := n.rootNode() parentDirFd, cName, errno := n.prepareAtSyscall(name) if errno != 0 { return errno } defer syscall.Close(parentDirFd) if rn.args.PlaintextNames { // Unlinkat with AT_REMOVEDIR is equivalent to Rmdir err := unix.Unlinkat(parentDirFd, cName, unix.AT_REMOVEDIR) return fs.ToErrno(err) } ...
identifier_body
node_dir_ops.go
package fusefrontend import ( "context" "fmt" "io" "runtime" "syscall" "golang.org/x/sys/unix" "github.com/hanwen/go-fuse/v2/fs" "github.com/hanwen/go-fuse/v2/fuse" "github.com/rfjakob/gocryptfs/v2/internal/configfile" "github.com/rfjakob/gocryptfs/v2/internal/cryptocore" "github.com/rfjakob/gocryptfs/v2...
(dirfd int, cName string, mode uint32, context *fuse.Context) error { rn := n.rootNode() if rn.args.DeterministicNames { return syscallcompat.MkdiratUser(dirfd, cName, mode, context) } // Between the creation of the directory and the creation of gocryptfs.diriv // the directory is inconsistent. Take the lock t...
mkdirWithIv
identifier_name
node_dir_ops.go
package fusefrontend import ( "context" "fmt" "io" "runtime" "syscall" "golang.org/x/sys/unix" "github.com/hanwen/go-fuse/v2/fs" "github.com/hanwen/go-fuse/v2/fuse" "github.com/rfjakob/gocryptfs/v2/internal/configfile" "github.com/rfjakob/gocryptfs/v2/internal/cryptocore" "github.com/rfjakob/gocryptfs/v2...
// Delete inconsistent directory (missing gocryptfs.diriv!) err2 := syscallcompat.Unlinkat(dirfd, cName, unix.AT_REMOVEDIR) if err2 != nil { tlog.Warn.Printf("mkdirWithIv: rollback failed: %v", err2) } } return err } // Mkdir - FUSE call. Create a directory at "newPath" with permissions "mode". // // Syml...
random_line_split
engine.py
#!/usr/bin/env pypy import random import math import argparse import cPickle as pickle import logging import os import sys import re import colorsys import bisect import operator from xml.dom.minidom import parse InkscapePath = "/Applications/Inkscape.app/Contents/Resources/bin/inkscape" try: import Image im...
if cell.attached: next_dm += self.diffusive_mass else: next_dm += cell.diffusive_mass return float(next_dm) / (len(self.neighbors) + 1) def attach(self, offset=0.0): self.crystal_mass = self.boundary_mass + self.crystal_mass + offset s...
if self.attached: return next_dm self.age += 1 for cell in self.neighbors:
random_line_split
engine.py
#!/usr/bin/env pypy import random import math import argparse import cPickle as pickle import logging import os import sys import re import colorsys import bisect import operator from xml.dom.minidom import parse InkscapePath = "/Applications/Inkscape.app/Contents/Resources/bin/inkscape" try: import Image im...
return self.__neighbors #@property #def attached_neighbors(self): # return [cell for cell in self.neighbors if cell.attached] #@property #def boundary(self): # return (not self.attached) and any([cell.attached for cell in self.neighbors]) def update_boundary(self): ...
self.__neighbors = self.lattice.get_neighbors(self.xy)
conditional_block
engine.py
#!/usr/bin/env pypy import random import math import argparse import cPickle as pickle import logging import os import sys import re import colorsys import bisect import operator from xml.dom.minidom import parse InkscapePath = "/Applications/Inkscape.app/Contents/Resources/bin/inkscape" try: import Image im...
def step(self, x): if self.curves == None: return for key in self.curves: self[key] = self.curves[key][x] @classmethod def build_env(self, name, steps, min_gamma=0.45, max_gamma=0.85): curves = { "beta": (1.3, 2), "theta": (0.01, 0.0...
if type(state) == dict: self.update(state) self.curves = None self.set_factory_settings() else: self.curves = state[0] self.factory_settings = state[1] self.update(state[2])
identifier_body
engine.py
#!/usr/bin/env pypy import random import math import argparse import cPickle as pickle import logging import os import sys import re import colorsys import bisect import operator from xml.dom.minidom import parse InkscapePath = "/Applications/Inkscape.app/Contents/Resources/bin/inkscape" try: import Image im...
(self): if not self.boundary: return False attach_count = len(self.attached_neighbors) if attach_count <= 2: if self.boundary_mass > self.env.beta: return True elif attach_count == 3: if self.boundary_mass >= 1: return T...
attachment_step
identifier_name
rcparser.py
__author__="Adam Walker" import sys, os, shlex import win32con import commctrl _controlMap = {"DEFPUSHBUTTON":0x80, "PUSHBUTTON":0x80, "Button":0x80, "GROUPBOX":0x80, "Static":0x82, "CTEXT":0x82, "RTEXT":0x82, "LTEX...
(self): self.token = self.lex.get_token() self.debug("getToken returns:", self.token) if self.token=="": self.token = None return self.token def getCommaToken(self): tok = self.getToken() assert tok == ",", "Token '%s' should be a comma!" % tok def loa...
getToken
identifier_name
rcparser.py
__author__="Adam Walker" import sys, os, shlex import win32con import commctrl _controlMap = {"DEFPUSHBUTTON":0x80, "PUSHBUTTON":0x80, "Button":0x80, "GROUPBOX":0x80, "Static":0x82, "CTEXT":0x82, "RTEXT":0x82, "LTEX...
self.dialogs[name] = dlg.createDialogTemplate() def dialogStyle(self, dlg): dlg.style, dlg.styles = self.styles( [], win32con.WS_VISIBLE | win32con.DS_SETFONT) def dialogExStyle(self, dlg): self.getToken() dlg.styleEx, dlg.stylesEx = self.styles( [], 0) def styles(self, defa...
if self.token=="STYLE": self.dialogStyle(dlg) elif self.token=="EXSTYLE": self.dialogExStyle(dlg) elif self.token=="CAPTION": self.dialogCaption(dlg) elif self.token=="FONT": self.dialogFont(dlg) elif self.to...
conditional_block
rcparser.py
__author__="Adam Walker" import sys, os, shlex import win32con import commctrl _controlMap = {"DEFPUSHBUTTON":0x80, "PUSHBUTTON":0x80, "Button":0x80, "GROUPBOX":0x80, "Static":0x82, "CTEXT":0x82, "RTEXT":0x82, "LTEX...
def dialogFont(self, dlg): if "FONT"==self.token: self.getToken() dlg.fontSize = int(self.token) self.getCommaToken() self.getToken() # Font name dlg.font = self.token[1:-1] # it's quoted self.getToken() while "BEGIN"!=self.token: self...
if "CAPTION"==self.token: self.getToken() self.token = self.token[1:-1] self.debug("Caption is:",self.token) if self.gettexted: dlg.caption = gt_str(self.token) else: dlg.caption = self.token self.getToken()
identifier_body
rcparser.py
__author__="Adam Walker" import sys, os, shlex import win32con import commctrl _controlMap = {"DEFPUSHBUTTON":0x80, "PUSHBUTTON":0x80, "Button":0x80, "GROUPBOX":0x80, "Static":0x82, "CTEXT":0x82, "RTEXT":0x82, "LTEX...
label = "" x = 0 y = 0 w = 0 h = 0 def __init__(self): self.styles = [] def toString(self): s = "<Control id:"+self.id+" controlType:"+self.controlType+" subType:"+self.subType\ +" idNum:"+str(self.idNum)+" style:"+str(self.style)+" styles:"+str(self.styles)+" lab...
idNum = 0 style = defaultControlStyle
random_line_split
ann_interface.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ 2017.1.24--- 時間 2017.1.4---- 音声を生で扱う Annotationとは別で扱う 2016.12.12---- 20161210_proc3p.jsonを使う。反転させてみる 2016.12.9---- 三人の対話におけるannotationのInterface 手動でannotationする slider barとtableを同期させた 2016.10.19---- interaction dataをannotationするためのinterface """ import sys import o...
im(0,len(self.input_annos)) plt.ylim(-0.2, 1.2) plt.legend() plt.show() """ print "joints shape:", self.input_joints.shape print "speaks shape:", self.input_speaks.shape print "annos shape:", self.input_annos.shape print "flags shape:", self....
+str(fps)+")") plt.title("speaker/listener result") plt.xl
conditional_block
ann_interface.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ 2017.1.24--- 時間 2017.1.4---- 音声を生で扱う Annotationとは別で扱う 2016.12.12---- 20161210_proc3p.jsonを使う。反転させてみる 2016.12.9---- 三人の対話におけるannotationのInterface 手動でannotationする slider barとtableを同期させた 2016.10.19---- interaction dataをannotationするためのinterface """ import sys import o...
def activatedUpdateTable(self, cItem): row = cItem.row() col = cItem.column() print "row:", row,", col:", col#, ". tip:",self.tip """ # 生Dataの入力 def inputData(self): filesize = int(self.frmSizeBox.text()) print "Input raw data:", filesize self...
random_line_split
ann_interface.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ 2017.1.24--- 時間 2017.1.4---- 音声を生で扱う Annotationとは別で扱う 2016.12.12---- 20161210_proc3p.jsonを使う。反転させてみる 2016.12.9---- 三人の対話におけるannotationのInterface 手動でannotationする slider barとtableを同期させた 2016.10.19---- interaction dataをannotationするためのinterface """ import sys import o...
def pubViz(self, tl): #print "pub Viz:", tl # drawing msgs = MarkerArray() amsg = Float64MultiArray() per_js = [] dim_p = 36 dim = len(self.edited_joints[tl]) for i in range(dim/dim_p): per_js.append(self.edited_joi...
ange(2): #print person[0, ls[l+add]], ls[l+add], l, add linepoint=self.set_point([data[0,ls[l+add]*3], data[0,ls[l+add]*3+1], data[0,ls[l+add]*3+2]], ...
identifier_body
ann_interface.py
#!/usr/bin/python # -*- coding: utf-8 -*- """ 2017.1.24--- 時間 2017.1.4---- 音声を生で扱う Annotationとは別で扱う 2016.12.12---- 20161210_proc3p.jsonを使う。反転させてみる 2016.12.9---- 三人の対話におけるannotationのInterface 手動でannotationする slider barとtableを同期させた 2016.10.19---- interaction dataをannotationするためのinterface """ import sys import o...
addx=addx, addy=addy, rotate=rotate)) pmsg.points = points return pmsg def set_vizmsg_line(self, u, data, color, lsize, llist, addx=0, addy=0, rotate=False): lmsg = self.rviz_obj(u, 'l'+str(u), 5, [lsize, lsize, lsize], color, 0) for ls in ll...
identifier_name
index.js
const path = require('path'); const yaml = require('js-yaml'); const toml = require('@iarna/toml'); const fse = require('fs-extra'); const _ = require('lodash'); const TaskQueue = require('./task-queue'); module.exports = { forEachPromise, mapPromise, findPromise, readDirRecursively, getFirst, ...
else { resolve(results); } } next(0); }); } function findPromise(array, callback, thisArg) { return new Promise((resolve, reject) => { function next(index) { if (index < array.length) { callback.call(thisArg, array[index], index,...
{ callback.call(thisArg, array[index], index, array).then(result => { results[index] = result; next(index + 1); }).catch(error => { reject(error); }); }
conditional_block
index.js
const path = require('path'); const yaml = require('js-yaml'); const toml = require('@iarna/toml'); const fse = require('fs-extra'); const _ = require('lodash'); const TaskQueue = require('./task-queue'); module.exports = { forEachPromise, mapPromise, findPromise, readDirRecursively, getFirst, ...
markdown = afterEndDelim.substring(afterEndDelimMatch[0].length); } } } }); return { frontmatter: frontmatter, markdown: markdown }; } function outputData(filePath, data) { let res = stringifyDataByFilePath(data, filePath); ret...
random_line_split
index.js
const path = require('path'); const yaml = require('js-yaml'); const toml = require('@iarna/toml'); const fse = require('fs-extra'); const _ = require('lodash'); const TaskQueue = require('./task-queue'); module.exports = { forEachPromise, mapPromise, findPromise, readDirRecursively, getFirst, ...
function outputData(filePath, data) { let res = stringifyDataByFilePath(data, filePath); return fse.outputFile(filePath, res); } function stringifyDataByFilePath(data, filePath) { const extension = path.extname(filePath).substring(1); let result; switch (extension) { case 'yml': c...
{ string = string.replace('\r\n', '\n'); let frontmatter = null; let markdown = string; let frontMatterTypes = [ { type: 'yaml', startDelimiter: '---\n', endDelimiter: '\n---', parse: (string) => yaml.safeLoad(string, {schema: yaml.JSON_SCHEMA}) ...
identifier_body
index.js
const path = require('path'); const yaml = require('js-yaml'); const toml = require('@iarna/toml'); const fse = require('fs-extra'); const _ = require('lodash'); const TaskQueue = require('./task-queue'); module.exports = { forEachPromise, mapPromise, findPromise, readDirRecursively, getFirst, ...
(array, callback, thisArg) { return new Promise((resolve, reject) => { function next(index) { if (index < array.length) { callback.call(thisArg, array[index], index, array).then(() => { next(index + 1); }).catch(error => { r...
forEachPromise
identifier_name
server.go
package server import ( "Polaris/src/common" pb "Polaris/src/rpc" "Polaris/src/util" "net" "Polaris/src/byzantineGroup" "Polaris/src/configuration" "Polaris/src/raftnode" "github.com/op/go-logging" grpcpool "github.com/processout/grpc-go-pool" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ...
server.log[i] = NewConsensusState(len(server.BGsInfo), -1, server) } i1, err := strconv.Atoi(server.RPCPort) common.AssertNil(err, "RPC port cannot be recognized.", logger) tcpPort := common.CalcTCPPortFromRPCPort(i1) server.tcpManager = NewTCPManager(strconv.Itoa(tcpPort)) server.tcpManager.SetServer(server)...
} for i := 0; i < common.MaxCycleNumberInStorage; i++ { // Fill it with -1
random_line_split
server.go
package server import ( "Polaris/src/common" pb "Polaris/src/rpc" "Polaris/src/util" "net" "Polaris/src/byzantineGroup" "Polaris/src/configuration" "Polaris/src/raftnode" "github.com/op/go-logging" grpcpool "github.com/processout/grpc-go-pool" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ...
(err error) (*grpcpool.Pool, bool) { errCode := grpc.Code(err) if errCode == common.NotLeaderErrorCode { leaderId := grpc.ErrorDesc(err) s.BGsInfo[s.BGID].UpdateLeader(leaderId) conn := s.BGsInfo[s.BGID].GetConnection(leaderId).GetConnectionPool() return conn, true } logger.Warningf("Unhandled ERROR: %v", ...
handleRPCError
identifier_name
server.go
package server import ( "Polaris/src/common" pb "Polaris/src/rpc" "Polaris/src/util" "net" "Polaris/src/byzantineGroup" "Polaris/src/configuration" "Polaris/src/raftnode" "github.com/op/go-logging" grpcpool "github.com/processout/grpc-go-pool" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ...
func (s *Server) IsBGLeader() bool { if s.currentBGLeaderSuperLeadId != s.SuperLeafID { return false } return s.IsLeader() } func (s *Server) saveLeaderAddress() { fName := fmt.Sprintf("./leader_%v.log", s.ID) f, err := os.Create(fName) if err != nil { logger.Fatalf("create leader log file error %v", err)...
{ // when the raft leader call getLeaderID, it will return 0 // it only shows in the first time return int(s.getLeaderID()) == s.RaftID || int(s.getLeaderID()) == 0 }
identifier_body
server.go
package server import ( "Polaris/src/common" pb "Polaris/src/rpc" "Polaris/src/util" "net" "Polaris/src/byzantineGroup" "Polaris/src/configuration" "Polaris/src/raftnode" "github.com/op/go-logging" grpcpool "github.com/processout/grpc-go-pool" "google.golang.org/grpc" "google.golang.org/grpc/reflection" ...
leader := s.rpcPeers[id-1] go s.BGsInfo[s.BGID].UpdateLeader(leader) logger.Debugf("server %v get leader %v, raft id %v", s.addr, leader, id) return leader } func (s *Server) IsLeader() bool { // when the raft leader call getLeaderID, it will return 0 // it only shows in the first time return int(s.getLeaderID...
{ return "" }
conditional_block
doom.py
from vizdoom import * import tensorflow as tf import numpy as np import random import time from skimage import transform import dqn2 import mem from collections import deque import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') #ignore the skimags warnings import argparse # Model ...
if not args['model']: stacked_frames = deque([np.zeros((84, 84), dtype=np.int) for i in range(stack_size)], maxlen=4) game, possible_actions = create_environment() print("Game Environment created") createnetwork() print("network created") memory = mem.Memory(max_size=memory_size) game.ne...
global game episodes = 10 for i in range(episodes): game.new_episode() while not game.is_episode_finished(): state = game.get_state() img = state.screen_buffer misc = state.game_variables action = random.choice(possible_actions) print("...
identifier_body
doom.py
from vizdoom import * import tensorflow as tf import numpy as np import random import time from skimage import transform import dqn2 import mem from collections import deque import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') #ignore the skimags warnings import argparse # Model ...
next_state, stacked_frames = stack_frames(stacked_frames, next_state, False) state = next_state env.close() def predict_action(decay_step, possible_actions, state, sess): global explore_start global explore_stop global decay_rate exp_exp_tradeoff = np.random.rand() ...
print("Score", total_rewards) total_test_rewards.append(total_rewards) break
conditional_block
doom.py
from vizdoom import * import tensorflow as tf import numpy as np import random import time from skimage import transform import dqn2 import mem from collections import deque import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') #ignore the skimags warnings import argparse # Model ...
(memory): global stacked_frames global saver sess = tf.Session() sess.run(tf.global_variables_initializer()) decay_step = 0 game.init() for episode in range(total_episodes): print("Training on episode: {}".format(episode)) step = 0 episode_rewards = [] game.n...
train
identifier_name
doom.py
from vizdoom import * import tensorflow as tf import numpy as np import random import time from skimage import transform import dqn2 import mem from collections import deque import matplotlib.pyplot as plt import warnings warnings.filterwarnings('ignore') #ignore the skimags warnings import argparse # Model ...
loss, _ = sess.run([DQNetwork.loss, DQNetwork.optimizer], feed_dict={DQNetwork.inputs_: states_mb, DQNetwork.target_Q: targets_mb, DQNetwork.actions_: actions_mb}) # Write TF Summa...
random_line_split
dataset3.js
module.exports = [ { x: '11.3034455', y: '536.486347', label: 'C2' }, { x: '10.1644948', y: '3.39302974', label: 'C1' }, { x: '9.36384167', y: '3.4662791', label: 'C1' }, { x: '1.71758171', y: '3.1736868', label: 'C2' }, { x: '6.26468703', y: '3.38746862', label: 'C1' }, { x: '9.96948149', y: '63.9384092', ...
{ x: '4.06277657', y: '3.30054593', label: 'C1' }, { x: '10.1004059', y: '73.8328052', label: 'C2' }, { x: '11.9150365', y: '3.37543243', label: 'C1' }, { x: '2.67113254', y: '5.12725717', label: 'C2' }, { x: '9.21185949', y: '14.5993617', label: 'C2' }, { x: '2.59559923', y: '5.1530681', label: 'C2' }, {...
{ x: '0.51454207', y: '2.55030179', label: 'C1' }, { x: '0.1780755', y: '1.52949356', label: 'C2' }, { x: '0.76631977', y: '2.5589982', label: 'C1' }, { x: '14.2249825', y: '19.6862421', label: 'C2' },
random_line_split
covid19co_pipe.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load i...
covid19co[attr] = covid19co[attr].transform(lambda value: str(value).title()) # Show dataframe covid19co.head() # %% # Fill NaN Values if covid19co.isna().sum().sum() > 0: covid19co.fillna(value='-', inplace=True) # Show dataframe covid19co.head() # %% # Setup Date Format def setup_date(value): try:...
# %% # Update texto to title text format for attr in covid19co.columns: if covid19co[attr].dtypes == 'object':
random_line_split
covid19co_pipe.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load i...
RL): # Target changes targets = ['Retail & recreation', 'Grocery & pharmacy', 'Parks', 'Transit stations', 'Workplaces', 'Residential'] # Mobility Changes mobility_changes = [] # Get Mobility Report with requests.get(URL) as mobility_report: if mobility_report.status_code == 200: ...
t_mobility_changes(U
identifier_name
covid19co_pipe.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load i...
Get URL report new_reports['url'] = new_reports['file'].transform(lambda value: get_report_url(value)) # Drop any report without URL new_reports.dropna(inplace=True) # Reset index new_reports.reset_index(inplace=True, drop=True) # Only new reports new_reports = new_reports.iloc[1:] # Show dataframe new_reports.head() ...
th requests.get('https://www.gstatic.com/covid19/mobility/' + file) as community_mobility_report: if community_mobility_report.status_code == 200: return community_mobility_report.url else: return np.nan #
identifier_body
covid19co_pipe.py
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # This Python 3 environment comes with many helpful analytics libraries installed # It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python # For example, here's several helpful packages to load i...
else: value = '-' except IndexError: value = '-' if len(value) != 10 and len(value) != 1: value = '-' return value # Date Columns date_columns = list(filter(lambda value: value.find('FECHA') != -1 or value.find('FIS') != -1, covid19co.columns)) # For each date column for...
value = value[2] + '/' + value[1] + '/' + value[0]
conditional_block
peermanager.go
/* * @file * @copyright defined in aergo/LICENSE.txt */ package p2p import ( "context" "fmt" "github.com/aergoio/aergo/p2p/metric" "github.com/libp2p/go-libp2p-peerstore/pstoremem" "net" "strconv" "strings" "sync" "time" "github.com/libp2p/go-libp2p-host" inet "github.com/libp2p/go-libp2p-net" "githu...
func (pm *peerManager) startListener() { var err error listens := make([]ma.Multiaddr, 0, 2) // FIXME: should also support ip6 later listen, err := ma.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", pm.bindAddress, pm.bindPort)) if err != nil { panic("Can't estabilish listening address: " + err.Error()) } listens...
{ return pm.Host.Peerstore() }
identifier_body
peermanager.go
/* * @file * @copyright defined in aergo/LICENSE.txt */ package p2p import ( "context" "fmt" "github.com/aergoio/aergo/p2p/metric" "github.com/libp2p/go-libp2p-peerstore/pstoremem" "net" "strconv" "strings" "sync" "time" "github.com/libp2p/go-libp2p-host" inet "github.com/libp2p/go-libp2p-net" "githu...
case id := <-pm.removePeerChannel: if pm.removePeer(id) { if meta, found := pm.designatedPeers[id]; found { pm.rm.AddJob(meta) } } case <-addrTicker.C: pm.checkAndCollectPeerListFromAll() pm.logPeerMetrics() case peerMetas := <-pm.fillPoolChannel: pm.tryFillPool(&peerMetas) case ...
{ if _, found := pm.designatedPeers[meta.ID]; found { pm.rm.CancelJob(meta.ID) } }
conditional_block
peermanager.go
/* * @file * @copyright defined in aergo/LICENSE.txt */ package p2p import ( "context" "fmt" "github.com/aergoio/aergo/p2p/metric" "github.com/libp2p/go-libp2p-peerstore/pstoremem" "net" "strconv" "strings" "sync" "time" "github.com/libp2p/go-libp2p-host" inet "github.com/libp2p/go-libp2p-net" "githu...
() pstore.Peerstore { return pm.Host.Peerstore() } func (pm *peerManager) startListener() { var err error listens := make([]ma.Multiaddr, 0, 2) // FIXME: should also support ip6 later listen, err := ma.NewMultiaddr(fmt.Sprintf("/ip4/%s/tcp/%d", pm.bindAddress, pm.bindPort)) if err != nil { panic("Can't estabil...
Peerstore
identifier_name
peermanager.go
/* * @file * @copyright defined in aergo/LICENSE.txt */ package p2p import ( "context" "fmt" "github.com/aergoio/aergo/p2p/metric" "github.com/libp2p/go-libp2p-peerstore/pstoremem" "net" "strconv" "strings" "sync" "time" "github.com/libp2p/go-libp2p-host" inet "github.com/libp2p/go-libp2p-net" "githu...
} peer, ok := pm.GetPeer(ID) if !ok { //pm.logger.Warnf("invalid peer id %s", ID.Pretty()) pm.logger.Warn().Str(LogPeerID, ID.Pretty()).Msg("invalid peer id") return } pm.actorServ.SendRequest(message.P2PSvc, &message.GetAddressesMsg{ToWhom: peer.ID(), Size: 20, Offset: 0}) } func (pm *peerManager) hasEnoug...
if pm.hasEnoughPeers() { return
random_line_split
Config.ts
import {chain_cmps, mkcmp, cmp_order, Comparator} from '../Utils' const image_ws_url = 'https://ws.spraakbanken.gu.se/ws/swell' const pseuws_url = 'https://ws.spraakbanken.gu.se/ws/larka/pseuws' export interface Example { source: string target: string } const ex = (source: string, target: string): Example => ({s...
I don't know his lives . // I don't know where he~his lives . He get to cleaned his son . // He got his~his son~son to:O clean:O the~ room~ . We wrote down the number . // We wrote the number down~down . ` .trim() .split(/\n\n+/gm) .map(line => ex.apply({}, line.split('//').map(side => side.trim()) as [string, ...
Their was a problem yesteray . // There was a problem yesterday .
random_line_split
Config.ts
import {chain_cmps, mkcmp, cmp_order, Comparator} from '../Utils' const image_ws_url = 'https://ws.spraakbanken.gu.se/ws/swell' const pseuws_url = 'https://ws.spraakbanken.gu.se/ws/larka/pseuws' export interface Example { source: string target: string } const ex = (source: string, target: string): Example => ({s...
axonomy: string, label: string): boolean { if (!(taxonomy in config.taxonomy)) return false const tax: Record<string, TaxonomyGroup[]> = config.taxonomy return !!tax[taxonomy].find(g => !!g.entries.find(l => l.label == label)) }
xonomy_has_label(t
identifier_name
Config.ts
import {chain_cmps, mkcmp, cmp_order, Comparator} from '../Utils' const image_ws_url = 'https://ws.spraakbanken.gu.se/ws/swell' const pseuws_url = 'https://ws.spraakbanken.gu.se/ws/larka/pseuws' export interface Example { source: string target: string } const ex = (source: string, target: string): Example => ({s...
const docs: Record<string, Record<string, string>> = { anonymization: { 'pseudonymization guidelines': doc_url('Pseudonymization_guidelines'), }, normalization: { 'normalization guidelines': doc_url('Normalization_guidelines'), }, correctannot: { 'annotation guidelines': doc_url('Correction-annota...
return 'https://spraakbanken.github.io/swell-project/' + title }
identifier_body
filesystem.rs
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{...
(filename: &String) -> String { format!("{}/{}", constants::DATA_DIR, filename) } // Returns messages to be gossiped pub fn handle_failed_node(failed_id: &String) -> BoxedErrorResult<Vec<SendableOperation>> { match heartbeat::is_master() { true => { let mut generated_operations: Vec<Sendabl...
distributed_file_path
identifier_name
filesystem.rs
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{...
} Err(format!("No new owners available for file {}", filename).into()) }, None => Err(format!("No owner found for file {}", filename).into()) } } fn distributed_file_path(filename: &String) -> String { format!("{}/{}", constants::DATA_DIR, filename) } // Returns messag...
{ return Ok(potential_owner.clone()); }
conditional_block
filesystem.rs
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{...
// TODO: This function makes the entire system assume there are always at least two nodes in the system // and the file must have an owner or else the operation will not work correctly. This is fine for now // but it is worth improving sooner rather than later (make distinct Error types to differentiate, e...
random_line_split
filesystem.rs
use async_std; use async_std::io::ReadExt; use async_std::stream::StreamExt; use async_std::task::spawn; use crate::{BoxedError, BoxedErrorResult}; use crate::component_manager::*; use crate::constants; use crate::easyhash::{EasyHash, Hex}; use crate::globals; use crate::heartbeat; use crate::operation::*; use serde::{...
async fn handle_connection(mut connection: async_std::net::TcpStream) -> BoxedErrorResult<()> { let (operation, source) = connection.try_read_operation().await?; // TODO: Think about what standard we want with these let _generated_operations = operation.execute(source)?; Ok(()) } // Helpers fn gen_fi...
{ let server = globals::SERVER_SOCKET.read(); let mut incoming = server.incoming(); while let Some(stream) = incoming.next().await { let connection = stream?; log(format!("Handling connection from {:?}", connection.peer_addr())); spawn(handle_connection(connection)); } Ok(()...
identifier_body
main.rs
mod utils; use chrono::{DateTime, Utc, TimeZone}; use actix::{Actor, Handler, Message, AsyncContext}; use actix_web::{http, web, HttpResponse, App}; use actix_web::middleware::cors::Cors; use futures::{Future}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use log::debug; use crate::utils::ErrSt...
; } } struct Downloader; impl Actor for Downloader { type Context = actix::Context<Self>; } impl Handler<DownloadFeed> for Downloader { type Result = <DownloadFeed as Message>::Result; fn handle(&mut self, msg: DownloadFeed, _: &mut Self::Context) -> Self::Result { let channel = rss::Channel:...
{ feed.merge(msg.feed) }
conditional_block
main.rs
mod utils; use chrono::{DateTime, Utc, TimeZone}; use actix::{Actor, Handler, Message, AsyncContext}; use actix_web::{http, web, HttpResponse, App}; use actix_web::middleware::cors::Cors; use futures::{Future}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use log::debug; use crate::utils::ErrSt...
server.start(); Ok(()) } pub fn main() -> Result<(), std::io::Error> { std::env::set_var("RUST_LOG", "actix_web=debug,rssreader=debug"); env_logger::init(); actix::System::run(|| {actix_main().expect("App crashed");} ) }
server.listen(l)? } else { server.bind("[::1]:8000")? }; println!("Started HTTP server on {:?}", server.addrs_with_scheme().iter().map(|(a, s)| format!("{}://{}/", s, a)).collect::<Vec<_>>());
random_line_split
main.rs
mod utils; use chrono::{DateTime, Utc, TimeZone}; use actix::{Actor, Handler, Message, AsyncContext}; use actix_web::{http, web, HttpResponse, App}; use actix_web::middleware::cors::Cors; use futures::{Future}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use log::debug; use crate::utils::ErrSt...
{ pub title: Option<String>, pub link: Option<String>, pub content: Option<String>, pub pub_date: Option<DateTime<Utc>>, pub guid: String, pub unread: bool, } #[derive(Clone, Debug, Serialize)] struct Feed { pub title: String, pub last_updated: DateTime<Utc>, pub items: Vec<Item>, ...
Item
identifier_name
sssmc39_scheme.rs
// Copyright 2019 The Grin Developers // // 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 agree...
); Ok(dms) } /// Decodes all Mnemonics to a list of shares and performs error checking fn decode_mnemonics(mnemonics: &[Vec<String>]) -> Result<Vec<GroupShare>, Error> { let mut shares = vec![]; if mnemonics.is_empty() { return Err(ErrorKind::Mnemonic( "List of mnemonics is empty.".to_string(), ))?; } let...
&ems.share_value, passphrase, ems.iteration_exponent, ems.identifier,
random_line_split
sssmc39_scheme.rs
// Copyright 2019 The Grin Developers // // 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 agree...
// For temporary use as we have no command-line at present #[test] fn split_master_secret() -> Result<(), Error> { let master_secret = b"fdd99010e03f3141662adb33644d5fd2bea0238fa805a2d21e396a22b926558c"; let mns = generate_mnemonics(1, &[(3, 5)], &master_secret.to_vec(), "", 0)?; for s in &mns { println!(...
{ let master_secret = b"\x0c\x94\x90\xbcn\xd6\xbc\xbf\xac>\xbe}\xeeV\xf2P".to_vec(); // single 3 of 5 test, splat out all mnemonics println!("Single 3 of 5 Encoded: {:?}", master_secret); let mns = generate_mnemonics(1, &[(3, 5)], &master_secret, "", 0)?; for s in &mns { println!("{}", s); } let resul...
identifier_body
sssmc39_scheme.rs
// Copyright 2019 The Grin Developers // // 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 agree...
let check_len = mnemonics[0].len(); for m in mnemonics { if m.len() != check_len { return Err(ErrorKind::Mnemonic( "Invalid set of mnemonics. All mnemonics must have the same length.".to_string(), ))?; } shares.push(Share::from_mnemonic(m)?); } let check_share = shares[0].clone(); for s in shares...
{ return Err(ErrorKind::Mnemonic( "List of mnemonics is empty.".to_string(), ))?; }
conditional_block
sssmc39_scheme.rs
// Copyright 2019 The Grin Developers // // 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 agree...
(mnemonics: &[Vec<String>]) -> Result<Vec<GroupShare>, Error> { let mut shares = vec![]; if mnemonics.is_empty() { return Err(ErrorKind::Mnemonic( "List of mnemonics is empty.".to_string(), ))?; } let check_len = mnemonics[0].len(); for m in mnemonics { if m.len() != check_len { return Err(ErrorKind::M...
decode_mnemonics
identifier_name
project.py
#!/usr/bin/env python # Import modules import numpy as np import sklearn from sklearn.preprocessing import LabelEncoder import pickle from sensor_stick.srv import GetNormals from sensor_stick.features import compute_color_histograms from sensor_stick.features import compute_normal_histograms from visualization_msgs.ms...
cloud (PointCloud_PointXYZRGB): A point cloud Returns: PointCloud_PointXYZRGB: A downsampled point cloud """ # Create a VoxelGrid filter object for our input point cloud vox = cloud.make_voxel_grid_filter() # Choose a voxel (also known as leaf) size LEAF_SIZE = 0.0...
""" Voxel Grid filter Args:
random_line_split
project.py
#!/usr/bin/env python # Import modules import numpy as np import sklearn from sklearn.preprocessing import LabelEncoder import pickle from sensor_stick.srv import GetNormals from sensor_stick.features import compute_color_histograms from sensor_stick.features import compute_normal_histograms from visualization_msgs.ms...
def euclidean_clustering(cloud): white_cloud = XYZRGB_to_XYZ(cloud) tree = white_cloud.make_kdtree() # Create a cluster extraction object ec = white_cloud.make_EuclideanClusterExtraction() # Set tolerances for distance threshold # as well as minimum and maximum cluster size (in points) ...
""" Segments a cloud using a sac model Args: cloud (PointCloud_PointXYZRGB): A point cloud sacmodel (pcl.SACMODEL): A model points will be fit to Returns: A set of inliers and coefficients """ # Create the segmentation object seg = cloud.make_segmenter()...
identifier_body
project.py
#!/usr/bin/env python # Import modules import numpy as np import sklearn from sklearn.preprocessing import LabelEncoder import pickle from sensor_stick.srv import GetNormals from sensor_stick.features import compute_color_histograms from sensor_stick.features import compute_normal_histograms from visualization_msgs.ms...
rospy.spin()
conditional_block