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
modules.go
package venus_sealer import ( "context" "crypto/rand" "encoding/hex" "errors" "math" "net/http" "time" "github.com/filecoin-project/go-bitfield" proof2 "github.com/filecoin-project/specs-actors/v2/actors/runtime/proof" api2 "github.com/filecoin-project/venus-market/api" "github.com/gbrlsnchs/jwt/v3" "git...
_, err = prover.ComputeProof(ctx, []proof2.SectorInfo{ { SealProof: si.SealProof, SectorNumber: sector, SealedCID: si.SealedCID, }, }, r) if err != nil { log.Errorw("failed to compute proof: %w, please check your storage and restart sealer after fixed", err) return nil } log.Infow("winnin...
{ return xerrors.Errorf("getting sector info: %w", err) }
conditional_block
modules.go
package venus_sealer import ( "context" "crypto/rand" "encoding/hex" "errors" "math" "net/http" "time" "github.com/filecoin-project/go-bitfield" proof2 "github.com/filecoin-project/specs-actors/v2/actors/runtime/proof" api2 "github.com/filecoin-project/venus-market/api" "github.com/gbrlsnchs/jwt/v3" "git...
func mutateCfg(cfg *config.StorageMiner, mutator func(*config.StorageMiner)) error { var typeErr error setConfigErr := cfg.LocalStorage().SetConfig(func(raw interface{}) { cfg, ok := raw.(*config.StorageMiner) if !ok { typeErr = errors.New("expected miner config") return } mutator(cfg) }) return m...
{ accessor(cfg) return nil }
identifier_body
modules.go
package venus_sealer import ( "context" "crypto/rand" "encoding/hex" "errors" "math" "net/http" "time" "github.com/filecoin-project/go-bitfield" proof2 "github.com/filecoin-project/specs-actors/v2/actors/runtime/proof" api2 "github.com/filecoin-project/venus-market/api" "github.com/gbrlsnchs/jwt/v3" "git...
_, err = prover.ComputeProof(ctx, []proof2.SectorInfo{ { SealProof: si.SealProof, SectorNumber: sector, SealedCID: si.SealedCID, }, }, r) if err != nil { log.Errorw("failed to compute proof: %w, please check your storage and restart sealer after fixed", err) return nil } log.Infow("winning...
si, err := api.StateSectorGetInfo(ctx, maddr, sector, types.EmptyTSK) if err != nil { return xerrors.Errorf("getting sector info: %w", err) }
random_line_split
asset.rs
/* * This file is part of the UnityPack rust package. * (c) Istvan Fehervari <gooksl@gmail.com> * * All rights reserved 2017 */ use assetbundle::AssetBundle; use assetbundle::Signature; use assetbundle::FSDescriptor; use typetree::{TypeMetadata, TypeNode}; use resources::default_type_metadata; use binaryreader::*...
{ asset_path: String, guid: Uuid, asset_type: i32, pub file_path: String, // probably want to add a reference to the calling Asset itself } impl AssetRef { pub fn new<R: Read + Seek + Teller>( buffer: &mut R, endianness: &Endianness, ) -> Result<AssetRef> { let asse...
AssetRef
identifier_name
asset.rs
/* * This file is part of the UnityPack rust package. * (c) Istvan Fehervari <gooksl@gmail.com> * * All rights reserved 2017 */ use assetbundle::AssetBundle; use assetbundle::Signature; use assetbundle::FSDescriptor; use typetree::{TypeMetadata, TypeNode}; use resources::default_type_metadata; use binaryreader::*...
} self.objects.insert(obj.path_id, obj); Ok(()) } pub fn read_id<R: Read + Seek + Teller>(&self, buffer: &mut R) -> io::Result<i64> { if self.format >= 14 { return buffer.read_i64(&self.endianness); } let result = buffer.read_i32(&self.endianness)? ...
{}
conditional_block
asset.rs
/* * This file is part of the UnityPack rust package. * (c) Istvan Fehervari <gooksl@gmail.com> * * All rights reserved 2017 */ use assetbundle::AssetBundle; use assetbundle::Signature; use assetbundle::FSDescriptor; use typetree::{TypeMetadata, TypeNode}; use resources::default_type_metadata; use binaryreader::*...
}
pub enum AssetOrRef { Asset, AssetRef(AssetRef),
random_line_split
TripAdvisor.py
from selenium import webdriver import time import csv preUrl = 'https://www.tripadvisor.com/Restaurant_Review' country_name = '' prefixOfFileName = time.strftime("%Y%m%d%H%M%S", time.localtime()) fileName = 'RESULT_SINGAPORE_' + prefixOfFileName + '.csv' # Make the preURL complete to be full URL # Argument: informat...
print('----------analyzeRating finished----------') return result # Read the postfix of URL file from desktop # Argument: country one of (South Korea, Singapore, Shanghai), STRING # Return type: information of restaurant, 2-D LIST [[numOfStar, postfixUrl, nameOfRestaurant], [numOfStar, ...], ...] def readP...
if e == '1.0 of 5 bubbles': result.append('1') elif e == '2.0 of 5 bubbles': result.append('2') elif e == '3.0 of 5 bubbles': result.append('3') elif e == '4.0 of 5 bubbles': result.append('4') elif e == '5.0 of 5 bubbles': resu...
conditional_block
TripAdvisor.py
from selenium import webdriver import time import csv preUrl = 'https://www.tripadvisor.com/Restaurant_Review' country_name = '' prefixOfFileName = time.strftime("%Y%m%d%H%M%S", time.localtime()) fileName = 'RESULT_SINGAPORE_' + prefixOfFileName + '.csv' # Make the preURL complete to be full URL # Argument: informat...
(driver): result = [] basics = driver.find_elements_by_class_name('inlineReviewUpdate') for inner in basics: if inner.text == '': continue #col = inner.find_element_by_class_name('col1of2') #memberInfo = inner.find_element_by_class_name('member_info') try: locati...
getMemberLocationInfo
identifier_name
TripAdvisor.py
from selenium import webdriver import time import csv preUrl = 'https://www.tripadvisor.com/Restaurant_Review' country_name = '' prefixOfFileName = time.strftime("%Y%m%d%H%M%S", time.localtime()) fileName = 'RESULT_SINGAPORE_' + prefixOfFileName + '.csv' # Make the preURL complete to be full URL # Argument: informat...
# Collect the reviews from 'TripAdvisor.com' # Argument: URL for collecting reviews and ratings, STRING # Return type: none def collectReviews(driver, URL): print('----------collectReviews is called----------') rating = [] dates = [] locations = [] try: parentOfMore = driver.find_elemen...
print('----------calculateNumOfPages is called----------') if int(numOfReviews/10) > 0: if numOfReviews%10 == 0: numOfPages = int(numOfReviews/10) else: numOfPages = int(numOfReviews/10) + 1 elif int(numOfReviews/10) == 0: if numOfReviews%10 == 0: numO...
identifier_body
TripAdvisor.py
from selenium import webdriver import time import csv preUrl = 'https://www.tripadvisor.com/Restaurant_Review' country_name = '' prefixOfFileName = time.strftime("%Y%m%d%H%M%S", time.localtime()) fileName = 'RESULT_SINGAPORE_' + prefixOfFileName + '.csv' # Make the preURL complete to be full URL # Argument: informat...
return result # Write the reviews, ratings and the others to csv file # Argument: file_name, reviews, ratings, STRING, LIST, LIST # Return type: none def writeReviewsToFile(fileName, reviews, ratings, locations, dates): with open(fileName, 'a') as csvFile: csvWriter = csv.writer(csvFile) idx =...
print('----------readPostifxFormFile finished----------')
random_line_split
hooks.py
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
def ProcessDatasetOverwrite(ref, args, request): """Process the if-exists flag on datasets create.""" del ref dataset_id = request.dataset.datasetReference.datasetId project_id = request.projectId if args.overwrite: if _DatasetExists(dataset_id, project_id): _TryDeleteDataset(dataset_id, projec...
"""Ensure that view parameters are set properly tables create request.""" del ref # unused if not args.view: request.table.view = None return request
identifier_body
hooks.py
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
(ref, args, request): """Process the overwrite flag on tables copy.""" del ref # Unused if args.overwrite: request.job.configuration.copy.writeDisposition = 'WRITE_TRUNCATE' return request def ProcessTableCopyConfiguration(ref, args, request): """Build JobConfigurationTableCopy from request resource a...
ProcessTableCopyOverwrite
identifier_name
hooks.py
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
delete_request_type = GetApiMessage('BigqueryTablesDeleteRequest') delete_request = delete_request_type(datasetId=dataset_id, tableId=table_id, projectId=project_id) service.Delete(delete_request) log.info('Deleted table [{}:{}:{}]'.format(project_id, dataset_id, table_id)...
random_line_split
hooks.py
# -*- coding: utf-8 -*- # # Copyright 2018 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requir...
return request def ProcessTableCopyConfiguration(ref, args, request): """Build JobConfigurationTableCopy from request resource args.""" del ref # Unused source_ref = args.CONCEPTS.source.Parse() destination_ref = args.CONCEPTS.destination.Parse() arg_utils.SetFieldInMessage( request, 'job.configu...
request.job.configuration.copy.writeDisposition = 'WRITE_TRUNCATE'
conditional_block
mod.rs
// Copyright 2020-2023 - Nym Technologies SA <contact@nymtech.net> // SPDX-License-Identifier: Apache-2.0 use crate::config::persistence::paths::MixNodePaths; use crate::config::template::CONFIG_TEMPLATE; use nym_bin_common::logging::LoggingSettings; use nym_config::defaults::{ mainnet, DEFAULT_HTTP_API_LISTENING_...
} }
random_line_split
mod.rs
// Copyright 2020-2023 - Nym Technologies SA <contact@nymtech.net> // SPDX-License-Identifier: Apache-2.0 use crate::config::persistence::paths::MixNodePaths; use crate::config::template::CONFIG_TEMPLATE; use nym_bin_common::logging::LoggingSettings; use nym_config::defaults::{ mainnet, DEFAULT_HTTP_API_LISTENING_...
(mut self, port: u16) -> Self { self.mixnode.mix_port = port; self } pub fn with_verloc_port(mut self, port: u16) -> Self { self.mixnode.verloc_port = port; self } pub fn with_http_api_port(mut self, port: u16) -> Self { self.mixnode.http_api_port = port; ...
with_mix_port
identifier_name
maximin.py
from copy import deepcopy from math import sqrt, inf import random def dist(pos1, pos2): """ returns distance between two co-ordinates (a,b) and (c,d) """ a, b = pos1 c, d = pos2 return sqrt((a-c)**2 + (b-d)**2) def eval_board(board, colour, num_defeated): """ evaluates a "goodnes...
# subtract number of opponent tokens on the board for hand, positions in opp_tokens.items(): for position in positions: score -= 1 return score class Player: def __init__(self, player): """ Called once at the beginning of a game to initialise this player. ...
min_target_dist = inf for target in targets: target_dist = dist(position, target) if target_dist < min_target_dist: min_target_dist = target_dist if min_target_dist == 0: # this shouldn't happen as the opponent shoul...
conditional_block
maximin.py
from copy import deepcopy from math import sqrt, inf import random def dist(pos1, pos2): """ returns distance between two co-ordinates (a,b) and (c,d) """ a, b = pos1 c, d = pos2 return sqrt((a-c)**2 + (b-d)**2) def eval_board(board, colour, num_defeated): """ evaluates a "goodnes...
for s in "rps": yield "THROW", s, x occupied = {x for x, s in self.board.items() if any(map(isplayer, s))} for x in occupied: adjacent_x = self._ADJACENT(x) for y in adjacent_x: yield "SLIDE", x, y if y in occupi...
(r, q) for r, q in self._SET_HEXES if sign * r >= 4 - throws ) for x in throw_zone:
random_line_split
maximin.py
from copy import deepcopy from math import sqrt, inf import random def dist(pos1, pos2): """ returns distance between two co-ordinates (a,b) and (c,d) """ a, b = pos1 c, d = pos2 return sqrt((a-c)**2 + (b-d)**2) def eval_board(board, colour, num_defeated): """ evaluates a "goodnes...
def _FORMAT_ACTION(action): atype, *aargs = action if atype == "THROW": return "THROW symbol {} to {}".format(*aargs) else: # atype == "SLIDE" or "SWING": return "{} from {} to {}".format(atype, *aargs)
""" Submit an action to the game for validation and application. If the action is not allowed, raise an InvalidActionException with a message describing allowed actions. Otherwise, apply the action to the game state. """ # validate the actions: for action, c in [(...
identifier_body
maximin.py
from copy import deepcopy from math import sqrt, inf import random def dist(pos1, pos2): """ returns distance between two co-ordinates (a,b) and (c,d) """ a, b = pos1 c, d = pos2 return sqrt((a-c)**2 + (b-d)**2) def eval_board(board, colour, num_defeated): """ evaluates a "goodnes...
: def __init__(self, player): """ Called once at the beginning of a game to initialise this player. Set up an internal representation of the game state. The parameter player is the string "upper" (if the instance will play as Upper), or the string "lower" (if the instance wi...
Player
identifier_name
HAN_Evaluator.py
import tensorflow as tf import numpy as np from datetime import datetime import os from CNN import CNN from LSTM import LSTM from BiLSTM import BiLSTM from SLAN import Attention from HAN2 import HierarchicalAttention import sklearn.metrics as metrics import DataProcessor as dp import matplotlib.pyplot as plt import num...
else: return -1 labels = list(map(fn, pred['labels'])) predicts = list(map(fn, pred['predictions'])) cnf_matrix = metrics.confusion_matrix(labels, predicts) # Plot non-normalized confusion matrix plt.figure() #classes = ["True", "Mostly-true", "Half-true", "Barely-true", "F...
return 0
conditional_block
HAN_Evaluator.py
import tensorflow as tf import numpy as np from datetime import datetime import os from CNN import CNN from LSTM import LSTM from BiLSTM import BiLSTM from SLAN import Attention from HAN2 import HierarchicalAttention import sklearn.metrics as metrics import DataProcessor as dp import matplotlib.pyplot as plt import num...
color = (0.0, 0.0, 0.0) else: color = (1.0, 1.0, 1.0) j, i = int(floor(x)), int(floor(y)) if sentence[i, j] != "PAD": word = sentence[i, j] else: word = "" fontsize = _font_size(len(word)) ...
x, y = p.vertices[:-2, :].mean(0) if np.all(color[:3] > 0.5):
random_line_split
HAN_Evaluator.py
import tensorflow as tf import numpy as np from datetime import datetime import os from CNN import CNN from LSTM import LSTM from BiLSTM import BiLSTM from SLAN import Attention from HAN2 import HierarchicalAttention import sklearn.metrics as metrics import DataProcessor as dp import matplotlib.pyplot as plt import num...
(data): #data = np.array(data) data.reverse() attention_weights_word = np.array([np.squeeze(x[1]) for x in data]) attention_weights_sent = np.array([np.squeeze(x[2]) for x in data]) #max_weight = attention_weights.max() #attention_weights = attention_weights/max_weight # increase weights to make...
visualize_attention
identifier_name
HAN_Evaluator.py
import tensorflow as tf import numpy as np from datetime import datetime import os from CNN import CNN from LSTM import LSTM from BiLSTM import BiLSTM from SLAN import Attention from HAN2 import HierarchicalAttention import sklearn.metrics as metrics import DataProcessor as dp import matplotlib.pyplot as plt import num...
sorted_correct = sorted(zipped_correct, key=get_predicted_prob, reverse=True) print(sorted_correct[0:2]) #selection = sorted_correct[1] selection_zipped_tuple = list(zip(selection[0], selection[4], selection[5])) #selection_zipped_tuple = list(zip(selection[0], selection[4])) selection_zipped...
return (x[3])[(x[2])]
identifier_body
inb4404.py
#!/usr/bin/env python3 import argparse import asyncio from base64 import b64decode import fnmatch import json import os import sys import time from textwrap import dedent import urllib.error from urllib.request import Request, urlopen import aiohttp # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Classes # ~~~~~~~~~~~~~~~~~~~~~~~~...
def parse_cli(): """Parse the command line arguments with argparse.""" defaults = DefaultOptions() parser = CustomArgumentParser(usage="%(prog)s [OPTIONS] THREAD [THREAD]...") parser.add_argument("thread", nargs="*", help="thread URL") parser.add_argument( "-l", "--list", action="append"...
"""Convert string provided by argparse to an archive path.""" path = os.path.abspath(string) try: with open(path, "r") as f: _ = f.read(1) except FileNotFoundError: pass except (OSError, UnicodeError): raise argparse.ArgumentTypeError(f"{path} is not a valid archive!"...
identifier_body
inb4404.py
#!/usr/bin/env python3 import argparse import asyncio from base64 import b64decode import fnmatch import json import os import sys import time from textwrap import dedent import urllib.error from urllib.request import Request, urlopen import aiohttp # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Classes # ~~~~~~~~~~~~~~~~~~~~~~~~...
(self, position, link): """Initialize thread object.""" self.count = 0 self.files = [] self.pos = position self.link = link.split("#")[0] info = link.partition(".org/")[2] # info has the form <board>/thread/<thread> or <board>/thread/<thread>/<dir name> i...
__init__
identifier_name
inb4404.py
#!/usr/bin/env python3 import argparse import asyncio from base64 import b64decode import fnmatch import json import os import sys import time from textwrap import dedent import urllib.error from urllib.request import Request, urlopen import aiohttp # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Classes # ~~~~~~~~~~~~~~~~~~~~~~~~...
# Retries imply attempts after the first try failed # So the max. number of attempts is opts.retries+1 attempt = 0 while attempt <= opts.retries or opts.retries < 0: if attempt > 0: err(f"Retrying... ({attempt} out of " f"{opts.retries if o...
err(f"Thread 404'd!") return msg(f"{self.fetch_progress()} {self.link}")
random_line_split
inb4404.py
#!/usr/bin/env python3 import argparse import asyncio from base64 import b64decode import fnmatch import json import os import sys import time from textwrap import dedent import urllib.error from urllib.request import Request, urlopen import aiohttp # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Classes # ~~~~~~~~~~~~~~~~~~~~~~~~...
else: progress = t_progress return progress async def get_file(self, link, name, md5, session): """Download a single file.""" if os.path.exists(name) or md5 in opts.archived_md5: self.count += 1 return async with session.get(link) as me...
progress = f"{t_progress} {f_progress}"
conditional_block
barista-examples.ts
import * as fs from 'fs'; import { basename, dirname, join, relative } from 'path'; import { sync as glob } from 'glob'; import { dest, series, src, task } from 'gulp'; import { flatten } from 'lodash'; import * as through from 'through2'; import * as ts from 'typescript'; import { buildConfig } from '../build-config...
/** Parse the AST of the given source file and collects Angular component metadata. */ export function retrieveExampleTemplateContent(fileName: string, content: string): string | undefined { const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, false); const componentTemplates: string[...
{ const sourceFile = ts.createSourceFile(fileName, content, ts.ScriptTarget.Latest, false); const componentClassNames: string[] = []; // tslint:disable-next-line:no-any const visitNode = (node: any): void => { if (node.kind === ts.SyntaxKind.ClassDeclaration) { if (node.decorators && node.decorators.l...
identifier_body
barista-examples.ts
import * as fs from 'fs'; import { basename, dirname, join, relative } from 'path'; import { sync as glob } from 'glob'; import { dest, series, src, task } from 'gulp'; import { flatten } from 'lodash'; import * as through from 'through2'; import * as ts from 'typescript'; import { buildConfig } from '../build-config...
.join('\n'); const exampleList = parsedData.map(m => m.component); return fs .readFileSync(join(examplesDir, './app.module.template'), 'utf8') .replace('${imports}', exampleImports) .replace('${examples}', `[\n ${exampleList.join(',\n ')},\n]`); } /** Generates the imports for each example file ...
/** Inlines the app module template with the specified parsed data. */ function populateAppModuleTemplate(parsedData: ExampleMetadata[]): string { const exampleImports = parsedData .map(m => buildImportsTemplate(m))
random_line_split
barista-examples.ts
import * as fs from 'fs'; import { basename, dirname, join, relative } from 'path'; import { sync as glob } from 'glob'; import { dest, series, src, task } from 'gulp'; import { flatten } from 'lodash'; import * as through from 'through2'; import * as ts from 'typescript'; import { buildConfig } from '../build-config...
done(); }); /** Creates the examples module */ task('barista-example:generate', done => { const metadata = getExampleMetadata(glob(join(examplesDir, '*/*.ts'))); generateAppModule(metadata, 'app.module.ts', examplesDir); generateAppComponent(metadata); const routeData = flatten(generateRouteMetadata(metada...
{ const errors = invalidExampleRefs.map( ref => `Invalid example name "${ref.name}" found in ${ref.sourcePath}.`, ); const errorMsg = errors.join('\n'); done(errorMsg); return; }
conditional_block
barista-examples.ts
import * as fs from 'fs'; import { basename, dirname, join, relative } from 'path'; import { sync as glob } from 'glob'; import { dest, series, src, task } from 'gulp'; import { flatten } from 'lodash'; import * as through from 'through2'; import * as ts from 'typescript'; import { buildConfig } from '../build-config...
( parsedData: ExampleMetadata[], outputFile: string, baseDir: string, ): void { const generatedModuleFile = populateAppModuleTemplate([...parsedData]); const generatedFilePath = join(baseDir, outputFile); if (!fs.existsSync(dirname(generatedFilePath))) { fs.mkdirSync(dirname(generatedFilePath)); } f...
generateAppModule
identifier_name
interpreter.rs
use super::{environment::Environment, primitives}; use calyx::{errors::FutilResult, ir}; use std::collections::HashMap; /// Evaluates a group, given an environment. pub fn eval_group( group: ir::RRC<ir::Group>, env: &Environment, ) -> FutilResult<Environment> { eval_assigns(&(group.borrow()).assignments, &...
Ok(write_env) } /// Evaluate guard implementation #[allow(clippy::borrowed_box)] // XXX: Allow for this warning. It would make sense to use a reference when we // have the `box` match pattern available in Rust. fn eval_guard(guard: &Box<ir::Guard>, env: &Environment) -> u64 { (match &**guard { ir::Guar...
write_env.map.get(&done_cell) );*/
random_line_split
interpreter.rs
use super::{environment::Environment, primitives}; use calyx::{errors::FutilResult, ir}; use std::collections::HashMap; /// Evaluates a group, given an environment. pub fn eval_group( group: ir::RRC<ir::Group>, env: &Environment, ) -> FutilResult<Environment> { eval_assigns(&(group.borrow()).assignments, &...
(assigns: &[ir::Assignment]) -> &ir::Assignment { assigns .iter() .find(|assign| { let dst = assign.dst.borrow(); dst.is_hole() && dst.name == "done" }) .expect("Group does not have a done signal") } /// Determines if writing a particular cell and cell port i...
get_done_signal
identifier_name
interpreter.rs
use super::{environment::Environment, primitives}; use calyx::{errors::FutilResult, ir}; use std::collections::HashMap; /// Evaluates a group, given an environment. pub fn eval_group( group: ir::RRC<ir::Group>, env: &Environment, ) -> FutilResult<Environment> { eval_assigns(&(group.borrow()).assignments, &...
} // write_env = iter_updates.do_tick() write_env = write_env.do_tick(); counter += 1; } /*println!( "\nFinal state of the done cell, i.e. {:1}: {:?} \n", &done_cell, write_env.map.get(&done_cell) );*/ Ok(write_env) } /// Evaluate guard implemen...
{ // check if the cells are constants? // cell of assign.src let src_cell = get_cell_from_port(&assign.src); // cell of assign.dst let dst_cell = get_cell_from_port(&assign.dst); /*println!( "src cell {:...
conditional_block
interpreter.rs
use super::{environment::Environment, primitives}; use calyx::{errors::FutilResult, ir}; use std::collections::HashMap; /// Evaluates a group, given an environment. pub fn eval_group( group: ir::RRC<ir::Group>, env: &Environment, ) -> FutilResult<Environment> { eval_assigns(&(group.borrow()).assignments, &...
/// Get the cell id a port belongs to. /// Very similar to ir::Port::get_parent_name, except it can also panic fn get_cell_from_port(port: &ir::RRC<ir::Port>) -> ir::Id { if port.borrow().is_hole() { panic!("Unexpected hole. Cannot get cell: {}", port.borrow().name) } port.borrow().get_parent_name...
{ (match &**guard { ir::Guard::Or(g1, g2) => { (eval_guard(g1, env) == 1) || (eval_guard(g2, env) == 1) } ir::Guard::And(g1, g2) => { (eval_guard(g1, env) == 1) && (eval_guard(g2, env) == 1) } ir::Guard::Not(g) => eval_guard(g, &env) != 0, ir::...
identifier_body
dg.py
# -*- coding: utf-8 -*- """ Created on 5:56 PM, 11/4/15 @author: wt """ import sys sys.path.append('..') from networkx import * import math import matplotlib.pyplot as plt import numpy as np import csv from sklearn.metrics import mean_squared_error import os # load a network from file (directed weighted network) ...
pos = spring_layout(DG) # pos = spectral_layout(DG) # plt.title('Plot of Network') draw(DG, pos) plt.show() def pdf(data, xmin=None, xmax=None, linear_bins=False, **kwargs): if not xmax: xmax = max(data) if not xmin: xmin = min(data) if linear_bins: bins = rang...
random_line_split
dg.py
# -*- coding: utf-8 -*- """ Created on 5:56 PM, 11/4/15 @author: wt """ import sys sys.path.append('..') from networkx import * import math import matplotlib.pyplot as plt import numpy as np import csv from sklearn.metrics import mean_squared_error import os # load a network from file (directed weighted network) ...
def rmse(predict, truth): # calculate RMSE of a prediction RMSE = mean_squared_error(truth, predict)**0.5 return RMSE def mean_bin(list_x, list_y, linear_bins=False): # the returned values are raw values, not logarithmic values size = len(list_x) xmin = min(list_x) xmax = max(list_x) ...
return [i for i in list_a if i>0]
identifier_body
dg.py
# -*- coding: utf-8 -*- """ Created on 5:56 PM, 11/4/15 @author: wt """ import sys sys.path.append('..') from networkx import * import math import matplotlib.pyplot as plt import numpy as np import csv from sklearn.metrics import mean_squared_error import os # load a network from file (directed weighted network) ...
new_bin_means_y.append(sum_y/hist_x[index]) return new_bin_meanx_x, new_bin_means_y def cut_lists(list_x, list_y, fit_start=-1, fit_end=-1): if fit_start != -1: new_x, new_y = [], [] for index in xrange(len(list_x)): if list_x[index] >= fit_start: new_x...
key = list_x[i] if (key >= range_min) and (key < range_max): sum_y += list_y[i]
conditional_block
dg.py
# -*- coding: utf-8 -*- """ Created on 5:56 PM, 11/4/15 @author: wt """ import sys sys.path.append('..') from networkx import * import math import matplotlib.pyplot as plt import numpy as np import csv from sklearn.metrics import mean_squared_error import os # load a network from file (directed weighted network) ...
(list_x, list_y, linear_bins=False): # the returned values are raw values, not logarithmic values size = len(list_x) xmin = min(list_x) xmax = max(list_x) if linear_bins: bins = range(int(xmin), int(xmax+1)) else: log_min_size = np.log10(xmin) log_max_size = np.log10(xmax...
mean_bin
identifier_name
lib.rs
#![warn(clippy::all, clippy::pedantic, clippy::nursery)] #![allow( clippy::default_trait_access, clippy::use_self, clippy::wildcard_imports )] use arr_macro::arr; use derivative::Derivative; use enr::*; use ethereum_types::*; use futures::{Sink, SinkExt}; use heapless::{ consts::{U16, U4096}, FnvIn...
if *current_bucket == *max_bucket { return None; } *current_bucket += 1; *current_bucket_remaining = None; } } } pub enum DiscoveryRequest { Ping, } pub enum DiscoveryResponse { Pong, } pub enum DiscoveryPacket { WhoAreYou, ...
{ // Safety: we have exclusive access to underlying node table return Some(unsafe { &mut *ptr.as_ptr() }); }
conditional_block
lib.rs
#![warn(clippy::all, clippy::pedantic, clippy::nursery)] #![allow( clippy::default_trait_access, clippy::use_self, clippy::wildcard_imports )] use arr_macro::arr; use derivative::Derivative; use enr::*; use ethereum_types::*; use futures::{Sink, SinkExt}; use heapless::{ consts::{U16, U4096}, FnvIn...
} pub struct BucketNodes<'a, K: EnrKey>(NodeEntries<'a, K>); impl<'a, K: EnrKey> Iterator for BucketNodes<'a, K> { type Item = &'a mut NodeEntry<K>; fn next(&mut self) -> Option<Self::Item> { self.0.next() } } pub struct Closest<'a, K: EnrKey>(NodeEntries<'a, K>); impl<'a, K: EnrKey> Iterator ...
{ Closest(NodeEntries { node_table: self, current_bucket: 0, max_bucket: 255, current_bucket_remaining: None, }) }
identifier_body
lib.rs
#![warn(clippy::all, clippy::pedantic, clippy::nursery)] #![allow( clippy::default_trait_access, clippy::use_self, clippy::wildcard_imports )] use arr_macro::arr; use derivative::Derivative; use enr::*; use ethereum_types::*; use futures::{Sink, SinkExt}; use heapless::{ consts::{U16, U4096}, FnvIn...
() { let _ = env_logger::try_init(); let host_id = H256::random(); let mut table = NodeTable::<SecretKey>::new(host_id); for _ in 0..9000 { table.add_node( EnrBuilder::new("v4") .build(&SecretKey::random(&mut rand::thread_rng())) ...
test_iterator
identifier_name
lib.rs
#![warn(clippy::all, clippy::pedantic, clippy::nursery)] #![allow( clippy::default_trait_access, clippy::use_self, clippy::wildcard_imports )] use arr_macro::arr; use derivative::Derivative; use enr::*; use ethereum_types::*; use futures::{Sink, SinkExt}; use heapless::{ consts::{U16, U4096}, FnvIn...
ptr::NonNull, sync::{Arc, Mutex}, time::{Duration, Instant}, }; use tokio::{ net::UdpSocket, prelude::*, stream::{StreamExt, *}, }; use tokio_util::{codec::*, udp::*}; pub mod proto; pub mod topic; pub type RawNodeId = [u8; 32]; #[must_use] pub fn distance(a: H256, b: H256) -> U256 { U256...
ops::BitXor,
random_line_split
codewander-plotlyScatterPlot.js
define( ["qlik", "text!./codewander-plotlyScatterPlot.ng.html", "css!./codewander-plotlyScatterPlot.css" ,"https://cdn.plot.ly/plotly-latest.min.js"], function ( qlik, template,css,Plotly ) { "use strict"; return { template: template, initialProperties: { qHyperCubeDef: { qMode:"S", qDimensions...
//var ff=window.getComputedStyle(getElementsByTagName("body")[0],null).getPropertyValue("font-family") ; var pdisplayModeBar=false if (self.$scope.layout.generalSettings.displayModeBar=='1') {pdisplayModeBar=true} else if (self.$scope.layout.generalSettings.displayModeBar=='-1') {pdisplayMo...
{ rightMargin=rightMargin + 100 }
conditional_block
codewander-plotlyScatterPlot.js
define( ["qlik", "text!./codewander-plotlyScatterPlot.ng.html", "css!./codewander-plotlyScatterPlot.css" ,"https://cdn.plot.ly/plotly-latest.min.js"], function ( qlik, template,css,Plotly ) { "use strict"; return { template: template, initialProperties: { qHyperCubeDef: { qMode:"S", qDimensions...
(Matrix) { var data=[]; var total_series_count = measures_count/2; var series_array =[] var settingArrayLength = self.$scope.layout.seriesSettings.length; var settingArray=self.$scope.layout.seriesSettings; for (var i =0 ;i<total_series_count;i++) { var series={} serie...
convert
identifier_name
codewander-plotlyScatterPlot.js
define( ["qlik", "text!./codewander-plotlyScatterPlot.ng.html", "css!./codewander-plotlyScatterPlot.css" ,"https://cdn.plot.ly/plotly-latest.min.js"], function ( qlik, template,css,Plotly ) { "use strict"; return { template: template, initialProperties: { qHyperCubeDef: { qMode:"S", qDimensions...
function render(data){ Plotly.newPlot('myDiv', data, graph_layout,graph_layout_setting); document.getElementById('myDiv').on('plotly_click', function(e){ var pts = ''; var DimVal= e.points[0].text; //var SecondDimVal = e.points[0].text; self.$scope.makeSelection(qElemNumber[...
{ var data=[]; var total_series_count = measures_count/2; var series_array =[] var settingArrayLength = self.$scope.layout.seriesSettings.length; var settingArray=self.$scope.layout.seriesSettings; for (var i =0 ;i<total_series_count;i++) { var series={} series.x=[]; ...
identifier_body
codewander-plotlyScatterPlot.js
define( ["qlik", "text!./codewander-plotlyScatterPlot.ng.html", "css!./codewander-plotlyScatterPlot.css" ,"https://cdn.plot.ly/plotly-latest.min.js"], function ( qlik, template,css,Plotly ) { "use strict"; return { template: template, initialProperties: { qHyperCubeDef: { qMode:"S", qDimensions...
$.each(Matrix,function(index,item){ data[index]={}; qElemNumber[item[0].qText]=item[0].qElemNumber; /*$.each(cols,function(col_index,col){ try { data[index][col]= col_index<= dimensions_count-1 ? item[col_index].qText : item[col_index].qNum; if (col_index<= dimensions_cou...
series.marker={size:12} } series_array.push(series); }
random_line_split
sdr_rec_type.go
/* Copyright (c) 2014 EOITek, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed t...
(data []byte) error { buffer := bytes.NewReader(data) err := binary.Read(buffer, binary.LittleEndian, &r.SDRRecordHeader) if err != nil { return err } //skip the record length _, err = buffer.ReadByte() if err != nil { return err } binary.Read(buffer, binary.LittleEndian, &r.sdrCompactSensorFields) idL...
UnmarshalBinary
identifier_name
sdr_rec_type.go
/* Copyright (c) 2014 EOITek, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed t...
EntityInstan uint8 OEM SDRSensorType DeviceIDCode SDRSensorReadingType DeviceIDStr uint16 } type SDRMCDeviceLoc struct { SDRRecordHeader sdrMCDeviceLocFields deviceId string }
Reserved [3]byte EntityID uint8
random_line_split
sdr_rec_type.go
/* Copyright (c) 2014 EOITek, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed t...
// section 43.2 type sdrCompactSensorFields struct { //size 26 SensorOwnerId uint8 SensorOwnerLUN uint8 SensorNumber uint8 EntityId uint8 EntityIns uint8 SensorInit uint8 SensorCap uint8 SensorType SDRSensorType ReadingType S...
{ buffer := bytes.NewReader(data) err := binary.Read(buffer, binary.LittleEndian, &r.SDRRecordHeader) if err != nil { return err } //skip the record length _, err = buffer.ReadByte() if err != nil { return err } binary.Read(buffer, binary.LittleEndian, &r.sdrFullSensorFields) idLen, err := buffer.ReadB...
identifier_body
sdr_rec_type.go
/* Copyright (c) 2014 EOITek, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed t...
id := make([]byte, int(idLen)) n, err := buffer.Read(id) if err != nil || n != int(idLen) { return ErrIdStringLenNotMatch } r.deviceId = string(id) return nil } // section 43.9 type sdrMCDeviceLocFields struct { //size 26 DeviceSlaveAddr uint8 ChannNum uint8 PowerStaNotif uint8 DeviceCapab ...
{ return err }
conditional_block
bytesearch.rs
use crate::insn::MAX_CHAR_SET_LENGTH; use core::fmt; extern crate memchr; #[cfg(not(feature = "std"))] use alloc::vec::Vec; /// Facilities for searching bytes. pub trait ByteSearcher { /// Search for ourselves in a slice of bytes. /// The length of the slice is unspecified and may be 0. /// \return the nex...
} None } } // CharSet helper. Avoid branching in the loop to get good unrolling. #[allow(unused_parens)] #[inline(always)] pub fn charset_contains(set: &[u32; MAX_CHAR_SET_LENGTH], c: u32) -> bool { let mut result = false; for &v in set.iter() { result |= (v == c); } result...
{ return Some(idx); }
conditional_block
bytesearch.rs
use crate::insn::MAX_CHAR_SET_LENGTH; use core::fmt; extern crate memchr; #[cfg(not(feature = "std"))] use alloc::vec::Vec; /// Facilities for searching bytes. pub trait ByteSearcher { /// Search for ourselves in a slice of bytes. /// The length of the slice is unspecified and may be 0. /// \return the nex...
(&self, rhs: &[u8]) -> bool { debug_assert!(rhs.len() == Self::LENGTH, "Slice has wrong length"); if cfg!(feature = "prohibit-unsafe") { // Here's what we would like to do. However this will emit an unnecessary length compare, and an unnecessary pointer compare. self == rhs ...
equals_known_len
identifier_name
bytesearch.rs
use crate::insn::MAX_CHAR_SET_LENGTH; use core::fmt; extern crate memchr; #[cfg(not(feature = "std"))] use alloc::vec::Vec; /// Facilities for searching bytes. pub trait ByteSearcher { /// Search for ourselves in a slice of bytes. /// The length of the slice is unspecified and may be 0. /// \return the nex...
format_bitmap("ByteBitmap", f, |v| self.contains(v)) } } /// A trivial ByteSearcher corresponding to the empty string. #[derive(Debug, Copy, Clone)] pub struct EmptyString {} impl ByteSearcher for EmptyString { #[inline(always)] fn find_in(&self, _bytes: &[u8]) -> Option<usize> { Some(0) ...
impl fmt::Debug for ByteBitmap { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
random_line_split
bytesearch.rs
use crate::insn::MAX_CHAR_SET_LENGTH; use core::fmt; extern crate memchr; #[cfg(not(feature = "std"))] use alloc::vec::Vec; /// Facilities for searching bytes. pub trait ByteSearcher { /// Search for ourselves in a slice of bytes. /// The length of the slice is unspecified and may be 0. /// \return the nex...
/// Set a bit in this bitmap. #[inline(always)] pub fn set(&mut self, val: u8) { let byte = val >> 4; let bit = val & 0xF; self.0[byte as usize] |= 1 << bit; } /// Update ourselves from another bitmap, in place. pub fn bitor(&mut self, rhs: &ByteBitmap) { for i...
{ let byte = val >> 4; let bit = val & 0xF; (self.0[byte as usize] & (1 << bit)) != 0 }
identifier_body
trainer.py
import os import gc import re import time import copy import shutil import pickle import logging import numpy as np import torch from torch import nn import torch.nn.functional as F import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import ReduceLROnPlateau fro...
self.net.load_state_dict(new_state_dict) else: try: self.net.load_state_dict(chkpt['state_dict']) except: new_state_dict = fix_multigpu_chkpt_names(chkpt['state_dict'], drop=True) self.net.load_state_dict(new_state_dict) ...
self.best_metric = chkpt['best_metric'] # fix the DataParallel caused problem with keys names if self.multi_gpu_flag: new_state_dict = fix_multigpu_chkpt_names(chkpt['state_dict'], drop=False)
random_line_split
trainer.py
import os import gc import re import time import copy import shutil import pickle import logging import numpy as np import torch from torch import nn import torch.nn.functional as F import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import ReduceLROnPlateau fro...
(state_dict, drop=False): """ fix the DataParallel caused problem with keys names """ new_state_dict = {} for k in state_dict: if drop: new_k = re.sub("module.", "", k) else: new_k = "module." + k new_state_dict[new_k] = copy.deepcopy(state_dict[k]) return...
fix_multigpu_chkpt_names
identifier_name
trainer.py
import os import gc import re import time import copy import shutil import pickle import logging import numpy as np import torch from torch import nn import torch.nn.functional as F import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import ReduceLROnPlateau fro...
def iterate(self, epoch, phase, data_set): """main method for traning: creates metric aggregator, dataloaders and updates the model params""" if phase not in self.possible_phases: raise ValueError('Phase type must be on of: {}'.format(self.possible_phases)) self.meter.reset_d...
for param in param_group['params']: param.data = param.data.add(-1.*self.weights_decay * param_group['lr'], param.data)
conditional_block
trainer.py
import os import gc import re import time import copy import shutil import pickle import logging import numpy as np import torch from torch import nn import torch.nn.functional as F import torch.backends.cudnn as cudnn from torch.utils.data import DataLoader from torch.optim.lr_scheduler import ReduceLROnPlateau fro...
def get_current_lr(self): for i, param_group in enumerate(self.optimizer.param_groups): return float(param_group['lr']) def start(self, train_set, val_set): """Runs training loop and saves intermediate state""" for epoch in range(self.start_epoch, self.num_epoc...
"""dumpы all metrics and training meta-data""" for dict_name in ["losses", "dice_scores", "iou_scores"]: pickle.dump(self.__dict__[dict_name], open(f"{self.model_path}/{dict_name}.pickle.dat", "wb")) # dump class variables for further traning training_meta = {} for k in self...
identifier_body
Zichen Pan - S&P500.py
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas_datareader as pdr import datetime import bs4 as bs import os import pandas_datareader.data as web import pickle import requests # In[2]: # get sp500 tickers def save_sp500_tickers(): resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_5...
future_dates = my_model.make_future_dataframe(periods=240, freq='B') future_dates.head() # In[74]: forecast = my_model.predict(future_dates) forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].head() # In[75]: _ = my_model.plot(forecast,uncertainty=True) # In[76]: _ = my_model.plot_components(forecast) ...
random_line_split
Zichen Pan - S&P500.py
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas_datareader as pdr import datetime import bs4 as bs import os import pandas_datareader.data as web import pickle import requests # In[2]: # get sp500 tickers def save_sp500_tickers(): resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_5...
with open("sp500tickers.pickle", "wb") as f: pickle.dump(tickers, f) return tickers # In[3]: tickers = sorted(save_sp500_tickers()) tickers[0] # In[4]: # get first stock ('A') from yahoo start_date = datetime.date(2018,1,1) end_date = datetime.date.today() current_ticker = pdr.get_data_yahoo(s...
ticker = row.findAll('td')[0].text tickers.append(ticker)
conditional_block
Zichen Pan - S&P500.py
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas_datareader as pdr import datetime import bs4 as bs import os import pandas_datareader.data as web import pickle import requests # In[2]: # get sp500 tickers def save_sp500_tickers(): resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_5...
(timeseries): #Determing rolling statistics rolmean = timeseries.rolling(7).mean() rolstd = timeseries.rolling(7).std() #Plot rolling statistics: orig = plt.plot(timeseries, color='blue',label='Original') mean = plt.plot(rolmean, color='red', label='Rolling Mean') std = plt.plot(rolstd...
test_stationarity
identifier_name
Zichen Pan - S&P500.py
#!/usr/bin/env python # coding: utf-8 # In[1]: import pandas_datareader as pdr import datetime import bs4 as bs import os import pandas_datareader.data as web import pickle import requests # In[2]: # get sp500 tickers def save_sp500_tickers(): resp = requests.get('http://en.wikipedia.org/wiki/List_of_S%26P_5...
# In[58]: test_stationarity(df_A) # In[59]: # We can tell that the dataset is approximately stationary # In[60]: df_A_weekly = df_A.resample('B').mean() df_A_weekly.fillna(method='ffill', inplace = True) df_A_weekly # In[61]: _ = df_A_weekly.plot(figsize = (20,6)) # ### ARIMA # In[62]: # ARIMA p =...
rolmean = timeseries.rolling(7).mean() rolstd = timeseries.rolling(7).std() #Plot rolling statistics: orig = plt.plot(timeseries, color='blue',label='Original') mean = plt.plot(rolmean, color='red', label='Rolling Mean') std = plt.plot(rolstd, color='black', label = 'Rolling Std') plt.legend(lo...
identifier_body
context.go
/* @Time : 2020/4/19 1:41 下午 @Author : Rebeta @Email : master@rebeta.cn @File : context @Software: GoLand */ package gin import ( "github.com/offcn-jl/gscf/binding" "github.com/offcn-jl/gscf/fake-http" "github.com/offcn-jl/gscf/render" "github.com/tencentyun/scf-go-lib/cloudevents/scf" "math" "st...
tcut for c.ShouldBindWith(obj, binding.JSON). func (c *Context) ShouldBindJSON(obj interface{}) error { return c.ShouldBindWith(obj, binding.JSON) } // ShouldBindWith 使用指定的绑定引擎绑定数据到传递到结构体指针 // ShouldBindWith binds the passed struct pointer using the specified binding engine. // See the binding package. func (c *Conte...
ShouldBindJSON 是 c.ShouldBindWith(obj, binding.JSON) 的快捷方式 // ShouldBindJSON is a shor
identifier_body
context.go
/* @Time : 2020/4/19 1:41 下午 @Author : Rebeta @Email : master@rebeta.cn @File : context @Software: GoLand */ package gin import ( "github.com/offcn-jl/gscf/binding" "github.com/offcn-jl/gscf/fake-http" "github.com/offcn-jl/gscf/render" "github.com/tencentyun/scf-go-lib/cloudevents/scf" "math" "st...
// ShouldBindJSON 是 c.ShouldBindWith(obj, binding.JSON) 的快捷方式 // ShouldBindJSON is a shortcut for c.ShouldBindWith(obj, binding.JSON). func (c *Context) ShouldBindJSON(obj interface{}) error { return c.ShouldBindWith(obj, binding.JSON) } // ShouldBindWith 使用指定的绑定引擎绑定数据到传递到结构体指针 // ShouldBindWith binds the passed stru...
random_line_split
context.go
/* @Time : 2020/4/19 1:41 下午 @Author : Rebeta @Email : master@rebeta.cn @File : context @Software: GoLand */ package gin import ( "github.com/offcn-jl/gscf/binding" "github.com/offcn-jl/gscf/fake-http" "github.com/offcn-jl/gscf/render" "github.com/tencentyun/scf-go-lib/cloudevents/scf" "math" "st...
cessive calls to Deadline return the same results. func (c *Context) Deadline() (deadline time.Time, ok bool) { return } // Done 返回一个通道,该通道在代表此上下文完成的工作应被取消时关闭。 // 如果无法取消此上下文,则 Done 可能返回 nil 。对 Done 的连续调用返回相同的值。 // Done returns a channel that's closed when work done on behalf of this // context should be canceled. Don...
set. Suc
identifier_name
context.go
/* @Time : 2020/4/19 1:41 下午 @Author : Rebeta @Email : master@rebeta.cn @File : context @Software: GoLand */ package gin import ( "github.com/offcn-jl/gscf/binding" "github.com/offcn-jl/gscf/fake-http" "github.com/offcn-jl/gscf/render" "github.com/tencentyun/scf-go-lib/cloudevents/scf" "math" "st...
(c *Context) JSON(code int, obj interface{}) { c.Render(code, render.JSON{Data: obj}) } // String 将给定的字符串写入响应体 // String writes the given string into the response body. func (c *Context) String(code int, format string, values ...interface{}) { c.Render(code, render.String{Format: format, Data: values}) } /*********...
&c.Response); err != nil { panic(err) } } // JSON 将给定的结构序列化为 JSON 类型后添加到响应体中 // 并且设置响应头中的 Content-Type 为 "application/json" func
conditional_block
texel.rs
// Distributed under The MIT License (MIT) // // Copyright (c) 2019, 2020 The `image-rs` developers #![allow(unsafe_code)] use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use core::marker::PhantomData; use core::{fmt, hash, mem, num, ptr, slice}; use crate::buf::buf; /// Marker struct to denote a texel ty...
() -> Texel<[T; 6]> { T::texel().array::<6>() } } impl<T: AsTexel> AsTexel for [T; 7] { fn texel() -> Texel<[T; 7]> { T::texel().array::<7>() } } impl<T: AsTexel> AsTexel for [T; 8] { fn texel() -> Texel<[T; 8]> { T::texel().array::<8...
texel
identifier_name
texel.rs
// Distributed under The MIT License (MIT) // // Copyright (c) 2019, 2020 The `image-rs` developers #![allow(unsafe_code)] use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use core::marker::PhantomData; use core::{fmt, hash, mem, num, ptr, slice}; use crate::buf::buf; /// Marker struct to denote a texel ty...
pub(crate) fn cast_buf<'buf>(self, buffer: &'buf buf) -> &'buf [P] { debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<MaxAligned>(), 0); debug_assert_eq!(buffer.as_ptr() as usize % mem::align_of::<P>(), 0); // Safety: // * data is valid for reads as memory size is not enlarg...
self.cast_mut_bytes(texel) }
identifier_body
texel.rs
// Distributed under The MIT License (MIT) // // Copyright (c) 2019, 2020 The `image-rs` developers #![allow(unsafe_code)] use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use core::marker::PhantomData; use core::{fmt, hash, mem, num, ptr, slice}; use crate::buf::buf; /// Marker struct to denote a texel ty...
} /// Try to reinterpret a slice of bytes as a slice of the texel. /// /// This returns `Some` if the buffer is suitably aligned, and `None` otherwise. pub fn try_to_slice_mut<'buf>(self, bytes: &'buf mut [u8]) -> Option<&'buf mut [P]> { if let Some(slice) = self.try_to_slice(bytes) { ...
None }
conditional_block
texel.rs
// Distributed under The MIT License (MIT) // // Copyright (c) 2019, 2020 The `image-rs` developers
#![allow(unsafe_code)] use core::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; use core::marker::PhantomData; use core::{fmt, hash, mem, num, ptr, slice}; use crate::buf::buf; /// Marker struct to denote a texel type. /// /// Can be constructed only for types that have expected alignment and no byte invariants. I...
random_line_split
lib.rs
#![warn( clippy::doc_markdown, clippy::redundant_closure, clippy::explicit_iter_loop, clippy::match_same_arms, clippy::needless_borrow, clippy::print_stdout, clippy::integer_arithmetic, clippy::cast_possible_truncation, clippy::map_unwrap_or, clippy::unseparated_literal_suffix, ...
( _: &PyType, py: Python, pyschema: &PyAny, draft: Option<u8>, with_meta_schemas: Option<bool>, ) -> PyResult<Self> { let obj_ptr = pyschema.as_ptr(); let object_type = unsafe { pyo3::ffi::Py_TYPE(obj_ptr) }; if unsafe { object_type != types::STR_TYPE ...
from_str
identifier_name
lib.rs
#![warn( clippy::doc_markdown, clippy::redundant_closure, clippy::explicit_iter_loop, clippy::match_same_arms, clippy::needless_borrow, clippy::print_stdout, clippy::integer_arithmetic, clippy::cast_possible_truncation, clippy::map_unwrap_or, clippy::unseparated_literal_suffix, ...
message.push(']'); } message.push(':'); message.push_str("\n "); message.push_str(&error.instance.to_string()); message } /// is_valid(schema, instance, draft=None, with_meta_schemas=False) /// /// A shortcut for validating the input instance against the schema. /// /// >>> is_valid(...
jsonschema::paths::PathChunk::Index(index) => message.push_str(&index.to_string()), // Keywords are not used for instances jsonschema::paths::PathChunk::Keyword(_) => unreachable!("Internal error"), };
random_line_split
lib.rs
#![warn( clippy::doc_markdown, clippy::redundant_closure, clippy::explicit_iter_loop, clippy::match_same_arms, clippy::needless_borrow, clippy::print_stdout, clippy::integer_arithmetic, clippy::cast_possible_truncation, clippy::map_unwrap_or, clippy::unseparated_literal_suffix, ...
} const SCHEMA_LENGTH_LIMIT: usize = 32; #[pyproto] impl<'p> PyObjectProtocol<'p> for JSONSchema { fn __repr__(&self) -> PyResult<String> { Ok(format!("<JSONSchema: {}>", self.repr)) } } #[allow(dead_code)] mod build { include!(concat!(env!("OUT_DIR"), "/built.rs")); } /// JSON Schema validatio...
{ iter_on_error(py, &self.schema, instance) }
identifier_body
view-profile.component.ts
import { Router } from '@angular/router'; import { Login } from '../../models/login.model'; import { NgZone } from '@angular/core'; import { Role } from '../../models/role.model'; import { User } from '../../models/user.model'; import { Component, OnInit } from '@angular/core'; import { Office } from '../../models/offi...
sessionCheck() { if (this.principal.id > 0) { this.session = true; } else { this.session = false; } } /** * Allows the form to be edited */ edit() { document.getElementById('firstName').removeAttribute('disabled'); document.getElementById('lastName').removeAttribute('dis...
{ this.authService.principal.subscribe(user => { this.principal = user; if (this.principal.id > 0) { this.existingBio = this.principal.bio; this.firstName = this.principal.firstName; this.lastName = this.principal.lastName; this.username = this.principal.email; th...
identifier_body
view-profile.component.ts
import { Router } from '@angular/router'; import { Login } from '../../models/login.model'; import { NgZone } from '@angular/core'; import { Role } from '../../models/role.model'; import { User } from '../../models/user.model'; import { Component, OnInit } from '@angular/core'; import { Office } from '../../models/offi...
populateLocation() { this.locationSerivce.getlocation(this.principal.location).subscribe(data => { console.log(data); this.principal.location = data; }); } /** * Enables limited ability to modify the User's role in the system */ switchRole() { if (this.principal.role === Role.Driv...
this.populateLocation(); } //Populate user location by finding the latitude and logitude via Maps service.
random_line_split
view-profile.component.ts
import { Router } from '@angular/router'; import { Login } from '../../models/login.model'; import { NgZone } from '@angular/core'; import { Role } from '../../models/role.model'; import { User } from '../../models/user.model'; import { Component, OnInit } from '@angular/core'; import { Office } from '../../models/offi...
(id: number) { this.result = window.confirm('Are you sure you want to make this trainer a rider?'); if (this.result) { this.userService.updateRole(id, Role.Rider).then(); location.reload(true); } else { alert('No changes will be made'); } } makeTrainer(id: number) { this.resul...
makeRider
identifier_name
view-profile.component.ts
import { Router } from '@angular/router'; import { Login } from '../../models/login.model'; import { NgZone } from '@angular/core'; import { Role } from '../../models/role.model'; import { User } from '../../models/user.model'; import { Component, OnInit } from '@angular/core'; import { Office } from '../../models/offi...
else { alert('No changes will be made'); } } tabSelect($event){ console.log($event); } /** Sets up contact information */ addContact(): void { const contact: ContactInfo = { id: null, type: null, info: null }; this.contactInfoArray.push(contact); } updateBio...
{ this.userService.updateRole(id, Role.Admin).then(); location.reload(true); }
conditional_block
main_2.py
# <------------------------ Imports ------------------------------> # from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy as np import tkinter as tk # <--- MySQL Errors ---> # import mysql.connector.errors as SQLErrors # <--- Miscellenaeous ---> # from typing import * import csv import dateti...
else: # plt.clf() return plot_graphs() # graph_active = True cursor.close() # <------------------------------- Beginning of Matplotlib helper code -----------------------> # # <----- Taken from https://github.com/PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Matplotlib.py ----->...
return plot_graphs()
conditional_block
main_2.py
# <------------------------ Imports ------------------------------> # from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy as np import tkinter as tk # <--- MySQL Errors ---> # import mysql.connector.errors as SQLErrors # <--- Miscellenaeous ---> # from typing import * import csv import dateti...
default_value="All", key="used_type", readonly=True)], [T("Sort by:"), Combo(["Name", "Amount", "Date of Transaction"], default_value="Name", key="sort_by", readonly=True), Combo(["Ascending", "Descending"], default_value="Ascending", key="asc...
random_line_split
main_2.py
# <------------------------ Imports ------------------------------> # from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy as np import tkinter as tk # <--- MySQL Errors ---> # import mysql.connector.errors as SQLErrors # <--- Miscellenaeous ---> # from typing import * import csv import dateti...
(user: Union[str, int], n: int = 10000, start_date: str = f"{year}-{month}-1", end_date: str = f"{year}-{month}-{day}", asc_or_desc: str = "ASC", orderer: str = "particulars") -> List[Tuple]: headings = [ ...
get_transactions
identifier_name
main_2.py
# <------------------------ Imports ------------------------------> # from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import numpy as np import tkinter as tk # <--- MySQL Errors ---> # import mysql.connector.errors as SQLErrors # <--- Miscellenaeous ---> # from typing import * import csv import dateti...
def Transactions(self): transaction_layout = [ [T("Transactions", font=("Helvetica", 18))], [TabGroup( [ [Tab("New Transaction", self.Create_Add_Trans_Layout())], [Tab("History", self.History())] ] ...
income, expenses = get_income_and_expense(self.user.uname) if (income, expenses) == (None, None): dash_layout = [ [T(f"Welcome {self.user.first_name}")], [T("Looks like you have no transactions!\nGo add one in the Transactions tab.", justification=...
identifier_body
calSettings.py
from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.relativelayout import RelativeLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.uix.label import Label from kivy.core.window import Window from kivy.properti...
self.right_arrow = Button(text=">", on_press=self.go_next, pos_hint={"top": 1, "right": 1}, size_hint=(.1, .1)) self.add_widget(self.left_arrow) self.add_widget(self.right_arrow) # Title self.title_label = Label(text=self.title, pos_hint=...
self.left_arrow = Button(text="<", on_press=self.go_prev, pos_hint={"top": 1, "left": 0}, size_hint=(.1, .1))
random_line_split
calSettings.py
from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.relativelayout import RelativeLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.uix.label import Label from kivy.core.window import Window from kivy.properti...
import pymysql def paintDates(): global holiday, halfday db = pymysql.connect(credentials['address'], credentials['username'], credentials['password'], credentials['db'], autocommit=True, connect_timeout=1) cur = db.cursor() cur.execute("SELECT DAY, MONTH, YEAR, DETAIL FROM essl.month_details") ...
""" Basic calendar widget """ def __init__(self, as_popup=False, touch_switch=False, *args, **kwargs): super(CalendarWidgetS, self).__init__(*args, **kwargs) self.as_popup = as_popup self.touch_switch = touch_switch #self.selectedDates = [] self.prepare_data() self....
identifier_body
calSettings.py
from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.relativelayout import RelativeLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.uix.label import Label from kivy.core.window import Window from kivy.properti...
(ToggleButton): pass class HolidayBtn(ToggleButton): pass class HalfdayBtn(ToggleButton): pass class CalendarWidgetS(RelativeLayout): """ Basic calendar widget """ def __init__(self, as_popup=False, touch_switch=False, *args, **kwargs): super(CalendarWidgetS, self).__init__(*args, **kwar...
ToggleBtn
identifier_name
calSettings.py
from kivy.uix.screenmanager import ScreenManager, Screen from kivy.uix.relativelayout import RelativeLayout from kivy.uix.gridlayout import GridLayout from kivy.uix.button import Button from kivy.uix.togglebutton import ToggleButton from kivy.uix.label import Label from kivy.core.window import Window from kivy.properti...
if self.as_popup: self.parent_popup.dismiss() #getInfo.openPopup() def go_prev(self, inst): """ Go to screen with previous month """ # Change active date self.active_date = [self.active_date[0], self.quarter_nums[0][1], self.quarte...
selectedDates.append(selected)
conditional_block
checktime.go
package time // Copyright (c) 2018, Arm Limited and affiliates. // SPDX-License-Identifier: Apache-2.0 // // 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/lic...
client.running = true client.locker.Unlock() timeout := time.Duration(1) for { select { case <-client.stopChannel: break case <-time.After(timeout): // run the client err, errcode, timeresp := client.getTime() timeout = client.checkTimeInterval if err != nil { if client.backingOff { ...
{ client.locker.Unlock() return }
conditional_block
checktime.go
package time // Copyright (c) 2018, Arm Limited and affiliates. // SPDX-License-Identifier: Apache-2.0 // // 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/lic...
// TimedOut means there was no response from server TimedOut = 2 // BadResponse means the response from server was not formatted correctly BadResponse = 3 // InsaneResponse means the server provided a time value which is crazy InsaneResponse = 4 // SycallFailed means the syscall failed to work to set the time S...
recentTime = int64(1514786400000) // SetTimeOk means the time was set Correctly SetTimeOk = 1
random_line_split
checktime.go
package time // Copyright (c) 2018, Arm Limited and affiliates. // SPDX-License-Identifier: Apache-2.0 // // 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/lic...
(config *ClientConfig) (err error) { client.pretend = config.Pretend client.host = config.Host client.port = config.Port client.checkTimeInterval = time.Duration(config.CheckTimeInterval) * time.Second if client.checkTimeInterval < 5 { client.checkTimeInterval = defaultCheckTimeInterval } if !config.NoTLS { ...
Reconfigure
identifier_name
checktime.go
package time // Copyright (c) 2018, Arm Limited and affiliates. // SPDX-License-Identifier: Apache-2.0 // // 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/lic...
func newClientError(resp *http.Response) (ret *ClientError) { ret = new(ClientError) ret.StatusCode = resp.StatusCode ret.Status = resp.Status return } // StatusChannel returns the status channel which can be used to know if time is set // if nothing reads the channel, the time will be set anyway, and a simple l...
{ return fmt.Sprintf("TIME Client Error: %d - %s", err.StatusCode, err.Status) }
identifier_body
x0CompilerUI.py
import sys, os, time import json import codecs import threading from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QApplication, QAbstractItemView, \ QFileDialog, QTableWidgetItem, QMessageBox from PyQt5.QtGui import QPainter, QColor, QFont, QBrush, QSyntaxHighlighter, QTextCharFormat from PyQt5.QtCore i...
if mod == 1: while window.debug == 0: time.sleep(0.05) window.setCodeStatus(run.c, False) if window.debug == 1: # next step pass if window.debug == 2: # step into pass if window.debug == 3: # over step mod = 0 window.setDebugEnabled(False) if window.debug == 4: # step out r...
break
conditional_block
x0CompilerUI.py
import sys, os, time import json import codecs import threading from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QApplication, QAbstractItemView, \ QFileDialog, QTableWidgetItem, QMessageBox from PyQt5.QtGui import QPainter, QColor, QFont, QBrush, QSyntaxHighlighter, QTextCharFormat from PyQt5.QtCore i...
ileInit(self): self.filetag = False self.filepath = os.getcwd() self.filename = "" self.workPathLabel.setText("") cleanfiles() def initUI(self): self.fileInit() self.errTbInit() #self.scroll = QScrollArea() #self.scroll.setWidgrt(self.) self.actionNew.triggered.connect(self.newFile) self.action...
his function is used to initialize the errMsgTable ''' self.errorMsgTable.clear() self.errorMsgTable.setColumnCount(3) self.errorMsgTable.setRowCount(1) self.errorMsgTable.setHorizontalHeaderLabels(['errno', 'line', 'message']) self.errorMsgTable.verticalHeader().setVisible(False) self.errorMsgTable.setEd...
identifier_body
x0CompilerUI.py
import sys, os, time import json import codecs import threading from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QApplication, QAbstractItemView, \ QFileDialog, QTableWidgetItem, QMessageBox from PyQt5.QtGui import QPainter, QColor, QFont, QBrush, QSyntaxHighlighter, QTextCharFormat from PyQt5.QtCore i...
if isfile(".\\~.tmp"): os.remove(".\\~.tmp") if isfile(os.getcwd()+"\\ferr.json"): os.remove(os.getcwd()+"\\ferr.json") if isfile(os.getcwd()+"\\fcode.json"): os.remove(os.getcwd()+"\\fcode.json") ''' This function is the real processing for backstage-interpretation and it should work in a new thread so tha...
def cleanfiles(): from os.path import isfile
random_line_split
x0CompilerUI.py
import sys, os, time import json import codecs import threading from PyQt5.QtWidgets import QWidget, QApplication, QMainWindow, QApplication, QAbstractItemView, \ QFileDialog, QTableWidgetItem, QMessageBox from PyQt5.QtGui import QPainter, QColor, QFont, QBrush, QSyntaxHighlighter, QTextCharFormat from PyQt5.QtCore i...
build&run or debug a processing ''' # clear output label and table contents self.label.setText("") self.outputLabel.setText("") self.tableWidget.clear() self.tableWidget.setRowCount(0); #添加表头: list = ['idx','name','value','level','addr','size'] for i in range(6): item = QTableWidgetItem(li...
ration for
identifier_name
form_input.rs
use super::error_message::get_error_message; use crate::styles::{get_palette, get_size, Palette, Size}; use wasm_bindgen_test::*; use yew::prelude::*; use yew::{utils, App}; /// # Form Input /// /// ## Features required /// /// forms /// /// ## Example /// /// ```rust /// use yew::prelude::*; /// use yew_styles::forms...
/// type Properties = (); /// fn create(_: Self::Properties, link: ComponentLink<Self>) -> Self { /// FormInputExample { /// link, /// value: "".to_string(), /// } /// } /// fn update(&mut self, msg: Self::Message) -> ShouldRender { /// match msg { /// ...
random_line_split
form_input.rs
use super::error_message::get_error_message; use crate::styles::{get_palette, get_size, Palette, Size}; use wasm_bindgen_test::*; use yew::prelude::*; use yew::{utils, App}; /// # Form Input /// /// ## Features required /// /// forms /// /// ## Example /// /// ```rust /// use yew::prelude::*; /// use yew_styles::forms...
(&mut self, props: Self::Properties) -> ShouldRender { if self.props != props { self.props = props; true } else { false } } fn view(&self) -> Html { html! { <> <input id=self.props.id.clone() ...
change
identifier_name
form_input.rs
use super::error_message::get_error_message; use crate::styles::{get_palette, get_size, Palette, Size}; use wasm_bindgen_test::*; use yew::prelude::*; use yew::{utils, App}; /// # Form Input /// /// ## Features required /// /// forms /// /// ## Example /// /// ```rust /// use yew::prelude::*; /// use yew_styles::forms...
#[wasm_bindgen_test] fn should_create_form_input() { let props = Props { key: "".to_string(), code_ref: NodeRef::default(), id: "form-input-id-test".to_string(), class_name: "form-input-class-test".to_string(), input_type: InputType::Text, oninput_signal: Callback::...
{ match input_type { InputType::Button => "button".to_string(), InputType::Checkbox => "checkbox".to_string(), InputType::Color => "color".to_string(), InputType::Date => "date".to_string(), InputType::Datetime => "datetime".to_string(), InputType::DatetimeLocal => "d...
identifier_body
main.rs
extern crate clap; use clap::{App, Arg}; use std::io::{stderr, stdin, stdout, Write, Read}; use std::time::{Duration, Instant}; use std::net::{SocketAddr, TcpListener, IpAddr}; const DEFAULT_BUFFER_SIZE: usize = 4096; const DEFAULT_ITERATION_COUNT: usize = 1; const DEFAULT_ADDRESS: &'static str = "127.0.0.1"; macro_...
fn byte_to_mem_units(bytes: f64) -> (f64, &'static str) { const KB: f64 = 1024.0; const MB: f64 = KB * 1024.0; const GB: f64 = MB * 1024.0; const TB: f64 = GB * 1024.0; if bytes >= TB { (bytes / TB, "TB") } else if bytes >= GB { (bytes / GB, "GB") } else if bytes >= MB { (bytes / MB, "MB"...
{ write!(output, "\x1b[{}A", lines)?; Ok(()) }
identifier_body
main.rs
extern crate clap; use clap::{App, Arg}; use std::io::{stderr, stdin, stdout, Write, Read}; use std::time::{Duration, Instant}; use std::net::{SocketAddr, TcpListener, IpAddr}; const DEFAULT_BUFFER_SIZE: usize = 4096; const DEFAULT_ITERATION_COUNT: usize = 1; const DEFAULT_ADDRESS: &'static str = "127.0.0.1"; macro_...
} else { measure_stdin(buffer_size, iterations, passthrough); } } fn measure_tcp_stream(address: &str, port: u16, buffer_size: usize, iterations: usize, passthrough: bool) { let parsed_addr: IpAddr = match address.parse() { Ok(parsed) => parsed, Err(_) => { print_err!("B...
}
random_line_split