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
extension.ts
// The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from 'vscode'; import { StructCommandManager } from './struct_command_manager' import { EditCommandManager } from './edit_command_manager'; import { runTestCase...
// this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will onl...
random_line_split
app.js
var MyApp = (function () { var socket = null; var socker_url = 'http://localhost:3000'; var meeting_id = ''; var user_id = ''; var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; fi...
function EventBinding() { $('#btnResetMeeting').on('click', function () { socket.emit('reset'); }); $('#btnsend').on('click', function () { socket.emit('sendMessage', $('#msgbox').val()); $('#msgbox').val(''); }); $('#invite').on('click...
{ socket = io.connect(socker_url); var serverFn = function (data, to_connid) { socket.emit('exchangeSDP', { message: data, to_connid: to_connid }); }; socket.on('reset', function () { location.reload(); }); socket.on('exchangeSDP', async funct...
identifier_body
app.js
var MyApp = (function () { var socket = null; var socker_url = 'http://localhost:3000'; var meeting_id = ''; var user_id = ''; var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; fi...
}); socket.on('userconnected', function (other_users) { $('#divUsers .other').remove(); if (other_users) { for (var i = 0; i < other_users.length; i++) { AddNewUser(other_users[i].user_id, other_users[i].connectionId); Wrt...
{ WrtcHelper.init(serverFn, socket.id); if (user_id != "" && meeting_id != "") { socket.emit('userconnect', { dsiplayName: user_id, meetingid: meeting_id }); } }
conditional_block
app.js
var MyApp = (function () { var socket = null; var socker_url = 'http://localhost:3000'; var meeting_id = ''; var user_id = ''; var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; fi...
socket.emit('sendMessage', $('#msgbox').val()); $('#msgbox').val(''); }); $('#invite').on('click', function () { var str1 = "https://127.0.0.1:5501/?mid="; var str2 = meeting_id; var res = str1.concat(str2); navigator.clipboard....
$('#btnResetMeeting').on('click', function () { socket.emit('reset'); }); $('#btnsend').on('click', function () {
random_line_split
app.js
var MyApp = (function () { var socket = null; var socker_url = 'http://localhost:3000'; var meeting_id = ''; var user_id = ''; var tag = document.createElement('script'); tag.src = "https://www.youtube.com/iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; fi...
(url) { const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|&v=)([^#&?]*).*/; const match = url.match(regExp); return (match && match[2].length === 11) ? match[2] : null; } function convertHMS(value) { const sec = parseInt(value, 10); // convert ...
getId
identifier_name
proxy.go
package proxy import ( "bytes" "context" "crypto/tls" "errors" "fmt" "io/ioutil" "net" "net/http" "net/http/cookiejar" "net/url" "regexp" "strings" "time" "github.com/DataHenHQ/datahen/pages" "github.com/DataHenHQ/till/internal/tillclient" "github.com/DataHenHQ/tillup/cache" "github.com/DataHenHQ/til...
// buildTargetRequest builds a target request from source request, and etc. func buildTargetRequest(scheme string, sreq *http.Request, pconf *PageConfig, sess *sessions.Session, p *pages.Page) (*http.Client, *http.Request, error) { // create transport for client t := &http.Transport{ Dial: (&net.Dialer{ Timeou...
{ var sess *sessions.Session if features.Allow(features.Cache) && !CacheConfig.Disabled { // check if past response exist in the cache. if so, then return it. cresp, err := cache.GetResponse(ctx, p.GID, pconf.CacheFreshness, pconf.CacheServeFailures) if err != nil { return nil, err } // if cachehit the...
identifier_body
proxy.go
package proxy import ( "bytes" "context" "crypto/tls" "errors" "fmt" "io/ioutil" "net" "net/http" "net/http/cookiejar" "net/url" "regexp" "strings" "time" "github.com/DataHenHQ/datahen/pages" "github.com/DataHenHQ/till/internal/tillclient" "github.com/DataHenHQ/tillup/cache" "github.com/DataHenHQ/til...
} // copy source headers into target headers th := copySourceHeaders(sreq.Header) if th != nil { treq.Header = th } // Delete headers related to proxy usage treq.Header.Del("Proxy-Connection") // if ForceUA is true, then override User-Agent header with a random UA if ForceUA { // using till session's ...
{ tclient.Jar.SetCookies(treq.URL, sess.Cookies.Get(u)) }
conditional_block
proxy.go
package proxy import ( "bytes" "context" "crypto/tls" "errors" "fmt" "io/ioutil" "net" "net/http" "net/http/cookiejar" "net/url" "regexp" "strings" "time" "github.com/DataHenHQ/datahen/pages" "github.com/DataHenHQ/till/internal/tillclient" "github.com/DataHenHQ/tillup/cache" "github.com/DataHenHQ/til...
(sh http.Header) (th http.Header) { th = make(http.Header) if sh == nil { return nil } for key, values := range sh { if dhHeadersRe.MatchString(key) { continue } for _, val := range values { th.Add(key, val) } } return th } // Overrides User-Agent header with a random one func generateRandomU...
copySourceHeaders
identifier_name
proxy.go
package proxy import ( "bytes" "context" "crypto/tls" "errors" "fmt" "io/ioutil" "net" "net/http" "net/http/cookiejar" "net/url" "regexp" "strings" "time" "github.com/DataHenHQ/datahen/pages" "github.com/DataHenHQ/till/internal/tillclient" "github.com/DataHenHQ/tillup/cache" "github.com/DataHenHQ/til...
// increment the requests counter *(StatMu.InstanceStat.InterceptedRequests) = *(StatMu.InstanceStat.InterceptedRequests) + uint64(1) StatMu.Mutex.Unlock() } // Atomically increments failed request delta in the instance stat func incrFailedRequestStatDelta() { StatMu.Mutex.Lock() // increment the requests count...
random_line_split
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro i...
//! [`format!`]: ../../std/macro.format.html //! [`to_string`]: ../../std/string/trait.ToString.html //! [`writeln!`]: ../../std/macro.writeln.html //! [`write_fmt`]: ../../std/io/trait.Write.html#method.write_fmt //! [`std::io::Write`]: ../../std/io/trait.Write.html //! [`print!`]: ../../std/macro.print.html //! [`pri...
random_line_split
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro i...
rgs.estimated_capacity(); let mut output = string::String::with_capacity(capacity); output.write_fmt(args).expect("a formatting trait implementation returned an error"); output }
identifier_body
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro i...
-> string::String { let capacity = args.estimated_capacity(); let mut output = string::String::with_capacity(capacity); output.write_fmt(args).expect("a formatting trait implementation returned an error"); output }
<'_>)
identifier_name
index.ts
import BScroll, { MountedBScrollHTMLElement } from '@better-scroll/core' import { Direction, EventEmitter, extend, warn, findIndex, } from '@better-scroll/shared-utils' import BScrollFamily from './BScrollFamily' import propertiesConfig from './propertiesConfig' export const DEFAUL_GROUP_ID = 'INTERNAL_NESTE...
hasVerticalScroll, x, y, minScrollX, maxScrollX, minScrollY, maxScrollY, movingDirectionX, movingDirectionY, } = scroll let ret = false const outOfLeftBoundary = x >= minScrollX && movingDirectionX === Direction.Negative const outOfRightBoundary = x <= maxScrollX && ...
hasHorizontalScroll,
random_line_split
index.ts
import BScroll, { MountedBScrollHTMLElement } from '@better-scroll/core' import { Direction, EventEmitter, extend, warn, findIndex, } from '@better-scroll/shared-utils' import BScrollFamily from './BScrollFamily' import propertiesConfig from './propertiesConfig' export const DEFAUL_GROUP_ID = 'INTERNAL_NESTE...
const k = findIndex(hooksFn, ([hooks]) => { return hooks === scroll.hooks }) if (k > -1) { const [hooks, eventType, handler] = hooksFn[k] hooks.off(eventType, handler) hooksFn.splice(k, 1) } } addBScroll(scroll: BScroll) { this.store.push(BScrollFamily.create(scroll)) ...
{ const bscrollFamily = store[i] bscrollFamily.purge() store.splice(i, 1) }
conditional_block
index.ts
import BScroll, { MountedBScrollHTMLElement } from '@better-scroll/core' import { Direction, EventEmitter, extend, warn, findIndex, } from '@better-scroll/shared-utils' import BScrollFamily from './BScrollFamily' import propertiesConfig from './propertiesConfig' export const DEFAUL_GROUP_ID = 'INTERNAL_NESTE...
(): NestedScroll[] { const instancesMap = NestedScroll.instancesMap return Object.keys(instancesMap).map((key) => instancesMap[key]) } static purgeAllNestedScrolls() { const nestedScrolls = NestedScroll.getAllNestedScrolls() nestedScrolls.forEach((ns) => ns.purgeNestedScroll()) } private handl...
getAllNestedScrolls
identifier_name
sha_256.rs
//! This module is an implementation of the SHA-256 hashing algorithm use padding::PaddingScheme; use padding::merkle_damgard::MDPadding512u32; // Logical functions used by SHA-256 (function names taken from NIST standard) fn ch(x: u32, y: u32, z: u32) -> u32 { (x & y) ^ (!x & z) } // fn maj(x: u32, y: u32, z: u...
(x: u32) -> u32 { x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10) } // Constants used by SHA-256 const K: [u32; 64] = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, ...
sigma_1
identifier_name
sha_256.rs
//! This module is an implementation of the SHA-256 hashing algorithm use padding::PaddingScheme; use padding::merkle_damgard::MDPadding512u32; // Logical functions used by SHA-256 (function names taken from NIST standard) fn ch(x: u32, y: u32, z: u32) -> u32 { (x & y) ^ (!x & z) } // fn maj(x: u32, y: u32, z: u...
// fn sigma_1(x: u32) -> u32 { x.rotate_right(17) ^ x.rotate_right(19) ^ (x >> 10) } // Constants used by SHA-256 const K: [u32; 64] = [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0...
{ x.rotate_right(7) ^ x.rotate_right(18) ^ (x >> 3) }
identifier_body
sha_256.rs
//! This module is an implementation of the SHA-256 hashing algorithm use padding::PaddingScheme; use padding::merkle_damgard::MDPadding512u32; // Logical functions used by SHA-256 (function names taken from NIST standard) fn ch(x: u32, y: u32, z: u32) -> u32 { (x & y) ^ (!x & z) } // fn maj(x: u32, y: u32, z: u...
g = f; f = e; e = d.wrapping_add(t_1); d = c; c = b; b = a; a = t_1.wrapping_add(t_2); } // Update the hash value hash[0] = hash[0].wrapping_add(a); hash[1] = hash[1].wrapping_add(b); hash[2] = h...
.wrapping_add(ch(e, f, g)) .wrapping_add(K[t]) .wrapping_add(w[t]); let t_2 = capital_sigma_0(a).wrapping_add(maj(a, b, c)); h = g;
random_line_split
transformer_models.py
import json import random import argparse import sys from sklearn.metrics import precision_recall_fscore_support, classification_report from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.linear_model import SGDClassifier from transformers im...
targets.extend(batch['label'].float().tolist()) outputs.extend(logits.argmax(dim=1).tolist()) precision_macro, recall_macro, f1_macro, _ = precision_recall_fscore_support(targets, outputs, labels=[0, 1], average...
logits = output.logits
random_line_split
transformer_models.py
import json import random import argparse import sys from sklearn.metrics import precision_recall_fscore_support, classification_report from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.linear_model import SGDClassifier from transformers im...
(path): """ Reads the file from the given path (json file). Returns list of instance dictionaries. """ data = [] with open(path, "r", encoding="utf-8") as file: for instance in file: data.append(json.loads(instance)) return data def evaluate_epoch(model, dataset): ...
read
identifier_name
transformer_models.py
import json import random import argparse import sys from sklearn.metrics import precision_recall_fscore_support, classification_report from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.linear_model import SGDClassifier from transformers im...
elif "roberta" in model_name: model = RobertaForSequenceClassification.from_pretrained(model_name).to(device) tokenizer = RobertaTokenizer.from_pretrained(model_name) elif "deberta" in model_name: # DebertaV2Tokenizer, DebertaV2Model, DebertaV2ForSequenceClassification, DebertaV2Confi...
config = BigBirdConfig.from_pretrained(model_name) config.gradient_checkpointing = True model = BigBirdForSequenceClassification.from_pretrained(model_name, config=config).to(device) tokenizer = BigBirdTokenizer.from_pretrained(model_name)
conditional_block
transformer_models.py
import json import random import argparse import sys from sklearn.metrics import precision_recall_fscore_support, classification_report from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.model_selection import train_test_split from sklearn.linear_model import SGDClassifier from transformers im...
def collate_fn(self, batch): model_inputs = self.tokenizer([i[0] for i in batch], return_tensors="pt", padding=True, truncation=True, max_length=64).to(self.device) labels = torch.tensor([i[1] for i in batch]).to(self.device) return {"model_inputs": mo...
return self.examples[idx]
identifier_body
smartnic.go
// {C} Copyright 2019 Pensando Systems Inc. All rights reserved. package impl import ( "context" "fmt" "reflect" "strings" "github.com/pensando/sw/api" "github.com/pensando/sw/api/generated/apiclient" "github.com/pensando/sw/api/generated/cluster" diagapi "github.com/pensando/sw/api/generated/diagnostics" "...
cl.logger.DebugLog("method", "smartNICPreCommitHook", "msg", fmt.Sprintf("updating module: %s with IP: %s", modObj.Name, modObj.Status.Node)) } } oldprofname := curNIC.Spec.DSCProfile //TODO:revisit once the feature stabilises var oldProfile cluster.DSCProfile if oldprofname != "" { oldProfile = cl...
{ cl.logger.ErrorLog("method", "smartNICPreCommitHook", "msg", fmt.Sprintf("error adding module obj [%s] to transaction for deletion", modObj.Name), "error", err) continue }
conditional_block
smartnic.go
// {C} Copyright 2019 Pensando Systems Inc. All rights reserved. package impl import ( "context" "fmt" "reflect" "strings" "github.com/pensando/sw/api" "github.com/pensando/sw/api/generated/apiclient" "github.com/pensando/sw/api/generated/cluster" diagapi "github.com/pensando/sw/api/generated/diagnostics" "...
(ctx context.Context, kvs kvstore.Interface, txn kvstore.Txn, key string, oper apiintf.APIOperType, dryrun bool, i interface{}) (interface{}, bool, error) { updNIC, ok := i.(cluster.DistributedServiceCard) if !ok { cl.logger.ErrorLog("method", "smartNICPreCommitHook", "msg", fmt.Sprintf("called for invalid object t...
smartNICPreCommitHook
identifier_name
smartnic.go
// {C} Copyright 2019 Pensando Systems Inc. All rights reserved. package impl import ( "context" "fmt" "reflect" "strings" "github.com/pensando/sw/api" "github.com/pensando/sw/api/generated/apiclient" "github.com/pensando/sw/api/generated/cluster" diagapi "github.com/pensando/sw/api/generated/diagnostics" "...
func (cl *clusterHooks) smartNICPreCommitHook(ctx context.Context, kvs kvstore.Interface, txn kvstore.Txn, key string, oper apiintf.APIOperType, dryrun bool, i interface{}) (interface{}, bool, error) { updNIC, ok := i.(cluster.DistributedServiceCard) if !ok { cl.logger.ErrorLog("method", "smartNICPreCommitHook", ...
{ NUMFields := []string{"ID", "NetworkMode", "MgmtVlan", "Controllers"} var errs []string updSpec := reflect.Indirect(reflect.ValueOf(updObj)).FieldByName("Spec") curSpec := reflect.Indirect(reflect.ValueOf(curObj)).FieldByName("Spec") for _, fn := range NUMFields { updField := updSpec.FieldByName(fn).Interfac...
identifier_body
smartnic.go
// {C} Copyright 2019 Pensando Systems Inc. All rights reserved. package impl import ( "context" "fmt" "reflect" "strings" "github.com/pensando/sw/api" "github.com/pensando/sw/api/generated/apiclient" "github.com/pensando/sw/api/generated/cluster" diagapi "github.com/pensando/sw/api/generated/diagnostics" "...
updNIC.Spec.PolicerAttachTenant = "default" } else if updNIC.Spec.PolicerAttachTenant != "default" { cl.logger.Errorf("PolicerAttachTenant is supported for default tenant only") return i, true, fmt.Errorf("PolicerAttachTenant is supported for default tenant only") } if oper == apiintf.CreateOper { var nicIP...
random_line_split
main.1.rs
extern crate brainfuck; extern crate rand; #[macro_use] extern crate log; extern crate env_logger; mod context; use brainfuck::parser; use context::Context; use std::time::{Duration, Instant}; use rand::random; use log::LevelFilter; use std::sync::mpsc::channel; use std::thread; use std::sync::{Arc, Mutex}; /* f64数组...
new_pop.push(self.populations[i]); } } let (tx, rx) = channel(); let elite_count = new_pop.len(); let new_pop = Arc::new(Mutex::new(new_pop)); for tid in 0..NUM_THREAD{ let target = self.target.clone(); let child_count...
.NUM_COPIES_ELITE{
identifier_name
main.1.rs
extern crate brainfuck; extern crate rand; #[macro_use] extern crate log; extern crate env_logger; mod context; use brainfuck::parser; use context::Context; use std::time::{Duration, Instant}; use rand::random; use log::LevelFilter; use std::sync::mpsc::channel; use std::thread; use std::sync::{Arc, Mutex}; /* f64数组...
oulette_selection()]); parents.push(self.populations[self.roulette_selection()]); } let tx = tx.clone(); let new_pop_clone = new_pop.clone(); thread::spawn(move || { let mut childs = vec![]; //println!("{}.start", tid); ...
new_pop.push(self.populations[i]); } } let (tx, rx) = channel(); let elite_count = new_pop.len(); let new_pop = Arc::new(Mutex::new(new_pop)); for tid in 0..NUM_THREAD{ let target = self.target.clone(); let child_count = (POPULATION_S...
identifier_body
main.1.rs
extern crate brainfuck; extern crate rand; #[macro_use] extern crate log; extern crate env_logger; mod context; use brainfuck::parser; use context::Context; use std::time::{Duration, Instant}; use rand::random; use log::LevelFilter; use std::sync::mpsc::channel; use std::thread; use std::sync::{Arc, Mutex}; /* f64数组...
self.genes[i] = shift_bit; shift_bit = temp; }else{ self.genes[i] = self.genes[self.length-1]; } } }else{ ...
if i>0{ let temp = self.genes[i];
random_line_split
main.1.rs
extern crate brainfuck; extern crate rand; #[macro_use] extern crate log; extern crate env_logger; mod context; use brainfuck::parser; use context::Context; use std::time::{Duration, Instant}; use rand::random; use log::LevelFilter; use std::sync::mpsc::channel; use std::thread; use std::sync::{Arc, Mutex}; /* f64数组...
selected_pos } //下一代 fn epoch(&mut self){ //计算总适应分 self.total_fitness = 0.0; for p in &mut self.populations{ self.total_fitness += p.fitness; } //按照得分排序 self.populations.sort_by(|a, b| b.fitness.partial_cmp(&a.fitness).unwrap()); le...
ness_total > slice{ selected_pos = i; break; } }
conditional_block
functionsSqueeze.py
import numpy as np import matplotlib.pyplot as plt import qutip import scipy.special as spe # import multiprocessing as mp from joblib import Parallel, delayed from qutip import * import time # testing atom on new pc def wQP(t, args): """calculates and returns the modulated frequency like in "Lit early universe...
def wQQdot(t, args): """calculates the time derivative of wQQ(t, args) at time t check help(wQQ) for further information on args""" if type(args) == list: w0, dw1, dt1, dw2, dt2, delay = args[0], args[1], args[2], args[3], args[4], args[5] elif type(args) == dict: w0, dw1, dt1, dw2, dt...
"""calculates and returns the modulated (two quenches) frequency like in 'Lit early universe' t time at which the frequency is calculated args: a list {w0, dw1, dt1, dw2, dt2, delay} or a dictionary with the following keys: w0 the unmodulated frequency dw1/2 (strength) and dt1/2 (duration) of t...
identifier_body
functionsSqueeze.py
import numpy as np import matplotlib.pyplot as plt import qutip import scipy.special as spe # import multiprocessing as mp from joblib import Parallel, delayed from qutip import * import time # testing atom on new pc def wQP(t, args): """calculates and returns the modulated frequency like in "Lit early universe...
freqD = - dw1*np.exp(-0.5*(t/dt1)**2) * t/(dt1**2) freqD += - dw2*np.exp(-0.5*((t-delay)/dt2)**2) * (t-delay)/(dt2**2) return(freqD) # defining the hamiltonian of the phonon evolution for vaiable w(t) def H(t, args): """calculates the hamiltonian of a harmonic oscillator with modulated frequency ...
return("wrong input form for args, list or dict")
conditional_block
functionsSqueeze.py
import numpy as np import matplotlib.pyplot as plt import qutip import scipy.special as spe # import multiprocessing as mp from joblib import Parallel, delayed from qutip import * import time # testing atom on new pc def wQP(t, args): """calculates and returns the modulated frequency like in "Lit early universe...
(t, args): """calculates the time derivative of wQQ(t, args) at time t check help(wQQ) for further information on args""" if type(args) == list: w0, dw1, dt1, dw2, dt2, delay = args[0], args[1], args[2], args[3], args[4], args[5] elif type(args) == dict: w0, dw1, dt1, dw2, dt2, delay = a...
wQQdot
identifier_name
functionsSqueeze.py
import numpy as np import matplotlib.pyplot as plt import qutip import scipy.special as spe # import multiprocessing as mp from joblib import Parallel, delayed from qutip import * import time # testing atom on new pc def wQP(t, args): """calculates and returns the modulated frequency like in "Lit early universe...
masterList[2].append(nBar) masterList[3].append(nT) if showProgress: progress += 1 print('\r', "Progress:", round(100*progress/nStates), "%, processing time:", round(time.time() - t1), "s", end = '') fig, (ax1, ax2, ax3, ax4, ax5) = plt.subplots(5) fig.set_size_i...
masterList[1].append(np.abs(xi))
random_line_split
DanhSachChoDuyet.page.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UtilService } from '../../../../service/util.service'; import { AppConsts } from '../../../../shared/AppConsts'; import * as moment from 'moment'; import { AlertController, LoadingController } from '@ionic/angular'; //...
kTimeUnread(){ this.page = 1; this.workTimeServiceProxy.getWorkTimeUnCheck(this.receiveId, this.page, this.pageSize).subscribe({ next: (res: any) => { this.checkList = res; for (const { index, value } of this.checkList.map((value, index) => ({ index, value }))){ this.checkList[in...
{ this.loadingDefault(); this._announcementServiceProxy.getAllUnRead(this.userId).subscribe({ next: (res) => { if (res) { this.totalUnred = res.length; } }, error: (err) => { this.showAlertController('Lỗi kết nối mạng, vui lòng thử lại.'); return; ...
identifier_body
DanhSachChoDuyet.page.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UtilService } from '../../../../service/util.service'; import { AppConsts } from '../../../../shared/AppConsts'; import * as moment from 'moment'; import { AlertController, LoadingController } from '@ionic/angular'; //...
} async loadingDefault(){ this.isLoading = true; return await this._loadingCtrl.create({ // message: 'Đang xử lý........', // duration: 3000 }).then(a => { a.present().then(() => { if (!this.isLoading) { a.dismiss().then(() => {}); } }); }); // l...
buttons: ['OK'] }); await alert.present();
random_line_split
DanhSachChoDuyet.page.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UtilService } from '../../../../service/util.service'; import { AppConsts } from '../../../../shared/AppConsts'; import * as moment from 'moment'; import { AlertController, LoadingController } from '@ionic/angular'; //...
page = 1; this.workTimeServiceProxy.getWorkTimeUnCheck(this.receiveId, this.page, this.pageSize).subscribe({ next: (res: any) => { this.checkList = res; for (const { index, value } of this.checkList.map((value, index) => ({ index, value }))){ this.checkList[index].isSelected = false;...
eUnread(){ this.
identifier_name
main.rs
//! Urbit Nock 4K data structures, with basic parsing, and evaluation. //! <https://urbit.org/docs/learn/arvo/nock/> #![feature(never_type, exact_size_is_empty)] use byteorder::{ByteOrder, LittleEndian}; use derive_more::Constructor; use env_logger; use log::{debug, error, info, log, trace, warn}; use std::{clone::Clon...
() -> Result<(), Box<dyn std::error::Error>> { env_logger::try_init()?; let subject = list(&[cell(atom(11), atom(12)), atom(2), atom(3), atom(4), atom(5)]); let formula = cell(atom(0), atom(7)); info!("subject: {}", subject); info!("formula: {}", formula); let product = nock(subject.clone(), ...
main
identifier_name
main.rs
//! Urbit Nock 4K data structures, with basic parsing, and evaluation. //! <https://urbit.org/docs/learn/arvo/nock/> #![feature(never_type, exact_size_is_empty)] use byteorder::{ByteOrder, LittleEndian}; use derive_more::Constructor; use env_logger; use log::{debug, error, info, log, trace, warn}; use std::{clone::Clon...
// *[a 4 b] -> +*[a b] 3 => Ok(cell(subject, parameter).tar()?.lus()?), // A formula [5 b c] treats b and c as formulas that become the input to // another axiomatic operator, =. *[a 5 b c] -> =[*[a b] // *[a c]] 5 => un...
} // In formulas [3 b] and [4 b], b is another formula, whose product against // the subject becomes the input to an axiomatic operator. 3 is ? and 4 is + // *[a 3 b] -> ?*[a b] 3 => Ok(cell(subject, parameter).tar()?.wut()),
random_line_split
main.rs
//! Urbit Nock 4K data structures, with basic parsing, and evaluation. //! <https://urbit.org/docs/learn/arvo/nock/> #![feature(never_type, exact_size_is_empty)] use byteorder::{ByteOrder, LittleEndian}; use derive_more::Constructor; use env_logger; use log::{debug, error, info, log, trace, warn}; use std::{clone::Clon...
/ Returns a reference to the Cell in this Noun, or a Crash if it's an atom. pub fn try_cell(&self) -> Result<&Cell, Crash> { match self { Noun::Cell(cell) => Ok(cell), Noun::Atom(_) => Err(Crash::from("required cell, had atom")), } } /// `*[subject formula]` nock for...
match self { Noun::Atom(atom) => Ok(atom), Noun::Cell(_) => Err(Crash::from("required atom, had cell")), } } //
identifier_body
symdumper.rs
use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use std::iter::once; use std::process::Command; use std::io::{Error, ErrorKind}; use crate::win32::ModuleInfo; type HANDLE = usize; extern { fn GetCurrentProcess() -> HANDLE; } #[allow(non_snake_case)] #[repr(C)] struct SrcCodeInfoW { SizeOfStruct: u3...
SizeOfStruct: std::mem::size_of::<SrcCodeInfoW>() as u32, Key: 0, ModBase: 0, Obj: [0; 261], FileName: [0; 261], LineNumber: 0, Address: 0, } } } #[allow(non_snake_case)] #[repr(C)] struct SymbolInfoW { SizeOfStruct: u3...
SrcCodeInfoW {
random_line_split
symdumper.rs
use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use std::iter::once; use std::process::Command; use std::io::{Error, ErrorKind}; use crate::win32::ModuleInfo; type HANDLE = usize; extern { fn GetCurrentProcess() -> HANDLE; } #[allow(non_snake_case)] #[repr(C)] struct SrcCodeInfoW { SizeOfStruct: u3...
} #[allow(non_snake_case)] #[repr(C)] struct ImagehlpModule64W { SizeOfStruct: u32, BaseOfImage: u64, ImageSize: u32, TimeDateStamp: u32, CheckSum: u32, NumSyms: u32, SymType: u32, ModuleName: [u16; 32], ImageName: [u16; 256], LoadedImageName: [u16; 256], LoadedPdbName: [u1...
{ ImagehlpLineW64 { SizeOfStruct: std::mem::size_of::<ImagehlpLineW64>() as u32, Key: 0, LineNumber: 0, FileName: std::ptr::null(), Address: 0, } }
identifier_body
symdumper.rs
use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use std::iter::once; use std::process::Command; use std::io::{Error, ErrorKind}; use crate::win32::ModuleInfo; type HANDLE = usize; extern { fn GetCurrentProcess() -> HANDLE; } #[allow(non_snake_case)] #[repr(C)] struct
{ SizeOfStruct: u32, Key: usize, ModBase: u64, Obj: [u16; 261], FileName: [u16; 261], LineNumber: u32, Address: u64, } impl Default for SrcCodeInfoW { fn default() -> Self { SrcCodeInfoW { SizeOfStruct: std::mem::size_of::<SrcCodeInfoW>() as u32, Key: 0,...
SrcCodeInfoW
identifier_name
symdumper.rs
use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; use std::iter::once; use std::process::Command; use std::io::{Error, ErrorKind}; use crate::win32::ModuleInfo; type HANDLE = usize; extern { fn GetCurrentProcess() -> HANDLE; } #[allow(non_snake_case)] #[repr(C)] struct SrcCodeInfoW { SizeOfStruct: u3...
// Symchk apparently ran, check output let stderr = std::str::from_utf8(&res.stderr) .expect("Failed to convert symchk output to utf-8"); let mut filename = None; for line in stderr.lines() { const PREFIX: &'static str = "DBGHELP: "; const POSTFIX: &'static str = " - OK"; ...
{ return Err(Error::new(ErrorKind::Other, "symchk returned with error")); }
conditional_block
Initial_Breif.go
package main //we Just Imported the main package import ( "fmt" "strconv" ) // we are import the "format" from the main package func main() { //Just like C,C++,JAVA, Python and other languages, here also we begins with main function fmt.Println("Hi Buddy! I am Your GoBuddy... :)") /* The game b...
else if (i % 1 == 0) && (i % 2 == 0){ // LOGICAL AND fmt.Println("Condition 2") fmt.Println(i) } else { fmt.Println("Condition DEFAULT") fmt.Println("No If else is satisfied") } } // 2. LIKE WHILE LOOP in C,C++,JAVA,PYTHON i := 1 for i <=...
{ //LOGICAL OR fmt.Println("Condition 1") fmt.Println(i) }
conditional_block
Initial_Breif.go
package main //we Just Imported the main package import ( "fmt" "strconv" ) // we are import the "format" from the main package func main() { //Just like C,C++,JAVA, Python and other languages, here also we begins with main function fmt.Println("Hi Buddy! I am Your GoBuddy... :)") /* The game b...
func perfromDivision1(n1 int, n2 int)string{ defer func(){ fmt.Println(recover()) fmt.Println("I am the saviour of this program, I didn't let the program stop :)") }() res := n1/n2 fmt.Println(res) r := "The result of the Division is: "+strconv.Itoa(res) // I just converted Int64 t...
{ fmt.Println(perfromDivision1(100,0)) fmt.Println(perfromDivision1(100,1)) }
identifier_body
Initial_Breif.go
package main //we Just Imported the main package import ( "fmt" "strconv" ) // we are import the "format" from the main package func main() { //Just like C,C++,JAVA, Python and other languages, here also we begins with main function fmt.Println("Hi Buddy! I am Your GoBuddy... :)")
There are multiple ways of declaring data types If you are habitual of using ; after end of a line, You can use, Go has No problems with that. (AND I FORGOT, THIS IS A MULTILINE COMMMENT)*/ // ret := justChecking() // fmt.Println(ret) // learnDataTypes() // playWithFORLOOP() // a...
/* The game begins If we know all the available Data Types
random_line_split
Initial_Breif.go
package main //we Just Imported the main package import ( "fmt" "strconv" ) // we are import the "format" from the main package func main() { //Just like C,C++,JAVA, Python and other languages, here also we begins with main function fmt.Println("Hi Buddy! I am Your GoBuddy... :)") /* The game b...
(n1 int, n2 int)string{ defer func(){ fmt.Println(recover()) fmt.Println("I am the saviour of this program, I didn't let the program stop :)") }() res := n1/n2 fmt.Println(res) r := "The result of the Division is: "+strconv.Itoa(res) // I just converted Int64 to Sting, strconv is imp...
perfromDivision1
identifier_name
cursor_renderer.rs
use std::time::{Duration, Instant}; use skulpin::skia_safe::{Canvas, Paint, Path, Point}; use crate::renderer::CachingShaper; use crate::editor::{EDITOR, Colors, Cursor, CursorShape}; use crate::redraw_scheduler::REDRAW_SCHEDULER; const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7; const MOTION_PERCENTAGE_SPREAD: f...
match self.state { BlinkState::Waiting | BlinkState::Off => false, BlinkState::On => true } } } #[derive(Debug, Clone)] pub struct Corner { pub current_position: Point, pub relative_position: Point, } impl Corner { pub fn new(relative_position: Poi...
if let Some(scheduled_frame) = scheduled_frame { REDRAW_SCHEDULER.schedule(scheduled_frame); }
random_line_split
cursor_renderer.rs
use std::time::{Duration, Instant}; use skulpin::skia_safe::{Canvas, Paint, Path, Point}; use crate::renderer::CachingShaper; use crate::editor::{EDITOR, Colors, Cursor, CursorShape}; use crate::redraw_scheduler::REDRAW_SCHEDULER; const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7; const MOTION_PERCENTAGE_SPREAD: f...
(&mut self, cursor: Cursor, default_colors: &Colors, font_width: f32, font_height: f32, paint: &mut Paint, shaper: &mut CachingShaper, canvas: &mut Canvas) { let render = self.blink_status.update_status(&cursor); self.previous_position = { ...
draw
identifier_name
cursor_renderer.rs
use std::time::{Duration, Instant}; use skulpin::skia_safe::{Canvas, Paint, Path, Point}; use crate::renderer::CachingShaper; use crate::editor::{EDITOR, Colors, Cursor, CursorShape}; use crate::redraw_scheduler::REDRAW_SCHEDULER; const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7; const MOTION_PERCENTAGE_SPREAD: f...
} #[derive(Debug, Clone)] pub struct Corner { pub current_position: Point, pub relative_position: Point, } impl Corner { pub fn new(relative_position: Point) -> Corner { Corner { current_position: Point::new(0.0, 0.0), relative_position } } ...
{ if self.previous_cursor.is_none() || new_cursor != self.previous_cursor.as_ref().unwrap() { self.previous_cursor = Some(new_cursor.clone()); self.last_transition = Instant::now(); if new_cursor.blinkwait.is_some() && new_cursor.blinkwait != Some(0) { se...
identifier_body
detail-permission-schema.component.ts
/* * 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, software * distribu...
false; } // 이름 길이 체크 if (CommonUtil.getByte(this.editName.trim()) > 150) { Alert.warning(this.translateService.instant('msg.groups.alert.name.len')); return false; } return true; } /** * description validation * @returns {boolean} * @private */ private _descValidation(...
error(error); }); } } /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Public Method - validation |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * name validation * @returns {boolean} * @private */ private _nameValidation(): boolean { // 스키마 이름이 비어 있다면 if (isUnde...
conditional_block
detail-permission-schema.component.ts
/* * 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, software * distribu...
this.loadingHide(); }).catch((error) => this.commonExceptionHandler(error)); } // function - _getWorkspacesByRoleSet /** * 퍼미션 스키마 복사 * @param {string} schemaId * @private */ private _clonePermissionSchema(schemaId: string): void { // 로딩 show this.loadingShow(); // 퍼미션 스키마 복사 ...
wsList.shift(0); this.otherWorkspaces = wsList; } } }
random_line_split
detail-permission-schema.component.ts
/* * 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, software * distribu...
Fl = false; // 스키마 정보 재조회 this._getPermissionSchemaDetail(this._schemaId); }).catch((error) => { // 로딩 hide this.loadingHide(); // error show if (error.hasOwnProperty('details') && error.details.includes('Duplicate')) { Alert.warning(this.translateService....
this.editName
identifier_name
detail-permission-schema.component.ts
/* * 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, software * distribu...
dateSchemaName(): void { // 이벤트 전파 stop event.stopImmediatePropagation(); // validation if (this._nameValidation()) { const params = { name: this.editName }; // 로딩 show this.loadingShow(); // 스키마 수정 this._updateSchema(params).then(() => { // alert ...
{ // 현재 그룹 설명 this.editDesc = this.roleSet.description; // flag this.editDescFl = true; } } // function - schemaDescEditMode /** * 스키마 이름 수정 */ public up
identifier_body
reader.rs
use std::sync::mpsc::{Receiver, Sender, SyncSender, channel}; use std::error::Error; use item::Item; use std::sync::{Arc, RwLock}; use std::process::{Command, Stdio, Child}; use std::io::{BufRead, BufReader}; use event::{EventSender, EventReceiver, Event, EventArg}; use std::thread::JoinHandle; use std::thread; use std...
} pub struct Reader { rx_cmd: EventReceiver, tx_item: SyncSender<(Event, EventArg)>, option: Arc<RwLock<ReaderOption>>, real_stdin: Option<File>, // used to support piped output } impl Reader { pub fn new(rx_cmd: EventReceiver, tx_item: SyncSender<(Event, EventArg)>, ...
{ if options.is_present("ansi") { self.use_ansi_color = true; } if let Some(delimiter) = options.value_of("delimiter") { self.delimiter = Regex::new(&(".*?".to_string() + delimiter)) .unwrap_or_else(|_| Regex::new(r".*?[\t ]").unwrap()); } ...
identifier_body
reader.rs
use std::sync::mpsc::{Receiver, Sender, SyncSender, channel}; use std::error::Error; use item::Item; use std::sync::{Arc, RwLock}; use std::process::{Command, Stdio, Child}; use std::io::{BufRead, BufReader}; use event::{EventSender, EventReceiver, Event, EventArg}; use std::thread::JoinHandle; use std::thread; use std...
(&mut self) { // event loop let mut thread_reader: Option<JoinHandle<()>> = None; let mut tx_reader: Option<Sender<bool>> = None; let mut last_command = "".to_string(); let mut last_query = "".to_string(); // start sender let (tx_sender, rx_sender) = channel(); ...
run
identifier_name
reader.rs
use std::sync::mpsc::{Receiver, Sender, SyncSender, channel}; use std::error::Error; use item::Item; use std::sync::{Arc, RwLock}; use std::process::{Command, Stdio, Child}; use std::io::{BufRead, BufReader}; use event::{EventSender, EventReceiver, Event, EventArg}; use std::thread::JoinHandle; use std::thread; use std...
} Err(_err) => {} // String not UTF8 or other error, skip. } } if !item_group.is_empty() { let _ = tx_sender.send((Event::EvReaderNewItem, Box::new(mem::replace(&mut item_group, Vec::new())))); } let _ = tx_control.send(true); }
{ let _ = tx_sender.send((Event::EvReaderNewItem, Box::new(mem::replace(&mut item_group, Vec::new())))); }
conditional_block
reader.rs
use std::sync::mpsc::{Receiver, Sender, SyncSender, channel}; use std::error::Error; use item::Item; use std::sync::{Arc, RwLock}; use std::process::{Command, Stdio, Child}; use std::io::{BufRead, BufReader}; use event::{EventSender, EventReceiver, Event, EventArg}; use std::thread::JoinHandle; use std::thread; use std...
} } pub fn parse_options(&mut self, options: &ArgMatches) { if options.is_present("ansi") { self.use_ansi_color = true; } if let Some(delimiter) = options.value_of("delimiter") { self.delimiter = Regex::new(&(".*?".to_string() + delimiter)) ...
matching_fields: Vec::new(), delimiter: Regex::new(r".*?\t").unwrap(), replace_str: "{}".to_string(), line_ending: b'\n',
random_line_split
core.py
# -*- coding: utf-8 -*- import re # used to get info from frd file import os import sys import subprocess # used to check ccx version from enum import Enum, auto from typing import List, Tuple import logging from .mesh import Mesher from .results import ResultProcessor import gmsh import numpy as np class Analy...
return True def version(self): if sys.platform == 'win32': cmdPath = os.path.join(self.CALCULIX_PATH, 'ccx.exe ') p = subprocess.Popen([cmdPath, '-v'], stdout=subprocess.PIPE, universal_newlines=True ) stdout, stderr = p.communicate() version = re...
raise AnalysisError('Material ({:s}) is not valid'.format(material.name))
conditional_block
core.py
# -*- coding: utf-8 -*- import re # used to get info from frd file import os import sys import subprocess # used to check ccx version from enum import Enum, auto from typing import List, Tuple import logging from .mesh import Mesher from .results import ResultProcessor import gmsh import numpy as np class Analy...
def writeInput(self) -> str: """ Writes the input deck for the simulation """ self.init() self.prepareConnectors() self.writeHeaders() self.writeMesh() self.writeNodeSets() self.writeElementSets() self.writeKinematicConnectors() ...
""" Creates node sets for any RBE connectors used in the simulation """ # Kinematic Connectors require creating node sets # These are created and added to the node set collection prior to writing numConnectors = 1 for connector in self.connectors: # Node are...
identifier_body
core.py
# -*- coding: utf-8 -*- import re # used to get info from frd file import os import sys import subprocess # used to check ccx version from enum import Enum, auto from typing import List, Tuple import logging from .mesh import Mesher from .results import ResultProcessor import gmsh import numpy as np class Analy...
: UX = 1 UY = 2 UZ = 3 RX = 4 RY = 5 RZ = 6 T = 11 class Simulation: """ Provides the base class for running a Calculix simulation """ NUMTHREADS = 1 """ Number of Threads used by the Calculix Solver """ CALCULIX_PATH = '' """ The Calculix directory path used f...
DOF
identifier_name
core.py
# -*- coding: utf-8 -*- import re # used to get info from frd file import os import sys import subprocess # used to check ccx version from enum import Enum, auto from typing import List, Tuple import logging from .mesh import Mesher from .results import ResultProcessor import gmsh import numpy as np class Analy...
def writeInitialConditions(self): self._input += os.linesep self._input += '{:*^125}\n'.format(' INITIAL CONDITIONS ') for initCond in self.initialConditions: self._input += '*INITIAL CONDITIONS,TYPE={:s}\n'.format(initCond['type'].upper()) self._input += '{:s},{:e}...
self._input += material.writeInput()
random_line_split
types_string.go
// Code generated by "stringer -type=CpuType,CpuSubtypeX86,CpuSubtypeX86_64,CpuSubtypePPC,CpuSubtypeARM,CpuSubtypeARM64,Magic,FileType,SectionType,LoadCommand,SymbolType,StabType,ReferenceType -output types_string.go"; DO NOT EDIT. package macho_widgets import "fmt" const ( _CpuType_name_0 = "CPU_TYPE_VAX" _CpuTyp...
return _CpuSubtypeARM64_name[_CpuSubtypeARM64_index[i]:_CpuSubtypeARM64_index[i+1]] } const ( _Magic_name_0 = "FAT_CIGAM" _Magic_name_1 = "FAT_CIGAM_64" _Magic_name_2 = "FAT_MAGICFAT_MAGIC_64" _Magic_name_3 = "MH_CIGAM" _Magic_name_4 = "MH_CIGAM_64" _Magic_name_5 = "MH_MAGICMH_MAGIC_64" ) var ( _Magic_index_...
{ return fmt.Sprintf("CpuSubtypeARM64(%d)", i) }
conditional_block
types_string.go
// Code generated by "stringer -type=CpuType,CpuSubtypeX86,CpuSubtypeX86_64,CpuSubtypePPC,CpuSubtypeARM,CpuSubtypeARM64,Magic,FileType,SectionType,LoadCommand,SymbolType,StabType,ReferenceType -output types_string.go"; DO NOT EDIT. package macho_widgets import "fmt" const ( _CpuType_name_0 = "CPU_TYPE_VAX" _CpuTyp...
() string { if i >= SectionType(len(_SectionType_index)-1) { return fmt.Sprintf("SectionType(%d)", i) } return _SectionType_name[_SectionType_index[i]:_SectionType_index[i+1]] } const _LoadCommand_name = "LC_SEGMENTLC_SYMTABLC_SYMSEGLC_THREADLC_UNIXTHREADLC_LOADFVMLIBLC_IDFVMLIBLC_IDENTLC_FVMFILELC_PREPAGELC_DYSY...
String
identifier_name
types_string.go
// Code generated by "stringer -type=CpuType,CpuSubtypeX86,CpuSubtypeX86_64,CpuSubtypePPC,CpuSubtypeARM,CpuSubtypeARM64,Magic,FileType,SectionType,LoadCommand,SymbolType,StabType,ReferenceType -output types_string.go"; DO NOT EDIT. package macho_widgets import "fmt" const ( _CpuType_name_0 = "CPU_TYPE_VAX" _CpuTyp...
return _CpuType_name_6 default: return fmt.Sprintf("CpuType(%d)", i) } } const _CpuSubtypeX86_name = "CPU_SUBTYPE_X86_ALLCPU_SUBTYPE_X86_ARCH1" var _CpuSubtypeX86_index = [...]uint8{0, 19, 40} func (i CpuSubtypeX86) String() string { i -= 3 if i >= CpuSubtypeX86(len(_CpuSubtypeX86_index)-1) { return fmt.Sp...
case i == 16777223: return _CpuType_name_4 case i == 16777228: return _CpuType_name_5 case i == 16777234:
random_line_split
types_string.go
// Code generated by "stringer -type=CpuType,CpuSubtypeX86,CpuSubtypeX86_64,CpuSubtypePPC,CpuSubtypeARM,CpuSubtypeARM64,Magic,FileType,SectionType,LoadCommand,SymbolType,StabType,ReferenceType -output types_string.go"; DO NOT EDIT. package macho_widgets import "fmt" const ( _CpuType_name_0 = "CPU_TYPE_VAX" _CpuTyp...
{ if i >= ReferenceType(len(_ReferenceType_index)-1) { return fmt.Sprintf("ReferenceType(%d)", i) } return _ReferenceType_name[_ReferenceType_index[i]:_ReferenceType_index[i+1]] }
identifier_body
caffenet.py
import sys import os import numpy as np from net import Net class CaffeNet(Net): def __init__(self, settings): """Initialize the caffe network. Initializing the caffe network includes two steps: (1) importing the caffe library. We are interested in the modified version that prov...
def get_input_id(self): """Get the identifier for the input layer. Result: The type of this dentifier depends on the underlying network library. However, the identifier returned by this method is suitable as argument for other methods in this class that expect...
"""Get the layer identifiers of the network layers. Arguments: include_input: a flag indicating if the input layer should be included in the result. Result: A list of identifiers (strings in the case of Caffe). Notice that the type of these ...
identifier_body
caffenet.py
import sys import os import numpy as np from net import Net class CaffeNet(Net): def __init__(self, settings):
(1) importing the caffe library. We are interested in the modified version that provides deconvolution support. (2) load the caffe model data. Arguments: settings: The settings object to be used. CaffeNet will only used settings prefixed with "caffe". ULF[todo]: check th...
"""Initialize the caffe network. Initializing the caffe network includes two steps:
random_line_split
caffenet.py
import sys import os import numpy as np from net import Net class CaffeNet(Net): def __init__(self, settings): """Initialize the caffe network. Initializing the caffe network includes two steps: (1) importing the caffe library. We are interested in the modified version that prov...
(self,layer_id): """Get the shape of the given layer. Returns a tuples describing the shape of the layer: Fully connected layer: 1-tuple, the number of neurons, example: (1000, ) Convolutional layer: n_filter x n_rows x n_columns, example: (96, 55, 55) ...
get_layer_shape
identifier_name
caffenet.py
import sys import os import numpy as np from net import Net class CaffeNet(Net): def __init__(self, settings): """Initialize the caffe network. Initializing the caffe network includes two steps: (1) importing the caffe library. We are interested in the modified version that prov...
elif self.settings.caffevis_data_mean is None: data_mean = None else: # The mean has been given as a value or a tuple of values data_mean = np.array(self.settings.caffevis_data_mean) # Promote to shape C,1,1 while len(data_mean.shape) < 1: ...
try: data_mean = np.load(self.settings.caffevis_data_mean) except IOError: print '\n\nCound not load mean file:', self.settings.caffevis_data_mean print 'Ensure that the values in settings.py point to a valid model weights file, network' print ...
conditional_block
simulator.ts
/// <reference path="../../built/pxtsim.d.ts" /> /// <reference path="../../localtypings/pxtparts.d.ts" /> import * as core from "./core"; import U = pxt.U interface SimulatorConfig { highlightStatement(stmt: pxtc.LocationInfo): void; restartSimulator(): void; editor: string; } export const FAST_TRACE_IN...
export function setTraceInterval(intervalMs: number) { driver.setTraceInterval(intervalMs); } export function proxy(message: pxsim.SimulatorCustomMessage) { if (!driver) return; driver.postMessage(message); $debugger.empty(); } function makeClean() { pxsim.U.removeClass(driver.container, getInv...
{ driver.unhide(); }
identifier_body
simulator.ts
/// <reference path="../../built/pxtsim.d.ts" /> /// <reference path="../../localtypings/pxtparts.d.ts" /> import * as core from "./core"; import U = pxt.U interface SimulatorConfig { highlightStatement(stmt: pxtc.LocationInfo): void; restartSimulator(): void; editor: string; } export const FAST_TRACE_IN...
export function isDirty(): boolean { // in need of a restart? return dirty; } export function run(pkg: pxt.MainPackage, debug: boolean, res: pxtc.CompileResult, mute?: boolean, highContrast?: boolean) { makeClean(); const js = res.outfiles[pxtc.BINARY_JS] const boardDefinition = pxt.appTarget.simulato...
random_line_split
simulator.ts
/// <reference path="../../built/pxtsim.d.ts" /> /// <reference path="../../localtypings/pxtparts.d.ts" /> import * as core from "./core"; import U = pxt.U interface SimulatorConfig { highlightStatement(stmt: pxtc.LocationInfo): void; restartSimulator(): void; editor: string; } export const FAST_TRACE_IN...
() { pxsim.U.removeClass(driver.container, getInvalidatedClass()); dirty = false; } function getInvalidatedClass() { if (pxt.appTarget.simulator && pxt.appTarget.simulator.invalidatedClass) { return pxt.appTarget.simulator.invalidatedClass; } return "sepia"; } function getStoppedClass() { ...
makeClean
identifier_name
main.rs
//! A simple demonstration of how to construct and use Canvasses by splitting up the window. #[macro_use] extern crate conrod; #[macro_use] extern crate serde_derive; extern crate chrono; extern crate serde; mod support; fn main() { feature::main(); } mod feature { const FILENAME : &str = "timetracker.json"...
widget_ids! { struct ListItem { master, toggle, remove, name, time, session, } } }
random_line_split
main.rs
//! A simple demonstration of how to construct and use Canvasses by splitting up the window. #[macro_use] extern crate conrod; #[macro_use] extern crate serde_derive; extern crate chrono; extern crate serde; mod support; fn main() { feature::main(); } mod feature { const FILENAME : &str = "timetracker.json"...
// Draw the Ui. fn set_widgets(ref mut ui: conrod::UiCell, ids: &mut Ids, ids_list: &mut Vec<ListItem>, timerstates : &mut Vec<support::TimerState> ,text : &mut String) { use conrod::{color, widget, Colorable, Borderable, Positionable, Labelable, Sizeable, Widget}; let main_color = co...
{ const WIDTH: u32 = 800; const HEIGHT: u32 = 600; const SLEEPTIME: Duration = Duration::from_millis(500); // Build the window. let mut events_loop = glium::glutin::EventsLoop::new(); let window = glium::glutin::WindowBuilder::new() .with_title("Timetracker")...
identifier_body
main.rs
//! A simple demonstration of how to construct and use Canvasses by splitting up the window. #[macro_use] extern crate conrod; #[macro_use] extern crate serde_derive; extern crate chrono; extern crate serde; mod support; fn main() { feature::main(); } mod feature { const FILENAME : &str = "timetracker.json"...
(t : chrono::DateTime<Utc>) -> String { let dur = t.signed_duration_since(chrono::MIN_DATE.and_hms(0u32,0u32,0u32)); let ret = format!( "{:02}:{:02}:{:02}", dur.num_hours(), dur.num_minutes()%60, dur.num_seconds()%60 ); ret } fn dur...
format_time
identifier_name
main.rs
//! A simple demonstration of how to construct and use Canvasses by splitting up the window. #[macro_use] extern crate conrod; #[macro_use] extern crate serde_derive; extern crate chrono; extern crate serde; mod support; fn main() { feature::main(); } mod feature { const FILENAME : &str = "timetracker.json"...
, Enter => { timerstates.push(support::TimerState::new(text.clone())); }, } } for _press in widget::Button::new() .h(50.) .w(50.) .label("+") .bottom_right_of(ids.tab_timers) ...
{ *text = txt; }
conditional_block
RBM_diagonalisation-V4.py
#!/usr/bin/env python3 """ Created on Wed Feb 12 10:44:59 2020 @author: German Sinuco Skeleton modified from https://www.tensorflow.org/tutorials/customization/custom_training https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough Training of an RBM parametrization of ...
(object): def __init__(self,delta=0.0,Omega=0.1,phase=0.0): self.spin = True self.omega_0 = 1.00 # Hamiltonian parameters self.delta = 0.00 self.omega = self.delta + self.omega_0 self.Omega = 1.00 self.phase = phase # the phase in cos(omega t + phase) # Initiali...
Model
identifier_name
RBM_diagonalisation-V4.py
#!/usr/bin/env python3 """ Created on Wed Feb 12 10:44:59 2020 @author: German Sinuco Skeleton modified from https://www.tensorflow.org/tutorials/customization/custom_training https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough Training of an RBM parametrization of ...
self.count = counter #Building of the marginal probability of the RBM using the training parameters and labels of the input layer #P(x)(b,c,W) = exp(bji . x) Prod_l=1^M 2 x cosh(c_l + W_{x,l} . x) # 1. Amplitude (norm) WX_n = [tf.reduce_sum(tf.multiply(self.x[1:counter+1],self.W_n[0]),1)+self...
for j in range(1,self.dim+1): if(self.S==4): y = [[i-2.5,j-2.5]] if(self.S==2): y = [[i-1.5,j-1.5]] self.x = tf.concat([self.x, y], 0) counter +=1
conditional_block
RBM_diagonalisation-V4.py
#!/usr/bin/env python3 """ Created on Wed Feb 12 10:44:59 2020 @author: German Sinuco Skeleton modified from https://www.tensorflow.org/tutorials/customization/custom_training https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough Training of an RBM parametrization of ...
def normalisation(U_): # U_ (in) original matrix # (out) matrix with normalised vectors normaU_ = tf.sqrt(tf.math.reduce_sum(tf.multiply(tf.math.conj(U_),U_,1),axis=0)) U_ = tf.math.truediv(U_,normaU_) return U_ def tf_gram_schmidt(vectors): # add batch dimension for matmul basis...
return self.H_TLS
identifier_body
RBM_diagonalisation-V4.py
#!/usr/bin/env python3 """ Created on Wed Feb 12 10:44:59 2020 @author: German Sinuco Skeleton modified from https://www.tensorflow.org/tutorials/customization/custom_training https://www.tensorflow.org/tutorials/customization/custom_training_walkthrough Training of an RBM parametrization of ...
WX_n = [tf.reduce_sum(tf.multiply(model.x[1:counter+1],model.W_n[0]),1)+model.c_n[0]] for j in range(1,model.hidden_n): y = tf.reduce_sum(tf.multiply(model.x[1:counter+1],model.W_n[j]),1)+model.c_n[j] WX_n = tf.concat([WX_n, [y]], 0) UF_n = tf.sqrt(tf.multiply(tf.reduce_prod(tf.mat...
#Building of the marginal probability of the RBM using the training parameters and labels of the input layer #P(x)(b,c,W) = exp(bji . x) Prod_l=1^M 2 x cosh(c_l + W_{x,l} . x) # 1. Amplitude (norm)
random_line_split
tropcor_pyaps.py
#! /usr/bin/env python2 ############################################################ # Program is part of PySAR v1.2 # # Copyright(c) 2015, Heresh Fattahi, Zhang Yunjun # # Author: Heresh Fattahi, Zhang Yunjun # ####################################################...
grib_file_list.append(grib_file) return grib_file_list def dload_grib(date_list, hour, grib_source='ECMWF', weather_dir='./'): '''Download weather re-analysis grib files using PyAPS Inputs: date_list : list of string in YYYYMMDD format hour : string in HH:MM or HH format ...
grib_file += 'merra-%s-%s.hdf' % (d, hour)
conditional_block
tropcor_pyaps.py
#! /usr/bin/env python2 ############################################################ # Program is part of PySAR v1.2 # # Copyright(c) 2015, Heresh Fattahi, Zhang Yunjun # # Author: Heresh Fattahi, Zhang Yunjun # ####################################################...
def dload_grib(date_list, hour, grib_source='ECMWF', weather_dir='./'): '''Download weather re-analysis grib files using PyAPS Inputs: date_list : list of string in YYYYMMDD format hour : string in HH:MM or HH format grib_source : string, weather_dir : string, Ou...
grib_file_list = [] for d in date_list: grib_file = grib_dir+'/' if grib_source == 'ECMWF' : grib_file += 'ERA-Int_%s_%s.grb' % (d, hour) elif grib_source == 'ERA' : grib_file += 'ERA_%s_%s.grb' % (d, hour) elif grib_source == 'NARR' : grib_file += 'narr-a_221_%s_%s00_000.grb...
identifier_body
tropcor_pyaps.py
#! /usr/bin/env python2 ############################################################ # Program is part of PySAR v1.2 # # Copyright(c) 2015, Heresh Fattahi, Zhang Yunjun # # Author: Heresh Fattahi, Zhang Yunjun # ####################################################...
(date_list, hour, grib_source='ECMWF', weather_dir='./'): '''Download weather re-analysis grib files using PyAPS Inputs: date_list : list of string in YYYYMMDD format hour : string in HH:MM or HH format grib_source : string, weather_dir : string, Output: gri...
dload_grib
identifier_name
tropcor_pyaps.py
#! /usr/bin/env python2 ############################################################ # Program is part of PySAR v1.2 # # Copyright(c) 2015, Heresh Fattahi, Zhang Yunjun # # Author: Heresh Fattahi, Zhang Yunjun # ####################################################...
main(sys.argv[1:])
############################################################### if __name__ == '__main__':
random_line_split
function_system.rs
use crate::{ archetype::{ArchetypeComponentId, ArchetypeGeneration, ArchetypeId}, component::{ComponentId, Tick}, prelude::FromWorld, query::{Access, FilteredAccessSet}, system::{check_system_change_tick, ReadOnlySystemParam, System, SystemParam, SystemParamItem}, world::{unsafe_world_cell::Unsa...
#[inline] fn is_exclusive(&self) -> bool { false } #[inline] unsafe fn run_unsafe(&mut self, input: Self::In, world: UnsafeWorldCell) -> Self::Out { let change_tick = world.increment_change_tick(); // SAFETY: // - The caller has invoked `update_archetype_component...
{ self.system_meta.is_send }
identifier_body
function_system.rs
use crate::{ archetype::{ArchetypeComponentId, ArchetypeGeneration, ArchetypeId}, component::{ComponentId, Tick}, prelude::FromWorld, query::{Access, FilteredAccessSet}, system::{check_system_change_tick, ReadOnlySystemParam, System, SystemParam, SystemParamItem}, world::{unsafe_world_cell::Unsa...
impl<Param: SystemParam> SystemState<Param> { /// Creates a new [`SystemState`] with default state. /// /// ## Note /// For users of [`SystemState::get_manual`] or [`get_manual_mut`](SystemState::get_manual_mut): /// /// `new` does not cache any of the world's archetypes, so you must call [`Sys...
world_id: WorldId, archetype_generation: ArchetypeGeneration, }
random_line_split
function_system.rs
use crate::{ archetype::{ArchetypeComponentId, ArchetypeGeneration, ArchetypeId}, component::{ComponentId, Tick}, prelude::FromWorld, query::{Access, FilteredAccessSet}, system::{check_system_change_tick, ReadOnlySystemParam, System, SystemParam, SystemParamItem}, world::{unsafe_world_cell::Unsa...
(&self, world_id: WorldId) { assert!(self.matches_world(world_id), "Encountered a mismatched World. A SystemState cannot be used with Worlds other than the one it was created with."); } /// Updates the state's internal view of the [`World`]'s archetypes. If this is not called before fetching the parame...
validate_world
identifier_name
de.communardo.confluence.plugins.subspace-subspace-search-resource.js
AJS.toInit( function() { initSubspacesQuickSearch() initSubspacesSearchCheckboxToggle(); }); function
() { jQuery(".subspaces-quicksearch .subspaces-quick-search-query").each(function(){ var quickSearchQuery = jQuery(this); // here we do the little placeholder stuff quickSearchQuery.focus(function () { if (jQuery(this).hasClass('placeholded')) { jQuery(this).val(""); jQuery(this).rem...
initSubspacesQuickSearch
identifier_name
de.communardo.confluence.plugins.subspace-subspace-search-resource.js
AJS.toInit( function() { initSubspacesQuickSearch() initSubspacesSearchCheckboxToggle(); }); function initSubspacesQuickSearch() { jQuery(".subspaces-quicksearch .subspaces-quick-search-query").each(function(){ var quickSearchQuery = jQuery(this); // here we do the little placeholder stuff ...
}; var spans = $("span", dd.$); for (var i = 0, ii = spans.length - 1; i < ii; i++) { (function () { var $this = $(this), html = $this.html(); // highlight matching tokens html = ...
{ searchBox.focus(); }
conditional_block
de.communardo.confluence.plugins.subspace-subspace-search-resource.js
AJS.toInit( function() { initSubspacesQuickSearch() initSubspacesSearchCheckboxToggle(); }); function initSubspacesQuickSearch() { jQuery(".subspaces-quicksearch .subspaces-quick-search-query").each(function(){ var quickSearchQuery = jQuery(this); // here we do the little placeholder stuff ...
function enableDisableSubspacesSearchElements() { //disable/enable the include subspaces and spaces input element if(jQuery('#topspaces_holder .checkbox_topLevelSpaces').is(':checked')) { jQuery('#search-filter-by-space').attr("disabled", true); jQuery('#checkbox_include_subspaces').attr("disabled", tr...
{ var topLevelSpaceCheckboxes = jQuery('#topspaces_holder .checkbox_topLevelSpaces'); topLevelSpaceCheckboxes.click(function() { //now the checkboxes can be used like radiobuttons if(jQuery(this).is(':checked')) { topLevelSpaceCheckboxes.attr('checked', false); jQuery(this).attr('checked', true); ...
identifier_body
de.communardo.confluence.plugins.subspace-subspace-search-resource.js
AJS.toInit( function() { initSubspacesQuickSearch() initSubspacesSearchCheckboxToggle(); }); function initSubspacesQuickSearch() { jQuery(".subspaces-quicksearch .subspaces-quick-search-query").each(function(){ var quickSearchQuery = jQuery(this); // here we do the little placeholder stuff ...
var childNodes = this.childNodes; var success = false; for (var j = childNodes.length - 1; j >= 0; j--) { var childNode = childNodes[j]; var truncatedChars = 1; ...
var $label = $(this); $label.show(); if (this.offsetLeft + this.offsetWidth + elwidth > width - rightPadding) {
random_line_split
cellgrid.rs
use ggez::graphics; use ggez::GameResult; use ggez::nalgebra as na; use crate::simulation::{SimGrid, Automaton}; use crate::commons::cells::BinaryCell; use crate::commons::grids::CellGrid; use crate::gameoflife::GameOfLife; /// Implementation of the Automaton trait for GameOfLife with a CellGrid grid, impl Automaton ...
} // Assign the new grid to the grid struct self.grid.setgrid(newgrid); } // Update the alive and dead cell value in the grid struct self.alive = alive; self.dead = dead; // Increment the generation value in the grid struct self.gener...
BinaryCell::Active => alive += 1 }
random_line_split
cellgrid.rs
use ggez::graphics; use ggez::GameResult; use ggez::nalgebra as na; use crate::simulation::{SimGrid, Automaton}; use crate::commons::cells::BinaryCell; use crate::commons::grids::CellGrid; use crate::gameoflife::GameOfLife; /// Implementation of the Automaton trait for GameOfLife with a CellGrid grid, impl Automaton ...
// A method that returns the graphics blending mode of the automaton grid fn blend_mode(&self) -> Option<graphics::BlendMode> { Some(graphics::BlendMode::Add) } // A method that set the graphics blend mode of the automaton grid (currently does nothing) fn set_blend_mode(&mut self, _: Opti...
{ // Get the grid dimesions and add the banner height if let Some(dimensions) = &self.grid.dimensions { Some(graphics::Rect::new(0.0, 0.0, dimensions.w, dimensions.h + 60.0)) } else {None} }
identifier_body
cellgrid.rs
use ggez::graphics; use ggez::GameResult; use ggez::nalgebra as na; use crate::simulation::{SimGrid, Automaton}; use crate::commons::cells::BinaryCell; use crate::commons::grids::CellGrid; use crate::gameoflife::GameOfLife; /// Implementation of the Automaton trait for GameOfLife with a CellGrid grid, impl Automaton ...
(&self) -> String { format!("Conway's Game of Life | Grid | {}", self.initialstate) } } // Implementation of helper methods for GameOfLife with a CellGrid grid, impl GameOfLife<CellGrid<BinaryCell>> { // A function that retrieves the number of alive cells in // the neighbouring vicity of a given c...
fullname
identifier_name
instance.rs
mod siginfo_ext; pub mod signals; pub use crate::instance::signals::{signal_handler_none, SignalBehavior, SignalHandler}; use crate::alloc::Alloc; use crate::context::Context; use crate::embed_ctx::CtxMap; use crate::error::Error; use crate::instance::siginfo_ext::SiginfoExt; use crate::module::{self, Global, Module}...
{ /// If true, the instance's `fatal_handler` will be called. pub fatal: bool, /// Information about the type of fault that occurred. pub trapcode: TrapCode, /// The instruction pointer where the fault occurred. pub rip_addr: uintptr_t, /// Extra information about the instruction pointer's ...
FaultDetails
identifier_name
instance.rs
mod siginfo_ext; pub mod signals; pub use crate::instance::signals::{signal_handler_none, SignalBehavior, SignalHandler}; use crate::alloc::Alloc; use crate::context::Context; use crate::embed_ctx::CtxMap; use crate::error::Error; use crate::instance::siginfo_ext::SiginfoExt; use crate::module::{self, Global, Module}...
pub fn globals(&self) -> &[i64] { unsafe { self.alloc.globals() } } /// Return the WebAssembly globals as a mutable slice of `i64`s. pub fn globals_mut(&mut self) -> &mut [i64] { unsafe { self.alloc.globals_mut() } } /// Check whether a given range in the host address space ove...
random_line_split
instance.rs
mod siginfo_ext; pub mod signals; pub use crate::instance::signals::{signal_handler_none, SignalBehavior, SignalHandler}; use crate::alloc::Alloc; use crate::context::Context; use crate::embed_ctx::CtxMap; use crate::error::Error; use crate::instance::siginfo_ext::SiginfoExt; use crate::module::{self, Global, Module}...
State::Ready { .. } => { panic!("instance in Ready state after returning from guest context") } } } fn run_start(&mut self) -> Result<(), Error> { if let Some(start) = self.module.get_start_func()? { self.run_func(start, &[])?; } ...
{ // Sandbox is no longer runnable. It's unsafe to determine all error details in the signal // handler, so we fill in extra details here. self.populate_fault_detail()?; if let State::Fault { ref details, .. } = self.state { if details....
conditional_block
instance.rs
mod siginfo_ext; pub mod signals; pub use crate::instance::signals::{signal_handler_none, SignalBehavior, SignalHandler}; use crate::alloc::Alloc; use crate::context::Context; use crate::embed_ctx::CtxMap; use crate::error::Error; use crate::instance::siginfo_ext::SiginfoExt; use crate::module::{self, Global, Module}...
/// Get a mutable reference to the instance's `Alloc`. fn alloc_mut(&mut self) -> &mut Alloc { &mut self.alloc } /// Get a reference to the instance's `Module`. fn module(&self) -> &dyn Module { self.module.deref() } /// Get a reference to the instance's `State`. fn s...
{ &self.alloc }
identifier_body