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
licensePlateDetectorOptimized.py
model = tf.keras.models.load_model(folder_path + "kerasModelandData/model.h5") #getting the model and loading it ######################################################################################## #################################### GENERAL SETUP ##################################### ###############...
letter_dict = {} #init the letter dictionary to get the letters that are put through the NN
random_line_split
licensePlateDetectorOptimized.py
def setup_exec(self): self.settings_init() #initializing all of the settings if optimize: #Currently, optimize makes it so that only the bottom portion of the screen is analyzed self.offset = int(self.img.shape[0] * (self.divideArea - 1) / self.divi...
self.check_wait = check_wait #initializing whether we need to wait between drawing contours for debugging if imgAddress is None and img is not None: #getting the image from the video self.img = img elif imgAddress is not None and img is None: self.img = cv.resize(cv.imread(i...
identifier_body
licensePlateDetectorOptimized.py
This is the denominator for how much of the screen is analyzed (analyzes the [1/(variable)] portion of the image/vid) #For example, if the bottom half should be analyzed, put in '2' self.amt_digits = 6 #defining the amount of characters and digits that should be found on th...
(self, height = 300): #shows the important images that are being used for execution # cv.imshow("Contours", imutils.resize(self.img_copy, height = height)) cv.imshow("Bounding Rects", self.img_rects) cv.imshow("Canny", imutils.resize(self.Canny, height = height)) self.show_im...
show_images_exec
identifier_name
SelfOrganizingMap.py
(self, iteration, epoch): ############################# # Description: Update the neighborhood size and learning rate # iteration: number of current iteration # epoch: total epochs to run the SOM for ######################################## self.neighborhoodSize = self.ne...
update_parameters
identifier_name
SelfOrganizingMap.py
ighborhoodSize)) print('Learning Rate : '+str(self.learningRate)) print('**************************************') if len(path)>0: self.plotMap(inputs, epoch, showPlot, windowSize,path,targets,labels = labels,legend_dict = legend_dict ) sel...
dist = ((s1 - s2) ** 2) return dist.flatten().sum()
identifier_body
SelfOrganizingMap.py
1 or column > self.hiddenSize[1] or column < 1: continue row = row % self.hiddenSize[0] column = column % self.hiddenSize[1] if row == 0: row = self.hiddenSize[0] if column == 0: ...
# minimum value is winner winnerNeuronIndex = np.argmin(distances) return winnerNeuronIndex def propogateForward(self, x, windowSize): ############ # Description: Function forward propogates from input to grid # x: single input # windowSize: window size ...
for j in range(0, self.hiddenSize[1]): # get weights associated to i-th and j-th node weights = self.weights_Kohonen[i, j, :,:] # make sure correct shape weights = np.reshape(weights, (1, np.shape(weights)[0], np.shape(weights)[1])) # form...
conditional_block
SelfOrganizingMap.py
< 1 or column > self.hiddenSize[1] or column < 1: continue row = row % self.hiddenSize[0] column = column % self.hiddenSize[1] if row == 0: row = self.hiddenSize[0] if column == 0: ...
#find all the neighbors for node at i,j neighbors = self.find_neighbor_indices(i, j) #remove self neighbors.remove((i, j)) #get weights for node at i,j weights = self.weights_Kohonen[i,j,:] weights = np.res...
Umatrix = np.zeros((self.hiddenSize[0],self.hiddenSize[1])) # Perform 2D convolution with input data and kernel to get sum of neighboring nodes for i in range(0,self.hiddenSize[0]): for j in range(0,self.hiddenSize[1]):
random_line_split
train.py
#训练集变化不大时使训练加速 def logging_func(log_file, message): with open(log_file,'a') as f: f.write(message)
def main(): setup_seed(1024) # Hyper Parameters parser = argparse.ArgumentParser() parser.add_argument('--data_path', default='D:/data/', help='path to datasets') parser.add_argument('--data_name', default='f30k_precomp', help='{coco,f30k}_pre...
f.close()
random_line_split
train.py
#训练集变化不大时使训练加速 def logging_func(log_file, message): with open(log_file,'a') as f: f.write(message) f.close() def main(): setup_seed(1024) # Hyper Parameters parser = argparse.ArgumentParser() parser.add_argument('--data_path', default='D:/data/', ...
te the encoding for all the validation images and captions img_embs, img_means, cap_embs, cap_lens, cap_means = encode_data( model, val_loader, opt.log_step, logging.info) print(img_embs.shape, cap_embs.shape) img_embs = numpy.array([img_embs[i] for i in range(0, len(img_embs), 5)]) sta...
# compu
identifier_name
train.py
#训练集变化不大时使训练加速 def logging_func(log_file, message): with open(log_file,'a') as f: f.write(message) f.close() def main(): setup_seed(1024) # Hyper Parameters parser = argparse.ArgumentParser() parser.add_argument('--data_path', default='D:/data/', ...
if (i + 1) % opt.log_step == 0: run_time += time.time() - start_time log = "epoch: %d; batch: %d/%d; loss: %.6f; time: %.4f" % (epoch, i, len(train_loader), loss.data.item(), ...
t.grad_clip) optimizer.step()
conditional_block
train.py
('--img_dim', default=2048, type=int, help='Dimensionality of the image embedding.') parser.add_argument('--no_imgnorm', action='store_true', help='Do not normalize the image embeddings.') parser.add_argument('--no_txtnorm', action='store_true', ...
ecified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append...
identifier_body
android_bootldr_qcom.go
asetools.py#105) * - Nexus 7 \[2013] (Wi-Fi) "flo" <a href="#doc-note-data-after-img-bodies">(\**)</a>: [sample][sample-flo] ([other samples][others-flo]), * [releasetools.py](https://android.googlesource.com/device/asus/flo/+/9d9fee9/releasetools.py#130) * * * MSM8996 Pro-AB ([devices](https://en.wikipedia....
func (this *AndroidBootldrQcom) Read(io *kaitai.Stream, parent interface{}, root *AndroidBootldrQcom) (err error) { this._io = io this._parent = parent this._root = root tmp1, err := this._io.ReadBytes(int(8)) if err != nil { return err } tmp1 = tmp1 this.Magic = tmp1
{ return &AndroidBootldrQcom{ } }
identifier_body
android_bootldr_qcom.go
leasetools.py#105) * - Nexus 7 \[2013] (Wi-Fi) "flo" <a href="#doc-note-data-after-img-bodies">(\**)</a>: [sample][sample-flo] ([other samples][others-flo]), * [releasetools.py](https://android.googlesource.com/device/asus/flo/+/9d9fee9/releasetools.py#130) * * * MSM8996 Pro-AB ([devices](https://en.wikipedi...
* The `bootloader-*.img` samples referenced above originally come from factory * images packed in ZIP archives that can be found on the page [Factory Images * for Nexus and Pixel Devices](https://developers.google.com/android/images) on * the Google Developers site. Note that the codenames on that page may be * di...
random_line_split
android_bootldr_qcom.go
asetools.py#105) * - Nexus 7 \[2013] (Wi-Fi) "flo" <a href="#doc-note-data-after-img-bodies">(\**)</a>: [sample][sample-flo] ([other samples][others-flo]), * [releasetools.py](https://android.googlesource.com/device/asus/flo/+/9d9fee9/releasetools.py#130) * * * MSM8996 Pro-AB ([devices](https://en.wikipedia....
(io *kaitai.Stream, parent interface{}, root *AndroidBootldrQcom) (err error) { this._io = io this._parent = parent this._root = root tmp1, err := this._io.ReadBytes(int(8)) if err != nil { return err } tmp1 = tmp1 this.Magic = tmp1
Read
identifier_name
android_bootldr_qcom.go
"marlin" <a href="#doc-note-bootloader-size">(\*)</a>: * [sample][sample-marlin] ([other samples][others-marlin]) * * * MSM8998 ([devices](https://en.wikipedia.org/wiki/Devices_using_Qualcomm_Snapdragon_processors#Snapdragon_835_(2017))) * - Pixel 2 "walleye" <a href="#doc-note-bootloader-size">(\*)</a>: [s...
{ return err }
conditional_block
username.go
"veining", "durability", "corrosion", "laterally", "winnipeg", "federally", "divest", "gasped", "unselfishly", "disclosing", "nurturing", "tramway", "palmed", "disruptions", "footman", "senators", "cleave", "effected", "ceramic", "leathery", "nicely", "frustrater", "warning", "lexicons", "exacti...
"cruisers", "psychoanalyst", "registrations", "agnostics", "ambivalently", "punishable", "philosophically", "storages", "wistful", "loveland", "preferential", "armchairs", "washington", "accretions", "interchangeable", "ambitions", "hostesss", "heading", "crucifies", "venturesome", "mullion", "fue...
random_line_split
username.go
var Words = []string{ "acquirable", "bestsellers", "farther", "prizer", "shasta", "evaporate", "auspices", "garments", "partnership", "blocs", "forestalling", "razors", "extensibility", "unavoidably", "logician", "embroidered", "crippling", "supranational", "milton", "healthily", "spiraling", "c...
{ word := Words[rand.Int31n(int32(len(Words)))] digits := rand.Int31n(1000) return fmt.Sprintf("%s%d", word, digits) }
identifier_body
username.go
() string { word := Words[rand.Int31n(int32(len(Words)))] digits := rand.Int31n(1000) return fmt.Sprintf("%s%d", word, digits) } var Words = []string{ "acquirable", "bestsellers", "farther", "prizer", "shasta", "evaporate", "auspices", "garments", "partnership", "blocs", "forestalling", "razors", "exte...
Username
identifier_name
lib.rs
{ type Target = Entry<K, V>; fn deref(&self) -> &Self::Target { &self.entry } } impl<'a, K, V> DerefMut for EntryMut<'a, K, V> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.entry } } impl<K: Hash, V: Hash> Entry<K, V> { fn new(key: K, val: V) -> Self { let...
// Get a mutable reference to the `Entry`, // locking the corresponding shard. fn entry_mut( &self, lane: usize, page: usize, slot: usize, ) -> EntryMut<K, V> { let shard = (page ^ slot) % NUM_SHARDS; // Lock the entry for writing let lock = SHAR...
{ // Get a reference to the `Entry` let page_ofs = PAGE_SIZE * page; let slot_ofs = page_ofs + slot * mem::size_of::<Entry<K, V>>(); unsafe { mem::transmute( (*self.lanes.get())[lane].as_ptr().offset(slot_ofs as isize), ) } }
identifier_body
lib.rs
> { type Target = Entry<K, V>; fn deref(&self) -> &Self::Target { &self.entry } } impl<'a, K, V> DerefMut for EntryMut<'a, K, V> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.entry } } impl<K: Hash, V: Hash> Entry<K, V> { fn new(key: K, val: V) -> Self { le...
pages: Mutex::new(num_pages as u64), _marker: PhantomData, }; // initialize index with at least one page if num_pages == 0 { assert_eq!(index.new_page()?, 0); } Ok(index) } /// Returns how many pages have been allocated so far pub...
// create the index let index = Index { lanes: UnsafeCell::new(lanes), path: PathBuf::from(path.as_ref()),
random_line_split
lib.rs
{ type Target = Entry<K, V>; fn
(&self) -> &Self::Target { &self.entry } } impl<'a, K, V> DerefMut for EntryMut<'a, K, V> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.entry } } impl<K: Hash, V: Hash> Entry<K, V> { fn new(key: K, val: V) -> Self { let kv_checksum = hash_val(&key).wrapping_add(has...
deref
identifier_name
blockchain.py
transaction): public_key = RSA.importKey(binascii.unhexlify(sender_public_key)) verifier = PKCS1_v1_5.new(public_key) h = SHA.new(str(transaction).encode('utf8')) try: verifier.verify(h, binascii.unhexlify(signature)) return True except ValueError: ...
register_node
identifier_name
blockchain.py
ICULTY = 2 t = time() class Blockchain: def __init__(self): self.transactions = [] self.chain = [] self.nodes = set() self.node_id = str(uuid4()).replace('-', '') # Create the genesis block self.create_block(0, '00') # data = {'block_number':0, "nonce": 0, "...
@app.route('/logout') def logout(): # remove the username from the session if it is there session.pop('miner_email', None) return redirect('/login') @app.route('/profile') def profile(): if not g.user: return redirect('/login') return render_template('profile.html') # @app.route('/register...
if request.method == 'POST': name = request.form.get('minerName') email = request.form.get('minerEmail') password = request.form.get('minerPass') minerdata = {'name':name, "email":email, "password":password} minerdb.insert_one(minerdata) return redirect('/login') r...
identifier_body
blockchain.py
ICULTY = 2 t = time() class Blockchain: def __init__(self): self.transactions = [] self.chain = [] self.nodes = set() self.node_id = str(uuid4()).replace('-', '') # Create the genesis block self.create_block(0, '00') # data = {'block_number':0, "nonce": 0, "...
# user = minerdb.find_one( { "email": email, "password" : password}) # if user: # return redirect('/') # else: # return redirect('/login') # return 'Miner email is {} and password is {}'.format(email, password) @app.route('/configure') def configure(): return render_template('./c...
random_line_split
blockchain.py
(last_hash) + str(nonce)).encode('utf8') h = hashlib.new('sha256') h.update(guess) guess_hash = h.hexdigest() return guess_hash[:difficulty] == '0' * difficulty def proof_of_work(self): last_block = self.chain[-1] last_hash = self.hash(last_block) nonce = 0 ...
blockchain.register_node(node)
conditional_block
HaarROG.py
6004, 0.7376237623762376, 0.6530612244897959, 0.7270531400966184, 0.7558823529411764] ''' #========================================================================== #команда для установки opencv #pip install opencv-python #========================================================================== #Дл...
0: local
identifier_name
HaarROG.py
ListParam, markedDataParam, key, rateCh, lowerBorder, topBorder): #список для найденных уникальных номерных пластин #список для общего количества найденных номерных пластин findPlates = [] findUnicPlates = [] #делаем копии, чтобы работать с локальными параметрами detectList = detectListParam.co...
istics: # положительные характеристики tp = 0 tn = 0 # отрицательные характеристики fp = 0 fn = 0 rateCh = Characteristics() # border для определения, правильно найден номер или не правильно # для площади пересечения номерных рамок lowerBorder = 0.7 ...
identifier_body
HaarROG.py
"x": 186, "y": 203, "width": 75, "height": 21 }, "region_attributes": {} } } } ''' #========================================================================== import math import random import PIL import cv2 import numpy as np #для хранения данных используем json, наи...
with open(dataPath, "r") as read_file: testData = json.load(read_file) # создаем список ключей в словаре keys = list(testData.keys()) except: pri
conditional_block
HaarROG.py
24797844, 0.21875, 0.26508820798514393, 0.43769470404984423, 0.5473579262213359, 0.5986547085201793, 0.545361875637105, 0.6641025641025641, 0.7389380530973452, 0.6848404255319149, 0.7845659163987139, 0.8201438848920863, 0.6258411843876177, 0.6970802919708029, 0.754424778761062, ...
#print('LL') #print(detectList) #print('MNPL') #print(markedNumPlatesList) #x1 < x2 #упорядочили по x if detectList[i][0] < detectList[i][2]: x1 = detectList[i][0] x2 = detectList[i][2] else...
]
random_line_split
transcation.go
.Close() block, err := node.GetBlockByNum(num) if err != nil { return err } processBlock(block) return nil } func processBlocks(blocks *api.BlockListExtention) { for _, v := range blocks.Block { processBlock(v) } } func processBlock(block *api.BlockExtention) { height := block.GetBlockHead...
:= common.LeftPadBytes(add[1:], 32) data = append(data, methodID...) data = append(data, paddedAddress...) return } func processTransaction(node *service.GrpcClient, contract, txid, from, to string, blockheight, amount int64) { // 合约是否存在 if !IsContract(contract) { return } // fmt.Printf("contract...
ring) (data []byte) { methodID, _ := hexutil.Decode("70a08231") add, _ := base58.DecodeCheck(addr) paddedAddress
identifier_body
transcation.go
node = getRandOneNode() block, err := node.GetBlockByLimitNext(start, end) if err != nil { // rpc error: code = DeadlineExceeded desc = context deadline exceeded will get again log.Warnf("node get bolck start %d end %d GetBlockByLimitNext err: %v will get again", start, end, err) time.Sleep(time.Second * ...
random_line_split
transcation.go
.Close() block, err := node.GetBlockByNum(num) if err != nil { return err } processBlock(block) return nil } func processBlocks(blocks *api.BlockListExtention) { for _, v := range blocks.Block { processBlock(v) } } func processBlock(block *api.BlockExtention) { height := block.GetBlockHead...
xID: txid, Contract: contract, Type: types, BlockHeight: blockheight, Amount: decimal.New(amount, -decimalnum).String(), Fee: decimal.New(fee, -trxdecimal).String(), Timestamp: time.Now().Unix(), Address: to, FromAddress: from, } _,
um := chargeContract(contract) var trans = &Transactions{ T
conditional_block
transcation.go
.Close() block, err := node.GetBlockByNum(num) if err != nil { return err } processBlock(block) return nil } func processBlocks(blocks *api.BlockListExtention) { for _, v := range blocks.Block { processBlock(v) } } func processBlo
i.BlockExtention) { height := block.GetBlockHeader().GetRawData().GetNumber() node := getRandOneNode() defer node.Conn.Close() for _, v := range block.Transactions { // transaction.ret.contractRe txid := hexutil.Encode(v.Txid) // https://tronscan.org/#/transaction/fede1aa9e5c5d7bd179fd62e23bdd11e3c1edd...
ck(block *ap
identifier_name
fmt.rs
to be formatted collect_files(&args, &ignore, is_supported_ext_fmt).and_then(|files| { if files.is_empty() { Err(generic_error("No target files found.")) } else { Ok(files) } }) }; let operation = |paths: Vec<PathBuf>| { let config = get_typescript_config(); async ...
get_json_config
identifier_name
fmt.rs
format( args: Vec<PathBuf>, ignore: Vec<PathBuf>, check: bool, watch: bool, ) -> Result<(), AnyError> { let target_file_resolver = || { // collect the files that are to be formatted collect_files(&args, &ignore, is_supported_ext_fmt).and_then(|files| { if files.is_empty() { Err(generic_...
} Ok(()) } fn files_str(len: usize) -> &'static str { if len <= 1 { "file" } else { "files" } } fn get_typescript_config( ) -> dprint_plugin_typescript::configuration::Configuration { dprint_plugin_typescript::configuration::ConfigurationBuilder::new() .deno()
{ return Err(generic_error(e)); }
conditional_block
fmt.rs
format( args: Vec<PathBuf>, ignore: Vec<PathBuf>, check: bool, watch: bool, ) -> Result<(), AnyError> { let target_file_resolver = || { // collect the files that are to be formatted collect_files(&args, &ignore, is_supported_ext_fmt).and_then(|files| { if files.is_empty() { Err(generic_...
/// Formats markdown (using https://github.com/dprint/dprint-plugin-markdown) and its code blocks /// (ts/tsx, js/jsx). fn format_markdown( file_text: &str, ts_config: dprint_plugin_typescript::configuration::Configuration, ) -> Result<String, String> { let md_config = get_markdown_config(); dprint_plugin_markd...
Ok(()) }
random_line_split
fmt.rs
blocks /// (ts/tsx, js/jsx). fn format_markdown( file_text: &str, ts_config: dprint_plugin_typescript::configuration::Configuration, ) -> Result<String, String> { let md_config = get_markdown_config(); dprint_plugin_markdown::format_text( &file_text, &md_config, Box::new(move |tag, text, line_width...
{ let file_bytes = fs::read(&file_path)?; let charset = text_encoding::detect_charset(&file_bytes); let file_text = text_encoding::convert_to_utf8(&file_bytes, charset)?; let had_bom = file_text.starts_with(BOM_CHAR); let text = if had_bom { // remove the BOM String::from(&file_text[BOM_CHAR.len_utf8(...
identifier_body
publish.go
(ctx context.Context, cmd *cobra.Command, f kcmdutil.Factory) error { logrus.Infof("Publishing image set from archive %q to registry %q", o.ArchivePath, o.ToMirror) var currentMeta v1alpha1.Metadata var incomingMeta v1alpha1.Metadata a := archive.NewArchiver() // Create workspace tmpdir, err := ioutil.TempDir(...
Run
identifier_name
publish.go
func (o *Options) Run(ctx context.Context, cmd *cobra.Command, f kcmdutil.Factory) error { logrus.Infof("Publishing image set from archive %q to registry %q", o.ArchivePath, o.ToMirror) var currentMeta v1alpha1.Metadata var incomingMeta v1alpha1.Metadata a := archive.NewArchiver() // Create workspace tmpdir,...
{ return fmt.Sprintf("Bundle Sequence out of order. Current sequence %v, incoming sequence %v", s.CurrSeq, s.inSeq) }
identifier_body
publish.go
err != nil { return fmt.Errorf("error reading current metadata: %v", err) } if err := workspace.ReadMetadata(ctx, &incomingMeta, config.MetadataBasePath); err != nil { return fmt.Errorf("error reading incoming metadata: %v", err) } logrus.Debug("Checking metadata UID") if incomingMeta.MetadataSpec.Ui...
if err := genOpts.Run(); err != nil { return fmt.Errorf("error running generic image mirror: %v", err) } } for _, m := range releaseMappings { logrus.Debugf("mirroring release image: %s", m.Source.String()) relOpts := release.NewMirrorOptions(o.IOStreams) relOpts.From = m.Source.String() relOpts.From...
{ return fmt.Errorf("invalid image mirror options: %v", err) }
conditional_block
publish.go
) for imageName, assoc := range assocs { assoc := assoc logrus.Debugf("reading assoc: %s", assoc.Name) // All manifest layers will be pulled below if associated, // so just sanity-check that the layers are referenced in some association. if len(assoc.ManifestDigests) != 0 { for _, manifestDigest := ran...
} if err := os.Chdir(wd); err != nil { return err }
random_line_split
tree_dir.py
size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2) self.master.geometry(size) def show_img_in_canvas(self, pil_image): self.imscale = 1.0 # scale for the canvas image zoom, public for outer classes self.__delta = 1.3 # zoom magnitude self....
# Vertical part of the image is in the visible area if box_scroll[1] == box_canvas[1] and box_scroll[3] == box_canvas[3]: box_scroll[1] = self.box_img_int[1]
random_line_split
tree_dir.py
file_list = self.get_path_list() print(file_list) if not file_list: return # merge image # 修复内存泄露的bug,由于没有清除之前打开的图片,第二次打开的图片仍然为之前的图片 try: self.photos.destroy() except: pass self.photos.imgs = file_list merged_photo = s...
"""
identifier_name
tree_dir.py
Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 text = self.item.GetText() or "<no text>" try: self.entry except AttributeError: pass else: self.edit_finish() try: self....
dit) self.label.bind("<Double-1>", self.flip) self.label.bind("<Control-1>", self.select_more) self.label.bind("<3>", self.execute_file) self.text_id = id class AutoScrollbar(ttk.Scrollbar): """ A scrollbar that hides itself if it's not needed. Works only for grid geometry manager ...
=self.label) self.label.bind("<1>", self.select_or_e
conditional_block
tree_dir.py
Double-1>", self.flip) x0, y0, x1, y1 = self.canvas.bbox(id) textx = max(x1, 200) + 10 text = self.item.GetText() or "<no text>" try: self.entry except AttributeError: pass else: self.edit_finish() try: self....
f.get_screen_size(self.master) self.center_window(self.screen_width-50, self.screen_height-50) self.master.resizable(width=False, height=False) self.build_tree_canvas() self.build_tree() self.build_img_canvas() def build_tree_canvas(self): # create frame self...
self.grid_remove() else: self.grid() ttk.Scrollbar.set(self, lo, hi) def pack(self, **kw): raise tk.TclError('Cannot use pack with the widget ' + self.__class__.__name__) def place(self, **kw): raise tk.TclError('Cannot use place with the widget ' + ...
identifier_body
global_stats.rs
_string()}); let hs_deps2 = Histogram { max: hs_deps1.max, buckets: hs_deps1.buckets.split_off(10), bucket_labels: hs_deps1.bucket_labels.split_off(10), }; let rev_deps = kitchen_sink.crates_io_all_rev_deps_counts().await?; let mut hs_rev_deps = Histogram::new(rev_deps, true, ...
, pub title: String, pub label: String, pub font_size: f
ategory
identifier_name
global_stats.rs
, downloads_last_year.1 / 2), max_downloads_per_week, dl_grid_line_every, hs_releases: Histogram::new(kitchen_sink.get_stats_histogram("releases")?.expect("hs_releases"), true, &[1,2,4,8,16,32,50,100,500], |n| if n > 2 {format!("≥{n}")} else {n.to_string()}), hs_sizes: Histogram::new(ki...
at: CATEGORIES.root.values().next().unwrap(), title: String::new(), label: String::new(), font_size: 0., color: String::new(), count: 0, weight: 0., bounds: Rect::new(), sub, } } // names don't fit get_
identifier_body
global_stats.rs
_bad_likely().is_some()) { Some((_, c)) => c, None => latest_ver, }; let newest_bad_raw = latest_ver_bad.newest_bad_likely().unwrap_or(0); let newest_bad = latest_ver.newest_bad().unwrap_or(0); let oldest_ok = latest_ver.oldest_ok().unwrap_or(999); let old...
items_flattened.append(&mut parent.sub);
random_line_split
global_stats.rs
let hs_deps2 = Histogram { max: hs_deps1.max, buckets: hs_deps1.buckets.split_off(10), bucket_labels: hs_deps1.bucket_labels.split_off(10), }; let rev_deps = kitchen_sink.crates_io_all_rev_deps_counts().await?; let mut hs_rev_deps = Histogram::new(rev_deps, true, &[0,1,2...
to_string()});
conditional_block
worker.go
(core.Task, core.TaskErrors) StopTaskTribe(id string) []serror.SnapError StartTaskTribe(id string) []serror.SnapError RemoveTaskTribe(id string) error } type getsMembers interface { GetPluginAgreementMembers() ([]Member, error) GetTaskAgreementMembers() ([]Member, error) GetRequestPassword() string } type Memb...
type worker struct { pluginManager ManagesPlugins memberManager getsMembers taskManager ManagesTasks id int pluginWork chan PluginRequest taskWork chan TaskRequest quitChan chan struct{} waitGroup *sync.WaitGroup logger *log.Entry } func DispatchWorkers(nworkers int, plu...
{ logger := log.WithFields(log.Fields{ "_module": "worker", "worker-id": id, }) worker := worker{ pluginManager: pm, taskManager: tm, memberManager: mm, id: id, pluginWork: pluginQueue, taskWork: taskQueue, waitGroup: wg, quitChan: quitChan, logger: logger...
identifier_body
worker.go
(core.Task, core.TaskErrors) StopTaskTribe(id string) []serror.SnapError StartTaskTribe(id string) []serror.SnapError RemoveTaskTribe(id string) error } type getsMembers interface { GetPluginAgreementMembers() ([]Member, error) GetTaskAgreementMembers() ([]Member, error) GetRequestPassword() string } type Memb...
_, err = w.pluginManager.Load(rp) if err != nil { logger.Error(err) return err } if w.isPluginLoaded(plugin.Name(), plugin.TypeName(), plugin.Version()) { return nil } return errors.New("failed to load plugin") } return errors.New("failed to find a member with the plugin") } func (w worker) dow...
{ logger.Error(err) return err }
conditional_block
worker.go
++ time.Sleep(retryDelay) w.pluginWork <- work } } } case <-w.quitChan: w.logger.Debug("stop tribe plugin worker") return } } }() } func (w worker) unloadPlugin(plugin core.Plugin) error { logger := w.logger.WithFields(log.Fields{ "plugin-name": plugin.Name(), "plu...
getSchedule
identifier_name
worker.go
) (core.Task, core.TaskErrors) StopTaskTribe(id string) []serror.SnapError StartTaskTribe(id string) []serror.SnapError RemoveTaskTribe(id string) error } type getsMembers interface { GetPluginAgreementMembers() ([]Member, error) GetTaskAgreementMembers() ([]Member, error) GetRequestPassword() string } type Mem...
GetAddr() net.IP GetRestPort() string GetRestProto() string GetRestInsecureSkipVerify() bool GetName() string } // newPluginWorker func newWorker(id int, pluginQueue chan PluginRequest, taskQueue chan TaskRequest, quitChan chan struct{}, wg *sync.WaitGroup, pm ManagesPlugins, tm ManagesTasks, mm getsMember...
random_line_split
selection_test.go
pg(p1, p3), pg(p1, p4), pg(p2, p3), pg(p2, p4), // Org1 and Org3 pg(p1, p5), pg(p1, p6), pg(p1, p7), pg(p2, p5), pg(p2, p6), pg(p2, p7), // Org1 and Org4 pg(p1, p8), pg(p1, p9), pg(p1, p10), pg(p2, p8), pg(p2, p9), pg(p2, p10), // Org1 and Org3 and Org4 pg(p1, p5, p8), pg(p1, p5, p9), pg(p1, p5, p10), pg(p...
{ panic(err) }
conditional_block
selection_test.go
), pg(p2, p5, p8), pg(p2, p5, p9), pg(p2, p5, p10), pg(p2, p6, p8), pg(p2, p6, p9), pg(p2, p6, p10), pg(p2, p7, p8), pg(p2, p7, p9), pg(p2, p7, p10), } verify(t, service, expected, channel1, cc1, cc2) } func TestGetEndorsersForChaincodeTwoCCsTwoChannels(t *testing.T) { service := newMockSelectionService( newMoc...
{ return &mockMembershipManager{peerConfigs: make(map[string][]api.ChannelPeer)} }
identifier_body
selection_test.go
", SwOpts: &bccspFactory.SwOpts{ HashFamily: "SHA2", SecLevel: 256, Ephemeral: false, FileKeystore: &bccspFactory.FileKeystoreOpts{KeyStorePath: "../sampleconfig/msp/keystore/"}, }, } bccspFactory.InitFactories(opts) // configData, err := ioutil.ReadFile("../sampleconfig/config.yaml") if ...
add(channel1, cc1, getPolicy1()), pgresolver.NewRoundRobinLBP()) // Channel1(Policy(cc1)) = Org1 expected := []api.PeerGroup{ // Org1 pg(p1), pg(p2), } verify(t, service, expected, channel1, cc1) } func TestGetEndorsersForChaincodeTwoCCs(t *testing.T) { service := newMockSelectionService( newMockMembe...
newMockMembershipManager(). add(channel1, p1, p2, p3, p4, p5, p6, p7, p8), newMockCCDataProvider().
random_line_split
selection_test.go
MSP") stub.MockTransactionStart("startTxn") stub.ChannelID = channelID return stub } //uplaodConfigToHL to upload key&config to repository func uplaodConfigToHL(stub *mockstub.MockStub, config []byte) error { configManager := mgmt.NewConfigManager(stub) if configManager == nil { return fmt.Errorf("Cannot insta...
verify
identifier_name
mod.rs
" }, /// Record { count: 10, animal: "cheetah", description: "fast" }, /// Record { count: 4, animal: "armadillo", description: "armored" }, /// Record { count: 9, animal: "platypus", description: "unique" }, /// ]; /// /// let mut wtr = typed_csv::Writer::from_memory(); /// for record in records.into_iter(...
// Write row. let mut erecord = csv::Encoded::new(); row.encode(&mut erecord)?; self.csv.write(erecord.unwrap().into_iter()) } /// Flushes the underlying buffer. pub fn flush(&mut self) -> Result<()> { self.csv.flush() } } #[cfg(test)] mod tests { use super...
{ let mut field_names_encoder = FieldNamesEncoder::new(); row.encode(&mut field_names_encoder)?; self.csv.write(field_names_encoder.into_field_names().into_iter())?; self.first_row = false; }
conditional_block
mod.rs
happy" }, /// Record { count: 10, animal: "cheetah", description: "fast" }, /// Record { count: 4, animal: "armadillo", description: "armored" }, /// Record { count: 9, animal: "platypus", description: "unique" }, /// ]; /// /// let mut wtr = typed_csv::Writer::from_memory(); /// for record in records.into_...
() { let mut w = Writer::from_memory(); let s1 = SimpleStruct { a: 0, b: 1 }; w.encode(s1).unwrap(); let s2 = SimpleStruct { a: 3, b: 4 }; w.encode(s2).unwrap(); assert_eq!(w.as_string(), "a,b\n0,1\n3,4\n"); } #[test] fn test_tuple_of_structs() { let ...
test_struct
identifier_name
mod.rs
happy" }, /// Record { count: 10, animal: "cheetah", description: "fast" }, /// Record { count: 4, animal: "armadillo", description: "armored" }, /// Record { count: 9, animal: "platypus", description: "unique" }, /// ]; /// /// let mut wtr = typed_csv::Writer::from_memory(); /// for record in records.into_...
/// ), /// ( /// Part1 { count: Count(9), animal: "platypus" }, /// Part2 { group: Group::Mammal, description: None }, /// ), /// ]; /// /// let mut wtr = typed_csv::Writer::from_memory(); /// for record in records.into_iter() { /// wtr.encode(reco...
random_line_split
mod.rs
" }, /// Record { count: 10, animal: "cheetah", description: "fast" }, /// Record { count: 4, animal: "armadillo", description: "armored" }, /// Record { count: 9, animal: "platypus", description: "unique" }, /// ]; /// /// let mut wtr = typed_csv::Writer::from_memory(); /// for record in records.into_iter(...
} impl<W: Write, E: Encodable> Writer<W, E> { /// Writes a record by encoding any `Encodable` value. /// /// When the first record is encoded, the headers (the field names in the /// struct) are written prior to encoding the record. /// /// The type that is being encoded into should correspond...
{ self.csv.into_bytes() }
identifier_body
interlock_handler.go
posetPosetDagContext struct { *evalContext dbReader *dbreader.DBReader lockStore *lockstore.MemStore resolvedLocks []uint64 posetPosetDagReq *fidelpb.PosetDagRequest keyRanges []*interlock.KeyRange startTS uint64 } // handleCoFIDelAGRequest handles interlock PosetDag request. ...
return heap, conds, nil } type evalContext struct { colIDs map[int64]int columnInfos []*fidelpb.DeferredCausetInfo fieldTps []*types.FieldType primaryDefCauss []int64 sc *stmtctx.StatementContext } func (e *evalContext) setDeferredCausetInfo(defcaus []*fidelpb.DeferredCausetInfo...
}
random_line_split
widget.js
Stage.Basic.NodeFilter.EMPTY_VALUE, storeValueInContext: true}, {id: 'charts', name: 'Charts table', description: 'Charts configuration table', default: '', type: Stage.Basic.GenericField.CUSTOM_TYPE, component: Stage.Basic.Form.Table, rows: 5, columns: [ {name: 'metric', label: 'Metric',...
(string){ return string.replace(/;/g, ''); }, _prepareInfluxQuery: function(queries, deploymentId, nodeId, nodeInstanceId, from, to, timeGroup) { return _.map(queries, (queryParams) => { let selectWhat = this._sanitizeQuery(queryParams.qSelect); let selectFrom = this._sa...
_sanitizeQuery
identifier_name
widget.js
Stage.Basic.NodeFilter.EMPTY_VALUE, storeValueInContext: true}, {id: 'charts', name: 'Charts table', description: 'Charts configuration table', default: '', type: Stage.Basic.GenericField.CUSTOM_TYPE, component: Stage.Basic.Form.Table, rows: 5, columns: [ {name: 'metric', label: 'Metric',...
deploymentId = nodeFilterFromWidget.deploymentId; nodeId = nodeFilterFromWidget.nodeId; nodeInstanceId = nodeFilterFromWidget.nodeInstanceId; } let timeFilterFromWidget = widget.configuration.timeFilter; let timeFilterFromContext = toolbox.getContext().getVal...
let nodeId = toolbox.getContext().getValue('nodeId'); let nodeInstanceId = toolbox.getContext().getValue('nodeInstanceId'); let nodeFilterFromWidget = widget.configuration.nodeFilter; if (nodeFilterFromWidget.deploymentId || nodeFilterFromWidget.nodeId || nodeFilterFromWidget.nodeInstanc...
random_line_split
widget.js
.Basic.NodeFilter.EMPTY_VALUE, storeValueInContext: true}, {id: 'charts', name: 'Charts table', description: 'Charts configuration table', default: '', type: Stage.Basic.GenericField.CUSTOM_TYPE, component: Stage.Basic.Form.Table, rows: 5, columns: [ {name: 'metric', label: 'Metric', defau...
, _prepareInfluxQuery: function(queries, deploymentId, nodeId, nodeInstanceId, from, to, timeGroup) { return _.map(queries, (queryParams) => { let selectWhat = this._sanitizeQuery(queryParams.qSelect); let selectFrom = this._sanitizeQuery(queryParams.qFrom); let selectWh...
{ return string.replace(/;/g, ''); }
identifier_body
widget.js
}, {id: 'type', name: 'Charts type', items: [ {name:'Line chart', value:Stage.Basic.Graphs.Graph.LINE_CHART_TYPE}, {name:'Bar chart', value:Stage.Basic.Graphs.Graph.BAR_CHART_TYPE}, {name:'Area chart', value:Stage.Basic.Graphs.Graph.AREA_CHART_TYPE}], default: Stage....
{ return ( <Message info icon> <Icon name='info' /> Please select deployment, node instance and metric in widget's configuration to present the data graph. </Message> ); }
conditional_block
parse.go
ds = p.closeStruct(state) } } else { p.err = "mismatched delimiter" return 1 } p.popState(ds) } return 1 case '(': p.pushState(root, PFLAG_CONTAINER|PFLAG_PARENS) return 1 case '[': p.pushState(root, PFLAG_CONTAINER|PFLAG_SQRBRACKETS) return 1 case '{': p.pushState(root, PFLAG_CON...
Produce
identifier_name
parse.go
letter */ func toHex(c byte) int { if c >= '0' && c <= '9' { return int(c) - '0' } else if c >= 'A' && c <= 'F' { return 10 + int(c) - 'A' } else if c >= 'a' && c <= 'f' { return 10 + int(c) - 'a' } else { return -1 } } func (parser *Parser) checkDead() { if parser.flag != 0 { JanetPanic("parser is de...
for i := state.argn - 1; i >= 0; i = i - 1 { array.Data[i] = p.args[len(p.args)-1] p.args = p.args[:len(p.args)-1] } return array } func (p *Parser) closeTuple(state *ParseState, flags int) *Tuple { tup := NewTuple(state.argn, state.argn) tup.Flags = flags for i := state.argn - 1; i >= 0; i = i - 1 { tup.V...
} func (p *Parser) closeArray(state *ParseState) *Array { array := NewArray(state.argn, state.argn)
random_line_split
parse.go
*/ func toHex(c byte) int { if c >= '0' && c <= '9' { return int(c) - '0' } else if c >= 'A' && c <= 'F' { return 10 + int(c) - 'A' } else if c >= 'a' && c <= 'f' { return 10 + int(c) - 'a' } else { return -1 } } func (parser *Parser) checkDead() { if parser.flag != 0 { JanetPanic("parser is dead, can...
t := NewTuple(2, 2) c := newtop.flags & 0xFF switch c { case '\'': which = "quote" case ',': which = "unquote" case ';': which = "splice" case '|': which = "short-fn" case '~': which = "quasiquote" default: } t.Vals[0] = Symbol(which) t.Vals[1] = val /* Quote ...
{ top := p.states[len(p.states)-1] p.states = p.states[:len(p.states)-1] newtop := &p.states[len(p.states)-1] if (newtop.flags & PFLAG_CONTAINER) != 0 { switch val := val.(type) { case *Tuple: val.Line = top.line val.Column = top.column default: } newtop.argn += 1 /* Keep track of numb...
conditional_block
parse.go
func checkEscape(c byte) int { switch c { default: return -1 case 'x': return 1 case 'n': return '\n' case 't': return '\t' case 'r': return '\r' case '0': return 0 case 'z': return 0 case 'f': return '\f' case 'v': return '\v' case 'e': return 27 case '"': return '"' case '\\': r...
{ return (symchars[c>>5] & (uint32(1) << (c & 0x1F))) != 0 }
identifier_body
flux_calc.py
in_dir = out_dir0 + 'gridded_polygons/' out_dir = out_dir0 + 'fluxes/' Lfun.make_dir(out_dir, clean=True) # load polygon results gpoly_dict = pickle.load(open(in_dir + 'gpoly_dict.p', 'rb')) shared_faces_dict = pickle.load(open(in_dir + 'shared_faces.p', 'rb')) # and specify z levels z_dict = {0:5, 1:-5, 2:-25, 3:...
out_dir0 = Ldir['parent'] + 'ptools_output/atlantis_fjord_2005/'
random_line_split
flux_calc.py
results of z level code # RESULT it works perfectly (to within roundoff error I think) fzt = 0. fza = 0. for nlay in range(NLAY): fzt += face_ztrans_dict[(npoly, nface, nlay)][0] fza += face_ztrans_dict[(npoly, nface, nlay)][1] if np.abs(fzt - face_trans_...
(face_ztrans, face_zarea) = face_ztrans_dict[(npoly, nface, nlay)] cc += face_ztrans
conditional_block
mpcs_app.py
password'), success_redirect=request.POST.get('redirect_url'), fail_redirect='/login') @route('/logout', method='GET', name="logout") def logout(): log.info(request.url) auth.logout(success_redirect='/login') ''' **************************************************************************...
'Key': resultfile[0] + '/' + resultfile[1] } )
random_line_split
mpcs_app.py
******************************************************************************* ''' import stripe # Display form to get subscriber credit card info @route('/subscribe', method='GET', name="subscribe") def subscribe(): log.info(request.url) # Check that user is authenticated auth.require(fail_redirect='/login?r...
conditional_block
mpcs_app.py
mpcs.env.templates'] + 'register_confirm', auth=auth, success=False, error_message=error) return template(request.app.config['mpcs.env.templates'] + 'register_confirm', auth=auth, success=True, error_message=None) ''' ******************************************************************************* Login, l...
get_annotation_details
identifier_name
mpcs_app.py
def register_confirm(reg_code): log.info(request.url) try: auth.validate_registration(reg_code) except Exception, error: return template(request.app.config['mpcs.env.templates'] + 'register_confirm', auth=auth, success=False, error_message=error) return template(request.app.config['mpcs.env.templ...
auth.require(fail_redirect='/login?redirect_url=' + request.url) # Get the current username username = auth.current_user.username res = ann_table.query( IndexName='username_index', KeyConditionExpression=Key('username').eq(username)) # Get all the relevant detail about current user items = res['Items'] ...
identifier_body
blockchain.go
(address string) *BlockChain { //return &BlockClain{ // []*Block{genesisBlock}, //} var lastHash []byte db, err := bolt.Open(BlockChainDB, 0600, nil) //defer db.Close() if err != nil { log.Fatal("create database failed") } err = db.Update(func(tx *bolt.Tx) error { bucket := tx.Bucket([]byte(BlockBucket)...
NewBlockChain
identifier_name
blockchain.go
xs, lastHash) bucket.Put(block.Hash,block.Serialize()) bucket.Put([]byte("LastHashKey"),block.Hash) //update the last hash bc.tail = block.Hash } return nil }) } //正向打印区块链 func (bc *BlockChain) Printchain() { bcI := bc.NewIterator() var blockHeight int var blocks []*Block for { block := bcI....
if !transaction.IsCoinbase(){ //遍历input,找到花费过的utxo的集合 for _, input := range transaction.TXInputs{ if bytes.Equal(HashPubKey(input.PubKey),pubKeyHash){ //key为签名的那个交易 //indexArray := spentOutput[string(input.TXID)] // //这个数组为签名的那个交易中 已经消费过的output的index值 //indexArray = append(indexA...
//找错误, continue只能跳出最近的for循环 fmt.Println(j) fmt.Println(i) var a bool a = int64(i) == j fmt.Println(a) */ //标识过下标和循环中的下标对比, 过滤到已经消费的output if int64(i) == j{ continue OUTPUT } } } if bytes.Equal(output.PubKeyHash,pubKeyHash){ //fmt.Pr...
conditional_block
blockchain.go
ddBlock 6.add a new block func (bc *BlockChain)AddBlock(txs []*Transaction) { for _, tx := range txs{ if !bc.VerifyTransaction(tx) { fmt.Println("校验交易失败") return } } //found the last block's hash lastHash := bc.tail db := bc.db //create a new block //send the new block into the blockchain db.Update...
{ coinBase := NewCoinbaseTX(address, "创世块") coinBases := []*Transaction{coinBase} return NewBlock(coinBases, []byte{}) } // A
identifier_body
blockchain.go
(txs, lastHash) bucket.Put(block.Hash,block.Serialize()) bucket.Put([]byte("LastHashKey"),block.Hash) //update the last hash bc.tail = block.Hash } return nil }) } //正向打印区块链 func (bc *BlockChain) Printchain() { bcI := bc.NewIterator() var blockHeight int var blocks []*Block for { block := bc...
return UTXO } //找到指定地址所有的UTXO,即未消费的,优化上面函数 //func (bc *BlockChain)FindUTXOs(pubKeyHash []byte) []TXOuput { // var UTXO []TXOuput // txs := bc.FindUTXOsBased(pubKeyHash) // for _, tx := range txs{ // for _, output := range tx.TXOuputs{ // if bytes.Equal(pubKeyHash,output.PubKeyHash){ // UTXO = append(UTXO, outpu...
} }
random_line_split
app.py
) #Create instance of controller to perform some operations n_controller = news_controller.NewsController(db) # Create instance of news controller to perform some operations b_controller = blogger_controller.BloggerController(db) #Create instance of blogger controller to perform some operations CORS(app) # ...
except: # To notify if a student hasn't conformed to an acceptable input format. return {'Error': 'Unable to retrieve student details. Ensure the inputs are valid'} elif str(user_type) == 'Lecturer': try: # Get additional inpuuts for lecturers depart...
return {'Error': 'This email has already been used to register'}
conditional_block
app.py
) #Create instance of controller to perform some operations n_controller = news_controller.NewsController(db) # Create instance of news controller to perform some operations b_controller = blogger_controller.BloggerController(db) #Create instance of blogger controller to perform some operations CORS(app) # ...
level_id = request.form.get('level_id') if getemail == None: # If email is not already registered, input the data into the database controller.add_data(student_model.Student( user_name, surname, first_name, email, password, user_type, program_id, matric_no,...
try: # Gets all input data from the user user_name = request.form.get('user_name') surname = request.form.get('surname') first_name = request.form.get('first_name') email = request.form.get('email') password = bcrypt.generate_password_hash(request.form.get('password')).de...
identifier_body
app.py
('department_id') title = request.form.get('title') position = request.form.get('position') if getemail == None: # If email is not already registered, input the data into the database controller.add_data(lecturer_model.Lecturer( user_name, surnam...
update_calendar
identifier_name
app.py
) #Create instance of controller to perform some operations n_controller = news_controller.NewsController(db) # Create instance of news controller to perform some operations b_controller = blogger_controller.BloggerController(db) #Create instance of blogger controller to perform some operations CORS(app) # ...
try: resp = controller.get_user(id) #Gets the details of a user given the user id. return resp.to_dict() except: return {'Error': 'User not found'} # Function to login @app.route('/token/auth', methods=['POST']) def login(): # Gets email and password inputed by the user emai...
# Function to retrieve a user details based on id @app.route('/users/<id>', methods=['GET']) @login_required def get_user(id):
random_line_split
DQN_Snake.py
import matplotlib.pyplot as plt from BrainDQN_Nature import BrainDQN ################################################################################################################## ################################################################################################################## import random, pyg...
random_line_split
DQN_Snake.py
global FPSCLOCK, DISPLAYSURF, BASICFONT pygame.init() # 初始化pygame FPSCLOCK = pygame.time.Clock() # 獲得pygame時鐘 DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) # 設置螢幕寬高 BASICFONT = pygame.font.Font('freesansbold.ttf', 18) # BASICFONT pygame.display.set_caption('Greedy Snake') # 設置視窗的標題 s...
reward=LOSE_REWARD print ("撞牆死....") for wormBody in self.wormCoords[1:]: # 檢查貪吃蛇是否撞到自己 if wormBody['x'] == self.wormCoords[self.HEAD]['x'] and wormBody['y'] == self.wormCoords[self.HEAD]['y']: terminal=True reward=LOSE_REWARD print ("撞自己死....") break if terminal==False: # 檢查貪吃蛇是否吃到appl...
: terminal=True
conditional_block
DQN_Snake.py
global FPSCLOCK, DISPLAYSURF, BASICFONT pygame.init() # 初始化pygame FPSCLOCK = pygame.time.Clock() # 獲得pygame時鐘 DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) # 設置螢幕寬高 BAS
andom.randint(5, CELLHEIGHT - 6) # 以這個點為起點,建立一個長度為3格的貪吃蛇(陣列) self.wormCoords = [{'x': startx, 'y': starty}, {'x': startx - 1, 'y': starty}, {'x': startx - 2, 'y': starty}] self.direction = RIGHT # 初始化一個運動的方向 self.apple = self.getRandomLocation() # 隨機一個app...
ICFONT = pygame.font.Font('freesansbold.ttf', 18) # BASICFONT pygame.display.set_caption('Greedy Snake') # 設置視窗的標題 self.HEAD = 0 # syntactic sugar: index of the worm's head # 貪吃蛇的頭() self.Bodylen=3 #showStartScreen() # 顯示開始畫面 self.runGame() def getRandomLocation(self): # 隨機生成一個座標位置 return {'x': ra...
identifier_body
DQN_Snake.py
FPSCLOCK, DISPLAYSURF, BASICFONT pygame.init() # 初始化pygame FPSCLOCK = pygame.time.Clock() # 獲得pygame時鐘 DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) # 設置螢幕寬高 BASICFONT = pygame.font.Font('freesansbold.ttf', 18) # BASICFONT pygame.display.set_caption('Greedy Snake') # 設置視窗的標題 self.HEAD...
lf.direction!=LEFT and self.direction!=RIGHT : self.direction = RIGHT elif action==MOVE_UP and self.direction!=UP and self.direction!=DOWN: self.direction = UP elif action==MOVE_DOWN and self.direction!=UP and self.direction!=DOWN: self.direction = DOWN elif action==MOVE_STAY : pass # 檢查貪吃蛇是否撞到撞到邊界 if self.w...
GHT and se
identifier_name
JS_Exercises.js
["Volvo", "Jeep", "Mercedes"]; // cars[0] = "Ford"; // console.log(cars[0]); // JS Arrays 3-1: Alert the number of items in an array, using the correct Array property. // const cars = ["Volvo", "Jeep", "Mercedes"]; // alert(cars.length); // JS Array Methods 1-1: Use the correct Array method to remove the last item of ...
// JS HTML DOM 9-1: Use the eventListener to assign an onclick event to the <button> element.
random_line_split
http_ece.rs
_key` is the `p256dh` and `peer_secret` the `auth` from /// browser subscription info. pub fn new( encoding: ContentEncoding, peer_public_key: &'a [u8], peer_secret: &'a [u8], vapid_signature: Option<VapidSignature>, ) -> HttpEce<'a> { HttpEce { rng: rand:...
} pub fn generate_headers( &self, public_key: &'a [u8], salt: &'a [u8], ) -> Vec<(&'static str, String)> { let mut crypto_headers = Vec::new(); let mut crypto_key = format!("dh={}", base64::encode_config(public_key, URL_SAFE_NO_PAD)); if let Some(ref signat...
random_line_split
http_ece.rs
_info], EceKey(12)) .unwrap() .into(); let mut nonce = EceNonce::default(); nonce.fill(nonce_bytes); let unbound_key = aead::UnboundKey::new(&aead::AES_128_GCM, &content_encryption_key)?; let mut sealing_key = aead::SealingKey::new(unbound_key, nonce); ...
test_front_pad
identifier_name
http_ece.rs
_key` is the `p256dh` and `peer_secret` the `auth` from /// browser subscription info. pub fn new( encoding: ContentEncoding, peer_public_key: &'a [u8], peer_secret: &'a [u8], vapid_signature: Option<VapidSignature>, ) -> HttpEce<'a> { HttpEce { rng: rand:...
/// The aesgcm encrypted content-encoding, draft 3. pub fn aes_gcm( &self, shared_secret: &'a [u8], as_public_key: &'a [u8], salt_bytes: &'a [u8], payload: &'a mut Vec<u8>, ) -> Result<(), WebPushError> { let mut context = Vec::with_capacity(140); c...
{ let mut crypto_headers = Vec::new(); let mut crypto_key = format!("dh={}", base64::encode_config(public_key, URL_SAFE_NO_PAD)); if let Some(ref signature) = self.vapid_signature { crypto_key = format!("{}; p256ecdsa={}", crypto_key, signature.auth_k); let sig_s: Stri...
identifier_body
http_ece.rs
_key` is the `p256dh` and `peer_secret` the `auth` from /// browser subscription info. pub fn new( encoding: ContentEncoding, peer_public_key: &'a [u8], peer_secret: &'a [u8], vapid_signature: Option<VapidSignature>, ) -> HttpEce<'a> { HttpEce { rng: rand:...
let private_key = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &self.rng)?; let public_key = private_key.compute_public_key()?; let mut salt_bytes = [0u8; 16]; self.rng.fill(&mut salt_bytes)?; let peer_public_key = agreement::UnparsedPublicKey::n...
{ return Err(WebPushError::PayloadTooLarge); }
conditional_block
weights_manager.py
_stride=1, stem_affine=True, stem_multiplier=1, # candidate candidate_eval_no_grad=True, # schedule schedule_cfg=None, ): super().__init__(search_space, device, rollout_type, schedule_cfg) nn.Module.__init__(self) self.macro_search_space = ( ...
if use_op != 0: outputs.append(op(inputs))
conditional_block
weights_manager.py
# type: Layer2Rollout def begin_virtual(self):
def forward(self, inputs): return self.supernet.forward(inputs, self.rollout) def _forward_with_params(self, *args, **kwargs): raise NotImplementedError() def get_device(self): return self.supernet.device class Layer2MacroSupernet(BaseWeightsManager, nn.Module): NAME = "lay...
raise NotImplementedError()
identifier_body
weights_manager.py
num_classes=10, dropout_rate=0.0, max_grad_norm=None, # stem use_stem="conv_bn_3x3", stem_stride=1, stem_affine=True, stem_multiplier=1, # candidate candidate_eval_no_grad=True, # schedule schedule_cfg=None, ): super()....
forward
identifier_name
weights_manager.py
rollout # type: Layer2Rollout def begin_virtual(self): raise NotImplementedError() def forward(self, inputs): return self.supernet.forward(inputs, self.rollout) def _forward_with_params(self, *args, **kwargs): raise NotImplementedError() def get_device(self): return...
self.classifier = nn.Linear(prev_num_channels, num_classes) self.to(self.device) def forward( self, inputs, rollout, # type: Layer2Rollout ): macro_rollout = rollout.macro # type: StagewiseMacroRollout micro_rollout = rollout.micro # type: DenseMicroR...
prev_num_channels = num_channels # make pooling and classifier self.pooling = nn.AdaptiveAvgPool2d((1, 1)) self.dropout = nn.Dropout(dropout_rate) if dropout_rate else nn.Identity()
random_line_split
downloadtaskmgr.go
*DownloadTask, 1024*5)}, //500KB/s {SpeedLimitKBs: 1500, CountLimit: ChannelRunningSize[3], RunningCountControlChan: make(chan bool, ChannelRunningSize[3]), IdleChan: make(chan *DownloadTask, 1024*3)}, //1500KB/s {SpeedLimitKBs: 2500, CountLimit: ChannelRunningSize[4], RunningCountControlChan: make(chan bool, Chann...
() []*DownloadTask { taskInLDB := LoopTasksInLDB() if taskInLDB == nil { return nil } list := []*DownloadTask{} for _, v := range taskInLDB { list = append(list, v) } return list } func TaskSuccess(task *DownloadTask) { logger.Debug("Task Success", "id", task.Id) //从map中删除任务 DelTaskFromLDB(task.Id) Del...
GetDownloadTaskList
identifier_name
downloadtaskmgr.go
Continent string Country string Area string SavePath string DownloadType string OriginRegion string TargetRegion string } type TaskStatus string //const Task_Success TaskStatus = "success" //const Task_Fail TaskStatus ="fail" const Task_UnStart TaskStatus = "unstart" const Task_Break TaskSt...
type DownloadInfo struct { TargetUrl string BindName string FileName string
random_line_split
downloadtaskmgr.go
CountLimit: ChannelRunningSize[3], RunningCountControlChan: make(chan bool, ChannelRunningSize[3]), IdleChan: make(chan *DownloadTask, 1024*3)}, //1500KB/s {SpeedLimitKBs: 2500, CountLimit: ChannelRunningSize[4], RunningCountControlChan: make(chan bool, ChannelRunningSize[4]), IdleChan: make(chan *DownloadTask, 1024*...
select { case task := <-globalDownloadTaskChan: //开始一个新下载任务 go func() { //任务结束,放回token defer func() { newRunningTaskControlChan <- true }() //执行任务 //logger.Debug("start a new task", "id", task.Id) task.Status = Task_Downloading AddTaskToDownloadingMap(task) Start...
identifier_body