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
extension.ts
var microphone = true; var codeBuffer = ""; var errorFlag = false; var language = ""; var cwd = ""; var ast_cwd = ""; var cred = ""; var datatypes = ["int", "float", "long", "double", "char"];
// 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
iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function init(uid, mid) { user_id = ui...
}); socket.on('informAboutConnectionEnd', function (connId) { $('#' + connId).remove(); WrtcHelper.closeExistingConnection(connId); }); socket.on('showChatMessage', function (data) { var name = document.createElement("P"); name.innerHTML...
{ 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
_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function init(uid, mid) { user_id = uid; ...
}); 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
iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function init(uid, mid) { user_id = ui...
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
iframe_api"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); // 3. This function creates an <iframe> (and YouTube player) // after the API code downloads. var player; function init(uid, mid) { user_id = ui...
(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
// ReleaseVersion is the version of Till release ReleaseVersion = "dev" StatMu *tillclient.InstanceStatMutex // Cache is the cache specific config CacheConfig cache.Config // LoggerConfig is the logger specific config LoggerConfig logger.Config // SessionsConfig is the sessions specific config SessionsConfi...
} incrRequestStatDelta() logReqSummary(p.GID, sreq.Method, sreq.URL.String(), cresp.StatusCode, true) // Build the target req and resp specifically for logging. _, treq, terr := buildTargetRequest(scheme, sreq, pconf, sess, p) // defer treq.Body.Close() if terr == nil && treq != nil { // reco...
{ 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
ReleaseVersion is the version of Till release ReleaseVersion = "dev" StatMu *tillclient.InstanceStatMutex // Cache is the cache specific config CacheConfig cache.Config // LoggerConfig is the logger specific config LoggerConfig logger.Config // SessionsConfig is the sessions specific config SessionsConfig ...
} // 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
(pages.Page) u := r.URL u.Host = r.Host u.Scheme = scheme p.SetURL(u.String()) p.SetMethod(r.Method) // build the page headers nh := map[string]interface{}{} for name, values := range r.Header { nh[name] = strings.Join(values, ",") } // remove User-Agent header if we force-user agent if pconf.ForceUA {...
copySourceHeaders
identifier_name
proxy.go
ToTarget(ctx context.Context, sconn net.Conn, sreq *http.Request, scheme string, p *pages.Page, pconf *PageConfig) (tresp *http.Response, err error) { var sess *sessions.Session if features.Allow(features.Cache) && !CacheConfig.Disabled { // check if past response exist in the cache. if so, then return it. cres...
random_line_split
fmt.rs
.Octal.html) //! * `x` ⇒ [`LowerHex`](trait.LowerHex.html) //! * `X` ⇒ [`UpperHex`](trait.UpperHex.html) //! * `p` ⇒ [`Pointer`](trait.Pointer.html) //! * `b` ⇒ [`Binary`] //! * `e` ⇒ [`LowerExp`](trait.LowerExp.html) //! * `E` ⇒ [`UpperExp`](trait.UpperExp.html) //! //! What this means is that any type of argument whi...
random_line_split
fmt.rs
let magnitude = (self.x * self.x + self.y * self.y) as f64; //! let magnitude = magnitude.sqrt(); //! //! // Respect the formatting flags by using the helper method //! // `pad_integral` on the Formatter object. See the method //! // documentation for details, and the function `...
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
. The meaning //! // of this format is to print the magnitude of a vector. //! impl fmt::Binary for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! let magnitude = (self.x * self.x + self.y * self.y) as f64; //! let magnitude = magnitude.sqrt(); //! //! // Respect t...
<'_>)
identifier_name
index.ts
} interface PluginAPI { purgeNestedScroll(groupId: NestedScrollGroupId): void } interface NestedScrollInstancesMap { [key: string]: NestedScroll [index: number]: NestedScroll } const forceScrollStopHandler = (scrolls: BScroll[]) => { scrolls.forEach((scroll) => { if (scroll.pending) { scroll.stop()...
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
} interface PluginAPI { purgeNestedScroll(groupId: NestedScrollGroupId): void } interface NestedScrollInstancesMap { [key: string]: NestedScroll [index: number]: NestedScroll } const forceScrollStopHandler = (scrolls: BScroll[]) => { scrolls.forEach((scroll) => { if (scroll.pending) { scroll.stop()...
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
} interface PluginAPI { purgeNestedScroll(groupId: NestedScrollGroupId): void } interface NestedScrollInstancesMap { [key: string]: NestedScroll [index: number]: NestedScroll } const forceScrollStopHandler = (scrolls: BScroll[]) => { scrolls.forEach((scroll) => { if (scroll.pending) { scroll.stop()...
(): 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
(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
// 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
0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]; // SHA-256 digests will be emitted in the following format pub const DIGEST_LEN: usize = 256/8; pub type Digest = [u8; DIGEST_LEN]; // Compute the SHA-256 hash of any message pub fn sha_256(message: &[u8]) -> Digest { ...
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
): """ Takes some data and makes predictions based on the seed which was learnt in the fit() part. Returns the predictions. """ random.seed(self.seed) preds = [{"id": instance['id'], "prediction": random.choice([0, 1])} for instance in test_data] return preds de...
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
""" Takes some data and makes predictions based on the seed which was learnt in the fit() part. Returns the predictions. """ random.seed(self.seed) preds = [{"id": instance['id'], "prediction": random.choice([0, 1])} for instance in test_data] return preds def
(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
""" Takes some data and makes predictions based on the seed which was learnt in the fit() part. Returns the predictions. """ random.seed(self.seed) preds = [{"id": instance['id'], "prediction": random.choice([0, 1])} for instance in test_data] return preds def r...
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
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
.ValueOf(curObj)).FieldByName("Spec") for _, fn := range NUMFields { updField := updSpec.FieldByName(fn).Interface() curField := curSpec.FieldByName(fn).Interface() if !reflect.DeepEqual(updField, curField) { errs = append(errs, fn) } } // if ipconfig field is not empty and non nil (old or new) then do ...
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
lect.ValueOf(curObj)).FieldByName("Spec") for _, fn := range NUMFields { updField := updSpec.FieldByName(fn).Interface() curField := curSpec.FieldByName(fn).Interface() if !reflect.DeepEqual(updField, curField) { errs = append(errs, fn) } } // if ipconfig field is not empty and non nil (old or new) then...
(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
// Reflect can't distinguish between empty object and nil object. So adding this additional check for IP Config // We perform the deepequal check only if either of the old or new spec are not nil and not empty if ((updIPConfig != nil) && !reflect.DeepEqual(updIPConfig, emptyIPConfig)) || ((curIPConfig != nil) && !re...
{ 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
lect.ValueOf(curObj)).FieldByName("Spec") for _, fn := range NUMFields { updField := updSpec.FieldByName(fn).Interface() curField := curSpec.FieldByName(fn).Interface() if !reflect.DeepEqual(updField, curField) { errs = append(errs, fn) } } // if ipconfig field is not empty and non nil (old or new) then...
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
处的字节为零,则跳过匹配]。 8 ] 向后跳转到匹配[除非指针处的字节为零。 */ const MUTATION_RATE: f64 = 0.05; const CROSSOVER_RATE: f64 = 0.80; const INITIAL_GENOME_SIZE: usize = 100; const NUM_ELITE: usize = 4;//精英选择个数 const NUM_COPIES_ELITE: usize = 1; //每个精英复制数 const NUM_THREAD: usize = 2;//线程数 const POPULATION_SIZE: usize = 50*NUM_THREAD+NUM_E...
new_pop.push(self.populations[i]); } } let (tx, rx)
.NUM_COPIES_ELITE{
identifier_name
main.1.rs
_COPIES_ELITE: usize = 1; //每个精英复制数 const NUM_THREAD: usize = 2;//线程数 const POPULATION_SIZE: usize = 50*NUM_THREAD+NUM_ELITE*NUM_COPIES_ELITE;//人口数量 //基因组 #[derive(Copy)] pub struct Genome { fitness: f64, genes: Vec<f64>, } impl Genome { fn new() -> Genome{ Genome{ fitness: 1.0, ...
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
处的字节为零,则跳过匹配]。 8 ] 向后跳转到匹配[除非指针处的字节为零。 */ const MUTATION_RATE: f64 = 0.05; const CROSSOVER_RATE: f64 = 0.80; const INITIAL_GENOME_SIZE: usize = 100; const NUM_ELITE: usize = 4;//精英选择个数 const NUM_COPIES_ELITE: usize = 1; //每个精英复制数 const NUM_THREAD: usize = 2;//线程数 const POPULATION_SIZE: usize = 50*NUM_THREAD+NUM_E...
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
处的字节为零,则跳过匹配]。 8 ] 向后跳转到匹配[除非指针处的字节为零。 */ const MUTATION_RATE: f64 = 0.05; const CROSSOVER_RATE: f64 = 0.80; const INITIAL_GENOME_SIZE: usize = 100; const NUM_ELITE: usize = 4;//精英选择个数 const NUM_COPIES_ELITE: usize = 1; //每个精英复制数 const NUM_THREAD: usize = 2;//线程数 const POPULATION_SIZE: usize = 50*NUM_THREAD+NUM_E...
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
return(freq) 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, ...
"""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
0], args[1], args[2], args[3], args[4], args[5] elif type(args) == dict: w0, dw1, dt1, dw2, dt2, delay = args['w0'], args['dw1'], args['dt1'], args['dw2'], args['dt2'], args['delay'] else:
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
(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
0*(t-delay)) if t > delay and t < delay+dtP else 0)' # + (dwP*sin(2*w0*(t-delay)) if t > delay and t < delay+dtP else 0) # time derivative of the time depandant frequency strDWQP = '- dwQ*exp(-0.5*(t/dtQ)**2) * t/(dtQ**2) + (2*w0*dwP*cos(2*w0*(t-delay)) if t > delay and t < delay+dtP else 0)' # + 2*w0...
masterList[1].append(np.abs(xi))
random_line_split
DanhSachChoDuyet.page.ts
} from '@angular/common/http'; import { AppSettings } from '../../../../AppSettings'; const { App } = Plugins; export const AUTH_KEY = 'AUTH'; @Component({ selector: 'danhsachchoduyet', templateUrl: 'DanhSachChoDuyet.page.html', styleUrls: ['DanhSachChoDuyet.page.scss'], }) export class DanhSachChoDuyet implem...
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
ErrorResponse } from '@angular/common/http'; import { AppSettings } from '../../../../AppSettings'; const { App } = Plugins; export const AUTH_KEY = 'AUTH'; @Component({ selector: 'danhsachchoduyet', templateUrl: 'DanhSachChoDuyet.page.html', styleUrls: ['DanhSachChoDuyet.page.scss'], }) export class DanhSachCh...
} 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
ErrorResponse } from '@angular/common/http'; import { AppSettings } from '../../../../AppSettings'; const { App } = Plugins; export const AUTH_KEY = 'AUTH'; @Component({ selector: 'danhsachchoduyet', templateUrl: 'DanhSachChoDuyet.page.html', styleUrls: ['DanhSachChoDuyet.page.scss'], }) export class DanhSachCh...
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
() -> 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
irreducible subexpression produces a Crash. #[derive(Debug, Hash, Eq, PartialEq, Clone, Constructor)] pub struct Crash { message: String, } /// The result of evaluating/nocking/tarring a Noun: a product Noun or a Crash. pub type NockResult = Result<Rc<Noun>, Crash>; /* Atom encoding and decoding * * * * * * * * ...
// *[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
byte slice. pub fn as_bytes_le(&self) -> &[u8] { &self.bytes_le } /// Returns the value of the atom as Some(u128) if it fits, else None. pub fn try_u128(&self) -> Option<u128> { if self.as_bytes_le().is_empty() { Some(0) } else if self.bytes_le.len() < 16 { ...
match self { Noun::Atom(atom) => Ok(atom), Noun::Cell(_) => Err(Crash::from("required atom, had cell")), } } //
identifier_body
symdumper.rs
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
: u64, Address: u64, Register: u32, Scope: u32, Tag: u32, NameLen: u32, MaxNameLen: u32, // technically this field is dynamically sized as specified by MaxNameLen Name: [u16; 8192], } impl Default for SymbolInfoW { fn default() -> Self { SymbolInfoW { // Subtrac...
} #[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
{ 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
LineNumber: 0, FileName: std::ptr::null(), Address: 0, } } } #[allow(non_snake_case)] #[repr(C)] struct ImagehlpModule64W { SizeOfStruct: u32, BaseOfImage: u64, ImageSize: u32, TimeDateStamp: u32, CheckSum: u32, NumSyms: u32, SymType: u32, ...
{ return Err(Error::new(ErrorKind::Other, "symchk returned with error")); }
conditional_block
Initial_Breif.go
"Rectangle structure" associated funtion func (r Rectangle) Area() int{ return r.side1 * r.side2 } func learnPointers(){ /* Pointers has always been tough to understand and implement for me. But now when I developed a certain method to understand them */ valX := 123 fmt.Println("Initial Value of X: ",...
{ //LOGICAL OR fmt.Println("Condition 1") fmt.Println(i) }
conditional_block
Initial_Breif.go
: ",val1,",VAL2: ",val2) // practiceArray() // practiceSlices() // use_defer() // how_to_RECOVER() // panicAndRecover() // learnPointers() // ---Uncomment this part to learn the Implementation of structures and their associated functions-------------- // rec1 := Rectangle{10,20,1...
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
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
: ",val1,",VAL2: ",val2) // practiceArray() // practiceSlices() // use_defer() // how_to_RECOVER() // panicAndRecover() // learnPointers() // ---Uncomment this part to learn the Implementation of structures and their associated functions-------------- // rec1 := Rectangle{10,20,1...
(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
const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7; const MOTION_PERCENTAGE_SPREAD: f32 = 0.5; const COMMAND_LINE_DELAY_FRAMES: u64 = 5; const DEFAULT_CELL_PERCENTAGE: f32 = 1.0 / 8.0; const STANDARD_CORNERS: &[(f32, f32); 4] = &[(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)]; enum BlinkState { Waiting, ...
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
; const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7; const MOTION_PERCENTAGE_SPREAD: f32 = 0.5; const COMMAND_LINE_DELAY_FRAMES: u64 = 5; const DEFAULT_CELL_PERCENTAGE: f32 = 1.0 / 8.0; const STANDARD_CORNERS: &[(f32, f32); 4] = &[(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)]; enum BlinkState { Waiting,...
(&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
const AVERAGE_MOTION_PERCENTAGE: f32 = 0.7; const MOTION_PERCENTAGE_SPREAD: f32 = 0.5; const COMMAND_LINE_DELAY_FRAMES: u64 = 5; const DEFAULT_CELL_PERCENTAGE: f32 = 1.0 / 8.0; const STANDARD_CORNERS: &[(f32, f32); 4] = &[(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)]; enum BlinkState { Waiting, ...
BlinkState::On => new_cursor.blinkon }.filter(|millis| millis > &0).map(|millis| Duration::from_millis(millis)); if delay.map(|delay| self.last_transition + delay < Instant::now()).unwrap_or(false) { self.state = match self.state { BlinkState::Waiting => Bli...
{ 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
SchemaSetComponent) private _permissionSchemaSetComp: PermissionSchemaSetComponent; // 스키마 아이디 private _schemaId: string; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | P...
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
Schema(modal['schemaId']) : this._deletePermissionSchema(modal['schemaId']); } /** * 스키마 이름 변경모드 */ public schemaNameEditMode(): void { if( !this.roleSet.readOnly ) { // 현재 그룹 이름 this.editName = this.roleSet.name; // flag this.editNameFl = true; } } // function - schemaNam...
wsList.shift(0); this.otherWorkspaces = wsList; } } }
random_line_split
detail-permission-schema.component.ts
SchemaSetComponent) private _permissionSchemaSetComp: PermissionSchemaSetComponent; // 스키마 아이디 private _schemaId: string; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | P...
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
SchemaSetComponent) private _permissionSchemaSetComp: PermissionSchemaSetComponent; // 스키마 아이디 private _schemaId: string; /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | Protected Variables |-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /*-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= | P...
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::process::{Command, Stdio, Child}; use std::io::{BufRead, BufReader}; use event::{EventSender, EventReceiver, Event, EventArg}; use std::thread::JoinHandle; use std::thread; use std::time::Duration; use std::collections::HashMap; use std::mem; use std::fs::File; use regex::Regex; use sender::CachedSender; use ...
.filter_map(|string| { parse_range(string) }).collect(); } if options.is_present("read0") { self.line_ending = b'\0'; } } } pub struct Reader { rx_cmd: EventReceiver, tx_item: SyncSender<(Event, EventArg)>, option...
{ 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::process::{Command, Stdio, Child}; use std::io::{BufRead, BufReader}; use event::{EventSender, EventReceiver, Event, EventArg}; use std::thread::JoinHandle; use std::thread; use std::time::Duration; use std::collections::HashMap; use std::mem; use std::fs::File; use regex::Regex; use sender::CachedSender; use ...
(&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
BufRead, BufReader}; use event::{EventSender, EventReceiver, Event, EventArg}; use std::thread::JoinHandle; use std::thread; use std::time::Duration; use std::collections::HashMap; use std::mem; use std::fs::File; use regex::Regex; use sender::CachedSender; use field::{FieldRange, parse_range}; use clap::ArgMatches; ...
{ let _ = tx_sender.send((Event::EvReaderNewItem, Box::new(mem::replace(&mut item_group, Vec::new())))); }
conditional_block
reader.rs
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::time::Duration; use std::collections::HashMap; use std::mem; use std::fs::File; use regex::Regex; use sender::CachedSender; use ...
} } 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
""" The Calculix directory path used for Windows platforms""" VERBOSE_OUTPUT = True """ When enabled, the output during the analysis is redirected to the console""" def __init__(self, meshModel: Mesher): self._input = '' self._workingDirectory = '' self._analysisCompleted = Fa...
raise AnalysisError('Material ({:s}) is not valid'.format(material.name))
conditional_block
core.py
and the second column the chosen face orientation """ return self._els @surfacePairs.setter def els(self, surfacePairs): self._elSurfacePairs = surfacePairs def writeInput(self) -> str: out = '*SURFACE,NAME={:s}\n'.format(self.name) for i in range(self._elSurface...
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
and the second column the chosen face orientation """ return self._els @surfacePairs.setter def els(self, surfacePairs): self._elSurfacePairs = surfacePairs def writeInput(self) -> str: out = '*SURFACE,NAME={:s}\n'.format(self.name) for i in range(self._elSurface...
: 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
string(self.els, precision=2, separator=', ', threshold=9999999999)[1:-1] return out class Connector: """ A Connector ir a rigid connector between a set of nodes and an (optional) reference node. """ def __init__(self, name, nodes, refNode = None): self.name = name self._refN...
self._input += material.writeInput()
random_line_split
types_string.go
6_64) String() string { switch { case i == 3: return _CpuSubtypeX86_64_name_0 case i == 8: return _CpuSubtypeX86_64_name_1 default: return fmt.Sprintf("CpuSubtypeX86_64(%d)", i) } } const ( _CpuSubtypePPC_name_0 = "CPU_SUBTYPE_POWERPC_ALLCPU_SUBTYPE_POWERPC_601CPU_SUBTYPE_POWERPC_602CPU_SUBTYPE_POWERPC_603...
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
6_64) String() string { switch { case i == 3: return _CpuSubtypeX86_64_name_0 case i == 8: return _CpuSubtypeX86_64_name_1 default: return fmt.Sprintf("CpuSubtypeX86_64(%d)", i) } } const ( _CpuSubtypePPC_name_0 = "CPU_SUBTYPE_POWERPC_ALLCPU_SUBTYPE_POWERPC_601CPU_SUBTYPE_POWERPC_602CPU_SUBTYPE_POWERPC_603...
() 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
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
1: _LoadCommand_name[0:10], 2: _LoadCommand_name[10:19], 3: _LoadCommand_name[19:28], 4: _LoadCommand_name[28:37], 5: _LoadCommand_name[37:50], 6: _LoadCommand_name[50:63], 7: _LoadCommand_name[63:74], 8: _LoadCommand_name[74:82], 9: ...
{ 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
'python')) import caffe print 'debug[caffe]: CaffeNet.__init__: using Caffe in', caffe.__file__ # Check if the imported caffe provides all required functions self._check_caffe_version(caffe) # Set the mode to CPU or GPU. # Note: in the latest Caffe versions, th...
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
(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
'python')) import caffe print 'debug[caffe]: CaffeNet.__init__: using Caffe in', caffe.__file__ # Check if the imported caffe provides all required functions self._check_caffe_version(caffe) # Set the mode to CPU or GPU. # Note: in the latest Caffe versions, th...
(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
'python')) import caffe print 'debug[caffe]: CaffeNet.__init__: using Caffe in', caffe.__file__ # Check if the imported caffe provides all required functions self._check_caffe_version(caffe) # Set the mode to CPU or GPU. # Note: in the latest Caffe versions, th...
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
", "yellow"]; let config: SimulatorConfig; let lastCompileResult: pxtc.CompileResult; let tutorialMode: boolean; let displayedModals: pxt.Map<boolean> = {}; export let simTranslations: pxt.Map<string>; let dirty = false; let $debugger: JQuery; export function setTranslations(translations: pxt.Map<string>) { simTr...
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
", "yellow"]; let config: SimulatorConfig; let lastCompileResult: pxtc.CompileResult; let tutorialMode: boolean; let displayedModals: pxt.Map<boolean> = {}; export let simTranslations: pxt.Map<string>; let dirty = false; let $debugger: JQuery; export function setTranslations(translations: pxt.Map<string>) { simTr...
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
", "yellow"]; let config: SimulatorConfig; let lastCompileResult: pxtc.CompileResult; let tutorialMode: boolean; let displayedModals: pxt.Map<boolean> = {}; export let simTranslations: pxt.Map<string>; let dirty = false; let $debugger: JQuery; export function setTranslations(translations: pxt.Map<string>) { simTr...
() { 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
_path).unwrap(); // A type used for converting `conrod::render::Primitives` into `Command`s that can be used // for drawing to the glium `Surface`. let mut renderer = conrod::backend::glium::Renderer::new(&display).unwrap(); // The image map describing each of our widget->image mapping...
random_line_split
main.rs
um::glium::Surface; extern crate serde_json; use support; use chrono::prelude::*; use chrono; pub fn main()
let font_path = assets.join("fonts/NotoSans/NotoSans-Regular.ttf"); ui.fonts.insert_from_file(font_path).unwrap(); // A type used for converting `conrod::render::Primitives` into `Command`s that can be used // for drawing to the glium `Surface`. let mut renderer = conrod::backen...
{ 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
::new(); let window = glium::glutin::WindowBuilder::new() .with_title("Timetracker") .with_dimensions(WIDTH, HEIGHT); let context = glium::glutin::ContextBuilder::new() .with_vsync(true) .with_multisampling(4); let display = glium::Display::new(win...
format_time
identifier_name
main.rs
; extern crate serde_json; use support; use chrono::prelude::*; use chrono; pub fn main() { const WIDTH: u32 = 800; const HEIGHT: u32 = 600; const SLEEPTIME: Duration = Duration::from_millis(500); // Build the window. let mut events_loop = glium:...
{ *text = txt; }
conditional_block
RBM_diagonalisation-V4.py
(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
1,1],dtype=tf.float64, minval=-1.0,maxval=1.0),trainable=True) self.b_n = tf.Variable(tf.random.stateless_uniform([self.dim*self.dim,2], seed=[1,1],dtype=tf.float64, ...
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
1,1],dtype=tf.float64, minval=-1.0,maxval=1.0),trainable=True) self.b_n = tf.Variable(tf.random.stateless_uniform([self.dim*self.dim,2], seed=[1,1],dtype=tf.float64, ...
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
_ph], seed=[1,1],dtype=tf.float64, minval=-1.0,maxval=1.0),trainable=True) UF_aux = tf.Variable(np.zeros((self.dim*self.dim), dtype=np.complex128),trainable = False) # ext. m...
#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
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
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
(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
ERA-Interim','ERA','MERRA','MERRA1','NARR'},\ help='source of the atmospheric data.\n'+\ 'By the time of 2018-Mar-06, ERA and ECMWF data download link is working.\n'+\ 'NARR is working for 1979-Jan to 2014-Oct.\n'+\ ...
############################################################### if __name__ == '__main__':
random_line_split
function_system.rs
[`SystemState`] matches the provided world. #[inline] fn validate_world(&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...
{ self.system_meta.is_send }
identifier_body
function_system.rs
/// // Later, fetch the cached system state, saving on overhead /// world.resource_scope(|world, mut cached_state: Mut<CachedSystemState>| { /// let mut event_reader = cached_state.event_state.get_mut(world); /// /// for events in event_reader.iter() { /// println!("Hello World!"); /// } /// }); ///...
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
/// // Later, fetch the cached system state, saving on overhead /// world.resource_scope(|world, mut cached_state: Mut<CachedSystemState>| { /// let mut event_reader = cached_state.event_state.get_mut(world); /// /// for events in event_reader.iter() { /// println!("Hello World!"); /// } /// }); ///...
(&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
() { 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
holded"); } }); quickSearchQuery.change(function () { if (jQuery(this).val() == "") { jQuery(this).val(jQuery(this).attr('placeholder')); jQuery(this).addClass("placeholded"); } }); /** * function to add a tooltip showing the space name to each drop down list item ...
}; 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
holded"); } }); quickSearchQuery.change(function () { if (jQuery(this).val() == "") { jQuery(this).val(jQuery(this).attr('placeholder')); jQuery(this).addClass("placeholded"); } }); /** * function to add a tooltip showing the space name to each drop down list item ...
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
holded"); } }); quickSearchQuery.change(function () { if (jQuery(this).val() == "") { jQuery(this).val(jQuery(this).attr('placeholder')); jQuery(this).addClass("placeholded"); } }); /** * function to add a tooltip showing the space name to each drop down list item ...
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
: f32) -> Self { Self { grid: Self::Grid::new(cellsize), initialstate: initialstate.to_string(), cellsize, generation: 0, alive: 0, dead: 0, } } /// A method that initializes the automaton for the given dimensions. fn i...
} // 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
: f32) -> Self { Self { grid: Self::Grid::new(cellsize), initialstate: initialstate.to_string(), cellsize, generation: 0, alive: 0, dead: 0, } } /// A method that initializes the automaton for the given dimensions. fn i...
// 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
: f32) -> Self { Self { grid: Self::Grid::new(cellsize), initialstate: initialstate.to_string(), cellsize, generation: 0, alive: 0, dead: 0, } } /// A method that initializes the automaton for the given dimensions. fn i...
(&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
/// Get a mutable reference to a context value of a particular type, if it exists. pub fn get_embed_ctx_mut<T: Any>(&mut self) -> Option<&mut T> { self.embed_ctx.get_mut::<T>() } /// Insert a context value. /// /// If a context value of the same type already existed, it is returned. ...
FaultDetails
identifier_name
instance.rs
) state: State, /// The memory allocated for this instance alloc: Alloc, /// Handler run for signals that do not arise from a known WebAssembly trap, or that involve /// memory outside of the current instance. fatal_handler: fn(&Instance) -> !, /// A fatal handler set from C c_fatal_handl...
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
let orig_len = self .alloc .expand_heap(additional_pages * WASM_PAGE_SIZE, self.module.as_ref())?; Ok(orig_len / WASM_PAGE_SIZE) } /// Return the WebAssembly heap as a slice of bytes. pub fn heap(&self) -> &[u8] { unsafe { self.alloc.heap() } } /// R...
{ // 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
) state: State, /// The memory allocated for this instance alloc: Alloc, /// Handler run for signals that do not arise from a known WebAssembly trap, or that involve /// memory outside of the current instance. fatal_handler: fn(&Instance) -> !, /// A fatal handler set from C c_fatal_handl...
/// 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