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
utpgo.go
return c.baseConn.Close() }() // wait for socket to enter StateDestroying <-c.baseConnDestroyed c.setEncounteredError(net.ErrClosed) socketCloseErr := c.utpSocket.Close() // even if err was already set, this one is likely to be more helpful/interesting. if socketCloseErr != nil { err = socketCloseErr } ...
close(c.connectChan) } }
random_line_split
utpgo.go
error) { s := utpDialState{ logger: &noopLogger, } for _, opt := range options { opt.apply(&s) } switch network { case "utp", "utp4", "utp6": default: return nil, fmt.Errorf("network %s not supported", network) } udpAddr, err := ResolveUTPAddr(network, addr) if err != nil { return nil, err } listen...
func (c *Conn) WriteContext(ctx context.Context, buf []byte) (n int, err error) { c.stateLock.Lock() if c.writePending { c.stateLock.Unlock() return 0, buffers.WriterAlreadyWaitingErr } c.writePending = true deadline := c.writeDeadline c.stateLock.Unlock() if err != nil { if err == io.EOF { // remote s...
return c.WriteContext(context.Background(), buf) }
identifier_body
chain_spec.rs
NDb1JRwaHHVWyP9 hex!["f26cdb14b5aec7b2789fd5ca80f979cef3761897ae1f37ffb3e154cbcc1c2663"].into(), // 5EPQdAQ39WQNLCRjWsCk5jErsCitHiY5ZmjfWzzbXDoAoYbn hex!["66bc1e5d275da50b72b15de072a2468a5ad414919ca9054d2695767cf650012f"].into(), // 5DMa31Hd5u1dwoRKgC4uvqyrdK45RHv3CpwvpUC1EzuwDit4 hex!["3919132b851e...
{ fn icefrog_config_genesis() -> GenesisConfig { darwinia_genesis( vec![ get_authority_keys_from_seed("Alice"), get_authority_keys_from_seed("Bob"), ], hex!["a60837b2782f7ffd23e95cd26d1aa8d493b8badc6636234ccd44db03c41fcc6c"].into(), // 5FpQFHfKd1xQ9HLZLQoG1JAQSCJoUEVBELnKsKNcuRLZejJR vec![ he...
identifier_body
chain_spec.rs
; const RING_ENDOWMENT: Balance = 20_000_000 * COIN; const KTON_ENDOWMENT: Balance = 10 * COIN; const STASH: Balance = 1000 * COIN; GenesisConfig { frame_system: Some(SystemConfig { code: WASM_BINARY.to_vec(), changes_trie_config: Default::default(), }), pallet_indices: Some(IndicesConfig { ids: en...
{ vec![initial_authorities[0].clone().1, initial_authorities[1].clone().1] }
conditional_block
chain_spec.rs
(Default::default()), // pallet_treasury: Some(Default::default()), pallet_ring: Some(BalancesConfig { balances: endowed_accounts .iter() .cloned() .map(|k| (k, RING_ENDOWMENT)) .chain(initial_authorities.iter().map(|x| (x.0.clone(), STASH))) .collect(), vesting: vec![], }), pallet_kt...
stakers: initial_authorities .iter() .map(|x| (x.0.clone(), x.1.clone(), STASH, StakerStatus::Validator)) .collect(), invulnerables: initial_authorities.iter().map(|x| x.0.clone()).collect(), slash_reward_fraction: Perbill::from_percent(10), ..Default::default() }), } } /// Staging testnet c...
pallet_staking: Some(StakingConfig { current_era: 0, validator_count: initial_authorities.len() as u32 * 2, minimum_validator_count: initial_authorities.len() as u32,
random_line_split
chain_spec.rs
1L1LU9jaNeeu9HJkP6eyg3BwXA7iNMzKm7qqruQ hex!["482dbd7297a39fa145c570552249c2ca9dd47e281f0c500c971b59c9dcdcd82e"].unchecked_into(), ), ( // 5DyVtKWPidondEu8iHZgi6Ffv9yrJJ1NDNLom3X9cTDi98qp hex!["547ff0ab649283a7ae01dbc2eb73932eba2fb09075e9485ff369082a2ff38d65"].into(), // 5FeD54vGVNpFX3PndHPXJ2MDak...
icefrog_config_genesis
identifier_name
mnist_benchmark.py
us """ GCP_ENV = 'PATH=/tmp/pkb/google-cloud-sdk/bin:$PATH' flags.DEFINE_string('mnist_data_dir', None, 'mnist train file for tensorflow') flags.DEFINE_string('imagenet_data_dir', 'gs://cloud-tpu-test-datasets/fake_imagenet', 'Directory where the input data is stored') flags.DEF...
return samples def MakeSamplesFromEvalOutput(metadata, output, elapsed_seconds): """Create a sample containing evaluation metrics. Args: metadata: dict contains all the metadata that reports. output: string, command output elapsed_seconds: float, elapsed seconds from saved checkpoint. Example o...
global_step_sec = get_mean(regex_util.ExtractAllMatches( r'global_step/sec: (\S+)', output)) samples.append(sample.Sample( 'Global Steps Per Second', global_step_sec, 'global_steps/sec', metadata_copy)) examples_sec = global_step_sec * metadata['train_batch_size'] if 'examples/sec: '...
conditional_block
mnist_benchmark.py
eastus """ GCP_ENV = 'PATH=/tmp/pkb/google-cloud-sdk/bin:$PATH' flags.DEFINE_string('mnist_data_dir', None, 'mnist train file for tensorflow') flags.DEFINE_string('imagenet_data_dir', 'gs://cloud-tpu-test-datasets/fake_imagenet', 'Directory where the input data is stored') flag...
metadata_with_index = copy.deepcopy(metadata) metadata_with_index['index'] = index samples.append(sample.Sample(metric, float(value), unit, metadata_with_index)) return samples def MakeSamplesFromTrainOutput(metadata, output, elapsed_seconds, step): """Create a sample ...
""" matches = regex_util.ExtractAllMatches(regex, output) samples = [] for index, value in enumerate(matches):
random_line_split
mnist_benchmark.py
eastus """ GCP_ENV = 'PATH=/tmp/pkb/google-cloud-sdk/bin:$PATH' flags.DEFINE_string('mnist_data_dir', None, 'mnist train file for tensorflow') flags.DEFINE_string('imagenet_data_dir', 'gs://cloud-tpu-test-datasets/fake_imagenet', 'Directory where the input data is stored') flag...
(benchmark_spec): """Update the benchmark_spec with supplied command line flags. Args: benchmark_spec: benchmark specification to update """ benchmark_spec.data_dir = FLAGS.mnist_data_dir benchmark_spec.iterations = FLAGS.tpu_iterations benchmark_spec.gcp_service_account = FLAGS.gcp_service_account b...
_UpdateBenchmarkSpecWithFlags
identifier_name
mnist_benchmark.py
eastus """ GCP_ENV = 'PATH=/tmp/pkb/google-cloud-sdk/bin:$PATH' flags.DEFINE_string('mnist_data_dir', None, 'mnist train file for tensorflow') flags.DEFINE_string('imagenet_data_dir', 'gs://cloud-tpu-test-datasets/fake_imagenet', 'Directory where the input data is stored') flag...
metadata_copy['epoch'] = step / num_examples_per_epoch metadata_copy['elapsed_seconds'] = elapsed_seconds return [sample.Sample('Eval Loss', float(loss), '', metadata_copy), sample.Sample('Accuracy', float(accuracy) * 100, '%', metadata_copy)] def Run(benchmark_spec): """Run MNIST on the cluster. ...
"""Create a sample containing evaluation metrics. Args: metadata: dict contains all the metadata that reports. output: string, command output elapsed_seconds: float, elapsed seconds from saved checkpoint. Example output: perfkitbenchmarker/tests/linux_benchmarks/mnist_benchmark_test.py Returns:...
identifier_body
ext.rs
_len: u32, result_ptr: *mut u8, result_len: u32, ) -> i32; /// Static call. /// Corresponds to "STACICCALL" opcode in EVM pub fn scall( gas: i64, address: *const u8, input_ptr: *const u8, input_len: u32, ...
/// Get the block's timestamp /// /// It can be viewed as an output of Unix's `time()` function at /// current block's inception. pub fn timestamp() -> u64 { unsafe { external::timestamp() as u64 } } /// Get the block's number /// /// This value represents number of ancestor blocks. /// The genesis block has a num...
unsafe { fetch_address(|x| external::coinbase(x) ) } }
identifier_body
ext.rs
_len: u32, result_ptr: *mut u8, result_len: u32, ) -> i32; /// Static call. /// Corresponds to "STACICCALL" opcode in EVM pub fn scall( gas: i64, address: *const u8, input_ptr: *const u8, input_len: u32, ...
else { Err(Error) } } } /// Returns hash of the given block or H256::zero() /// /// Only works for 256 most recent blocks excluding current /// Returns H256::zero() in case of failure pub fn block_hash(block_number: u64) -> H256 { let mut res = H256::zero(); unsafe { external::...
{ Ok(()) }
conditional_block
ext.rs
_len: u32, result_ptr: *mut u8, result_len: u32, ) -> i32; /// Static call. /// Corresponds to "STACICCALL" opcode in EVM pub fn scall( gas: i64, address: *const u8, input_ptr: *const u8, input_len: u32, ...
if external::create( endowment_arr.as_ptr(), code.as_ptr(), code.len() as u32, (&mut result).as_mut_ptr() ) == 0 { Ok(result) } else { Err(Error) } } } #[cfg(feature = "kip4")] /// Create a new account with the ...
random_line_split
ext.rs
_len: u32, result_ptr: *mut u8, result_len: u32, ) -> i32; /// Static call. /// Corresponds to "STACICCALL" opcode in EVM pub fn scall( gas: i64, address: *const u8, input_ptr: *const u8, input_len: u32, ...
-> u64 { unsafe { external::blocknumber() as u64 } } /// Get the block's difficulty. pub fn difficulty() -> U256 { unsafe { fetch_u256(|x| external::difficulty(x) ) } } /// Get the block's gas limit. pub fn gas_limit() -> U256 { unsafe { fetch_u256(|x| external::gaslimit(x) ) } } #[cfg(feature = "kip6")...
ock_number()
identifier_name
networking.py
self.listen_thread.start() def listen(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("", self.port)) s.listen(1) while True: try: clientsock, clientaddr = s.accept() ...
(self): w = Writer() w.single("H", self.dmo_id) w.string(self.image_name) w.single("HH", *self.position) w.single("B", (self.hidden << 0) + (self.obstruction << 1)) w.string(self.minimapimage) return w.data.getvalue() @classmethod def from_stream(cls, stre...
pack
identifier_name
networking.py
self.listen_thread.start() def listen(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("", self.port)) s.listen(1) while True: try: clientsock, clientaddr = s.accept() ...
type_id = 116 # TODO class MResourceQuantity(Message): type_id = 117 struct_format = "!hhh" attrs = ("tx", "ty", "q") # Player/connection stuff class MNewPlayer(Message): type_id = 120 attrs = ("player_id", "name", "color", "loading") def pack(self): w = Writer() w.s...
type_id = 115 struct_format = "!HB" attrs = ("dmo_id", "hidden") class MDMOPosition(Message):
random_line_split
networking.py
self.listen_thread.start() def listen(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("", self.port)) s.listen(1) while True: try: clientsock, clientaddr = s.accept() ...
self.data.write(struct.pack(format, *values)) def multi(self, format, values): self.single("!H", len(values)) if len(format.strip("@=<>!")) > 1: for v in values: self.single(format, *v) else: for v in values: self.single(forma...
format = "!"+format
conditional_block
networking.py
self.listen_thread.start() def listen(self): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind(("", self.port)) s.listen(1) while True: try: clientsock, clientaddr = s.accept() ...
def values(self): l = [] for a in self.attrs: l.append(getattr(self, a)) return l @classmethod def from_stream(cls, stream): res = struct.unpack(cls.struct_format, stream.read(struct.calcsize(cls.struct_format))) return cls(*res) de...
attrs = list(self.attrs) for arg in pargs: n = attrs.pop(0) setattr(self, n, arg) for n in attrs: setattr(self, n, kwargs.pop(n)) if kwargs: raise TypeError("unexpected keyword argument '%s'" % kwargs.keys()[0])
identifier_body
async_await_basics.rs
}); // Drop the spawner so that our executor knows it is finished and won't // receive more incoming tasks to run. drop(spawner); // Run the executor until the task queue is empty. // This will print "howdy!", pause, and then print "done!". executor.run(); } struct Song { name: String...
{ shared_state: Arc<Mutex<SharedState>>, } /// Shared state between the future and the waiting thread struct SharedState { /// Whether or not the sleep time has elapsed completed: bool, /// The waker for the task that `TimerFuture` is running on. /// The thread can use this after setting `complet...
TimerFuture
identifier_name
async_await_basics.rs
!"); }); // Drop the spawner so that our executor knows it is finished and won't // receive more incoming tasks to run. drop(spawner); // Run the executor until the task queue is empty. // This will print "howdy!", pause, and then print "done!". executor.run(); } struct Song { name: S...
// function, but we omit that here to keep things simple. shared_state.waker = Some(cx.waker().clone()); Poll::Pending } } } impl TimerFuture { /// Create a new `TimerFuture` which will complete after the provided /// timeout. pub fn new(duration: Duration) -...
// // N.B. it's possible to check for this using the `Waker::will_wake`
random_line_split
async_await_basics.rs
}); // Drop the spawner so that our executor knows it is finished and won't // receive more incoming tasks to run. drop(spawner); // Run the executor until the task queue is empty. // This will print "howdy!", pause, and then print "done!". executor.run(); } struct Song { name: String...
async fn learn_and_sing() { let song = learn_song().await; sing_song(song).await; } async fn async_main() { let f2 = dance(); let f1 = learn_and_sing(); futures::join!(f2, f1); } // Each time a future is polled, it is polled as part of a "task". Tasks are the top-level futures // that have been...
{ println!("Dance!!") }
identifier_body
async_await_basics.rs
}); // Drop the spawner so that our executor knows it is finished and won't // receive more incoming tasks to run. drop(spawner); // Run the executor until the task queue is empty. // This will print "howdy!", pause, and then print "done!". executor.run(); } struct Song { name: String...
} } } } // In practice, this problem is solved through integration with an IO-aware system blocking primitive, // such as epoll on Linux, kqueue on FreeBSD and Mac OS, IOCP on Windows, and ports on Fuchsia (all // of which are exposed through the cross-platform Rust crate mio). These primitive...
{ // We're not done processing the future, so put it // back in its task to be run again in the future. *future_slot = Some(future); }
conditional_block
controller.py
knekkes, samt rom det skal søkes i, (muligens størrelse på hver enkelt arbeidoppgave?) og eventuell hashing-algoritme. Fordeler arbeidoppgaver ved å motta en forespørsel, og sender ut "Kode", tegn, arbeidsnodens søkerom, samt hashing-algoritme. Tar inn resultater (enten svar, eller beskjed om at koden ikke er i ...
int, end_point, keyword, chars, searchwidth, algorithm, id): self.start_point = start_point # Where to start searching self.end_point = end_point # Where to end the search self.keyword = keyword # What you're searching for self.chars = chars # Characters t...
start_po
identifier_name
controller.py
ommet den ble gitt), og slutter å dele ut oppgaver basert på den koden om den er funnet (returnerer svar til den som sendte dette inn). All kommunikasjon skal foregå via JSON api-kall """ #Webserver from http.server import HTTPServer, BaseHTTPRequestHandler from io import BytesIO #Other needed packages impor...
conditional_block
controller.py
knekkes, samt rom det skal søkes i, (muligens størrelse på hver enkelt arbeidoppgave?) og eventuell hashing-algoritme. Fordeler arbeidoppgaver ved å motta en forespørsel, og sender ut "Kode", tegn, arbeidsnodens søkerom, samt hashing-algoritme. Tar inn resultater (enten svar, eller beskjed om at koden ikke er i ...
k_id(tasks): task_id_unique = False temp_id = floor(random()*10000) while not task_id_unique: task_id_unique = True temp_id = floor(random()*10000) for task in tasks: if task.id == temp_id: task_id_unique = False return temp_id class Task: ...
ps(get_next_job()) def gen_tas
identifier_body
controller.py
skal knekkes, samt rom det skal søkes i, (muligens størrelse på hver enkelt arbeidoppgave?) og eventuell hashing-algoritme. Fordeler arbeidoppgaver ved å motta en forespørsel, og sender ut "Kode", tegn, arbeidsnodens søkerom, samt hashing-algoritme. Tar inn resultater (enten svar, eller beskjed om at koden ikke ...
self.current_point = self.start_point # Will be increased as workers are given blocks to search through self.finished = False self.keyword_found = "" def get_task(self): return { 'id':self.id, 'finished':self.finished, 'algorithm':self.a...
random_line_split
main.rs
ClassStruct<Self>; glib_object_subclass!(); fn new() -> Self { Self { widgets: OnceCell::new(), counter: Cell::new(0), } } } static MUSIC_FOLDER: &str = "musics"; impl ObjectImpl for SimpleWindowPrivate { glib_object_impl!(); // Here we are overriding the ...
{ glib::Object::new( Self::static_type(), &[ ("application-id", &"org.gtk-rs.SimpleApplication"), ("flags", &ApplicationFlags::empty()), ], ) .expect("Failed to create SimpleApp") .downcast() .expect("Created sim...
identifier_body
main.rs
use gio::subclass::application::ApplicationImplExt; use gio::ApplicationFlags; use glib::subclass; use glib::subclass::prelude::*; use glib::translate::*; use gtk::subclass::prelude::*; use once_cell::unsync::OnceCell; use std::cell::Cell; mod audio_handler; #[derive(Debug)] struct WindowWidgets { headerbar: gtk...
audio_player_clone.pause_music(); }); // Connect our method `on_increment_clicked` to be called // when the increment button is clicked. increment.connect_clicked(clone!(@weak self_ => move |_| { let priv_ = SimpleWindowPrivate::from_instance(&self_); ...
pause_button.connect_clicked(move |_| {
random_line_split
main.rs
use gio::subclass::application::ApplicationImplExt; use gio::ApplicationFlags; use glib::subclass; use glib::subclass::prelude::*; use glib::translate::*; use gtk::subclass::prelude::*; use once_cell::unsync::OnceCell; use std::cell::Cell; mod audio_handler; #[derive(Debug)] struct WindowWidgets { headerbar: gtk...
(&self) { self.counter.set(self.counter.get() + 1); let w = self.widgets.get().unwrap(); w.label .set_text(&format!("Your life has {} meaning", self.counter.get())); } fn on_decrement_clicked(&self) { self.counter.set(self.counter.get().wrapping_sub(1)); let w...
on_increment_clicked
identifier_name
configfunction.js
34\u503C\u4E0D\u80FD\u4E3A\u7A7A\u3002<br>"; }else{ var obj={attributeName:texts[0].split(":")[1],attributeCode:texts[1].split(":")[1],attributeType:texts[2].split(":")[1],lstConfigValueVO:[]}; jsonHead.push(obj); } }else{ msg+="\u6570\u636E\u503C\u533A\u57DF\u7B2C"+(i+1)+"\u5217\u9898\u5934\u5...
eBorder(obj){
identifier_name
configfunction.js
10)>30){ //return "值为'"+data+"'的日期类型数据"+parseInt(dateArray[1],10)+"月份天数不能超过30天。<br>"; return "\u503C\u4E3A'"+data+"'\u7684\u65E5\u671F\u7C7B\u578B\u6570\u636E"+parseInt(dateArray[1],10)+"\u6708\u4EFD\u5929\u6570\u4E0D\u80FD\u8D85\u8FC7\u0033\u0030\u5929\u3002<br>"; } }else{ if(parseInt(dateArray[2]...
if(td){
random_line_split
configfunction.js
\u6708\u4EFD\u5929\u6570\u4E0D\u80FD\u4E3A\u0030\u5929\u3002<br>"; } } //}else if(types=="4"||types=="布尔型"){ }else if(types=="4"||types=="\u5E03\u5C14\u578B"){ if(data!="true" && data!="false" && data!="TRUE" && data!="FALSE"){ //return "类型为布尔型的数据值必须为布尔型。如 true/false<br>"; return "\u7C7B\u578B\u4E3A\u5E0...
eDataRegexInfo; } flag = false; //只有值不为空时才进行验证 //验证输入的值是否合法 var attributeType = trimSpace(jsonHead[j-1].attributeType); var vInfo = validationData(attributeType,trimSpace(tempValues)); if(vInfo!=""){ //msg += "数据值区域第"+i+"行,第"+(j+1)+"列"+vInfo; msg += "\u6570\u636E\u503C\u53...
conditional_block
configfunction.js
C\u4E0D\u80FD\u4E3A\u7A7A\u3002<br>"; }else{ var obj={attributeName:texts[0].split(":")[1],attributeCode:texts[1].split(":")[1],attributeType:texts[2].split(":")[1],lstConfigValueVO:[]}; jsonHead.push(obj); } }else{ msg+="\u6570\u636E\u503C\u533A\u57DF\u7B2C"+(i+1)+"\u5217\u9898\u5934\u503C\u4E...
identifier_body
lstm.py
00000) # df.head() # print(df.shape) df_filtered=df[df['stars'] !=3] # print(df_filtered.shape) #print(df_filtered.describe().T) text=list(df_filtered['text']) stars=list(df_filtered['stars']) print(type(text)) label=[] for item in stars: if item>= 4: y=1 else: y=0 label.append(y) label...
(self, x, hidden): """ Perform a forward pass of our model on some input and hidden state. """ batch_size = x.size(0) # embeddings and lstm_out embeds = self.embedding(x) lstm_out, hidden = self.lstm(embeds, hidden) # stack up lstm outputs ...
forward
identifier_name
lstm.py
100000) # df.head() # print(df.shape) df_filtered=df[df['stars'] !=3] # print(df_filtered.shape) #print(df_filtered.describe().T) text=list(df_filtered['text']) stars=list(df_filtered['stars']) print(type(text)) label=[] for item in stars: if item>= 4: y=1 else: y=0 label.append(y) labe...
output, h = net(inputs, h) # calculate the loss and perform backprop loss = criterion(output.squeeze(), labels.float()) loss.backward() # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. nn.utils.clip_grad_norm_(net.parameters(), cl...
h = net.init_hidden(batch_size, train_on_gpu) counter = 0 # batch loop for inputs, labels in train_loader: counter += 1 #print('epoce: {e}, batch: {b}'.format(e=e, b=counter)) if (labels.shape[0] != batch_size): continue inputs = inputs.type(torch.LongTensor) ...
conditional_block
lstm.py
00000) # df.head() # print(df.shape) df_filtered=df[df['stars'] !=3] # print(df_filtered.shape) #print(df_filtered.describe().T) text=list(df_filtered['text']) stars=list(df_filtered['stars']) print(type(text)) label=[] for item in stars: if item>= 4: y=1 else: y=0 label.append(y) label...
def forward(self, x, hidden): """ Perform a forward pass of our model on some input and hidden state. """ batch_size = x.size(0) # embeddings and lstm_out embeds = self.embedding(x) lstm_out, hidden = self.lstm(embeds, hidden) # stack up lst...
""" Initialize the model by setting up the layers. """ super(SentimentRNN, self).__init__() self.output_size = output_size self.n_layers = n_layers self.hidden_dim = hidden_dim # embedding and LSTM layers self.embedding = nn.Embedding(vocab_size,...
identifier_body
lstm.py
00000) # df.head() # print(df.shape) df_filtered=df[df['stars'] !=3] # print(df_filtered.shape) #print(df_filtered.describe().T)
print(type(text)) label=[] for item in stars: if item>= 4: y=1 else: y=0 label.append(y) label=np.array(label) #we can get punctuation from string library from string import punctuation print(punctuation) all_reviews=[] for item in text: item = item.lower() item = "".join([ch for ch in...
text=list(df_filtered['text']) stars=list(df_filtered['stars'])
random_line_split
Master Solution.py
processing and data analysis). Please comment your code appropriately. You will be evaluated for properly structuring your code and for building checks and balances in your analysis- which should be included in your code as well.* # # *2. If some data visualization tool such as Tableau/PowerBI is used for presentati...
(data): #convert text to lower-case data['processed_text'] = data['Query Text'].apply(lambda x:' '.join(x.lower() for x in x.split())) #remove punctuations, unwanted characters data['processed_text_1']= data['processed_text'].apply(lambda x: "".join([char for char in x if char not in string.punctu...
text_preprocessing
identifier_name
Master Solution.py
data processing and data analysis). Please comment your code appropriately. You will be evaluated for properly structuring your code and for building checks and balances in your analysis- which should be included in your code as well.* # # *2. If some data visualization tool such as Tableau/PowerBI is used for prese...
# In[9]: df.isnull().sum() # In[10]: df.drop_duplicates(subset ="Query Text", keep = 'last', inplace = True) # In[11]: df.info() # In[12]: # check the length of documents document_lengths = np.array(list(map(len, df['Query Text'].str.split(' ')))) print("The average number of wor...
random_line_split
Master Solution.py
processing and data analysis). Please comment your code appropriately. You will be evaluated for properly structuring your code and for building checks and balances in your analysis- which should be included in your code as well.* # # *2. If some data visualization tool such as Tableau/PowerBI is used for presentati...
# In[15]: #pre-processing or cleaning data text_preprocessing(df) df.head() # In[16]: #create tokenized data for LDA df['final_tokenized'] = list(map(nltk.word_tokenize, df.final_text)) df.head() # ## LDA training # In[17]: # Create Dictionary id2word = corpora.Dictionary(df['final_tokenized']) tex...
data['processed_text'] = data['Query Text'].apply(lambda x:' '.join(x.lower() for x in x.split())) #remove punctuations, unwanted characters data['processed_text_1']= data['processed_text'].apply(lambda x: "".join([char for char in x if char not in string.punctuation])) #remove numbers data['processed...
identifier_body
Master Solution.py
: {}.".format(min(document_lengths))) print("The maximum number of words in a document is: {}.".format(max(document_lengths))) # In[13]: print("There are {} documents with tops 5 words.".format(sum(document_lengths == 1))) print("There are {} documents with tops 5 words.".format(sum(document_lengths == 2))) print("...
nt.label_) ent_common.append(ent.text) print("U
conditional_block
helpers.go
updated string // with replaced coordinates and the list of coordinates func ExtractCoordinates(text string) (string, Coordinates) { var ( // <a href="geo:49.976136, 36.267256">49.976136, 36.267256</a> geoHrefRe = regexp.MustCompile("<a.+?href=\"geo:(\\d{2}[.,]\\d{3,}),?\\s*(\\d{2}[.,]\\d{3,})\">(.+?)</a>") // ...
if mrHr := reHr.FindAllStringSubmatch(res, -1); len(mrHr) > 0 { for _, item := range mrHr { res = regexp.MustCompile(item[0]).ReplaceAllLiteralString(res, "\n") } } if mrP := reP.FindAllStringSubmatch(res, -1); len(mrP) > 0 { for _, item := range mrP { res = regexp.MustCompile(regexp.QuoteMeta(item[0])). ...
for _, item := range mrBr { res = regexp.MustCompile(item[0]).ReplaceAllLiteralString(res, "\n") } }
conditional_block
helpers.go
updated string // with replaced coordinates and the list of coordinates func ExtractCoordinates(text string) (string, Coordinates) { var ( // <a href="geo:49.976136, 36.267256">49.976136, 36.267256</a> geoHrefRe = regexp.MustCompile("<a.+?href=\"geo:(\\d{2}[.,]\\d{3,}),?\\s*(\\d{2}[.,]\\d{3,})\">(.+?)</a>") // ...
// scripts in the task. To skip tag, it is necessary to call Next() two times: // 1) returns TextToken with the script body // 2) returns EndTagToken for the closed script tag // Usually script tag doesn't have any neste tags, so this aproach should work log.Printf("[INFO] Skipping script tag") ...
{ var ( parser = html.NewTokenizer(strings.NewReader(text)) tagStack = stack.New() textToTag = map[int]string{} ) for { node := parser.Next() switch node { case html.ErrorToken: result := strings.Replace(textToTag[0], "&nbsp;", " ", -1) return result case html.TextToken: t := string(parse...
identifier_body
helpers.go
updated string // with replaced coordinates and the list of coordinates func ExtractCoordinates(text string) (string, Coordinates) { var ( // <a href="geo:49.976136, 36.267256">49.976136, 36.267256</a> geoHrefRe = regexp.MustCompile("<a.+?href=\"geo:(\\d{2}[.,]\\d{3,}),?\\s*(\\d{2}[.,]\\d{3,})\">(.+?)</a>") // ...
reCenter = regexp.MustCompile("<center>((?s:.*?))</center>") reFont = regexp.MustCompile("<font.+?color\\s*=\\\\?[\"«]?#?(\\w+)\\\\?[\"»]?.*?>((?s:.*?))</font>") reA = regexp.MustCompile("<a.+?href=\\\\?\"(.+?)\\\\?\".*?>(.+?)</a>") res = text ) res = strings.Replace(text, "_", "\\_", -1) if mrB...
reStrong = regexp.MustCompile("<strong.*?>(.*?)</strong>") reItalic = regexp.MustCompile("<i>((?s:.+?))</i>") reSpan = regexp.MustCompile("<span.*?>(.*?)</span>")
random_line_split
helpers.go
(text string, re *regexp.Regexp) (string, Coordinates) { var ( result = text mr = re.FindAllStringSubmatch(text, -1) coords = Coordinates{} ) if len(mr) > 0 { for _, item := range mr { lon, _ := strconv.ParseFloat(item[1], 64) lat, _ := strconv.ParseFloat(item[2], 64) if len(item) > 3 { coor...
extractCoordinates
identifier_name
trainPredictor.py
pathjoin = os.path.join pathexists = os.path.exists mdy = dtime.datetime.now().strftime('%m%d%y') product_type = 'interferogram' cache_dir = 'cached' train_folds = np.inf # inf = leave-one-out, otherwise k-fold cross validation train_state = 42 # random seed train_verbose = 0 train_jobs = -1 cv_type...
print(process,exitv,message)
identifier_body
trainPredictor.py
ProductMeta(prod_url,verbose=False,remove=True): """ curlProductMeta(prod_url,verbose=False) Arguments: - prod_url: product url Keyword Arguments: - verbose: verbose output (default=False) Returns: metadata dict from product .met.json """ if prod_url.endswith...
(usertags,classmap): ''' return dictionary of matched (tag,label) pairs in classmap for all tags returns {} if none of the tags are present in classmap ''' labelmap = {} for tag in usertags: tag = tag.strip() for k,v in list(classmap.items()): if tag.count(k): ...
usertags2label
identifier_name
trainPredictor.py
search query...') from utils.queryBuilder import postQuery, buildQuery from utils.contextUtils import toContext ret,status = postQuery(buildQuery(querymeta,queryoptions)) if cache and status: # only dump the query if caching enabled and postQuery succeeds with op...
model_clf = RandomForestClassifier(**rf_defaults) model_tuned = [rf_tuned]
conditional_block
trainPredictor.py
return url.replace(product_type,'features').replace('features__','features_'+product_type+'__') def fdict2vec(featdict,clfinputs): ''' extract feature vector from dict given classifier parameters specifying which features to use ''' fvec = [] try: featspec = clfinputs['feature...
- feature id for url """
random_line_split
photcalibration.py
::-1] ps1colorterms['i'] = [+0.01170, -0.00400, +0.00066, -0.00058][::-1] ps1colorterms['z'] = [-0.01062, +0.07529, -0.03592, +0.00890][::-1] def __init__(self, basedir): self.basedir = basedir self.skytable = None def PS1toSDSS(self, table): """ Modify table in situ fr...
search = "%s/*-[es][19]1.fits.fz" % (directory) inputlist = glob.glob(search) initialsize = len (inputlist) rejects = [] if not args.redo: for image in inputlist: if db.exists(image): rejects.append (image) for r in rejects: inputlist.remove (r)...
identifier_body
photcalibration.py
, 'defaultZP': 0.0} FILTERMAPPING['rp'] = {'refMag': 'r', 'colorTerm': 0.0, 'airmassTerm': 0.12, 'defaultZP': 0.0} FILTERMAPPING['ip'] = {'refMag': 'i', 'colorTerm': 0.0, 'airmassTerm': 0.08, 'defaultZP': 0.0} FILTERMAPPING['zp'] = {'refMag': 'z', 'colorTerm': 0.0, 'airmassTerm': 0.05, 'defaultZP': 0.0} ...
cat_ra_shifted[cat_ra > 180] -= 360
conditional_block
photcalibration.py
'] = [-0.01062, +0.07529, -0.03592, +0.00890][::-1] def __init__(self, basedir): self.basedir = basedir self.skytable = None def PS1toSDSS(self, table): """ Modify table in situ from PS1 to SDSS, requires column names compatible with ps1colorterms definition. :param ta...
:param site: :param camera:
random_line_split
photcalibration.py
only from the input catalog. ## Why reverse the order of the color term entries? Data are entered in the order as they are ## shown in paper. Reverse after the fact to avoid confusion when looking at paper ps1colorterms = {} ps1colorterms['g'] = [-0.01808, -0.13595, +0.01941, -0.00183][::-1] ps1c...
crawlDirectory
identifier_name
genetic.py
states if DEBUG: print(gene_pool) counter = 0
flips = 0 while counter < GIVE_UP: if rand_restarts and counter>0 and not (counter % restart): # random restarts if not tb: print("restarting: (" + str(new_vals[0]) + "/" + str(NUM_CLAUSES) + ")") initialize_states(gene_pool, gene_pool[0]) if not tb: print("iteration", ...
restart = int(tries/5)
random_line_split
genetic.py
states if DEBUG: print(gene_pool) counter = 0 restart = int(tries/5) flips = 0 while counter < GIVE_UP: if rand_restarts and counter>0 and not (counter % restart): # random restarts if not tb: print("restarting: (" + str(new_vals[0]) + "/" + str(NUM_CLAUSES) + ")") ...
# not currently using def flip_heuristic(safe, new_pool, evaluations): for i in range(safe, POOL_SIZE): flipped = flip_bits(new_pool[i]) value = evaluate(flipped) if value >= evaluations[i]: evaluations[i] = value new_pool[i] = flipped def flip_bits(string): n...
new_str = string[:index] + ("1" if string[index]=="0" else "0") + string[(index+1):] new_eval = evaluate(new_str) if new_eval > evaluation: return (new_str, new_eval) return (None, None)
identifier_body
genetic.py
(NUM_CLAUSES) +") clauses.") return (0, flips) counter += 1 if not tb: # test bench print(">> GAVE UP after " + str(GIVE_UP) + " tries.") print(">> Current Best:", readable(gene_pool[0])) print(">> Satisfied (" + str(new_vals[0]) + "/" + str(NUM_CLAUSES) +") clauses.")...
for j in range(num): res[i][j] = calc_dist(cities[i][1], cities[j][1]) res[j][i] = res[i][j]
conditional_block
genetic.py
if DEBUG: print(gene_pool) counter = 0 restart = int(tries/5) flips = 0 while counter < GIVE_UP: if rand_restarts and counter>0 and not (counter % restart): # random restarts if not tb: print("restarting: (" + str(new_vals[0]) + "/" + str(NUM_CLAUSES) + ")") in...
(safe, new_pool): for i in range(safe, POOL_SIZE): if flip_coin(.9): mutant = "" for j in range(len(new_pool[i])): if flip_coin(): mutant += str(1 - int(new_pool[i][j])) else: mutant += new_pool[i][j] ...
mutate
identifier_name
Data_Exploration.py
l.append(d) # theresult_json = json.dumps(l, default=json_serial) conn.close() return theresult_json @app.route("/api/correlation/<col1>/<col2>") def Correlation(col1, col2): engine = create_engine('postgresql+psycopg2://student:123456@132.249.238.27:5432/bookstore_dp') conn = engi...
c = request.args[item] print (c) d[c] = result[c]
conditional_block
Data_Exploration.py
@app.route("/api/web_method/<format>") def api_web_method(format): engine = create_engine('postgresql+psycopg2://student:123456@132.249.238.27:5432/bookstore_dp') conn = engine.connect() sql = """ select * from orderlines o, products p where o.productid = p.productid LIMIT 10 """ ...
"""JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError ("Type %s not serializable" % type(obj))
identifier_body
Data_Exploration.py
(obj): """JSON serializer for objects not serializable by default json code""" if isinstance(obj, (datetime, date)): return obj.isoformat() raise TypeError ("Type %s not serializable" % type(obj)) @app.route("/api/web_method/<format>") def api_web_method(format): engine = create_engine('postg...
json_serial
identifier_name
Data_Exploration.py
app = Flask(__name__) @app.route("/") def Hello(): return "Hello World!" @app.route('/api/service', methods=['POST']) def api_service(): query = request.get_json(silent=True) # needs to change to reading from xml file xml = VirtualIntegrationSchema() web_session = WebSession(xml) return j...
from json import loads import psycopg2 from sqlalchemy import create_engine, text import pysolr from textblob import TextBlob as tb
random_line_split
ConfiguredResourceUploader.js
= ""; if (parsedResponse.ResultSet.Result.length !== 0) { script = parsedResponse.ResultSet.Result[0].script; //sort of a hack to get this code to work with generic nrg_config return values if(script == undefined ){ script = parsedResponse.ResultSet.Result[0].contents; } this.con...
if(tempConfigs.length>0){ if(value.dontHide){ $(value).color(value.defaultColor); $(value).css('cursor:pointer'); } $(this).click(function(){ XNAT.app.crUploader.show(this); return false; }); $(this).show(); }else{ if(!value.dontHide){ $(this).hid...
var tempConfigs=XNAT.app.crConfigs.getAllConfigsByType(type,props)
random_line_split
ConfiguredResourceUploader.js
script = ""; if (parsedResponse.ResultSet.Result.length !== 0) { script = parsedResponse.ResultSet.Result[0].script; //sort of a hack to get this code to work with generic nrg_config return values if(script == undefined ){ script = parsedResponse.ResultSet.Result[0].contents; } t...
this.dialog.hide(); }, confirm : function (header, msg, handleYes, handleNo) { var dialog = new YAHOO.widget.SimpleDialog('widget_confirm', { visible:false, width: '20em', zIndex: 9998, close: false, fixedcenter: true, modal: true, draggable: true, constraintoviewport: tru...
{ showMessage("page_body","Failed upload.",response.responseText); }
conditional_block
extractdicom.go
(dicomReader, nReaderBytes, nil) if err != nil { return nil, err } parsedData, err := SafelyDicomParse(p, dicom.ParseOptions{ DropPixelData: false, }) if parsedData == nil || err != nil { return nil, fmt.Errorf("Error reading zip: %v", err) } var rescaleSlope, rescaleIntercept, windowWidth, windowCenter...
random_line_split
extractdicom.go
{ imgRows = int(elem.Value[0].(uint16)) } else if elem.Tag == dicomtag.Columns { imgCols = int(elem.Value[0].(uint16)) } // If imgPixels is still uninitialized and we're on a rows or columns // tag, and both rows and columns are populated, initialize imgPixels' // backing array's capacity to the numbe...
{ // 1: StoredValue to ModalityValue var modalityValue float64 if rescaleSlope == 0 { // Via https://dgobbi.github.io/vtk-dicom/doc/api/image_display.html : // For modalities such as ultrasound and MRI that do not have any units, // the RescaleSlope and RescaleIntercept are absent and the Modality // Values ...
identifier_body
extractdicom.go
(zipPath, dicomName string, includeOverlay bool) (image.Image, error) { return ExtractDicomFromGoogleStorage(zipPath, dicomName, includeOverlay, nil) } // ExtractDicomFromZipReader consumes a zip reader of the UK Biobank format, // finds the dicom of the desired name, and returns that image, with or without // the ov...
ExtractDicomFromLocalFile
identifier_name
extractdicom.go
Bit uint16 _, _, _ = bitsAllocated, bitsStored, highBit var nOverlayRows, nOverlayCols int var img *image.Gray16 var imgRows, imgCols int var imgPixels []int var overlayPixels []int for _, elem := range parsedData.Elements { // The typical approach is to extract bitsAllocated, bitsStored, and the highBit ...
{ row := i / nOverlayCols col := i % nOverlayCols if overlayValue != 0 { img.SetGray16(col, row, color.White) } }
conditional_block
lib.rs
when it goes out of scope //! ``` //! Pull from pool and `detach()` //! ``` //! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // returns None when the pool is saturated //! reusable_buff.clear(); // clear the buff before using //! le...
elf.run_block.lock(); log::trace!("attach started<<<<<<<<<<<<<<<<"); log::trace!("recyled an item "); let mut wait_list = { self.waiting.lock() }; log::trace!("check waiting list ok :{}", wait_list.len()); if wait_list.len() > 0 && self.len() >= wait_list[0].min_request { ...
_x = s
identifier_name
lib.rs
when it goes out of scope //! ``` //! Pull from pool and `detach()` //! ``` //! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // returns None when the pool is saturated //! reusable_buff.clear(); // clear the buff before using //! le...
waiting.lock().len() * 60 + 2 }; log::trace!("try again :{} with retries backoff:{}", str, to_retry); for i in 0..to_retry { sleep(std::time::Duration::from_secs(1)); if let Ok(item) = self.objects.1.try_recv() { log::trace!("get ok:{}", str); ...
); (Some(Reusable::new(&self, item)), false) /* } else if (self.pending.lock().len() == 0) { log::trace!("get should pend:{}", str); self.pending.lock().push(PendingInfo { id: String::from(str), notif...
conditional_block
lib.rs
when it goes out of scope //! ``` //! Pull from pool and `detach()` //! ``` //! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // returns None when the pool is saturated //! reusable_buff.clear(); // clear the buff before using //! le...
usize { self.objects.1.len() } #[inline] pub fn is_empty(&self) -> bool { self.objects.1.is_empty() } #[inline] pub fn pending(&'static self, str: &str, sender: channel::Sender<Reusable<T>>, releasable: usize) -> (Option<Reusable<T>>, bool) { log::trace!("pending item:{...
{}", cap); log::trace!("mempool remains:{}", cap); let mut objects = channel::unbounded(); for _ in 0..cap { &objects.0.send(init()); } MemoryPool { objects, pending: Arc::new(Mutex::new(Vec::new())), waiting: Arc::new(Mutex::new(Ve...
identifier_body
lib.rs
//! some_file.read_to_end(reusable_buff); //! // reusable_buff is automatically returned to the pool when it goes out of scope //! ``` //! Pull from pool and `detach()` //! ``` //! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // retu...
//! let pool: MemoryPool<Vec<u8>> = MemoryPool::new(32, || Vec::with_capacity(4096)); //! let mut reusable_buff = pool.pull().unwrap(); // returns None when the pool is saturated //! reusable_buff.clear(); // clear the buff before using
random_line_split
counter.rs
AT_LOCK: Mutex<u32> = Mutex::new(42); } /// Configure event counter parameters. /// /// Unless specified, a counter is allocated in counting mode with a system-wide /// scope, recording events across all CPUs. /// /// ```no_run /// let config = CounterConfig::default().attach_to(vec![0]); /// /// let instr = config.al...
(&mut self) { unsafe { pmc_stop(self.counter.id) }; } } /// An allocated PMC counter. /// /// Counters are initialised using the [`CounterBuilder`] type. /// /// ```no_run /// use std::{thread, time::Duration}; /// /// let instr = CounterConfig::default() /// .attach_to(vec![0]) /// .allocate("inst...
drop
identifier_name
counter.rs
AT_LOCK: Mutex<u32> = Mutex::new(42); } /// Configure event counter parameters. /// /// Unless specified, a counter is allocated in counting mode with a system-wide /// scope, recording events across all CPUs. /// /// ```no_run /// let config = CounterConfig::default().attach_to(vec![0]); /// /// let instr = config.al...
handles.push(AttachHandle { id, pid }) } c.attached = Some(handles) } Ok(c) } /// Start this counter. /// /// The counter stops when the returned [`Running`] handle is dropped. #[must_use = "counter only runs until handle is dropped"] ...
{ return match io::Error::raw_os_error(&io::Error::last_os_error()) { Some(libc::EBUSY) => unreachable!(), Some(libc::EEXIST) => Err(new_os_error(ErrorKind::AlreadyAttached)), Some(libc::EPERM) => Err(new_os_error(ErrorKind::For...
conditional_block
counter.rs
_FAT_LOCK: Mutex<u32> = Mutex::new(42); } /// Configure event counter parameters. /// /// Unless specified, a counter is allocated in counting mode with a system-wide /// scope, recording events across all CPUs. /// /// ```no_run /// let config = CounterConfig::default().attach_to(vec![0]); /// /// let instr = config....
// Allocate the PMC let mut id = 0; if unsafe { pmc_allocate( c_spec.as_ptr(), pmc_mode, 0, cpu.unwrap_or(CPU_ANY), &mut id, 0, ) } != 0 { return ma...
let c_spec = CString::new(event_spec.into()).map_err(|_| new_error(ErrorKind::InvalidEventSpec))?;
random_line_split
sync.js
// for each op (colormap, pan, etc.) for(i=0; i<xops.length; i++){ // current op xop = xops[i]; this.syncs[xop] = this.syncs[xop] || []; ims = this.syncs[xop]; // add images not already in the list for(j=0; j<xlen; j++){ xim = xims[j]; if( $.inArray(xim, ims) < 0 ){ // add to list ims.push(...
{ delete opts.reverse; for(i=0; i<xlen; i++){ JS9.Sync.sync.call(xims[i], xops, [this]); } return; }
conditional_block
sync.js
if( xim && (xim.id !== this.id || (xim.display.id !== this.display.id)) ){ xims[j++] = xim; } } return xims; }; // sync image(s) when operations are performed on an originating image // called in the image context JS9.Sync.sync = function(...args){ let i, j, xop, xim, xops, xims, xlen; let ...
} else { xim = ims[i]; } // exclude the originating image
random_line_split
model_sql.go
+= fmt.Sprintf(" AND %s = ?", m.FieldAddAlias(field)) } whereValue = append(whereValue, data[field]) fileTitles = append(fileTitles, m.attr.Fields[m.attr.fieldIndexMap[field]].Title) } //非自增PK表,检查PK字段 if !m.attr.AutoInc { if where == "" { where = fmt.Sprintf("%s = ?", pk) } else { where = fmt.Sprin...
fields = append(fields, keyField, valueField) // 树型必备字段 if m.attr.IsTree {
random_line_split
model_sql.go
//查询 data := make([]map[string]interface{}, 0) if err = theDB.Select(fields).Find(&data).Error; err != nil { return } //处理结果 desc = make(Kvs) for i, v := range data { key := cast.ToString(v["__mc_key"]) //树形 if m.attr.IsTree && qo.ReturnPath { key = cast.ToString(v[m.attr.Tree.PathField]) } inden...
填字段 func (m *Model) CheckRequiredValues(data map[string]interface{}) (err error) { fieldTitles := make([]string, 0) //非自增PK表,检查PK字段 if !m.attr.AutoInc { if cast.ToString(data[m.attr.Pk]) == "" { fieldTitles = append(fieldTitles, m.attr.Fields[m.attr.fieldIndexMap[m.attr.Pk]].Title) } } //检查配置中的必填字段 for _, ...
r } else if total > 0 { return &Result{Message:fmt.Sprintf("记录已存在:【%s】存在重复", strings.Join(fileTitles, "、"))} } return nil } // 检查必
conditional_block
model_sql.go
.attr.Pk, symbol), delIds).Delete(nil) return db.RowsAffected, db.Error } // 分析查询条件 (此批条件只作用于返回的db对象上,不会作用于模型的db上) // @param extraWhere 额外的查询条件 // @param searchValues 查询字段值 // @param notSearch 是否使用查询字段条件 func (m *Model) ParseWhere(db *gorm.DB, extraWhere []interface{}, searchValues map[string]interface{}, notSearch b...
t.ToString(data[i][m.attr.Tree.NameField]) } } return } // 分析树形结构查询必须的扩展字段 func (m *Model) ParseTreeExtraField() (field []string) { pathField := m.FieldAddAlias(m.attr.Tree.PathField) __mc_pathField := fmt.Sprintf("`__mc_%s`.`%s`", m.attr.Table, m.attr.Tree.PathField) __mc_pkField := fmt.Sprintf("`__mc_%s`.`%s...
identifier_body
model_sql.go
!= nil { return } //创建数据 db := m.BaseDB(false).Create(data) return db.RowsAffected, db.Error } //保存记录(根据pk自动分析是update 或 create) func (m *Model) Save(data map[string]interface{}, oldPkValue interface{})(rowsAffected int64, err error) { if oldPkValue == nil { //创建 return m.Create(data) } else { //更新 return ...
ing]["__mc_va
identifier_name
script.padrao.js
ext = URLHOST.host.indexOf('intru') > -1; if (ext != null && ext != undefined) { if (ext != true) { return; } } var cod = recuperaUserCodCookie(); if (cod == '' || cod == null || cod == undefined) { if (window.location.href == `${urlHost}/Security/Login/`)...
alert(error); } } const API = { /** *Requisições do tipo GET * @param {Opções para a definição da requisição} options */ GET: (options) => { try { if (options == undefined || options == null) { return false; } Ajax(options); ...
} } catch (error) {
conditional_block
script.padrao.js
var ext = URLHOST.host.indexOf('intru') > -1; if (ext != null && ext != undefined) { if (ext != true) { return; } } var cod = recuperaUserCodCookie(); if (cod == '' || cod == null || cod == undefined) { if (window.location.href == `${urlHost}/Security/Logi...
var divSpinner = Elements.Create('div', 'divGrowing', null, null, `z-index: 150 !important; color: ${spinnerColor} !important;`, ["spinner-grow", "text-primary"]); span = Elements.Create('span', 'loadGrowing', "visually-hidden", null); divSpinner....
div = Elements.Create('div', 'loadMestre', null, null, style);
random_line_split
mod.rs
use rstd::prelude::*; use codec::{Encode, Decode}; use support::{ StorageValue, StorageMap, decl_event, decl_storage, decl_module, ensure, traits::{ Currency, ReservableCurrency, OnFreeBalanceZero, OnUnbalanced, WithdrawReason, ExistenceRequirement, Imbalance, Get, }, dispatch::Result, }; use sr_primitives...
//! # Activity Module //! #![cfg_attr(not(feature = "std"), no_std)]
random_line_split
mod.rs
this module type ReputationCurrency: Currency<Self::AccountId>; /// Handler for the unbalanced reduction when taking transaction fees. type TransactionPayment: OnUnbalanced<NegativeImbalanceOf<Self>>; /// The overarching event type. type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>; /// The...
<T: Trait>(#[codec(compact)] BalanceOf<T>); impl<T: Trait> TakeFees<T> { /// utility constructor. Used only in client/factory code. pub fn from(fee: BalanceOf<T>) -> Self { Self(fee) } /// Compute the final fee value for a particular transaction. /// /// The final fee is composed of: /// - _length-fee_: Th...
TakeFees
identifier_name
mod.rs
this module type ReputationCurrency: Currency<Self::AccountId>; /// Handler for the unbalanced reduction when taking transaction fees. type TransactionPayment: OnUnbalanced<NegativeImbalanceOf<Self>>; /// The overarching event type. type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>; /// The...
// PRIVATE MUTABLES fn charge_for_energy(who: &T::AccountId, value: BalanceOf<T>) -> Result { // ensure reserve if !T::Currency::can_reserve(who, value) { return Err("not enough free funds"); } // check current_charged let current_charged = <Charged<T>>::get(who); let new_charged = current_charged.ch...
{ T::EnergyCurrency::available_free_balance(who) }
identifier_body
compile.ts
_INSIDE_PATH_BINARY } from "./sandbox"; import config, { serverSideConfig } from "./config"; import { runTaskQueued } from "./taskQueue"; import { getFile, getFileHash } from "./file"; import * as fsNative from "./fsNative"; export interface CompilationConfig extends SandboxConfigWithoutMountInfo { messageFile?: str...
public async dereference() { if (--this.referenceCount === 0) { await fsNative.remove(this.binaryDirectory); } } async copyTo(newBinaryDirectory: string) { this.reference(); await fsNative.copy(this.binaryDirectory, newBinaryDirectory); await this.dereference(); return new Compile...
{ this.referenceCount++; return this; }
identifier_body
compile.ts
OX_INSIDE_PATH_BINARY } from "./sandbox"; import config, { serverSideConfig } from "./config"; import { runTaskQueued } from "./taskQueue"; import { getFile, getFileHash } from "./file"; import * as fsNative from "./fsNative"; export interface CompilationConfig extends SandboxConfigWithoutMountInfo { messageFile?: s...
() { if (--this.referenceCount === 0) { await fsNative.remove(this.binaryDirectory); } } async copyTo(newBinaryDirectory: string) { this.reference(); await fsNative.copy(this.binaryDirectory, newBinaryDirectory); await this.dereference(); return new CompileResultSuccess( this.co...
dereference
identifier_name
compile.ts
OX_INSIDE_PATH_BINARY } from "./sandbox"; import config, { serverSideConfig } from "./config"; import { runTaskQueued } from "./taskQueue"; import { getFile, getFileHash } from "./file"; import * as fsNative from "./fsNative"; export interface CompilationConfig extends SandboxConfigWithoutMountInfo { messageFile?: s...
await fsNative.copy(this.binaryDirectory, newBinaryDirectory); await this.dereference(); return new CompileResultSuccess( this.compileTaskHash, this.message, newBinaryDirectory, this.binaryDirectorySize, this.extraInfo ); } } // Why NOT using the task hash as the directo...
async copyTo(newBinaryDirectory: string) { this.reference();
random_line_split
supervised_ml_(classification)_assignment_(final).py
how our data is distributes per each column. Though, this doesnt represent much use since some of the attributes are numerical encodings and aren’t represented well like this. In order to see correlations, lets visually interpret this data through a heatmap of correlated values, and a pair plot to draw visual inferen...
ams(n_estimators=n_trees) # Fit the model RF.fit(x_train, y_train) # Get the oob error oob_error = 1 - RF.oob_score_ # Store it oob_list.append(pd.Series({'n_trees': n_trees, 'oob': oob_error})) rf_oob_d
conditional_block
supervised_ml_(classification)_assignment_(final).py
* Value 2: showing probable or definite left ventricular hypertrophy by Estes' criteria * thalach : maximum heart rate achieved * target : 0= less chance of heart attack 1= more chance of heart attack Let's begin by importing our data into pandas. """ #path must point to the heart.csv file. data = pd.read_csv...
plt.show() """--- # Data Engineering/Modelling Because the data is already in a numerical form (int-type), it will not be required to engineer the data or reencode values. Though, given the tasks ahead, we may require data scaling for input into specific classifier models. We shall address this problem as we arr...
random_line_split
supervised_ml_(classification)_assignment_(final).py
Value 2: showing probable or definite left ventricular hypertrophy by Estes' criteria * thalach : maximum heart rate achieved * target : 0= less chance of heart attack 1= more chance of heart attack Let's begin by importing our data into pandas. """ #path must point to the heart.csv file. data = pd.read_csv('/...
e, y_pred, label): return pd.Series({'accuracy':accuracy_score(y_true, y_pred), 'precision': precision_score(y_true, y_pred), 'recall': recall_score(y_true, y_pred), 'f1': f1_score(y_true, y_pred)}, name=label) train_test_full_...
e_error(y_tru
identifier_name
supervised_ml_(classification)_assignment_(final).py
Value 2: showing probable or definite left ventricular hypertrophy by Estes' criteria * thalach : maximum heart rate achieved * target : 0= less chance of heart attack 1= more chance of heart attack Let's begin by importing our data into pandas. """ #path must point to the heart.csv file. data = pd.read_csv(...
n_test_full_error = pd.concat([measure_error(y_train, y_train_pred, 'train'), measure_error(y_test, y_test_pred, 'test')], axis=1) train_test_full_error """The above output shows out accuracy prediction. This is quite low, could it be improved with Grid Sear...
pd.Series({'accuracy':accuracy_score(y_true, y_pred), 'precision': precision_score(y_true, y_pred), 'recall': recall_score(y_true, y_pred), 'f1': f1_score(y_true, y_pred)}, name=label) trai
identifier_body
tls.go
scores = conf.categoryScores(tally) reqACLs = conf.ACLs.requestACLs(cr, authUser) if invalidSSL { reqACLs["invalid-ssl"] = true } if r == nil { // It's a transparently-intercepted request instead of a real // CONNECT request. reqACLs["transparent"] = true } } session.ACLs.data = reqACLs sessio...
callStarlarkFunctions("ssl_bump", session) dialer := &net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, } if session.SourceIP != nil { dialer.LocalAddr = &net.TCPAddr{ IP: session.SourceIP, } } session.chooseAction() logAccess(cr, nil, 0, false, user, tally,...
{ session.PossibleActions = append(session.PossibleActions, "ssl-bump") }
conditional_block
tls.go
0, 0, time.Local), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, DNSNames: []string{sni}, SignatureAlgorithm: x509.UnknownSignatureAlgorithm, } newCertBytes, err := x509.CreateCertificate(rand.Reader, template, conf.ParsedTLSCert, conf.ParsedTLSCert.PublicKey, con...
addTrustedRoots
identifier_name
tls.go
session.ClientIP = client } obsoleteVersion := false invalidSSL := false // Read the client hello so that we can find out the name of the server (not // just the address). clientHello, err := readClientHello(conn) if err != nil { logTLS(user, serverAddr, "", fmt.Errorf("error reading client hello: %v", err)...
client := conn.RemoteAddr().String() if host, _, err := net.SplitHostPort(client); err == nil { session.ClientIP = host } else {
random_line_split
tls.go
s = conf.ACLs.requestACLs(cr, authUser) if invalidSSL { reqACLs["invalid-ssl"] = true } if r == nil { // It's a transparently-intercepted request instead of a real // CONNECT request. reqACLs["transparent"] = true } } session.ACLs.data = reqACLs session.Scores.data = scores session.PossibleActio...
{ return 0, errors.New("unhashable type: TLSSession") }
identifier_body
kek.py
s = pd.read_csv('spam.csv', encoding = 'latin-1') oldmails.head() mailz = pd.read_csv('messages.csv', encoding = 'latin-1') mailz.head() #Преобразовани таблицы с данными, удаление лишних столбцов oldmails.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis = 1, inplace = True) oldmails.head() mailz.drop(['subject'...
ие словрей спам и не спам слов spam_words = ' '.join(list(mails[mails['label'] == 1]['message'])) ham_words = ' '.join(list(mails[mails['label'] == 0]['message'])) trainData.head() trainData['label'].value_counts() testData.head() testData['label'].value_counts() #Обработка текста сообщений def process_message(mes...
ts() #Формирован
conditional_block
kek.py
ate(spam_words) plt.figure(figsize = (10, 8), facecolor = 'k') plt.imshow(spam_wc) plt.axis('off') plt.tight_layout(pad = 0) plt.show() #Функция визуализации словаря легетимных слов def show_ham(ham_words): ham_wc = WordCloud(width = 512,height = 512).generate(ham_words) plt.figure(figsize =...
слов def show_spam(spam_words): spam_wc = WordCloud(width = 512,height = 512).gener
identifier_body
kek.py
mails = pd.read_csv('spam.csv', encoding = 'latin-1') oldmails.head() mailz = pd.read_csv('messages.csv', encoding = 'latin-1') mailz.head() #Преобразовани таблицы с данными, удаление лишних столбцов oldmails.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis = 1, inplace = True) oldmails.head() mailz.drop(['subj...
= self.spam_mails / self.total_mails, self.ham_mails / self.total_mails #Вычисление вероятностей def calc_TF_and_IDF(self): noOfMessages = self.mails.shape[0] self.spam_mails, self.ham_mails = self.labels.value_counts()[1], self.labels.value_counts()[0] self.total_mails = self.spam_mail...
_mail
identifier_name
kek.py
from sklearn.feature_extraction.text import TfidfTransformer from sklearn.naive_bayes import MultinomialNB from sklearn.metrics import confusion_matrix import pickle #Функция сохранения состояния обученности классификатора def save(obj): with open('sis.pickle', 'wb') as f: pickle.dump(obj, f) #Функция загру...
import numpy as np import pandas as pd import nltk from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import CountVectorizer
random_line_split