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
utils.py
import io import os import torch import logging import json import pickle import argparse from pprint import pprint # 3rd party libraries from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from torch.utils import data from sklearn import decomposition from keras.preprocessing.sequ...
labels[i] = dataset.iloc[i][label_col] # set parameters for DataLoader -- num_workers = cores params = {'batch_size': 32, 'shuffle': True, 'num_workers': 0 } tokenizer = AutoTokenizer.from_pretrained(vocab) dataset[text_col] = dataset[text_col].app...
'valid': ids[int(total_len * 0.7): ] } for i in dataset.iloc[:, unique_id_col]:
random_line_split
utils.py
import io import os import torch import logging import json import pickle import argparse from pprint import pprint # 3rd party libraries from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from torch.utils import data from sklearn import decomposition from keras.preprocessing.sequ...
else: sequence = np.pad(sequence, (0, max_l - (len(sequence))), 'constant', constant_values=(0)) return sequence def __glove_embed__(sequence, model): """ Embed words in a sequence using GLoVE model """ embedded = [] for word in sequence: embedded.append(model[word]) return e...
sequence = sequence[:max_l]
conditional_block
utils.py
import io import os import torch import logging import json import pickle import argparse from pprint import pprint # 3rd party libraries from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from torch.utils import data from sklearn import decomposition from keras.preprocessing.sequ...
(metric_type: str, preds: list, labels: list): """ Provides various metrics between predictions and labels. Arguments: metric_type {str} -- type of metric to use ['flat_accuracy', 'f1', 'roc_auc', 'precision', 'recall'] preds {list} -- predictions. labels {list} -- labels. Returns: ...
metrics
identifier_name
utils.py
import io import os import torch import logging import json import pickle import argparse from pprint import pprint # 3rd party libraries from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler from torch.utils import data from sklearn import decomposition from keras.preprocessing.sequ...
def __glove_embed__(sequence, model): """ Embed words in a sequence using GLoVE model """ embedded = [] for word in sequence: embedded.append(model[word]) return embedded def load_embeddings(config, name, vocab, training_generator, validation_generator): """Load embeddings either from c...
""" Padding function for 1D sequences """ if max_l - len(sequence) < 0: sequence = sequence[:max_l] else: sequence = np.pad(sequence, (0, max_l - (len(sequence))), 'constant', constant_values=(0)) return sequence
identifier_body
ioapic.rs
use core::{fmt, ptr}; use alloc::vec::Vec; use spin::Mutex; #[cfg(feature = "acpi")] use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride}; use crate::arch::interrupt::irq; use crate::memory::Frame; use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAdd...
} impl fmt::Debug for IoApic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { struct RedirTable<'a>(&'a Mutex<IoApicRegs>); impl<'a> fmt::Debug for RedirTable<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut guard = self.0.lock(); ...
random_line_split
ioapic.rs
use core::{fmt, ptr}; use alloc::vec::Vec; use spin::Mutex; #[cfg(feature = "acpi")] use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride}; use crate::arch::interrupt::irq; use crate::memory::Frame; use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAdd...
fn resolve(irq: u8) -> u32 { get_override(irq).map_or(u32::from(irq), |over| over.gsi) } fn find_ioapic(gsi: u32) -> Option<&'static IoApic> { ioapics().iter().find(|apic| gsi >= apic.gsi_start && gsi < apic.gsi_start + u32::from(apic.count)) } pub unsafe fn mask(irq: u8) { let gsi = resolve(irq); let...
{ src_overrides().iter().find(|over| over.bus_irq == irq) }
identifier_body
ioapic.rs
use core::{fmt, ptr}; use alloc::vec::Vec; use spin::Mutex; #[cfg(feature = "acpi")] use crate::acpi::madt::{self, Madt, MadtEntry, MadtIoApic, MadtIntSrcOverride}; use crate::arch::interrupt::irq; use crate::memory::Frame; use crate::paging::{KernelMapper, Page, PageFlags, PhysicalAddress, RmmA, RmmArch, VirtualAdd...
<'a>(&'a Mutex<IoApicRegs>); impl<'a> fmt::Debug for RedirTable<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut guard = self.0.lock(); let count = guard.max_redirection_table_entries(); f.debug_list().entries((0..count).map(|i| g...
RedirTable
identifier_name
handler.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
func (h *handler) CreateServiceBroker(in *servicecatalog.Broker) (*servicecatalog.Broker, error) { authUsername, authPassword, err := GetAuthCredentialsFromBroker(h.k8sClient, in) if err != nil { return nil, err } client := h.newClientFunc(in.Name, in.Spec.URL, authUsername, authPassword) sbcat, err := client...
{ glog.Infof("Creating Service Binding: %v", in) inst, err := instanceForBinding(h.apiClient, in) if err != nil { return nil, err } sc, err := serviceClassForInstance(h.apiClient, inst) if err != nil { return nil, err } broker, err := brokerForServiceClass(h.apiClient, sc) if err != nil { return nil, er...
identifier_body
handler.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
parameters := make(map[string]interface{}) if in.Spec.Parameters != nil && len(in.Spec.Parameters.Raw) > 0 { err = yaml.Unmarshal([]byte(in.Spec.Parameters.Raw), &parameters) if err != nil { glog.Errorf("Failed to unmarshal Binding parameters\n%s\n %v", in.Spec.Parameters, err) return nil, err } } cr...
{ in.Spec.OSBGUID = uuid.NewV4().String() }
conditional_block
handler.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
catalogURLFormatString = "%s/v2/catalog" serviceInstanceFormatString = "%s/v2/service_instances/%s" bindingFormatString = "%s/v2/service_instances/%s/service_bindings/%s" defaultNamespace = "default" ) // Handler defines an interface used as a facade for data access operations. // The contr...
random_line_split
handler.go
/* Copyright 2016 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, ...
(in *servicecatalog.Broker) (*servicecatalog.Broker, error) { authUsername, authPassword, err := GetAuthCredentialsFromBroker(h.k8sClient, in) if err != nil { return nil, err } client := h.newClientFunc(in.Name, in.Spec.URL, authUsername, authPassword) sbcat, err := client.GetCatalog() if err != nil { return...
CreateServiceBroker
identifier_name
Quirk.ts
import { renderHTML } from "../Templates/QuirkField"; import { setCookieBool } from "../CookieManager"; import { Category } from "../Categories/Category"; import { OptionalCheckbox } from "./OptionalCheckbox"; import { selectAllAndCopy } from "../Copy2Clipboard"; export abstract class Quirk { static inputField: H...
(bruh: string): void { this.shortName = bruh; this.id = bruh.toLocaleLowerCase(); } public getShortName(): string { return this.shortName; } public getColorClass(): string { return this.colorClass; } public getTextAreaElement(): HTMLTextAreaElement { re...
setShortName
identifier_name
Quirk.ts
import { renderHTML } from "../Templates/QuirkField"; import { setCookieBool } from "../CookieManager"; import { Category } from "../Categories/Category"; import { OptionalCheckbox } from "./OptionalCheckbox"; import { selectAllAndCopy } from "../Copy2Clipboard"; export abstract class Quirk { static inputField: H...
// Dynamically increase the height of a textarea. static autoSize(element: HTMLTextAreaElement): void { let minHeight: number = parseInt(window.getComputedStyle(element).getPropertyValue("min-height")); element.style.height = "auto"; // Lets the element shrink size. element.style.heig...
{ this.textArea.value = this.input; // Auto resize. Quirk.autoSize(this.textArea); }
identifier_body
Quirk.ts
import { renderHTML } from "../Templates/QuirkField"; import { setCookieBool } from "../CookieManager"; import { Category } from "../Categories/Category"; import { OptionalCheckbox } from "./OptionalCheckbox"; import { selectAllAndCopy } from "../Copy2Clipboard"; export abstract class Quirk { static inputField: HT...
this.replaceMatchCase("now", "meow"); this.replaceMatchCase("(per|pre)", "pur"); } applyFishPuns(): void { this.replaceMatchCase("kill", "krill"); this.replaceMatchCase("well", "whale"); this.replaceMatchCase("fine", "fin"); this.replaceMatchCase("see", "sea"); ...
this.replaceMatchCase("cause", "claws");
random_line_split
Quirk.ts
import { renderHTML } from "../Templates/QuirkField"; import { setCookieBool } from "../CookieManager"; import { Category } from "../Categories/Category"; import { OptionalCheckbox } from "./OptionalCheckbox"; import { selectAllAndCopy } from "../Copy2Clipboard"; export abstract class Quirk { static inputField: H...
let visible = !this.row.hidden // Save setting to cookies. setCookieBool(this.id, visible, 31); let optionalCheckboxSet: HTMLDivElement = <HTMLDivElement>document.getElementById(category.tabName.toLocaleLowerCase() + "-optional-checkboxes"); if (visible) { this.up...
{ optionals[i].hidden = !this.activeCheckbox.checked; }
conditional_block
main.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the L...
def apply_default_style(ax): ax.set_xlim([0, 20001]) ax.get_xaxis().set_major_formatter( FuncFormatter(lambda x, p: format(int(x/1000), ','))) ax.set_xlabel("Training steps (in thousands)") plt.tick_params(top=False, right=False, bottom=False, left=False) handles, labels = ax.get_legend_handles_label...
"""Convert results class to a data frame.""" label = "{}, {}, {}".format(nets, critic, loss) rows = list( zip( itertools.repeat(exp_name), itertools.repeat(nets), itertools.repeat(critic), itertools.repeat(loss), itertools.repeat(seed), result.iterat...
identifier_body
main.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the L...
self._num_masked = num_masked # At construction time, we don't know input_depth. self._input_depth = None if bool(shift_and_log_scale_fn) == bool(bijector_fn): raise ValueError('Exactly one of `shift_and_log_scale_fn` and ' '`bijector_fn` should be specified.') if shift...
raise ValueError('num_masked must be a non-negative integer.')
conditional_block
main.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the L...
(self, input_shape): return input_shape class ConvNet(tf.keras.Sequential): def __init__(self, channels=64, kernel_size=5, input_dim=DIMS//2, output_dim=100, activation=tf.nn.relu): # Note: This works only for the specific data set considered here. super(ConvNet, self).__init__([ ...
compute_output_shape
identifier_name
main.py
# 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the L...
with tf.Graph().as_default(): g1, g2 = nets[nets_name]() critic = critics[critic_name]() loss_fn = loss_fns[loss_name] results_per_run = [] for n in range(NRUNS): try: print("{:d}th run, loss: {}".format(n, loss_name)) if loss_name == "drfc" and TFDS_NAME ==...
for nets_name, critic_name, loss_name in grid: print("[New experiment] encoder: {}, critic: {}, loss: {}".format( nets_name, critic_name, loss_name))
random_line_split
preprocessing.py
#!/usr/bin/env python3 # coding: utf-8 """Chromosight's preprocessing submodule implements a number of functions to operate on Hi-C contact maps before detection. These functions can be used to improve the signal or filter unneeded signal. There are also functions to edit (zoom, crop, factorize) kernel matrices. """ ...
(x): return ss.median_abs_deviation(x, nan_policy="omit") if not inter: if matrix.shape[0] != matrix.shape[1]: raise ValueError("Intrachromosomal matrices must be symmetric.") # Replace nonzero pixels by ones to work on prop. of nonzero pixels matrix.data = np.ones(matrix.data.s...
mad
identifier_name
preprocessing.py
#!/usr/bin/env python3 # coding: utf-8 """Chromosight's preprocessing submodule implements a number of functions to operate on Hi-C contact maps before detection. These functions can be used to improve the signal or filter unneeded signal. There are also functions to edit (zoom, crop, factorize) kernel matrices. """ ...
return good_bins def detrend( matrix, detectable_bins=None, max_dist=None, smooth=False, fun=np.nanmean, max_val=10, ): """ Detrends a Hi-C matrix by the distance law. The input matrix should have been normalised beforehandand. Parameters ---------- matrix : scipy...
sum_rows, sum_cols = matrix.sum(axis=1).A1, matrix.sum(axis=0).A1 mad_rows, mad_cols = mad(sum_rows), mad(sum_cols) med_rows, med_cols = np.median(sum_rows), np.median(sum_cols) detect_threshold_rows = max(1, med_rows - mad_rows * n_mads) detect_threshold_cols = max(1, med_cols - mad_col...
conditional_block
preprocessing.py
#!/usr/bin/env python3 # coding: utf-8 """Chromosight's preprocessing submodule implements a number of functions to operate on Hi-C contact maps before detection. These functions can be used to improve the signal or filter unneeded signal. There are also functions to edit (zoom, crop, factorize) kernel matrices. """ ...
Returns ------- scipy.sparse.coo_matrix: The detrended Hi-C matrix """ mat = matrix.copy() mu = np.mean(mat.data) sd = np.std(mat.data) mat.data -= mu mat.data /= sd return mat def sum_mat_bins(mat): """ Compute the sum of matrices bins (i.e. rows or columns)...
random_line_split
preprocessing.py
#!/usr/bin/env python3 # coding: utf-8 """Chromosight's preprocessing submodule implements a number of functions to operate on Hi-C contact maps before detection. These functions can be used to improve the signal or filter unneeded signal. There are also functions to edit (zoom, crop, factorize) kernel matrices. """ ...
def distance_law( matrix, detectable_bins=None, max_dist=None, smooth=True, fun=np.nanmean ): """ Computes genomic distance law by averaging over each diagonal in the upper triangle matrix. If a list of detectable bins is provided, pixels in missing bins will be excluded from the averages. A maxi...
""" Trim an upper triangle sparse matrix so that only the first n diagonals are kept. Parameters ---------- mat : scipy.sparse.csr_matrix or numpy.ndarray The sparse matrix to be trimmed n : int The number of diagonals from the center to keep (0-based). Returns -------...
identifier_body
graph.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, of, forkJoin } from 'rxjs'; import * as Rx from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import { FullDocNode, DocNode2, Doc2, Link, Change, Db } from './standard-map'...
if (anyChanged || t.column.autoFilterSrc == changedTab.column || (parentChanged && t == changedTab)) { anyChanged = true; // filter child tree GraphFilter.runFilter(t.column); } } //if (anyChanged) this.updateSubject.next(0); ...
var t = tabs[i]; if (!t) continue;
random_line_split
graph.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, of, forkJoin } from 'rxjs'; import * as Rx from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import { FullDocNode, DocNode2, Doc2, Link, Change, Db } from './standard-map'...
( private messageService: MessageService, private http: HttpClient) { this.addTab("ISO"); } public runFilters(changedTab: GraphTab, parentChanged: boolean) { if (this.runningFilters) return; // prevent re-entry this.runningFilters = true; var tabs = this.graphTabs; ...
constructor
identifier_name
graph.service.ts
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, of, forkJoin } from 'rxjs'; import * as Rx from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import { FullDocNode, DocNode2, Doc2, Link, Change, Db } from './standard-map'...
}
{ for (var t of this.graphTabs) if (t.anyErrors) return true; return false; }
identifier_body
binomial.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2016-2017 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. Thi...
for i in results.iter_mut() { *i = binomial.sample(rng) as f64; } let mean = results.iter().sum::<f64>() / results.len() as f64; assert!( (mean as f64 - expected_mean).abs() < expected_mean / 50.0, "mean: {}, expected_mean: {}", mean, ...
let mut results = [0.0; 1000];
random_line_split
binomial.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2016-2017 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. Thi...
else { result } } } #[cfg(test)] mod test { use super::Binomial; use crate::distributions::Distribution; use crate::Rng; fn test_binomial_mean_and_variance<R: Rng>(n: u64, p: f64, rng: &mut R) { let binomial = Binomial::new(n, p); let expected_mean = n as f64 ...
{ self.n - result }
conditional_block
binomial.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2016-2017 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. Thi...
() { let mut rng = crate::test::rng(351); test_binomial_mean_and_variance(150, 0.1, &mut rng); test_binomial_mean_and_variance(70, 0.6, &mut rng); test_binomial_mean_and_variance(40, 0.5, &mut rng); test_binomial_mean_and_variance(20, 0.7, &mut rng); test_binomial_mean_an...
test_binomial
identifier_name
binomial.rs
// Copyright 2018 Developers of the Rand project. // Copyright 2016-2017 The Rust Project Developers. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your // option. Thi...
let lambda_l = lambda((f_m - x_l) / (f_m - x_l * p)); let lambda_r = lambda((x_r - f_m) / (x_r * q)); // p1 + area of left tail let p3 = p2 + c / lambda_l; // p1 + area of right tail let p4 = p3 + c / lambda_r; // return value ...
{ a * (1. + 0.5 * a) }
identifier_body
main.rs
use anyhow::{Result, bail}; use futures::{FutureExt, StreamExt}; use warp::Filter; use warp::ws::{Message, WebSocket}; use tokio::sync::{mpsc, RwLock}; use std::collections::{HashMap, hash_map}; use std::sync::{ Arc, atomic::{AtomicUsize, Ordering}, }; use rand::seq::IteratorRandom; use std::convert::Infallible; use...
<Card: DeserializeOwned>(filename: &str) -> Result<Vec<Card>, Box<dyn std::error::Error>> { let file = File::open(filename)?; Ok(ron::de::from_reader(file)?) } fn load_prompts(filename: &str) -> Result<impl Iterator<Item=Prompt>, Box<dyn std::error::Error>> { Ok(load_deck::<Prompt>(filename)? .into_iter() .map(...
load_deck
identifier_name
main.rs
use anyhow::{Result, bail}; use futures::{FutureExt, StreamExt}; use warp::Filter; use warp::ws::{Message, WebSocket}; use tokio::sync::{mpsc, RwLock}; use std::collections::{HashMap, hash_map}; use std::sync::{ Arc, atomic::{AtomicUsize, Ordering}, }; use rand::seq::IteratorRandom; use std::convert::Infallible; use...
use ron; use std::fs::File; use serde::de::DeserializeOwned; fn load_deck<Card: DeserializeOwned>(filename: &str) -> Result<Vec<Card>, Box<dyn std::error::Error>> { let file = File::open(filename)?; Ok(ron::de::from_reader(file)?) } fn load_prompts(filename: &str) -> Result<impl Iterator<Item=Prompt>, Box<dyn std...
{ let game = &mut *game.write().await; game.clients.remove(&user_id); if let Some(player) = game.players.remove(&user_id) { // Discard player's answers game.answers.discard(&player.hand); // Discard player's submitted answers, if any let mut user_is_czar = false; if let Game { answers, round: Some(...
identifier_body
main.rs
use anyhow::{Result, bail}; use futures::{FutureExt, StreamExt}; use warp::Filter; use warp::ws::{Message, WebSocket}; use tokio::sync::{mpsc, RwLock}; use std::collections::{HashMap, hash_map}; use std::sync::{ Arc, atomic::{AtomicUsize, Ordering}, }; use rand::seq::IteratorRandom; use std::convert::Infallible; use...
}, } // Check whether all players have answered if round.answers.len() == players.len() - 1 { round.state = RoundState::Judging; // If so, notify them that JUDGEMENT HAS BEGUN // TODO maybe obfuscate the player IDs before sending for id in players.keys() { clients[id].send(Ws...
random_line_split
cougballoon_rcv.py
################################## ## Michael Hamilton ## michael.l.hamilton@wsu.edu ## #cougballoon ## v1.0 Mar 1, 2015 ## v1.1 Mar 13, 2015 - added JSON ## v1.2 Apr 5, 2015 - finalized graphs ## v1.3 Apr 6, 2015 - repaired value errors ################################## #Axis titles and legends have been crea...
#) #trace12 = Scatter( # x=[], # y=[], # mode='lines+markers', # stream=stream12 #) trace13 = Scatter( x=[], y=[], mode='lines+markers', stream=stream13 ) #Set up the plotly graphs data_graph_a = Data([trace1, trace3, trace5]) data_graph_b = Data([trace6, trace7]) data_graph_c = Data([tra...
#trace11 = Scatter( # x=[], # y=[], # mode='lines+markers', # stream=stream11
random_line_split
cougballoon_rcv.py
################################## ## Michael Hamilton ## michael.l.hamilton@wsu.edu ## #cougballoon ## v1.0 Mar 1, 2015 ## v1.1 Mar 13, 2015 - added JSON ## v1.2 Apr 5, 2015 - finalized graphs ## v1.3 Apr 6, 2015 - repaired value errors ################################## #Axis titles and legends have been cre...
(nmeaString): #Commented out lines are for .docs, we are using .txt files instead. #f = open('/Users/michaelhamilton/gpsbabel/nmeaRawData.doc', 'a') f = open('/Users/michaelhamilton/gpsbabel/nmeaRawData.txt', 'a') f.write(nmeaString) f.close() saveAllIncomingData(nmeaString) #os.system("cd /Users/michaelh...
handleGPSdata
identifier_name
cougballoon_rcv.py
################################## ## Michael Hamilton ## michael.l.hamilton@wsu.edu ## #cougballoon ## v1.0 Mar 1, 2015 ## v1.1 Mar 13, 2015 - added JSON ## v1.2 Apr 5, 2015 - finalized graphs ## v1.3 Apr 6, 2015 - repaired value errors ################################## #Axis titles and legends have been cre...
#Save all incoming data with a current date/time string def saveData(a): x = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f') saveAllIncomingData(x) saveAllIncomingData(a) #Convert GPS strings to floats (Couldn't get str.isnumeric() to work correctly) def StringToFloatGPS(a): a = a.rstrip('\n'); ...
hours = hours.rstrip('\n'); hours = hours.rstrip('\r'); hours = int(hours) + 17 if (hours > 24): hours = hours - 24 hours = str(hours) return hours
identifier_body
cougballoon_rcv.py
################################## ## Michael Hamilton ## michael.l.hamilton@wsu.edu ## #cougballoon ## v1.0 Mar 1, 2015 ## v1.1 Mar 13, 2015 - added JSON ## v1.2 Apr 5, 2015 - finalized graphs ## v1.3 Apr 6, 2015 - repaired value errors ################################## #Axis titles and legends have been cre...
#What data do we want here? elif ((line.find("V")) == 0): print "Temperature(from 10dof):" print line y = StringToFloat(line, temperature10DOF) saveData(line) temperature10DOF = y print y s5.write(dict(x=x, y=y)) #Take care of the incoming GPS data, send to plotly and post ...
print "Altitude(from press/temp):" print line y = StringToFloat(line, pressureAltitude) saveData(line) pressureAltitude = y print y s4.write(dict(x=x, y=y))
conditional_block
options.go
// Copyright 2017, The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package cmp import ( "fmt" "reflect" "runtime" "strings" ) // Option configures for specific behavior of Equal and Diff. In particular, // the fundame...
() {} func (o option) String() string { // TODO: Add information about the caller? // TODO: Maintain the order that filters were added? var ss []string switch op := o.op.(type) { case *transformer: fn := getFuncName(op.fnc.Pointer()) ss = append(ss, fmt.Sprintf("Transformer(%s, %s)", op.name, fn)) case *com...
option
identifier_name
options.go
// Copyright 2017, The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package cmp import ( "fmt" "reflect" "runtime" "strings" ) // Option configures for specific behavior of Equal and Diff. In particular, // the fundame...
// FilterPath returns a new Option where opt is only evaluated if filter f // returns true for the current Path in the value tree. // // The option passed in may be an Ignore, Transformer, Comparer, Options, or // a previously filtered Option. func FilterPath(f func(Path) bool, opt Option) Option { if f == nil { pan...
{ fnc := runtime.FuncForPC(p) if fnc == nil { return "<unknown>" } name := fnc.Name() // E.g., "long/path/name/mypkg.(mytype).(long/path/name/mypkg.myfunc)-fm" if strings.HasSuffix(name, ")-fm") || strings.HasSuffix(name, ")·fm") { // Strip the package name from method name. name = strings.TrimSuffix(name, "...
identifier_body
options.go
// Copyright 2017, The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package cmp
"runtime" "strings" ) // Option configures for specific behavior of Equal and Diff. In particular, // the fundamental Option functions (Ignore, Transformer, and Comparer), // configure how equality is determined. // // The fundamental options may be composed with filters (FilterPath and // FilterValues) to control t...
import ( "fmt" "reflect"
random_line_split
options.go
// Copyright 2017, The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE.md file. package cmp import ( "fmt" "reflect" "runtime" "strings" ) // Option configures for specific behavior of Equal and Diff. In particular, // the fundame...
name := fnc.Name() // E.g., "long/path/name/mypkg.(mytype).(long/path/name/mypkg.myfunc)-fm" if strings.HasSuffix(name, ")-fm") || strings.HasSuffix(name, ")·fm") { // Strip the package name from method name. name = strings.TrimSuffix(name, ")-fm") name = strings.TrimSuffix(name, ")·fm") if i := strings.Last...
{ return "<unknown>" }
conditional_block
combat.rs
use crate::components::*; use crate::map::*; use crate::NewState; use bracket_lib::prelude::*; use legion::systems::CommandBuffer; use legion::*; use std::collections::HashSet; pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState { let mut player_entity = None; let mut target = None; ...
( ecs: &mut World, commands: &mut CommandBuffer, dead_entities: Vec<Entity>, splatter: &mut Option<RGB>, ) { dead_entities.iter().for_each(|entity| { crate::stats::record_death(); let mut was_decor = false; let mut was_player = false; if let Ok(mut er) = ecs.entry_mut...
kill_things
identifier_name
combat.rs
use crate::components::*; use crate::map::*; use crate::NewState; use bracket_lib::prelude::*; use legion::systems::CommandBuffer; use legion::*; use std::collections::HashSet; pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState { let mut player_entity = None; let mut target = None; ...
pub fn hit_tile_contents( ecs: &mut World, pt: Point, layer: u32, commands: &mut CommandBuffer, splatter: &mut Option<RGB>, power: i32, ) -> i32 { let mut rng_lock = crate::RNG.lock(); let rng = rng_lock.as_mut().unwrap(); let mut power_loss = 0; let mut dead_entities = Vec::n...
{ let mut attacker_pos = None; let mut victim_pos = None; // Find positions for the start and end if let Ok(ae) = ecs.entry_ref(attacker) { if let Ok(pos) = ae.get_component::<Position>() { attacker_pos = Some(pos.clone()); } } if let Ok(ae) = ecs.entry_ref(victim) {...
identifier_body
combat.rs
use crate::components::*; use crate::map::*; use crate::NewState; use bracket_lib::prelude::*; use legion::systems::CommandBuffer; use legion::*; use std::collections::HashSet; pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState { let mut player_entity = None; let mut target = None; ...
// If necessary, kill them. let mut commands = CommandBuffer::new(ecs); let mut splatter = None; kill_things(ecs, &mut commands, dead_entities, &mut splatter); // Splatter blood. It's good for you. } fn kill_things( ecs: &mut World, commands: &mut CommandBuffer, dead_entities: Vec<En...
{ if let Ok(hp) = v.get_component_mut::<Health>() { hp.current = i32::max(0, hp.current - melee_power); if hp.current == 0 { dead_entities.push(victim); } } if let Ok(blood) = v.get_component::<Blood>() { let idx = map.get_layer(dpo...
conditional_block
combat.rs
use crate::components::*; use crate::map::*; use crate::NewState; use bracket_lib::prelude::*; use legion::systems::CommandBuffer; use legion::*; use std::collections::HashSet; pub fn player_open_fire_at_target(ecs: &mut World, map: &mut Map) -> NewState { let mut player_entity = None; let mut target = None; ...
}, Glyph { glyph: to_cp437('*'), color: ColorPair::new(RED, BLACK), }, )); commands.flush(ecs); } pub fn hit_tile_contents( ecs: &mut World, pt: Point, layer: u32, commands: &mut CommandBuffer, splatter: &mut Option<RGB>, power: i32, ) ->...
layer: current_layer as usize,
random_line_split
tutor-details.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import { Meteor } from 'meteor/meteor'; import { MeteorObservable } from 'meteor-rxjs'; import { InjectUser } from "angular2-meteor-accounts-ui"; import {ROUTER_D...
private myDatePickerOptions: IMyOptions = { // other options... dateFormat: 'dd.mm.yyyy', inline: true, disableDateRanges: [{ begin: {year: this.today.getFullYear(), month: this.today.getMonth()-2, day: this.today.getDate()}, end: {year: this.today.getFullYear(), month: th...
{}
identifier_body
tutor-details.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import { Meteor } from 'meteor/meteor'; import { MeteorObservable } from 'meteor-rxjs'; import { InjectUser } from "angular2-meteor-accounts-ui"; import {ROUTER_D...
(): void{ this.checkout = false; } GoToCheckOut(): void{ // if(!this.user_skype_email){ // alert('Please enter your skype username so the teatch can contact you :)'); // }else{ // alert('you are now registered in this class :)'); // } console.log(this.slot); console.log(this.tut...
step1
identifier_name
tutor-details.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import { Meteor } from 'meteor/meteor'; import { MeteorObservable } from 'meteor-rxjs'; import { InjectUser } from "angular2-meteor-accounts-ui"; import {ROUTER_D...
else if(this.tutorSchedule[this.day][i]==1){ this.tutorSchedule[this.day][i]=0; this.colorsSched[this.day][i]='blue'; } // else if(this.colorsSched[this.day][i]='blue'){ // this.colorsSched[this.day][i]='green'; // } } onDateChanged(event: IMyDateModel) { let _MS_PER_DAY = 1000 * ...
{ this.tutorSchedule[this.day][i]=1; this.colorsSched[this.day][i]='green'; }
conditional_block
tutor-details.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core'; import { Observable } from 'rxjs/Observable'; import { Subscription } from 'rxjs/Subscription'; import { Meteor } from 'meteor/meteor'; import { MeteorObservable } from 'meteor-rxjs'; import { InjectUser } from "angular2-meteor-accounts-ui"; import {ROUTER_D...
console.log('payment form valid') Stripe.card.createToken({ number: this.payment_form.value.cardNumber, cvc: this.payment_form.value.cvc, exp_month: this.payment_form.value.expiryMonth, exp_year: this.payment_form.value.expiryYear }, function(status, response) { ...
} } CheckoutFn():void{ if (this.payment_form.valid) {
random_line_split
lib.go
package main import ( "encoding/json" "fmt" "github.com/gorilla/websocket" log "github.com/sirupsen/logrus" "gopkg.in/routeros.v2" "gopkg.in/yaml.v2" "io/ioutil" "strings" "sync" "time" )
pongWait = 60 * time.Second // Send pings to client with this period. Must be less than pongWait. pingPeriod = (pongWait * 9) / 10 // Time allowed to write the file to the client. writeWait = 10 * time.Second ) // Event types const ( EVENT_CONNECT = iota EVENT_ROAMING EVENT_DISCONNECT EVENT_LEVEL ) type Le...
const ( // Time allowed to read the next pong message from the client.
random_line_split
lib.go
package main import ( "encoding/json" "fmt" "github.com/gorilla/websocket" log "github.com/sirupsen/logrus" "gopkg.in/routeros.v2" "gopkg.in/yaml.v2" "io/ioutil" "strings" "sync" "time" ) const ( // Time allowed to read the next pong message from the client. pongWait = 60 * time.Second // Send pings to ...
func FindLeaseByMAC(list []LeaseEntry, mac string) (e LeaseEntry, ok bool) { for _, e := range list { if e.MAC == mac { return e, true } } return } func RTLoop(c *routeros.Client, conf *Config) { for { cmd := "/caps-man/registration-table/print" if strings.ToLower(config.Router.Mode) == "wifi" { cm...
{ ticker := time.NewTicker(config.DHCP.Interval) for { // nolint:gosimple select { case <-ticker.C: l, err := GetDHCPLeases(config.DHCP.Address, config.DHCP.Username, config.DHCP.Password) if err != nil { log.WithFields(log.Fields{"dhcp-addr": config.DHCP.Address}).Error("Error reloading DHCP Leases: ",...
identifier_body
lib.go
package main import ( "encoding/json" "fmt" "github.com/gorilla/websocket" log "github.com/sirupsen/logrus" "gopkg.in/routeros.v2" "gopkg.in/yaml.v2" "io/ioutil" "strings" "sync" "time" ) const ( // Time allowed to read the next pong message from the client. pongWait = 60 * time.Second // Send pings to ...
() { } // Handle report update request func (b *BroadcastData) reportUpdate(report []ReportEntry) error { output, err := json.Marshal(report) if err != nil { return err } // Lock mutex b.RLock() defer b.RUnlock() // Prepare new list of entries rm := map[string]ReportEntry{} for _, v := range report { r...
usage
identifier_name
lib.go
package main import ( "encoding/json" "fmt" "github.com/gorilla/websocket" log "github.com/sirupsen/logrus" "gopkg.in/routeros.v2" "gopkg.in/yaml.v2" "io/ioutil" "strings" "sync" "time" ) const ( // Time allowed to read the next pong message from the client. pongWait = 60 * time.Second // Send pings to ...
default: } } } }
{ if (len(dev.OnLevel.HttpPost) > 0) || (len(dev.OnLevel.HttpGet) > 0) { go makeRequest(dev.OnLevel, map[string]string{ "name": dev.Name, "mac": data.Old.MAC, "roaming.to": "", "roaming.from": "", "level.from": data.Old.Signal, "level.to": da...
conditional_block
uiTools.js
/* globals getPropValue, getProperty, toTitleCase:true, firmlyInSlicingMode:true, axisIndex:true, guiUtils:true, AxisList:true, slicingOrChanging:true, disabledIfSlicingOrChanging:true, UI, getRoundedProp:true, getAllDataForKesmName:true, KesmNames,propertyCollections, roundIfNumber:true */ // make things like Meteor...
Template.registerHelper('data', function(data) { return data.hash; }); Meteor.cb = function(e,r) { if (e) console.error(e); if(r) { if (_.isArray(r) && console.table) { console.table(r); } else { console.log(r); } } }; guiUtils = {}; guiUtils.makeMeteorReactiveTextBox = function(textI...
// {{> controllerTemplate}} // {{/with}}
random_line_split
uiTools.js
/* globals getPropValue, getProperty, toTitleCase:true, firmlyInSlicingMode:true, axisIndex:true, guiUtils:true, AxisList:true, slicingOrChanging:true, disabledIfSlicingOrChanging:true, UI, getRoundedProp:true, getAllDataForKesmName:true, KesmNames,propertyCollections, roundIfNumber:true */ // make things like Meteor...
if (tbQuery) { $(textInputQuery).val(tbQuery.value); } }; // Call this first when the slider is initialized, and when changes happen Tracker.autorun(updateTextBoxFromMeteor); // jQuery-ui -> Meteor var pushTextChangeToMeteor = function() { var currentValue = $(textInputQuery).val(); ...
{ return; }
conditional_block
BatteryMonitor6813Tester.go
package main import ( "BatteryMonitor6813Tester/LTC6813" "database/sql" "errors" "flag" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" "io/ioutil" "log" "log/syslog" "net/http" "os" "periph.io/x/periph/conn/physic" "periph.io/x/periph/conn/pin" "periph.io/x/periph/conn/pin/pinreg" "p...
chainLength-- if chainLength > 0 { ltc = LTC6813.New(spiConnection, chainLength) if err := ltc.Initialise(); err != nil { fmt.Print(err) log.Fatal(err) } _, err := ltc.MeasureVoltages() if err != nil { fmt.Println("MeasureVoltages - ", err) } _, err = ltc.MeasureTemperatures() if err != nil ...
{ testLtc := LTC6813.New(spiConnection, chainLength) if _, err := testLtc.Test(); err != nil { fmt.Println(err) break } testLtc = nil chainLength++ }
conditional_block
BatteryMonitor6813Tester.go
package main import ( "BatteryMonitor6813Tester/LTC6813" "database/sql" "errors" "flag" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" "io/ioutil" "log" "log/syslog" "net/http" "os" "periph.io/x/periph/conn/physic" "periph.io/x/periph/conn/pin" "periph.io/x/periph/conn/pin/pinreg" "p...
sensor, _ := strconv.ParseInt(r.URL.Query().Get("sensor"), 0, 8) t, err := ltc.GetI2CCurrent(int(sensor)) if err != nil { fmt.Fprint(w, err) } else { fmt.Fprintf(w, "Current on sensor %d = %f", sensor, t) } } /** WEB service to read the voltage from the I2C port */ func getI2CVoltage(w http.ResponseWriter, r...
/** WEB service to read the current from the I2C port */ func getI2CCurrent(w http.ResponseWriter, r *http.Request) {
random_line_split
BatteryMonitor6813Tester.go
package main import ( "BatteryMonitor6813Tester/LTC6813" "database/sql" "errors" "flag" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" "io/ioutil" "log" "log/syslog" "net/http" "os" "periph.io/x/periph/conn/physic" "periph.io/x/periph/conn/pin" "periph.io/x/periph/conn/pin/pinreg" "p...
(*sql.DB, error) { if pDB != nil { _ = pDB.Close() pDB = nil } var sConnectionString = *pDatabaseLogin + ":" + *pDatabasePassword + "@tcp(" + *pDatabaseServer + ":" + *pDatabasePort + ")/" + *pDatabaseName fmt.Println("Connecting to [", sConnectionString, "]") db, err := sql.Open("mysql", sConnectionString) ...
nnectToDatabase()
identifier_name
BatteryMonitor6813Tester.go
package main import ( "BatteryMonitor6813Tester/LTC6813" "database/sql" "errors" "flag" "fmt" _ "github.com/go-sql-driver/mysql" "github.com/gorilla/mux" "io/ioutil" "log" "log/syslog" "net/http" "os" "periph.io/x/periph/conn/physic" "periph.io/x/periph/conn/pin" "periph.io/x/periph/conn/pin/pinreg" "p...
func connectToDatabase() (*sql.DB, error) { if pDB != nil { _ = pDB.Close() pDB = nil } var sConnectionString = *pDatabaseLogin + ":" + *pDatabasePassword + "@tcp(" + *pDatabaseServer + ":" + *pDatabasePort + ")/" + *pDatabaseName fmt.Println("Connecting to [", sConnectionString, "]") db, err := sql.Open("mys...
if !*verbose { log.SetOutput(ioutil.Discard) } log.SetFlags(log.Lmicroseconds) if flag.NArg() != 0 { return errors.New("unexpected argument, try -help") } for { nDevices, err := getLTC6813() if err == nil && nDevices > 0 { break } fmt.Println("Looking for a device") } done := make(chan bool) ti...
identifier_body
image_caption.py
# importing libraries import matplotlib.pyplot as plt import pandas as pd import pickle import numpy as np import os import glob from keras.applications.resnet50 import ResNet50 from keras.optimizers import Adam from keras.layers import Dense, Flatten,Input, Convolution2D, Dropout, LSTM, TimeDistributed, Embed...
# Loading cap as values and images as key in dictionary tok = {} for item in range(len(cap)-1): tem = cap[item].split("#") #tem[0]= imgname.jpg ..... tem[1]=0 captionn. if tem[0] in tok: tok[tem[0]].append(tem[1][2:]) else: tok[tem[0]] = [tem[1][2:]] #tem[n]= imgName ... #tok[tem[n...
x_training = open(training_path, 'r').read().split("\n") x_valid = open(valid_path, 'r').read().split("\n") x_testing = open(testing_path , 'r').read().split("\n")
random_line_split
image_caption.py
# importing libraries import matplotlib.pyplot as plt import pandas as pd import pickle import numpy as np import os import glob from keras.applications.resnet50 import ResNet50 from keras.optimizers import Adam from keras.layers import Dense, Flatten,Input, Convolution2D, Dropout, LSTM, TimeDistributed, Embed...
resnet = ResNet50(include_top=False,weights='imagenet',input_shape=(224,224,3),pooling='avg') img = "/content/drive/My Drive/Flickr_Data/Flickr_Data/Images/3376942201_2c45d99237.jpg" test_img = get_encode(resnet, img) def predict_cap(image): start_wor = ["<start>"] while True: par_ca...
image = preprocess(img) pred = model.predict(image).reshape(2048) return pred
identifier_body
image_caption.py
# importing libraries import matplotlib.pyplot as plt import pandas as pd import pickle import numpy as np import os import glob from keras.applications.resnet50 import ResNet50 from keras.optimizers import Adam from keras.layers import Dense, Flatten,Input, Convolution2D, Dropout, LSTM, TimeDistributed, Embed...
testing_dataset.close() for img in x_valid: if img == '': continue for capt in tok[img]: caption = "<start> "+ capt + " <end>" valid_dataset.write((img+"\t"+caption+"\n").encode()) valid_dataset.flush() valid_dataset.close() # Here, we're using ResNet50 Model from...
if img == '': continue for capt in tok[img]: caption = "<start> "+ capt + " <end>" testing_dataset.write((img+"\t"+caption+"\n").encode()) testing_dataset.flush()
conditional_block
image_caption.py
# importing libraries import matplotlib.pyplot as plt import pandas as pd import pickle import numpy as np import os import glob from keras.applications.resnet50 import ResNet50 from keras.optimizers import Adam from keras.layers import Dense, Flatten,Input, Convolution2D, Dropout, LSTM, TimeDistributed, Embed...
(model, img): image = preprocess(img) pred = model.predict(image).reshape(2048) return pred resnet = ResNet50(include_top=False,weights='imagenet',input_shape=(224,224,3),pooling='avg') img = "/content/drive/My Drive/Flickr_Data/Flickr_Data/Images/3376942201_2c45d99237.jpg" test_img = get_encode(r...
get_encode
identifier_name
idempotent.rs
//! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE //! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is //! mut_aliased refs on some another obj, or shared data //! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS | 0 // fns with side-effs: --==...
} fn fetchOrders(userId) { ajax( "http://some.api/orders/" + userId, fn onOrders(orders) { for (let i = 0; i < orders.length; i++) { // keep a reference to latest order for each user users[userId].latestOrder = orders[i]; userOrders[orders[i].o...
users[userId] = userData; });
random_line_split
idempotent.rs
//! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE //! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is //! mut_aliased refs on some another obj, or shared data //! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS | 0 // fns with side-effs: --==...
// not IDEMPOTENT because: *WRONG: we update, and/but not completly rewrite `x`, // *RIGHT: mut_aliasing (our computed value for `x` rely on mut_aliased `x`) // (BUT) // BTW(p.s.)--v: `some_fn` break rule: /// "mutate only TREE_in_the_WOOD , emit "own_copied/immutabl" value" // ...
{ x += n*x }
identifier_body
idempotent.rs
//! mut_aliasing -- several links, AT_LEAST one of them is MUTABLE //! BTW: bunch_of_closures_with_mut_refs is like obj which alias through its params, which is //! mut_aliased refs on some another obj, or shared data //! that_is: CLOSURE_CAPUTRING == OBJ.MUT_ALIASED_REFS | 0 // fns with side-effs: --==...
(a = [], n) { a.push(n) } // ^-- here was: "ADD value, not just change." // BUT actually .. it's also can be considered as MUT_alising .. since result of `push` // depends of `a`, .. and if we call 2 times `some_fn` of course it's gives different sideeff, // since its computation based on MUTated value,...
some_fn
identifier_name
core_convert.py
from datetime import timedelta, datetime def filter_dict(obj, val=None): # TODO: We should not always remove all None items (maybe!?) return dict(filter(lambda item: item[1] is not val, obj.items())) def get_season_tag_name(key): table = { "Clas Ohlson": "COB", "Matkasse": "MK", ...
nit(validoo_unit): # data from prefilledautomaten.unit unit_table = { "H87": 1, # st, PIECES "GRM": 2, # g, WEIGHT "KGM": 3, # kg, WEIGHT "DLT": 6, # dl, VOLUME "LTR": 7, # L, VOLUME "MLT": 10, # ml, VOLUME "CLT": 11, # cl, VOLUME "HGM": 12,...
== product.article.gtin: return next_lower_article.quantity_of_lower_layer * upper_quantity return None def convert_u
conditional_block
core_convert.py
from datetime import timedelta, datetime def filter_dict(obj, val=None): # TODO: We should not always remove all None items (maybe!?) return dict(filter(lambda item: item[1] is not val, obj.items())) def get_season_tag_name(key): table = { "Clas Ohlson": "COB", "Matkasse": "MK", ...
(key): table = { 'Volume': 1, 'Weight': 2, 'KfpDfp': 3, 'LastSalesDay': 4, 'LastReceiptDay': 5, 'OldPz1': 6, 'OldPz2': 7, 'OldPz3': 8, 'MaxStock': 9, 'Season': 10, 'OrderFactor': 11, 'MinStock': 12, 'DfpLengthMM'...
'Ekonomipack': 1, 'Nyckelhålsmärkt': 1736, 'Ekologisk': 2167, 'Glutenfri': 2168, 'Laktosfri': 2169, 'Låglaktos': 2170, 'Premiumkvalité': 2171, 'Mjölkproteinfri': 2172, # 'Nyhet': 2173, '18Åldersgräns': 2174, 'Fairtrade': 2175, ...
identifier_body
core_convert.py
from datetime import timedelta, datetime def filter_dict(obj, val=None): # TODO: We should not always remove all None items (maybe!?) return dict(filter(lambda item: item[1] is not val, obj.items())) def get_season_tag_name(key): table = { "Clas Ohlson": "COB", "Matkasse": "MK", ...
"MLT": 10, # ml, VOLUME "CLT": 11, # cl, VOLUME "HGM": 12, # hg, WEIGHT "G24": 13, # msk, VOLUME "G25": 14, # tsk, VOLUME # "???": 16, # st tekoppar, VOLUME # "???": 17, # st kaffekoppar, VOLUME # "???": 18, # glas, VOLUME "MGM": 25, # mg,...
"H87": 1, # st, PIECES "GRM": 2, # g, WEIGHT "KGM": 3, # kg, WEIGHT "DLT": 6, # dl, VOLUME "LTR": 7, # L, VOLUME
random_line_split
core_convert.py
from datetime import timedelta, datetime def filter_dict(obj, val=None): # TODO: We should not always remove all None items (maybe!?) return dict(filter(lambda item: item[1] is not val, obj.items())) def get_season_tag_name(key): table = { "Clas Ohlson": "COB", "Matkasse": "MK", ...
able = { "Crossdocking": "X", "Nightorder": "A", } return table[key] if key in table else None def get_attribute_id(key): # data from prefilledautomaten.attribute table = { 'Ekonomipack': 1, 'Nyckelhålsmärkt': 1736, 'Ekologisk': 2167, 'Glutenfri': 2168, ...
r_route_from_product_type(key): t
identifier_name
parser.go
package juniperUDP import ( "path/filepath" "os" "log" "fmt" "runtime" "time" "reflect" "strconv" "github.com/golang/protobuf/jsonpb" "encoding/json" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/plugins/parsers/juniperUDP/telemetry_top" _"github...
sequenceNum := 0 for key, sensorData := range jnprSensorData.(map[string]interface{}){ var fields map[string]interface{} if reflect.ValueOf(sensorData).Kind() == reflect.Map { _ = sensorName sensorName = key[1:len(key)-1] var measurementName string measurementName = sensorName /* if val, ok := s...
random_line_split
parser.go
package juniperUDP import ( "path/filepath" "os" "log" "fmt" "runtime" "time" "reflect" "strconv" "github.com/golang/protobuf/jsonpb" "encoding/json" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/plugins/parsers/juniperUDP/telemetry_top" _"github...
func (p *JuniperUDPParser) ParseLine(line string) (telegraf.Metric, error) { metrics, err := p.Parse([]byte(line + "\n")) if err != nil { return nil, err } if len(metrics) < 1 { return nil, fmt.Errorf( "Can not parse the line: %s, for data format: influx ", line) } return metrics[0], nil } func (p ...
{ //out, _ := os.Create("telegraf_udp.log") dir, err := filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { log.Fatal(err) } path := dir+"/logs" if _, err := os.Stat(path); os.IsNotExist(err) { os.Mkdir(path, 0777) } out, errFile := os.OpenFile("logs/telegraf_udp.log", os.O_APPEND|os....
identifier_body
parser.go
package juniperUDP import ( "path/filepath" "os" "log" "fmt" "runtime" "time" "reflect" "strconv" "github.com/golang/protobuf/jsonpb" "encoding/json" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/plugins/parsers/juniperUDP/telemetry_top" _"github...
// fmt.Printf("\nData (JSON) = \n%s\n", data) // fmt.Println("\nJuniper Sensor Name: \n%s\n", jnprSensorName) // fmt.Println("\nDevice name: \n%s\n", deviceName) // fmt.Println("\nGPB time: \n%s\n", gpbTime) // fmt.Println(measurementPrefix) // fmt.Println("\nMetrics: \n") // fmt.Println(metrics) newLog.Printf("Par...
{ var fields map[string]interface{} if reflect.ValueOf(sensorData).Kind() == reflect.Map { _ = sensorName sensorName = key[1:len(key)-1] var measurementName string measurementName = sensorName /* if val, ok := sensorMapping[sensorName]; ok { measurementName = val } else { measuremen...
conditional_block
parser.go
package juniperUDP import ( "path/filepath" "os" "log" "fmt" "runtime" "time" "reflect" "strconv" "github.com/golang/protobuf/jsonpb" "encoding/json" "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/metric" "github.com/influxdata/telegraf/plugins/parsers/juniperUDP/telemetry_top" _"github...
(tags map[string]string) { p.DefaultTags = tags }
SetDefaultTags
identifier_name
alain.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { t...
ct) { var _a; if (schema.path === undefined) { schema.path = `/${path.join(project.sourceRoot, (_a = alainProject === null || alainProject === void 0 ? void 0 : alainProject.routesRoot) !== null && _a !== void 0 ? _a : 'app/routes')}`; } } exports.refreshPathRoot = refreshPathRoot; function resolveS...
ema, alainProje
identifier_name
alain.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { t...
= true) { const source = (0, ast_1.getSourceFile)(tree, filePath); const node = (0, ast_utils_1.findNode)(source, ts.SyntaxKind.Identifier, variableName); if (!node) { throw new schematics_1.SchematicsException(`Could not find any [${variableName}] variable in path '${filePath}'.`); } // es...
ce, filePath, serviceName, importPath); const declarationRecorder = tree.beginUpdate(filePath); changes.forEach(change => { if (change.path == null) return; if (change instanceof change_1.InsertChange) { declarationRecorder.insertLeft(change.pos, change.toAdd); } ...
identifier_body
alain.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { t...
} // module name if (schema.module) { ret.push(schema.module); } // target name if (schema.target) { ret.push(...schema.target.split('/')); } // name ret.push(core_1.strings.dasherize(schema.name)); return ret.join('-'); } function buildName(schema, prefix) { ...
{ ret.push(projectPrefix); }
conditional_block
alain.js
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { t...
schema.service === 'ignore' ? (0, schematics_1.filter)(filePath => !filePath.endsWith('.service.ts.template')) : (0, schematics_1.noop)(), schema.skipTests ? (0, schematics_1.filter)(filePath => !filePath.endsWith('.spec.ts.template')) : (0, schematics_1.noop)(), schema.inlineStyle ?...
// Don't support inline schema.inlineTemplate = false; const templateSource = (0, schematics_1.apply)((0, schematics_1.url)(schema._filesPath), [ (0, schematics_1.filter)(filePath => !filePath.endsWith('.DS_Store')),
random_line_split
plot.py
#!/usr/bin/env python """ Author: Matthew Christey-Reid Email: s1438675@ed.ac.uk Date: 02/06/2020 plot.py - Main functions to determine properties of the eclipsing binaries from observed data """ # Import libraries for data processing import math import numpy as np import matplotlib.pyplot as plt from math import ...
(_band, _period): """ Plots an observed band using pyplot :param _band: Array to be plotted :param _period: Period of object """ # Frequency = 1 / Period _freq = 1 / _period _xfit, _lobf = calclobf(_band, _period) # Plot the data in the array to screen, lightly coloured and z rank be...
plotband
identifier_name
plot.py
#!/usr/bin/env python """ Author: Matthew Christey-Reid Email: s1438675@ed.ac.uk Date: 02/06/2020 plot.py - Main functions to determine properties of the eclipsing binaries from observed data """ # Import libraries for data processing import math import numpy as np import matplotlib.pyplot as plt from math import ...
# Iterate through data array for _row in _data: np.seterr(divide='ignore') # Convert magnitude to luminosity _row[0] = _row[0] - 5 * (np.log10(_row[2]) - 1) # Convert B-V colour to temperature _row[1] = 4600 * ((1 / (0.92 * _row[1] + 1.7)) + 1 / (0.92 * _row[1] + 0.62)) ...
for _line in _file: # Split each line into constituent values _x = _line.split() # Append data array with each value, converted to float, convert parallax angle to distance _data = np.append(_data, np.array([float(_x[1]), float(_x[2]), (1 / float(_x[3]))], ndmin=2), axis=0)
random_line_split
plot.py
#!/usr/bin/env python """ Author: Matthew Christey-Reid Email: s1438675@ed.ac.uk Date: 02/06/2020 plot.py - Main functions to determine properties of the eclipsing binaries from observed data """ # Import libraries for data processing import math import numpy as np import matplotlib.pyplot as plt from math import ...
# Delete first empty row of the array _largestar = np.delete(_largestar, 0, axis=0) # Determine the spectral flux density from the small star i = 0 while i < 5: # Determine the maximum and minimum values of the observed band _max, _min = lightcurve.maxminvals(_bands[i]) # S...
_max, _min = lightcurve.maxminvals(_bands[i]) # The large star uses the maximum flux value (smallest magnitude) _largestar = np.append(_largestar, np.array([_lambda[i], (magtoflux(_min, i))], ndmin=2), axis=0) i += 1
conditional_block
plot.py
#!/usr/bin/env python """ Author: Matthew Christey-Reid Email: s1438675@ed.ac.uk Date: 02/06/2020 plot.py - Main functions to determine properties of the eclipsing binaries from observed data """ # Import libraries for data processing import math import numpy as np import matplotlib.pyplot as plt from math import ...
def plotallbands(_zband, _yband, _jband, _hband, _kband, _period): """ Plots all observed bands to the same graph :param _zband: Observed z-band :param _yband: Observed y-band :param _jband: Observed j-band :param _hband: Observed h-band :param _kband: Observed k-band :param _period: ...
""" Rounds the provided value to 2 significant figures :param _val: Value to be rounded :return: Float, original value rounded to 2 significant figures """ return round(_val, 3 - int(floor(log10(abs(_val)))) - 1)
identifier_body
routing.rs
//! Functions for adding ingress/egress nodes. //! //! In particular: //! //! - New nodes that are children of nodes in a different domain must be preceeded by an ingress //! - Egress nodes must be added to nodes that now have children in a different domain //! - Egress nodes that gain new children must gain channel...
{ // ensure all egress nodes contain the tx channel of the domains of their child ingress nodes for &node in new { let n = &graph[node]; if let node::Type::Ingress = **n { // check the egress connected to this ingress } else { continue; } for egr...
identifier_body
routing.rs
//! Functions for adding ingress/egress nodes. //! //! In particular: //! //! - New nodes that are children of nodes in a different domain must be preceeded by an ingress //! - Egress nodes must be added to nodes that now have children in a different domain //! - Egress nodes that gain new children must gain channel...
(log: &Logger, graph: &mut Graph, main_txs: &HashMap<domain::Index, mpsc::SyncSender<Packet>>, new: &HashSet<NodeIndex>) { // ensure all egress nodes contain the tx channel of the domains of their child ingress nodes for &node in new { let n = &graph[node]; ...
connect
identifier_name
routing.rs
//! Functions for adding ingress/egress nodes. //! //! In particular: //! //! - New nodes that are children of nodes in a different domain must be preceeded by an ingress //! - Egress nodes must be added to nodes that now have children in a different domain //! - Egress nodes that gain new children must gain channel...
// of `node` with the ids of the egress nodes. thus, we actually need to do swaps on // the values in `swaps`, not insert new entries (that, or we'd need to change the // resolution process to be recursive, which is painful and unnecessary). note that we // *also* need to...
let was_materialized = graph.remove_edge(old).unwrap(); graph.add_edge(ingress, node, was_materialized); // tracking swaps here is a bit tricky because we've already swapped the "true" parents
random_line_split
main.rs
// cargo build --target=mips-unknown-linux-gnu //extern crate rand; //#![deny(warnings)] #![feature(type_ascription)] #[macro_use] extern crate log; extern crate bytes; extern crate futures; extern crate hyper; extern crate pretty_env_logger; extern crate regex; //extern crate reqwest; //extern crate tokio; #[macro_...
fn testGoogleSSL() { println!("===== TestBody ====="); let body = reqwest::Client::builder() //.danger_accept_invalid_hostnames(true) //.danger_accept_invalid_certs(true) //.add_root_certificate(cert) .build() .unwrap() .get("https://www.google.de/") .se...
{ /* extern crate openssl; println!("===== testOpenSSL ====="); use openssl::ssl::{SslConnector, SslMethod}; use std::io::{Read, Write}; use std::net::TcpStream; let connector = SslConnector::builder(SslMethod::tls()).unwrap().build(); let stream = TcpStream::connect("google.com:443")....
identifier_body
main.rs
// cargo build --target=mips-unknown-linux-gnu //extern crate rand; //#![deny(warnings)] #![feature(type_ascription)] #[macro_use] extern crate log; extern crate bytes; extern crate futures; extern crate hyper; extern crate pretty_env_logger; extern crate regex; //extern crate reqwest; //extern crate tokio; #[macro_...
(uri: &Uri) -> String { //let in_addr: SocketAddr = get_in_addr(); let uri_string = uri.path_and_query().map(|x| x.as_str()).unwrap_or(""); //let uri: String = uri_string.parse().unwrap(); //let in_uri_string = format!("http://{}/{}", in_addr, req.uri()); let in_remove_string = "/fwd/"; debug!(...
reduce_forwarded_uri
identifier_name
main.rs
// cargo build --target=mips-unknown-linux-gnu //extern crate rand; //#![deny(warnings)] #![feature(type_ascription)] #[macro_use] extern crate log; extern crate bytes; extern crate futures; extern crate hyper; extern crate pretty_env_logger; extern crate regex; //extern crate reqwest; //extern crate tokio; #[macro_...
if len > 0 { //Ok(Some(buf.iter().take(32).freeze().into())) Ok(Some(buf.iter().take(32).into())) } else { Ok(None) } } let akjsd = decode(chunks);*/ use bytes::{BigEndian, B...
random_line_split
mod.rs
// Copyright (C) 2020 Alibaba Cloud. All rights reserved. // SPDX-License-Identifier: Apache-2.0 //! Fuse passthrough file system, mirroring an existing FS hierarchy. //! //! This file system mirrors the existing file system hierarchy of the system, starting at the //! root file system. This is implemented by just "pa...
if fd < 0 { return Err(io::Error::last_os_error()); } // Safe because we just opened this fd. Ok(unsafe { File::from_raw_fd(fd) }) } fn do_lookup(&self, parent: Inode, name: &CStr) -> io::Result<Entry> { let p = self.inode_map.get(parent)?; let f = Se...
unsafe { libc::openat(dfd, pathname.as_ptr(), flags) } };
conditional_block
mod.rs
// Copyright (C) 2020 Alibaba Cloud. All rights reserved. // SPDX-License-Identifier: Apache-2.0 //! Fuse passthrough file system, mirroring an existing FS hierarchy. //! //! This file system mirrors the existing file system hierarchy of the system, starting at the //! root file system. This is implemented by just "pa...
use std::mem::MaybeUninit; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::str::FromStr; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, RwLock, RwLockWriteGuard}; use std::time::Duration; use vm_memory::ByteValued; use crate::abi::linux_abi as fuse; use ...
use std::ffi::{CStr, CString}; use std::fs::File; use std::io; use std::marker::PhantomData;
random_line_split
mod.rs
// Copyright (C) 2020 Alibaba Cloud. All rights reserved. // SPDX-License-Identifier: Apache-2.0 //! Fuse passthrough file system, mirroring an existing FS hierarchy. //! //! This file system mirrors the existing file system hierarchy of the system, starting at the //! root file system. This is implemented by just "pa...
lf, inode: Inode, handle: Handle) -> io::Result<()> { self.handle_map.release(handle, inode) } } #[cfg(not(feature = "async-io"))] impl<D: AsyncDrive> BackendFileSystem for PassthroughFs<D> { type D = D; fn mount(&self) -> io::Result<(Entry, u64)> { let entry = self.do_lookup(fuse::ROOT_ID,...
elease(&se
identifier_name
mod.rs
// Copyright (C) 2020 Alibaba Cloud. All rights reserved. // SPDX-License-Identifier: Apache-2.0 //! Fuse passthrough file system, mirroring an existing FS hierarchy. //! //! This file system mirrors the existing file system hierarchy of the system, starting at the //! root file system. This is implemented by just "pa...
impl Default for CachePolicy { fn default() -> Self { CachePolicy::Auto } } /// Options that configure the behavior of the passthrough fuse file system. #[derive(Debug, Clone, PartialEq)] pub struct Config { /// How long the FUSE client should consider directory entries to be valid. If the contents...
match s { "never" | "Never" | "NEVER" | "none" | "None" | "NONE" => Ok(CachePolicy::Never), "auto" | "Auto" | "AUTO" => Ok(CachePolicy::Auto), "always" | "Always" | "ALWAYS" => Ok(CachePolicy::Always), _ => Err("invalid cache policy"), } } }
identifier_body
CollectGame.js
BasicGame.CollectGame = function (game) { this.state_label = 'CollectGame'; this.current_level = 1; this.level_images = []; this.level_images[1] = { //'background': 'sky', 'background': 'bg_desert', 'tilemap': '', 'tileset': '' }; this.text_style = {font: '65px kenvector_future', fill: 'white', align: 'ce...
} if (this.answer == answer) { this.right_answer_sound.play(); this.displayNewProblem(); this.game.global_vars.diff_score += 1; this.score += 100; this.numCollected += 1; } this.difficulty_text.destroy(); this.difficulty_text = this.game.add.text(80, 10, 'Difficulty ' + this.game.global_vars.d...
{ this.score = 0; }
conditional_block
CollectGame.js
BasicGame.CollectGame = function (game) { this.state_label = 'CollectGame'; this.current_level = 1; this.level_images = []; this.level_images[1] = { //'background': 'sky', 'background': 'bg_desert', 'tilemap': '', 'tileset': '' }; this.text_style = {font: '65px kenvector_future', fill: 'white', align: 'ce...
//boulder.value = this.boulderVal; //console.log('VALUE: ' + boulder.value); //console.log('boulder'); //boulder_text = this.game.add.text(15, 15, boulder.value, {font: '40px kenvector_future', fill: '#fff', align: 'center'}); }, /*reset: function() { this.zcar.x = 337; this.started = false; this.boul...
random_line_split
app.js
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var offsetX = document.getElementById('canvas').offsetLeft; var offsetY = document.getElementById('canvas').offsetTop; var xPadding = 50; var yPadding = 50; var canvasWidth = 600; var canvasHeight = 600; canvas.style.width = '100%'; ...
function handleMouseOut(e) { if (!flagPin) { handleMouseUp(e); } } function handleMouseMove(e) { if (!flagPin) { if (draggingResizer > -1) { mouseX = parseInt(e.clientX - document.getElementById('canvas').offsetLeft)*canvas.width/canvas.clientWidth; mouseY = pars...
{ if (!flagPin) { draggingResizer = -1; draggingImage = false; draw(true, false); } }
identifier_body
app.js
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var offsetX = document.getElementById('canvas').offsetLeft; var offsetY = document.getElementById('canvas').offsetTop; var xPadding = 50; var yPadding = 50; var canvasWidth = 600; var canvasHeight = 600; canvas.style.width = '100%'; ...
// bottom-left dx = x - canvas2realX(imageX); dy = y - canvas2realY(imageBottom); if (dx * dx + dy * dy <= rr) { return (3); } return (-1); } function hitImage(x, y) { return (x > canvas2realX(imageX) && x < canvas2realX(imageX + imageWidth) && y > canvas2realY(imageY) && y < canva...
{ return (2); }
conditional_block
app.js
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var offsetX = document.getElementById('canvas').offsetLeft; var offsetY = document.getElementById('canvas').offsetTop; var xPadding = 50; var yPadding = 50; var canvasWidth = 600; var canvasHeight = 600; canvas.style.width = '100%'; ...
}; reader.readAsDataURL(file); } } evt.preventDefault(); }, false); updateAxis(); addTable(); function togglePin() { if (flagPin) { document.getElementById('idButtonPin').innerHTML = 'Start pinning'; flagPin = false; } else { document.getElementB...
random_line_split
app.js
var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var offsetX = document.getElementById('canvas').offsetLeft; var offsetY = document.getElementById('canvas').offsetTop; var xPadding = 50; var yPadding = 50; var canvasWidth = 600; var canvasHeight = 600; canvas.style.width = '100%'; ...
(withAnchors, withBorders) { // clear the canvas ctx.clearRect(0, 0, canvas.width, canvas.height); updateAxis(); // draw the image ctx.globalAlpha = 0.4; ctx.drawImage(imagDrop, 0, 0, imagDrop.width, imagDrop.height, imageX, imageY, imageWidth, imageHeight); // optionally draw the dragga...
draw
identifier_name
Z_normal_8_2.py
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt,mpld3 from collections import defaultdict from sklearn.metrics.pairwise import euclidean_distances from flask import Flask, render_template, request import math import itertools """------------- Intiali...
num+=chunk_size words.append(zlp) indices.append(curr_count) curr_count=curr_count+skip_offset-1 temp_list=[] temp_list.append(sub_section) temp_df = pd.DataFrame(temp_list) temp_df.insert(loc=0, column='keys', value=zlp) temp...
for j in range(0,word_lenth): chunk = sub_section[num:num + chunk_size] curr_word=alphabetize_ts(chunk) zlp+=str(curr_word) complete_indices.append(curr_count)
random_line_split
Z_normal_8_2.py
# -*- coding: utf-8 -*- import numpy as np import pandas as pd import matplotlib.pyplot as plt,mpld3 from collections import defaultdict from sklearn.metrics.pairwise import euclidean_distances from flask import Flask, render_template, request import math import itertools """------------- Intiali...
else: raise ValueError('A wrong idx value supplied.') def normalize(x): X = np.asanyarray(x) if np.nanstd(X) < epsilon: res = [] for entry in X: if not np.isnan(entry): res.append(0) else: ...
return chr(97 + idx)
conditional_block