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 |
|---|---|---|---|---|
livestream.rs | ::mpsc as bchan;
pub type VideoFrame=(Vec<u8>, usize, usize, usize);
use crate::inference_engine::{start_inference_service, InfererHandler};
use crate::time_now;
// 10 Frames as a batch.
pub struct VideoBatchContent{
pub data: Vec<u8>,
pub sizes: [usize; 10],
pub capture_timestamps: [usize; 10],
... | data: v,
size,
start: 0,
end: 0,
offset: 0,
next_index: 0
}
}
pub fn info(&self){
println!("<RingBuffer size={}, start={}, end={}, offset={}, next_index={}>", self.size, self.start, self.end, self.offset, self.next_... | v.push(None);
}
RingBuffer{
| random_line_split |
create_tumor_dataset.py | (pet_image, pixel_shape, pixel_spacing, mask=None, patient="?", mask_name="?"):
"""
The transparent option makes all zeros transparent, and all ones red (expects image with only
1s and 0s)
"""
# create axis for plotting
pixel_shape = pet_image.shape
x = np.arange(0.0, (pixel_shape[1] + 1) * ... | plot_pet_volume | identifier_name | |
create_tumor_dataset.py | _data()
volume = np.zeros(nii_data.shape[:3], dtype=int)
for i in range(nii_data.shape[-1]):
volume += nii_data[:, :, :, 0, i] << (8 * i)
volume = np.swapaxes(volume, 0, 1)
volume = np.flip(volume, 2)
print(" * Structures folder: {}".format(mt... | ignored_patients[patient] = "No valid MTV contour found"
num_ignored_patients += 1
print("Patient", patient, "has no MTV contour. \nThis patient will be ignored!\n")
if patient in volumes:
volumes.pop(patient) | conditional_block | |
create_tumor_dataset.py | elif median == 0:
x, y = x, z
median_pet_image = pet_image[int(pet_image.shape[0] / 2), :, :]
projected_mask = mask[0, :, :]
for i in range(mask.shape[0]):
projected_mask += mask[i, :, :]
print(median_pet_image.shape)
masked_pet_image = np.ma.masked_array(median_p... | """
Plot pet_medians and project mask. median can be 0, 1 or 2
"""
# create axis for plotting
pixel_shape = pet_image.shape
x = np.arange(0.0, (pixel_shape[1] + 1) * pixel_spacing[0], pixel_spacing[0])
y = np.arange(0.0, (pixel_shape[0] + 1) * pixel_spacing[1], pixel_spacing[1])
z = np.arang... | identifier_body | |
create_tumor_dataset.py | # normalize values
vmin = np.min(pet_image)
vmax = np.max(pet_image)
cmap = plt.cm.gray
cmap.set_bad('r', 1)
# show images
fig = plt.figure(fig_num)
plt.clf()
ax = fig.add_subplot(121)
ax.pcolormesh(x, y, median_pet_image, vmin=vmin, vmax=vmax, cmap=cmap)
ax.set_aspect('equal')
... | for y in range(h):
for z in range(d):
centroid[0] += image[x, y, z] * x
centroid[1] += image[x, y, z] * y
centroid[2] += image[x, y, z] * z
cumulative += image[x, y, z]
centroid = centroid[0] / cumulative... | centroid = [0, 0, 0]
for x in range(w): | random_line_split |
variants.ts | [p]
if (!addIn || !proc) continue
proc(addIn, res)
}
return res.length === 0 ? null : res
}
//****************************
// EXPORTS FOR SHEET
//****************************
//export const setCanModify = (root: SheetWithAddIns) => root[Consts.canModify] = true
// transform sheet to mergable and patchabl... | return sheet
}
export const mergeSheetsAndFinish = (sheet: SheetWithAddIns, modifiers: SheetWithAddIns[], onFinishAddInClasses: FinishAddIns, canModify?: boolean) => {
// deep merge
sheet = mergeSheets(sheet, modifiers, canModify)
sheet = finishAddInsClasses(sheet, onFinishAddInClasses, canModify)
nameRuleset... | random_line_split | |
DLModeler.py | _label.reshape(-1, 1))
self.train_CNN(member,train_data,encoded_label,valid_data,valid_label)
elif 'UNET' in self.model_type:
#train_label[train_label >= 50.] = 50.
#log_train_label = np.log((train_label+1.0))
self.train_UNET(member,train_data,train_label,valid_... | (self,member,trainX,trainY,validX,validY):
model_file = self.model_path + f'/{member}_{self.model_args}_{self.model_type}.h5'
'''
if os.path.exists(model_file):
del trainX,trainY,validX,validY
unet = tf.keras.models.load_model(model_file,compile=False)
... | train_UNET | identifier_name |
DLModeler.py | (train_label.reshape(-1, 1))
self.train_CNN(member,train_data,encoded_label,valid_data,valid_label)
elif 'UNET' in self.model_type:
#train_label[train_label >= 50.] = 50.
#log_train_label = np.log((train_label+1.0))
self.train_UNET(member,train_data,train_label,... |
if self.model_type == 'UNET':
model_obj_params['filter_num'] = [16, 32, 64, 128]# 256]
unet_model_obj = models.unet_2d
compile_params = {'loss': 'mean_squared_error'}
else:
compile_params = {'loss': ['mean_squared_error',
... | model_file = self.model_path + f'/{member}_{self.model_args}_{self.model_type}.h5'
'''
if os.path.exists(model_file):
del trainX,trainY,validX,validY
unet = tf.keras.models.load_model(model_file,compile=False)
print(f'\nOpening {model_file}\n')
#s... | identifier_body |
DLModeler.py |
self.predictors = np.array(long_predictors)
#Class to read data and standardize
self.dldataeng = DLDataEngineering(self.model_path,self.hf_path,
self.num_examples,self.class_percentages,self.predictors,
self.model_args)
return
... | if "_" in predictor:
predictor_name = predictor.split('_')[0].upper() + predictor.split('_')[-1]
elif " " in predictor:
predictor_name = ''.join([v[0].upper() for v in predictor.split()])
else: predictor_name = predictor
long_predictors.append(predic... | conditional_block | |
DLModeler.py | (model,validX,validY,threshold_file)
return
'''
print('\nTraining {0} models'.format(member))
print('Training data shape {0}'.format(np.shape(trainX)))
print('Training label data shape {0}\n'.format(np.shape(trainY)))
#print('Validation data shape {0}'.format(np.shap... | return
prob_thresh = 0 #pd.read_csv(threshold_file).loc[0,'size_threshold']+0.05
print(prob_thresh) | random_line_split | |
nodes.ts | export function GetNodeMap(): NodeMap {
return GetData('nodes');
}
export function GetNodes(): MapNode[] {
const nodeMap = GetNodeMap();
return CachedTransform('GetNodes', [], nodeMap, () => (nodeMap ? nodeMap.VValues(true) : []));
}
export function GetNodesL2(): MapNodeL2[] {
const nodes = GetNodes();
return Cach... | if (!asPartOfCut && (node.parents || {}).VKeys(true).length <= 1) return `${baseText}doing so would orphan it. Try deleting it instead.`;
if (IsRootNode(node)) return `${baseText}it's the root-node of a map.`;
if (IsNodeSubnode(node)) return `${baseText}it's a subnode. Try deleting it instead.`;
return null; | random_line_split | |
nodes.ts | = 10,
Relevance = 20,
}
export type NodeMap = {[key: string]: MapNode};
export function GetNodeMap(): NodeMap {
return GetData('nodes');
}
export function GetNodes(): MapNode[] {
const nodeMap = GetNodeMap();
return CachedTransform('GetNodes', [], nodeMap, () => (nodeMap ? nodeMap.VValues(true) : []));
}
export f... | (parentID: string, newChild: Pick<MapNode, '_key' | 'type'>, permissions: PermissionGroupSet, newHolderType?: HolderType) {
if (!CanGetBasicPermissions(permissions)) return "You're not signed in, or lack basic permissions.";
const parent = GetNode(parentID);
if (parent == null) return 'Parent data not found.';
// c... | ForNewLink_GetError | identifier_name |
nodes.ts | = 10,
Relevance = 20,
}
export type NodeMap = {[key: string]: MapNode};
export function GetNodeMap(): NodeMap |
export function GetNodes(): MapNode[] {
const nodeMap = GetNodeMap();
return CachedTransform('GetNodes', [], nodeMap, () => (nodeMap ? nodeMap.VValues(true) : []));
}
export function GetNodesL2(): MapNodeL2[] {
const nodes = GetNodes();
return CachedTransform('GetNodes', [], nodes, () => nodes.map(a => GetNodeL2(a... | {
return GetData('nodes');
} | identifier_body |
mod.rs | Global(DataId),
Local(StackSlot),
}
struct Compiler<T: Backend> {
module: Module<T>,
scope: Scope<InternedStr, Id>,
debug: bool,
// if false, we last saw a switch
last_saw_loop: bool,
strings: HashMap<Vec<u8>, DataId>,
loops: Vec<(Block, Block)>,
// switch, default, end
// i... | (
&mut self,
params: Vec<Symbol>,
func_start: Block,
location: &Location,
builder: &mut FunctionBuilder,
) -> CompileResult<()> {
// Cranelift requires that all block params are declared up front
let ir_vals: Vec<_> = params
.iter()
.ma... | store_stack_params | identifier_name |
mod.rs | Global(DataId),
Local(StackSlot),
}
struct Compiler<T: Backend> {
module: Module<T>,
scope: Scope<InternedStr, Id>,
debug: bool,
// if false, we last saw a switch
last_saw_loop: bool,
strings: HashMap<Vec<u8>, DataId>,
loops: Vec<(Block, Block)>,
// switch, default, end
// i... | location,
}))
};
let data = StackSlotData {
kind,
size,
offset: None,
};
let stack_slot = builder.create_stack_slot(data);
self.scope.insert(decl.symbol.id, Id::Local(stack_slot));
if let Some(init) = decl.in... | data: "cannot store items on the stack that are more than 4 GB, it will overflow the stack".into(), | random_line_split |
mod.rs | atable<Declaration>>,
debug: bool,
) -> (Result<Module<B>, CompileError>, VecDeque<CompileWarning>) {
// really we'd like to have all errors but that requires a refactor
let mut err = None;
let mut compiler = Compiler::new(module, debug);
for decl in program {
let current = match (decl.data.... | {
// void function, return nothing
builder.ins().return_(&[]);
} | conditional_block | |
mod.rs | Global(DataId),
Local(StackSlot),
}
struct Compiler<T: Backend> {
module: Module<T>,
scope: Scope<InternedStr, Id>,
debug: bool,
// if false, we last saw a switch
last_saw_loop: bool,
strings: HashMap<Vec<u8>, DataId>,
loops: Vec<(Block, Block)>,
// switch, default, end
// i... | *location
),
Ok(size) => size,
};
let stack_data = StackSlotData {
kind: StackSlotKind::ExplicitSlot,
size: u32_size,
offset: None,
};
let slot = builder.create_stack_slot(... | {
// Cranelift requires that all block params are declared up front
let ir_vals: Vec<_> = params
.iter()
.map(|param| {
let ir_type = param.ctype.as_ir_type();
Ok(builder.append_block_param(func_start, ir_type))
})
.collect:... | identifier_body |
main.py | import indexer as csindexer
# Use absolute paths to avoid any issues.
project_dir = os.path.dirname(os.path.realpath(__file__))
# Create argument parser.
parser = argparse.ArgumentParser(description="Endpoint for running tests on"
" the compressed sparse indexer.")
parse... | idx = np.random.choice(M.nnz, n_indexers, replace=True)
indexer['row'] = M.row[idx]
indexer['col'] = M.col[idx]
indexer['data'] = np.random.rand(idx.size).astype(np.float64)
if debug:
print("\tTime to generate indexer: %s" % t.elapsed)
# Convert sparse matrix.
with ... | """A function for timing our cxindexer and scipy indexer. It first creates
sparse matrices, sorts if necessary, runs indexers on both and returns
the times."""
if debug:
print("Benchmarking:\n\tSORT = %s\n\tN_THREADS = %s\n\tSPARSE_FORMAT ="
" %s\n\tROWS = %s\n\tCOLS = %s\n\tNNZ = %s\n... | identifier_body |
main.py | import indexer as csindexer
# Use absolute paths to avoid any issues.
project_dir = os.path.dirname(os.path.realpath(__file__))
# Create argument parser.
parser = argparse.ArgumentParser(description="Endpoint for running tests on"
" the compressed sparse indexer.")
parse... | (sort, n_threads, sparse_format, rows, cols, nnz, n_indexers,
search_type, operation, debug):
"""A function for timing our cxindexer and scipy indexer. It first creates
sparse matrices, sorts if necessary, runs indexers on both and returns
the times."""
if debug:
print("Benchmarki... | index_time | identifier_name |
main.py | import indexer as csindexer
# Use absolute paths to avoid any issues.
project_dir = os.path.dirname(os.path.realpath(__file__))
# Create argument parser.
parser = argparse.ArgumentParser(description="Endpoint for running tests on"
" the compressed sparse indexer.")
parse... |
elif sparse_format == 'CSC':
M = sp.sparse.csc_matrix(M)
else:
raise Exception("sparse_format must be either CSR or CSC.")
if debug:
print("\tTime to convert sparse matrix: %s" % t.elapsed)
# Sort.
with Timer() as t:
if sort:
if sparse_f... | M = sp.sparse.csr_matrix(M) | conditional_block |
main.py | import indexer as csindexer
# Use absolute paths to avoid any issues.
project_dir = os.path.dirname(os.path.realpath(__file__))
# Create argument parser.
parser = argparse.ArgumentParser(description="Endpoint for running tests on"
" the compressed sparse indexer.")
parse... | elif sparse_format == 'CSC':
M = sp.sparse.csc_matrix(M)
else:
raise Exception("sparse_format must be either CSR or CSC.")
if debug:
print("\tTime to convert sparse matrix: %s" % t.elapsed)
# Sort.
with Timer() as t:
if sort:
if sparse_fo... | M = sp.sparse.csr_matrix(M) | random_line_split |
feature-select.py | row_num * data_train_proportion
train_data = data_classed.loc[0:(train_row_num)]
test_data = data_classed.loc[train_row_num:]
train_data = train_data.reset_index() #重设索引
train_data.drop(['index'],axis=1,inplace=True) #去除多余索引
... | cat( [temp, data_list[count]], axis = 0)
temp = temp.reset_index() #重设索引
temp.drop(['index'],axis=1,inplace=True) #去除多余索引
return temp
def get_next_batch(all_data,batch_size,step):
row_num = all_data.shape[0]
batch_num = row_num/batch_size
batch_count = step%batch_... | ],axis=1,inplace=True) #去除多余索引
def pack_data_list(data_list):
temp = data_list[0]
row_num = len(data_list)
for count in range(1,row_num):
temp = pd.con | conditional_block |
feature-select.py | row_num * data_train_proportion
train_data = data_classed.loc[0:(train_row_num)]
test_data = data_classed.loc[train_row_num:]
train_data = train_data.reset_index() #重设索引
train_data.drop(['index'],axis=1,inplace=True) #去除多余索引
... | um[2]], initializer=tf.constant_initializer(0.0))
layer3 = tf.nn.tanh(tf.matmul(layer2, weights3) + biases3)
weights_out = get_weight_variable("weights_out",[layer_node_num[2], output_num], regularizer)
biases_out = tf.get_variable("biases_out", [output_num], initializer=tf.constant_initializer(0.0))
layer_out = ... | .nn.relu(tf.matmul(layer1, weights2) + biases2)
weights3 = get_weight_variable("weights3", [layer_node_num[1], layer_node_num[2]],regularizer)
biases3 = tf.get_variable("biases3", [layer_node_n | identifier_body |
feature-select.py | _num * data_train_proportion
train_data = data_classed.loc[0:(train_row_num)]
test_data = data_classed.loc[train_row_num:]
train_data = train_data.reset_index() #重设索引
train_data.drop(['index'],axis=1,inplace=True) #去除多余索引
test... | g='ISO-8859-1')
drop_list = [] #去除字符串形式的数据
for col in base_dataset:
if base_dataset.loc[:,col].dtype == 'object':
drop_list.append(col)
base_dataset.drop(drop_list,axis=1,inplace=True)
drop_index_rule(base_dataset, np.isnan(base_dataset.family_income)) #去除缺省行
base_datase... | e.csv",encodin | identifier_name |
feature-select.py | 行
# data_list[0] = pd.concat( [data_list[0], data_list[0]], axis = 0)
for count in range(len(data_list)):
row_num = data_list[count].shape[0]
if row_num < row_expand_aim_num:
err = row_expand_aim_num - row_num
temp = data_list[count].sample(n = err, replace=True)
... | # AdamOptimizer
# FtrlOptimizer
# RMSPropOptimizer
# train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
| random_line_split | |
misc.py | '
Args:
seconds: Number of seconds of the time duration.
short_units: Whether or not to use short units ("d", "h", "m", "s")
instead of long units ("day", "hour", "minute", "second")?
keep_zeros: Whether or not to keep zero components?
(e.g., to keep "0h 0m" in "1d 0... |
if not skip_incomplete and start < length:
yield slice(start, length, 1)
def optional_apply(f, value):
"""
If `value` is not None, return `f(value)`, otherwise return None.
>>> optional_apply(int, None) is None
True
>>> optional_apply(int, '123')
123
Args:
f: The fun... | yield slice(start, start + batch_size, 1)
start += batch_size | conditional_block |
misc.py | Args:
seconds: Number of seconds of the time duration.
short_units: Whether or not to use short units ("d", "h", "m", "s")
instead of long units ("day", "hour", "minute", "second")?
keep_zeros: Whether or not to keep zero components?
(e.g., to keep "0h 0m" in "1d 0h 0... |
Yields
Slices of each mini-batch. The last mini-batch may contain less
elements than `batch_size`.
"""
start = 0
stop1 = (length // batch_size) * batch_size
while start < stop1:
yield slice(start, start + batch_size, 1)
start += batch_size
if not skip_incomp... | """
Iterate through all the mini-batch slices.
>>> arr = np.arange(10)
>>> for batch_s in minibatch_slices_iterator(len(arr), batch_size=4):
... print(arr[batch_s])
[0 1 2 3]
[4 5 6 7]
[8 9]
>>> for batch_s in minibatch_slices_iterator(
... len(arr), batch_size=4, skip_i... | identifier_body |
misc.py | uvalue
elif keep_zeros and pieces:
pieces.append(f'0{uname}')
uname, uname_plural = units[-1][1:]
if seconds > np.finfo(np.float64).eps:
pieces.append(f'{seconds:.4g}{uname_plural if seconds > 1 else uname}')
elif not pieces or keep_zeros:
pieces.append(f'0{uname}')
... | for node in self._nodes:
if issubclass(type_, node.type):
node.add_child(this_node)
elif issubclass(node.type, type_):
this_node.add_child(node) | random_line_split | |
misc.py | (self):
return 'NOT_SET'
NOT_SET = NotSet()
def format_duration(seconds: Union[float, int],
short_units: bool = True,
keep_zeros: bool = False):
"""
Format specified time duration as human readable text.
>>> format_duration(0)
'0s'
>>> format_dura... | __repr__ | identifier_name | |
cube_reader.py | header = fits_file[0].header
image_data = fits_file[1].data
segmentation_data = fits_file[2].data
header_keywords = {'CRVAL3': 0, 'CRPIX3': 0, 'CD3_3': 0}
# clause to differentiate between CDELT3 and CD3_3
for hdr_key, hdr_value in header_keywords.items():
# finding required header va... | random_line_split | ||
cube_reader.py | = peakutils.indexes(sn_data, thres=300, thres_abs=True)
sky_peaks_x = peakutils.interpolate(x_range, sn_data, sky_peaks)
if (sky_peaks_x.size != 0):
sky_peak = sky_peaks_x[0]
sky_peak_index = find_nearest(sky_peak, x_range)
else:
sky_peak = 6000
sky_peak_index = 0
sky_... | s.mkdir(data_dir)
| conditional_block | |
cube_reader.py | slt.best_values
sn_gauss_data = sn_gauss_rslt.best_fit
sn_line_csqs = chisq(sn_line_data, otwo_region, stddev_val)
sn_gauss_csqs = chisq(sn_gauss_data, otwo_region, stddev_val)
signal_noise = np.sqrt(sn_line_csqs['chisq'] - sn_gauss_csqs['chisq'])
# saving data to text files
curr_f... | phs_otwo_region(): | identifier_name | |
cube_reader.py | image_sum[i_ra][i_dec] = pd_sum
return {'median': image_median, 'sum': image_sum}
def spectrum_creator(file_name):
""" creating a spectra from the area as defined in the segementation area """
file_data = read_file(file_name)
image_data = file_data[1]
segmentation_data = file... | """ collapses image data so it can be passed as a heatmap """
file_data = read_file(file_name)
header_data = file_data[0]
image_data = file_data[1]
data_shape = np.shape(image_data)
ra_axis = data_shape[2]
dec_axis = data_shape[1]
wl_axis = data_shape[0]
image_median... | identifier_body | |
route_import.go | file"`
}
func (h *ImportHandler) Import(c droplet.Context) (interface{}, error) {
input := c.Input().(*ImportInput)
Force := input.Force
// file check
suffix := path.Ext(input.FileName)
if suffix != ".json" && suffix != ".yaml" && suffix != ".yml" {
return nil, fmt.Errorf("required file type is .yaml, .yml or ... | }
routes[value.Method] = route
parsed = append(parsed, value)
}
}
return routes, nil
}
func OpenAPI3ToRoute(swagger *openapi3.Swagger) ([]*entity.Route, error) {
var routes []*entity.Route
paths := swagger.Paths
var upstream *entity.UpstreamDef
var err error
for k, v := range paths {
k = regPathR... | {
var parsed []PathValue
var routes = map[string]*entity.Route{}
for _, value := range values {
value.Value.OperationID = strings.Replace(value.Value.OperationID, value.Method, "", 1)
var eq = false
for _, v := range parsed {
if utils.ValueEqual(v.Value, value.Value) {
eq = true
if routes[v.Method].... | identifier_body |
route_import.go | data.ErrNotFound {
return &data.SpecCodeResponse{StatusCode: http.StatusBadRequest},
fmt.Errorf(consts.IDNotFound, "upstream", route.UpstreamID)
}
return &data.SpecCodeResponse{StatusCode: http.StatusBadRequest}, err
}
}
if _, err := h.routeStore.CreateCheck(route); err != nil {
return ha... | // todo: import consumers
for _, securities := range security {
for name := range securities { | random_line_split | |
route_import.go | "`
}
func (h *ImportHandler) Import(c droplet.Context) (interface{}, error) {
input := c.Input().(*ImportInput)
Force := input.Force
// file check
suffix := path.Ext(input.FileName)
if suffix != ".json" && suffix != ".yaml" && suffix != ".yml" {
return nil, fmt.Errorf("required file type is .yaml, .yml or .jso... |
}
var values []PathValue
if v.Get != nil {
value := PathValue{
Method: http.MethodGet,
Value: v.Get,
}
values = append(values, value)
}
if v.Post != nil {
value := PathValue{
Method: http.MethodPost,
Value: v.Post,
}
values = append(values, value)
}
if v.Head != nil {... | {
return nil, err
} | conditional_block |
route_import.go | "`
}
func (h *ImportHandler) Import(c droplet.Context) (interface{}, error) {
input := c.Input().(*ImportInput)
Force := input.Force
// file check
suffix := path.Ext(input.FileName)
if suffix != ".json" && suffix != ".yaml" && suffix != ".yml" {
return nil, fmt.Errorf("required file type is .yaml, .yml or .jso... | (val *openapi3.Operation) (*entity.Route, error) {
routeMap := map[string]interface{}{}
for key, val := range val.Extensions {
if strings.HasPrefix(key, "x-apisix-") {
routeMap[strings.TrimPrefix(key, "x-apisix-")] = val
}
}
route := new(entity.Route)
routeJson, err := json.Marshal(routeMap)
if err != nil... | parseExtension | identifier_name |
ml_ex_03.py |
def getLabels(fileName):
labelData = load_data(dirPath + "/" + fileName)
labels = labelData[:,0].clip(min=0)
return np.array(labels)
def svm_intern_folds(data_train, data_test, labelsTrain, labelsTest):
acxmax = 0
c_max=0
gamma_max=0
for c in [2**(-5), 1, 2**(5), 2**(10)]:
for gam... | lineNum = rawData.shape[0]
colNum = rawData.shape[1]
data = np.array(rawData[0:lineNum, 0:colNum-1])
for i in range(lineNum):
classList.append(rawData[i][colNum - 1])
return [data, np.array(classList) ] | identifier_body | |
ml_ex_03.py | Num):
classList.append(rawData[i][colNum - 1])
return [data, np.array(classList) ]
def getLabels(fileName):
labelData = load_data(dirPath + "/" + fileName)
labels = labelData[:,0].clip(min=0)
return np.array(labels)
def svm_intern_folds(data_train, data_test, labelsTrain, labelsTest):
acxm... | (matrix, percent):
print "\n---- PCA - Choose components number ----"
print "Variance :", percent
mat = np.matrix(matrix) * np.matrix(matrix).transpose()
U,S,V = np.linalg.svd(mat)
#print U.shape, S.shape, V.shape
s_sum_all = sum(S)
totalComponents = matrix.shape[1]
num = totalCompone... | chooseComponentsNumber | identifier_name |
ml_ex_03.py | (lineNum):
classList.append(rawData[i][colNum - 1])
return [data, np.array(classList) ]
def getLabels(fileName):
labelData = load_data(dirPath + "/" + fileName)
labels = labelData[:,0].clip(min=0)
return np.array(labels)
def svm_intern_folds(data_train, data_test, labelsTrain, labelsTest):
... | c_max = c
gamma_max = gamm
return [acxmax, c_max, gamma_max]
def chooseComponentsNumber(matrix, percent):
print "\n---- PCA - Choose components number ----"
print "Variance :", percent
mat = np.matrix(matrix) * np.matrix(matrix).transpose()
U,S,V = np.linalg.svd(m... | accuracy = svm.score(data_test, labelsTest)
if accuracy > acxmax:
acxmax = accuracy | random_line_split |
ml_ex_03.py | Num):
classList.append(rawData[i][colNum - 1])
return [data, np.array(classList) ]
def getLabels(fileName):
labelData = load_data(dirPath + "/" + fileName)
labels = labelData[:,0].clip(min=0)
return np.array(labels)
def svm_intern_folds(data_train, data_test, labelsTrain, labelsTest):
acxm... |
final_accuracy = final_accuracy + model_score(alg, params_final,
new_data_train,
new_labels_train,
new_data_test,
... | acx = params[0]
params_final[0] = params[1]
if len(params) > 2:
params_final[1] = params[2] | conditional_block |
fork_resolver.rs | /*
* Copyright 2018 Intel Corporation
*
* 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 agre... | // Delete states for all blocks not in chain
let chain_len_to_delete = chain_head.block_num - cache_block.block_num;
delete_states_upto(
cache_block.block_id,
chain_head.clone().block_id,
... | // Mark all blocks upto common ancestor
// in the chain as invalid. | random_line_split |
fork_resolver.rs | /*
* Copyright 2018 Intel Corporation
*
* 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 agre... | else {
fork_won = if fork_cc < chain_cc { true } else { false };
}
}
}
if fork_won {
info!("Discarding the block in progress.");
service.cancel_block();
pu... | {
fork_won = if get_cert_from(&block).duration_id
< get_cert_from(&chain_head).duration_id
{
true
} else {
false
... | conditional_block |
fork_resolver.rs | /*
* Copyright 2018 Intel Corporation
*
* 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 agre... | (
ancestor: BlockId,
head: BlockId,
delete_len: u64,
service: &mut Poet2Service,
state_store: &mut ConsensusStateStore,
) -> () {
let mut next = head;
let mut count = 0_u64;
loop {
if ancestor == next || count >= delete_len {
break;
}
count += 1;
... | delete_states_upto | identifier_name |
fork_resolver.rs | /*
* Copyright 2018 Intel Corporation
*
* 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 agre... | state_store.delete(next.clone());
next = BlockId::from(
state_
.unwrap()
.estimate_info
.previous_block_id
.as_bytes()
.to_vec(),
);
}
}
}
fn get_cert_fro... | {
let mut next = head;
let mut count = 0_u64;
loop {
if ancestor == next || count >= delete_len {
break;
}
count += 1;
let state_ = state_store.get(next.clone());
if state_.is_err() {
debug!("State not found. Getting block via service.");
... | identifier_body |
roll.go | : %v\n", parser.errors))
}
// Walk and Resolve the AST
result, work := expr.Eval()
// Send a nice stylish message.
embed := &discordgo.MessageEmbed{
Author: &discordgo.MessageEmbedAuthor{},
Color: 0x00ff00, // Green
Description: strings.Join(args, ""),
Fields: []*discordgo.MessageEmbedField{
... |
// Satisfies the rule for `Primary => '(' Expr ')' | DIE | NUMBER`
func (p *DiceParser) Primary() AstExpr {
//log.Error().Str("Val", fmt.Sprintf("%v", p.peek())).Bool("Eq?", p.peek().Type == Const).Msg("Fuck")
// If the current token is a Constant value..
if p.check(Const) {
t := p.consume()
// This should n... | {
expr := p.Primary()
for p.check(Factor) {
t := p.consume()
operator := t // A Token
right := p.Primary() // An AstExpr
expr = AstOp{expr, right, operator}
}
return expr
} | identifier_body |
roll.go | ([]Token, error) {
var tokens []Token
var sb strings.Builder
for _, char := range raw {
// Consume until a transition token is reached
switch char {
case '\t', '\n', '\v', '\f', '\r', ' ', '\x85', '\xA0':
continue // Ignore whitespace.
case '+', '-', '*', '/', '(', ')':
// The previous token is over.... | return int(c), strconv.Itoa(int(c))
}
// A die's value is rolled, 1-[right] rolled [left] times, then summed.
type AstDie struct { | random_line_split | |
roll.go |
// Walk and Resolve the AST
result, work := expr.Eval()
// Send a nice stylish message.
embed := &discordgo.MessageEmbed{
Author: &discordgo.MessageEmbedAuthor{},
Color: 0x00ff00, // Green
Description: strings.Join(args, ""),
Fields: []*discordgo.MessageEmbedField{
{
Name: "Rolls",
... | {
s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("Errs: %v\n", parser.errors))
} | conditional_block | |
roll.go | (s *discordgo.Session, m *discordgo.MessageCreate, args []string) {
// If they used !roll, remove that from the args list. Otherwise they used ![expr]
if args[0] == "roll" {
args = args[1:]
}
// Convert the input string into a token stream
tokens, err := tokenizeExpr(strings.Join(args, ""))
if err != nil {
s... | RollHandler | identifier_name | |
OlMapView.js | = ctx.getImageData(0, 0, evt.tile.size.w, evt.tile.size.h);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) |
ctx.putImageData(imgd, 0, 0);
evt.tile.imgDiv.removeAttribute("crossorigin");
evt.tile.imgDiv.src = ctx.canvas.toDataURL();
}
}
}
});
this.map.addLayer(this.baseLayer);
// var style = new OpenLayers.Style({
// pointRadius: "${ra... | {
var tmp = (3 * pix[i] + 4 * pix[i + 1] + pix[i + 2]) / 8;
pix[i] = pix[i + 1] = pix[i + 2] = Math.sqrt( tmp / 256.0 ) * 256 * 1.05;
} | conditional_block |
OlMapView.js | this.dotLayer = null;
this.contentlensManager = null;
//example
// this.strategy = null;
// this.clusters = null;
this.features = [];
this.tweetsHeatmapManager = null;
// histogramManager = null;
//polygon selection:
this.polygon_layer = null;
this.cachedCenter = [];
this.cachedZoom = null;
};
OlMapVi... | this.map = null;
this.fromProjection = new OpenLayers.Projection("EPSG:4326");
this.toProjection = new OpenLayers.Projection("EPSG:900913");
this.baseLayer = null; | random_line_split | |
actions.rs | ?;
let wallet = opts.private_key.parse::<LocalWallet>()?;
let client = SignerMiddleware::new(provider, wallet);
let client = Arc::new(client);
let contract = DKGContract::new(opts.contract_address, client);
for addr in opts.address {
let tx = contract.allowlist(addr).block(BlockNumber::Pen... | {
println!("Success. Your share and threshold pubkey are ready.");
if let Some(path) = output_path {
let file = File::create(path)?;
write_output(&file, &output)?;
} else {
write_output(std::io::stdout(), &output)?;
}
... | conditional_block | |
actions.rs | Some(path) = opts.path {
let f = File::create(path)?;
serde_json::to_writer(&f, &output)?;
} else {
serde_json::to_writer(std::io::stdout(), &output)?;
}
Ok(())
}
pub async fn deploy(opts: DeployOpts) -> Result<()> {
// hard-code the contract's bytecode when deploying
let ... |
let contract = DKGContract::new(opts.contract_address, client);
for addr in opts.address {
let tx = contract.allowlist(addr).block(BlockNumber::Pending);
let tx = tx.send().await?.await?;
println!("Sent `allow` tx for {:?} (hash: {:?})", addr, tx);
}
Ok(())
}
pub async fn sta... | let client = Arc::new(client); | random_line_split |
actions.rs | Some(path) = opts.path {
let f = File::create(path)?;
serde_json::to_writer(&f, &output)?;
} else {
serde_json::to_writer(std::io::stdout(), &output)?;
}
Ok(())
}
pub async fn deploy(opts: DeployOpts) -> Result<()> {
// hard-code the contract's bytecode when deploying
let ... | <P, C, R, M: Middleware + 'static>(
mut dkg: DKGContract<M>,
phase0: P,
rng: &mut R,
output_path: Option<String>,
) -> Result<()>
where
C: Curve,
// We need to bind the Curve's Point and Scalars to the Scheme
// S: Scheme<Public = <C as Curve>::Point, Private = <C as Curve>::Scalar>,
P: ... | run_dkg | identifier_name |
transaction_verify_centre.rs | .
//! 3. ReplayStage
//! - Transactions in blobs are processed and applied to the bank.
//! - TODO We need to verify the signatures in the blobs.
//! 4. StorageStage
//! - Generating the keys used to encrypt the ledger and sample it for storage mining.
// use crate::bank_forks::BankForks;
use crate::treasury_forks::Ba... | .skip_while(|line| line.starts_with("#!"))
.skip_while(|line| line.is_empty())
.take(2)
.map(|s| s.trim_start_matches("# "));
!LICENSE_HEADER.lines().eq(maybe_license)
}
};
if missing_header {
return Err("missing a lice... | random_line_split | |
transaction_verify_centre.rs | //! 3. ReplayStage
//! - Transactions in blobs are processed and applied to the bank.
//! - TODO We need to verify the signatures in the blobs.
//! 4. StorageStage
//! - Generating the keys used to encrypt the ledger and sample it for storage mining.
// use crate::bank_forks::BankForks;
use crate::treasury_forks::Bank... | {
pub fetch: Vec<UdpSocket>,
pub repair: UdpSocket,
pub retransmit: UdpSocket,
}
impl Tvu {
/// This service receives messages from a leader in the network and processes the transactions
/// on the bank state.
/// # Arguments
/// * `node_group_info` - The node_group_info state.
/// * `... | Sockets | identifier_name |
transaction_verify_centre.rs | //! 3. ReplayStage
//! - Transactions in blobs are processed and applied to the bank.
//! - TODO We need to verify the signatures in the blobs.
//! 4. StorageStage
//! - Generating the keys used to encrypt the ledger and sample it for storage mining.
// use crate::bank_forks::BankForks;
use crate::treasury_forks::Bank... |
//TODO
//the packets coming out of blob_receiver need to be sent to the GPU and verified
//then sent to the window, which does the erasure coding reconstruction
let retransmit_stage = RetransmitStage::new(
bank_forks.clone(),
leader_schedule_cache,
bl... | {
let keypair: Arc<Keypair> = node_group_info
.read()
.expect("Unable to read from node_group_info during Tvu creation")
.keypair
.clone();
let Sockets {
repair: repair_socket,
fetch: fetch_sockets,
retransmit: retransm... | identifier_body |
transaction_verify_centre.rs | //! 3. ReplayStage
//! - Transactions in blobs are processed and applied to the bank.
//! - TODO We need to verify the signatures in the blobs.
//! 4. StorageStage
//! - Generating the keys used to encrypt the ledger and sample it for storage mining.
// use crate::bank_forks::BankForks;
use crate::treasury_forks::Bank... |
};
if missing_header {
return Err("missing a license header".into());
}
Ok(())
}
#[cfg(test)]
pub mod tests {
use super::*;
use crate::treasury_stage::create_test_recorder;
use crate::block_buffer_pool::get_tmp_ledger_path;
use crate::node_group_info::{NodeGroupInfo, Node};
... | {
let maybe_license = contents
.lines()
.skip_while(|line| line.starts_with("#!"))
.skip_while(|line| line.is_empty())
.take(2)
.map(|s| s.trim_start_matches("# "));
!LICENSE_HEADER.lines().eq(maybe_license)
... | conditional_block |
process.go | {
var result []qostxtype.TransItem
log.Printf("buyad warpperReceivers article:%+v", article)
investors = calculateRevenue(cdc, article, amount, investors, communityAddr)
for _, v := range investors {
if !v.Revenue.IsZero() {
result = append(
result,
warpperTransItem(
v.Address,
[]qbasetyp... | if strings.ToU | identifier_name | |
process.go | func warpperInvestorTx(cdc *wire.Codec, articleHash string, amount int64) []qostxtype.TransItem {
investors, err := jianqian.ListInvestors(config.GetCLIContext().QSCCliContext, cdc, articleHash)
var result []qostxtype.TransItem
log.Printf("buyAd warpperInvestorTx investors:%+v", investors)
if err == nil {
totalI... | random_line_split | ||
process.go | ])
break
}
if counter >= waittime {
log.Println("time out")
reason = "time out"
if resultstr == "" {
code = common.ResultCodeQstarsTimeout
} else {
code = common.ResultCodeQOSTimeout
}
break
}
time.Sleep(500 * time.Millisecond)
counter++
}
if code != common.ResultCodeSuccess... | Receivers(result)
}
// calculateInvestorRevenue 计算投资者收入
func calculateInvestorRevenue(cdc *wire.Codec, investors jianqian.Investors, amount qbasetypes.BigInt) jianqian.Investors {
log.Printf("buyAd calculateInvestorRevenue investors:%+v", investors)
totalInvest := investors.TotalInvest()
log.Printf("buyAd calculat... | nd(
result,
warpperTransItem(
v.Address,
[]qbasetypes.BaseCoin{{Name: coinsName, Amount: v.Revenue}}))
}
}
return merge | conditional_block |
process.go | waittime, err := strconv.Atoi(config.GetCLIContext().Config.WaitingForQosResult)
if err != nil {
panic("WaitingForQosResult should be able to convert to integer." + err.Error())
}
counter := 0
for {
resultstr, err := fetchResult(cdc, height, commitresult.Hash.String())
log.Printf("fetchResult result:%s, err... | ew(txs.TxStd)
err := cdc.UnmarshalJSON([]byte(txb), ts)
log.Printf("buyad.BuyAdBackground ts:%+v, err:%+v", ts, err)
if err != nil {
return common.InternalError(err.Error()).Marshal()
}
cliCtx := *config.GetCLIContext().QSCCliContext
_, commitresult, err := utils.SendTx(cliCtx, cdc, ts)
log.Printf("buyad.BuyA... | identifier_body | |
tensor.rs |
self.by_input_ix_mut(ix).unwrap()
}
pub fn add(&mut self, other: TensorValues) {
let mut tensor = other.input_index.and_then(|ix| self.by_input_ix_mut(ix));
if tensor.is_none() {
tensor = other.name.as_deref().and_then(|ix| self.by_name_mut(ix))
}
if let S... | {
self.add(TensorValues { input_index: Some(ix), ..TensorValues::default() });
} | conditional_block | |
tensor.rs | (&mut self, name: &str) -> Option<&mut TensorValues> {
self.0.iter_mut().find(|t| t.name.as_deref() == Some(name))
}
pub fn by_name_mut_with_default(&mut self, name: &str) -> &mut TensorValues {
if self.by_name_mut(name).is_none() {
self.add(TensorValues { name: Some(name.to_string()... | by_name_mut | identifier_name | |
tensor.rs | ::open(filename).with_context(|| format!("Can't open {filename:?}"))?;
*/
let proto = ::tract_onnx::tensor::proto_from_reader(reader)?;
Ok((
Some(proto.name.to_string()).filter(|s| !s.is_empty()),
Tensor::try_from(proto)?.into(),
))
... | }
Ok((0..tmp[0].len()).map(|turn| tmp.iter().map(|t| t[turn].clone()).collect()).collect())
}
fn make_inputs(values: &[impl std::borrow::Borrow<TypedFact>]) -> TractResult<TVec<TValue>> { | random_line_split | |
tensor.rs | (".npz:") {
let mut tokens = filename.split(':');
let (_filename, inner) = (tokens.next().unwrap(), tokens.next().unwrap());
let mut npz = ndarray_npy::NpzReader::new(reader)?;
Ok((None, for_npz(&mut npz, inner)?.into()))
} else {
Ok((None, tensor_for_text_data(symbol_table, ... | {
make_inputs(
&model
.input_outlets()
.iter()
.map(|&t| model.outlet_typedfact(t))
.collect::<TractResult<Vec<TypedFact>>>()?,
)
} | identifier_body | |
setup.py | = bind_and_hide_internal.strip()
# NETCDF_LIBDIR must be given, either for the static library or the shared-object library
netcdf_libdir = os.getenv("NETCDF_LIBDIR")
if netcdf_libdir:
netcdf_libdir = netcdf_libdir.strip()
if not netcdf_libdir:
raise ValueError("Environment variable NETCDF_LIBDIR is not define... |
# HDF5_LIBDIR is only given if the HDF5 and NetCDF libraries are to be statically linked
hdf5_libdir = os.getenv("HDF5_LIBDIR")
if hdf5_libdir:
hdf5_libdir = hdf5_libdir.strip()
# SZ_LIBDIR is the location of the SZ library to be linked in
sz_libdir = os.getenv("SZ_LIBDIR")
if sz_libdir:
sz_libdir = sz_libdir... | random_line_split | |
setup.py | = bind_and_hide_internal.strip()
# NETCDF_LIBDIR must be given, either for the static library or the shared-object library
netcdf_libdir = os.getenv("NETCDF_LIBDIR")
if netcdf_libdir:
netcdf_libdir = netcdf_libdir.strip()
if not netcdf_libdir:
raise ValueError("Environment variable NETCDF_LIBDIR is not define... |
# Linking in the rest of the system libraries were moved to addn_link_flags
# in order to make sure the appropriate netcdff, netcdf, hdf5_hl, hdf5, and
# cairo libraries are used.
addn_link_args = [ ]
# Link to the appropriate netcdf libraries.
# The hdf5 libraries are only used to resolve netcdf library function
# ... | lib_list.extend(fer_lib_list)
lib_list.extend(fer_lib_list)
lib_list.extend(fer_lib_list)
lib_list.extend(fer_lib_list) | conditional_block |
viewer.ts | * await view.set_depth(0);
* ```
*/
async getView(): Promise<perspective.View> {
await this.load_wasm();
const view = await this.instance.js_get_view();
return view;
}
/**
* Restore this element to a state as generated by a reciprocal call to
* `save`. In `json... | resetThemes | identifier_name | |
viewer.ts | Promise<void> {
await this.load_wasm();
await this.instance.js_load(Promise.resolve(table));
}
/**
* Redraw this `<perspective-viewer>` and plugin when its dimensions or
* visibility has been updated. By default, `<perspective-viewer>` will
* auto-size when its own dimensions c... |
/**
* Returns the `perspective.Table()` which was supplied to `load()`
*
* @category Data
* @param wait_for_table Whether to await `load()` if it has not yet been
* invoked, or fail immediately.
* @returns A `Promise` which resolves to a `perspective.Table`
* @example <caption>S... | {
await this.load_wasm();
await this.instance.js_set_auto_size(autosize);
} | identifier_body |
viewer.ts |
}
/**
* Part of the Custom Elements API. This method is called by the browser,
* and should not be called directly by applications.
*
* @ignore
*/
async connectedCallback(): Promise<void> {
await this.load_wasm();
this.instance.connected_callback();
}
/**... | {
this.instance = new PerspectiveViewerElement(this);
} | conditional_block | |
viewer.ts | }
/**
* Register a new plugin via its custom element name. This method is called
* automatically as a side effect of importing a plugin module, so this
* method should only typically be called by plugin authors.
*
* @category Plugin
* @param name The `name` of the custom element ... | this.instance.connected_callback(); | random_line_split | |
Toys.py | _discord_id(target_discord_id)
cookie_count = DataAccess.modify_cookie_count(db_user_id, cookie_type['modifier'])
# check if goal was reached by the claimer
cookie_goal = ConfiguredCog.config['content']['cookie_hunt_goal']
if cookie_count >= cookie_goal:
# announce winner
... | # that we randomly picked, we move on to the next one safely.
random_channel_pick_list = sample(ConfiguredCog.config['content']['cookie_hunt_allowed_channels'],
len(ConfiguredCog.config['content']['cookie_hunt_allowed_channels']))
for selected_channel_na... | random_line_split | |
Toys.py | _discord_id(target_discord_id)
cookie_count = DataAccess.modify_cookie_count(db_user_id, cookie_type['modifier'])
# check if goal was reached by the claimer
cookie_goal = ConfiguredCog.config['content']['cookie_hunt_goal']
if cookie_count >= cookie_goal:
# announce winner
... |
discord_user = self.bot.get_user(int(Discord_Id))
if discord_user:
user_name = discord_user.name
else:
user_name = f'Unknown ({Discord_Id})'
user_name = f'{user_name}:'
... | embed = Embed(title='Top Cookie Collectors',
color=ConfiguredCog.convert_color('#8a4b38'))
collectors_displayed = True | conditional_block |
Toys.py | : commands.Context, options: str = None):
"""The origin point for the `sugar` command. Shows relevant cookie count scores based on the options provided.
:param ctx: The command context.
:param options: The (optional) parameters for the sugar command, as enumerated by the
... | """Overridden from commands.Cog; starts the automated task."""
self._get_sketch_prompt.start() | identifier_body | |
Toys.py | _discord_id(target_discord_id)
cookie_count = DataAccess.modify_cookie_count(db_user_id, cookie_type['modifier'])
# check if goal was reached by the claimer
cookie_goal = ConfiguredCog.config['content']['cookie_hunt_goal']
if cookie_count >= cookie_goal:
# announce winner
... | (self) -> list:
"""Gets an arbitrarily ordered list of weights mapped to the cookie data dictionary.
:return: A list of weights.
"""
cookie_weights = []
for cookie_type in self.cookie_data:
cookie_weights.append(cookie_type['weight'])
return cookie_weight... | _get_cookie_weights | identifier_name |
rtic-i2s-audio-in-out.rs | SCK | pc6 |
//! | BCK | pb13 + pc10 |
//! | DIN | pc12 |
//! | LCK | pb12 + pa4 |
//! | GND | Gnd |
//! | VIN | +3V3 |
//! | FLT | Gnd or +3V3 |
//! | DEMP | Gnd |
//! | XSMT | +3V3 |
//! | A3V3 | |
//! |... |
// processing audio
#[task(binds = SPI5, local = [count: u32 = 0,process_c,process_p])]
fn process(cx: process::Context) {
let count = cx.local.count;
let process_c = cx.local.process_c;
let process_p = cx.local.process_p;
while let Some(mut smpl) = process_c.dequeue() {
... | {
writeln!(cx.local.logs_chan, "{}", message).unwrap();
} | identifier_body |
rtic-i2s-audio-in-out.rs | | SCK | pc6 |
//! | BCK | pb13 + pc10 |
//! | DIN | pc12 |
//! | LCK | pb12 + pa4 |
//! | GND | Gnd |
//! | VIN | +3V3 |
//! | FLT | Gnd or +3V3 |
//! | DEMP | Gnd |
//! | XSMT | +3V3 |
//! | A3V3 | |
//!... | (cx: i2s2::Context) {
let frame_state = cx.local.frame_state;
let frame = cx.local.frame;
let adc_p = cx.local.adc_p;
let i2s2_driver = cx.shared.i2s2_driver;
let status = i2s2_driver.status();
// It's better to read first to avoid triggering ovr flag
if status.rx... | i2s2 | identifier_name |
rtic-i2s-audio-in-out.rs | | SCK | pc6 |
//! | BCK | pb13 + pc10 |
//! | DIN | pc12 |
//! | LCK | pb12 + pa4 |
//! | GND | Gnd |
//! | VIN | +3V3 |
//! | FLT | Gnd or +3V3 |
//! | DEMP | Gnd |
//! | XSMT | +3V3 |
//! | A3V3 | |
//!... | let gpiob = device.GPIOB.split();
let gpioc = device.GPIOC.split();
let rcc = device.RCC.constrain();
let clocks = rcc
.cfgr
.use_hse(8u32.MHz())
.sysclk(96.MHz())
.hclk(96.MHz())
.pclk1(50.MHz())
.pclk2(100.MHz())
... | let gpioa = device.GPIOA.split(); | random_line_split |
Renderer.ts | if(bases.length === 0){
// element[MIN]
// elms.length > 0なのでundefinedにはならない…はず。
// お前がbaseになるんだよ
const base = <SDT.SurfaceElement&{canvas:Canvas}>others.shift();
if(base != null){
bases.push(base);
console.warn("SurfaceRenderer#composeElements: base surface not found. fai... | ataB[iB + 3] === 0) dataA[iA + 3] = dataB[iB + 3];
} | conditional_block | |
Renderer.ts | Cnv2, type: "overlay", x: 50, y: 50}
// ]
composeElements(elms: {type: string, x: number, y: number, canvas: Canvas}[]): Canvas {
// baseを決定
const bases = elms.filter(({type})=> type === "base");
const others = elms.filter(({type})=> type !== "base");
// element[MAX].base > element0 > element[MIN]
... | hape
this.srfCnv.basePosX += (-left);
}
if(right<0){
this.cnv.width += (-right); // reshape
}
if(top<0){
offsetY = (-top);
this.cnv.height += (-top); // reshape
this.srfCnv.basePosY += (-top);
}
if(bottom<0){
this.cnv.height += (-bottom... | prepareOverlay: reshape occured");
// 現状をtmpcnvへコピー
Util.fastcopy(this.cnv, this.tmpctx);
if(left<0){
offsetX = (-left);
this.cnv.width += (-left); // res | identifier_body |
Renderer.ts | Cnv2, type: "overlay", x: 50, y: 50}
// ]
composeElements(elms: {type: string, x: number, y: number, canvas: Canvas | Canvas {
// baseを決定
const bases = elms.filter(({type})=> type === "base");
const others = elms.filter(({type})=> type !== "base");
// element[MAX].base > element0 > element[MIN]
if(bases.length === 0){
// element[MIN]
// elms.length > 0なのでundefinedにはならない…はず。
// お前がbaseになるんだよ
... | }[]): | identifier_name |
Renderer.ts | Cnv2, type: "overlay", x: 50, y: 50}
// ]
composeElements(elms: {type: string, x: number, y: number, canvas: Canvas}[]): Canvas {
// baseを決定
const bases = elms.filter(({type})=> type === "base");
const others = elms.filter(({type})=> type !== "base");
// element[MAX].base > element0 > element[MIN]
... | }
}
let base = bases.slice(-1)[0]; /* last */
this.base(base.canvas);
others.forEach(({canvas, type, x, y})=>{
this.composeElement(canvas, type, x, y);
});
return this.srfCnv;
}
composeElement(canvas: Canvas, type: string, x=0, y=0): void {
switch (type) {
case "overla... | console.warn("SurfaceRenderer#composeElements: base surface not found. failback.", bases, others);
}else{
console.error("SurfaceRenderer#composeElements: cannot decide base surface.", base, others);
return this.srfCnv; | random_line_split |
crypto_box.rs | 4.
pub const BLOCK_PADDING_DELIMITER: u8 = 0x80;
/// Newtype for the nonce for safety.
#[derive(Debug, PartialEq, Clone)]
pub struct CryptoBoxNonce([u8; NONCE_BYTES]);
impl CryptoBoxNonce {
async fn new_random() -> Self {
rayon_exec(move || {
let mut rng = rand::thread_rng();
let m... |
Err(_) => Ok(None),
}
})
.await
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test(flavor = "multi_thread")]
async fn it_can_encrypt_and_decrypt() {
for input in [
// Empty vec.
| {
match block_padding::Iso7816::unpad(&decrypted_data) {
// @todo do we want associated data to enforce the originating DHT space?
Ok(unpadded) => Ok(Some(CryptoBoxData {
data: Arc::new(unpadded.to_vec()),
})),
... | conditional_block |
crypto_box.rs | -4.
pub const BLOCK_PADDING_DELIMITER: u8 = 0x80;
/// Newtype for the nonce for safety.
#[derive(Debug, PartialEq, Clone)]
pub struct CryptoBoxNonce([u8; NONCE_BYTES]);
impl CryptoBoxNonce {
async fn new_random() -> Self {
rayon_exec(move || {
let mut rng = rand::thread_rng();
let ... | ];
to_encrypt.extend(padding_delimiter);
to_encrypt.extend(padding);
let encrypted_data = Arc::new(sender_box.encrypt(
AsRef::<[u8; NONCE_BYTES]>::as_ref(&nonce).into(),
to_encrypt.as_slice(),
)?);
// @todo do we want associated data to enforce t... | BLOCK_PADDING_SIZE
- (data.data.len() + 1) % BLOCK_PADDING_SIZE | random_line_split |
crypto_box.rs | -4.
pub const BLOCK_PADDING_DELIMITER: u8 = 0x80;
/// Newtype for the nonce for safety.
#[derive(Debug, PartialEq, Clone)]
pub struct CryptoBoxNonce([u8; NONCE_BYTES]);
impl CryptoBoxNonce {
async fn new_random() -> Self {
rayon_exec(move || {
let mut rng = rand::thread_rng();
let ... | (slice: &[u8]) -> Result<Self, Self::Error> {
if slice.len() == NONCE_BYTES {
let mut inner = [0; NONCE_BYTES];
inner.copy_from_slice(slice);
Ok(Self(inner))
} else {
Err(crate::error::LairError::CryptoBoxNonceLength)
}
}
}
impl CryptoBoxNonce... | try_from | identifier_name |
crypto_box.rs | 4.
pub const BLOCK_PADDING_DELIMITER: u8 = 0x80;
/// Newtype for the nonce for safety.
#[derive(Debug, PartialEq, Clone)]
pub struct CryptoBoxNonce([u8; NONCE_BYTES]);
impl CryptoBoxNonce {
async fn new_random() -> Self {
rayon_exec(move || {
let mut rng = rand::thread_rng();
let m... |
}
impl CryptoBoxData {
/// Length of newtype is length of inner.
pub fn len(&self) -> usize {
AsRef::<[u8]>::as_ref(self).len()
}
/// For clippy.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl From<Vec<u8>> for CryptoBoxData {
fn from(v: Vec<u8>) -> Self {
... | {
self.data.as_ref()
} | identifier_body |
scoped_signal_handler.rs |
/// The implementation of handle_signal needs to be async signal-safe.
///
/// NOTE: panics are caught when possible because a panic inside ffi is undefined behavior.
pub unsafe trait SignalHandler {
/// A function that is called to handle the passed signal.
fn handle_signal(signal: Signal);
}
/// Wrap the ha... | let mut buffer = [0u8; 64];
let mut cursor = Cursor::new(buffer.as_mut());
if writeln!(cursor, "signal handler got error for: {:?}", signal_debug).is_ok() {
let len = cursor.position() as usize;
// Safe in the sense that buffer is owned and the length is checked. This may... | {
// Make an effort to surface an error.
if catch_unwind(|| H::handle_signal(Signal::try_from(signum).unwrap())).is_err() {
// Note the following cannot be used:
// eprintln! - uses std::io which has locks that may be held.
// format! - uses the allocator which enforces mutual exclusion.... | identifier_body |
scoped_signal_handler.rs | .as_ptr() as *const c_void, bytes.len()) };
}
}
}
/// Represents a signal handler that is registered with a set of signals that unregistered when the
/// struct goes out of scope. Prefer a signalfd based solution before using this.
pub struct ScopedSignalHandler {
signals: Vec<Signal>,
}
impl ScopedSi... | {
return Ok(matches!(
stripped.trim_start().chars().next(),
Some('S') | Some('D')
));
} | conditional_block | |
scoped_signal_handler.rs |
/// The implementation of handle_signal needs to be async signal-safe.
///
/// NOTE: panics are caught when possible because a panic inside ffi is undefined behavior.
pub unsafe trait SignalHandler {
/// A function that is called to handle the passed signal.
fn handle_signal(signal: Signal);
}
/// Wrap the ha... | // format! - uses the allocator which enforces mutual exclusion.
// Get the debug representation of signum.
let signal: Signal;
let signal_debug: &dyn fmt::Debug = match Signal::try_from(signum) {
Ok(s) => {
signal = s;
&signal as &dyn fmt::De... | // eprintln! - uses std::io which has locks that may be held. | random_line_split |
scoped_signal_handler.rs |
/// The implementation of handle_signal needs to be async signal-safe.
///
/// NOTE: panics are caught when possible because a panic inside ffi is undefined behavior.
pub unsafe trait SignalHandler {
/// A function that is called to handle the passed signal.
fn handle_signal(signal: Signal);
}
/// Wrap the ha... | ;
/// # Safety
/// Safe because handle_signal is async-signal safe.
unsafe impl SignalHandler for EmptySignalHandler {
fn handle_signal(_: Signal) {}
}
/// Blocks until SIGINT is received, which often happens because Ctrl-C was pressed in an
/// interactive terminal.
///
/// Note: if you are using a multi-threaded... | EmptySignalHandler | identifier_name |
twitter.go | .Errorf("Twitter API is not available")
}
func (a *TwitterAPI) Enabled() bool {
return a.api != nil
}
// CheckUser cheks if user is matched for the given allowSelf and users
// arguments.
func (a *TwitterAPI) CheckUser(user string, allowSelf bool, users []string) (bool, error) {
if allowSelf {
self, err := a.GetS... | if err != nil {
return utils.WithStack(err)
}
id = col.Response.TimelineId
}
_, err = a.api.AddEntryToCollection(id, tweet.Id, nil)
if err != nil {
return utils.WithStack(err)
}
return nil
}
func (a *TwitterAPI) GetSearch(query string, url url.Values) (anaconda.SearchResponse, error) {
return a.api.G... | {
self, err := a.GetSelf()
if err != nil {
return utils.WithStack(err)
}
list, err := a.api.GetCollectionListByUserId(self.Id, nil)
if err != nil {
return utils.WithStack(err)
}
exists := false
var id string
for i, t := range list.Objects.Timelines {
if collection == t.Name {
exists = true
id = i
... | identifier_body |
twitter.go | (auth oauth.OAuthCreds, config Config, cache data.Cache) *TwitterAPI {
at, ats := auth.GetCreds()
var api models.TwitterAPI
if len(at) > 0 && len(ats) > 0 {
api = anaconda.NewTwitterApi(at, ats)
}
return NewTwitterAPI(api, config, cache)
}
func NewTwitterAPI(api models.TwitterAPI, config Config, cache data.Cach... | NewTwitterAPIWithAuth | identifier_name | |
twitter.go | .Errorf("Twitter API is not available")
}
func (a *TwitterAPI) Enabled() bool {
return a.api != nil
}
// CheckUser cheks if user is matched for the given allowSelf and users
// arguments.
func (a *TwitterAPI) CheckUser(user string, allowSelf bool, users []string) (bool, error) {
if allowSelf {
self, err := a.GetS... | else {
users, err := a.api.GetUsersLookup(usernames, nil)
if err != nil {
return nil, utils.WithStack(err)
}
userids := []string{}
for _, u := range users {
userids = append(userids, u.IdStr)
}
v.Set("follow", strings.Join(userids, ","))
stream := a.api.PublicStreamFilter(v)
return &TwitterUser... | {
return nil, errors.New("No user specified")
} | conditional_block |
twitter.go | fmt.Errorf("Twitter API is not available")
}
func (a *TwitterAPI) Enabled() bool {
return a.api != nil
}
// CheckUser cheks if user is matched for the given allowSelf and users
// arguments.
func (a *TwitterAPI) CheckUser(user string, allowSelf bool, users []string) (bool, error) {
if allowSelf {
self, err := a.... | if err != nil {
return nil, nil, utils.WithStack(err)
}
}
return processedTweets, processedActions, nil
}
func (a *TwitterAPI) processTweet(
t anaconda.Tweet,
action data.Action,
slack *SlackAPI,
) error {
if action.Twitter.Retweet && !t.Retweeted {
var id int64
if t.RetweetedStatus == nil {
id = t... | random_line_split | |
wavelet_tree_pointer.rs | ///they are managed by the tree and the user has no direct access
#[derive(Serialize, Deserialize)]
struct BinNode {
///The bitmap stored in the node
value: RankSelect,
///The left Child of the node
left: Option<Box<BinNode>>,
///The right child of the node
right: Option<Box<BinNode>>,
}
///The ... | + Clone + Ord + Debug>(alphabet: &[E], sequence: Vec<E>) -> BinNode {
let count = sequence.len();
if alphabet.len() <= 1 {
let value = BitVec::new_fill(true, count as u64);
BinNode {
value: RankSelect::new(value, 1),
left: None,
rig... | de<E: Hash | identifier_name |
wavelet_tree_pointer.rs | == result {
return &self.alphabet[i];
}
}
panic!("Index in Bounds but not found");
}
///Returns the the position of the index'th occurence of the character
pub fn select(&self, character: T, index: usize) -> Result<u64, Error> {
// Abfangen von fehlerhaf... | f.value.bits().len()
}
}
///Impleme | identifier_body | |
wavelet_tree_pointer.rs | lerhafter Eingabe, Index darf hier nicht 0 sein
ensure!(index > 0, SelectSmaller0);
//------------------------
let character_index1 = &self.alphabet.binary_search(&character); // speichere an welchem index steht das gesuchte zeichen im alphabet steht
let character_index = match characte... | type Item = T;
type IntoIter = Iterhelper<'de, T>;
fn into_iter(self) -> Self::IntoIter { | random_line_split | |
wavelet_tree_pointer.rs | unwrap() < &(index as u64) {
return Err(Error::NotEnoughElements);
}
let result = match &self.root {
Some(x) => x.select(index as u64, character_index, 0, self.alphabet.len() - 1),
None => return Err(Error::TempError), //Err("Fehler"),
};
match result... | None
}
}
}
| conditional_block | |
classifier.d15b2d9b.js | "zcr_mean", "zcr_std", "zcr_var", "harm_mean", "harm_std", "harm_var", "perc_mean", "perc_std", "perc_var", "frame_mean", "frame_std", "frame_var"];
this.featuresToIgnore = [];
}
ShapeData.prototype.makeDatasetForTensors = function (data) {
var dataInputs = [];
var dataOutputs = [];
... | var singleNormalizedData = [];
for (var i = 0; i < arrayLikeData[song].length; i++) {
var norm = this.normalize(arrayLikeData[song][i], featuresRange[i].min, featuresRange[i].max);
singleNormalizedData.push(norm);
}
normalizedData.push(sing... | for (var song in arrayLikeData) { | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.