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
processOps.ts
const BASE_PATH = 'editor.composition.i' const TOOLBOX_PATH = 'editor.$toolbox' declare var global: any export function processOps ( { state, props } ) { const { ops } = props if ( ! ops ) { return } let newselection ops.forEach ( op => { const path = op.path && `${BASE_PATH}.${op.path.join('.i...
return { selection: newselection } } }
random_line_split
list.rs
use super::{print_size, io, Header, Operation, App, Arg, ArgMatches, SubCommand, PathBuf, Regex, RegexFault}; fn valid_path(x: String) -> Result<(), String> { let p = PathBuf::from(&x); match (p.exists(), p.is_file()) { (true, true) => Ok(()), (false, _) => Err(format!("Cannot pro...
(x: &ArgMatches) -> Operation { Operation::List( PathBuf::from(x.value_of("file").unwrap()), match x.value_of("regex") { Option::None => None, Option::Some(r) => Regex::new(&r).ok(), }, x.is_present("group"), x.is_present("user"), x.is_present(...
get
identifier_name
list.rs
use super::{print_size, io, Header, Operation, App, Arg, ArgMatches, SubCommand, PathBuf, Regex, RegexFault}; fn valid_path(x: String) -> Result<(), String> { let p = PathBuf::from(&x); match (p.exists(), p.is_file()) { (true, true) => Ok(()), (false, _) => Err(format!("Cannot pro...
/// print data pub fn exec( header: &Header, regex: &Option<Regex>, group: bool, user: bool, gid: bool, uid: bool, size: bool, ) -> io::Result<()> { let flag = match regex { &Option::None => true, &Option::Some(ref regex) => { let path = header.path()?; ...
{ SubCommand::with_name("list") .about("lists contents of a regex") .arg( Arg::with_name("group") .long("groupname") .takes_value(false) .next_line_help(true) .help("display group name"), ) .arg( ...
identifier_body
list.rs
use super::{print_size, io, Header, Operation, App, Arg, ArgMatches, SubCommand, PathBuf, Regex, RegexFault}; fn valid_path(x: String) -> Result<(), String> { let p = PathBuf::from(&x); match (p.exists(), p.is_file()) { (true, true) => Ok(()), (false, _) => Err(format!("Cannot proce...
.takes_value(true) .multiple(false) .value_name("REGEX") .validator(valid_regex) .next_line_help(true) .help("regex to filter list by"), ) } /// print data pub fn exec( header: &Header, regex: &Option<Regex>...
Arg::with_name("regex") .short("r") .long("regex")
random_line_split
syndicate-create-write-read.py
#!/usr/bin/env python """ Copyright 2016 The Trustees of Princeton University 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 Unle...
testlib.save_output( output_dir, save_name, out ) return exitcode, out def overlay( expected_data, buf, offset ): expected_data_list = list(expected_data) i = offset for c in list(buf): if i >= len(expected_data_list): padlen = i - len(expected_data_list) + 1 for j ...
def stop_and_save( output_dir, proc, out_path, save_name ): exitcode, out = testlib.stop_gateway( proc, out_path )
random_line_split
syndicate-create-write-read.py
#!/usr/bin/env python """ Copyright 2016 The Trustees of Princeton University 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 Unle...
( output_dir, proc, out_path, save_name ): exitcode, out = testlib.stop_gateway( proc, out_path ) testlib.save_output( output_dir, save_name, out ) return exitcode, out def overlay( expected_data, buf, offset ): expected_data_list = list(expected_data) i = offset for c in list(buf): if...
stop_and_save
identifier_name
syndicate-create-write-read.py
#!/usr/bin/env python """ Copyright 2016 The Trustees of Princeton University 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 Unle...
if __name__ == "__main__": local_path = testlib.make_random_file(16384) expected_data = None with open(local_path, "r") as f: expected_data = f.read() config_dir, output_dir = testlib.test_setup() volume_name = testlib.add_test_volume( config_dir, blocksize=1024 ) RG_gateway_name =...
expected_data_list = list(expected_data) i = offset for c in list(buf): if i >= len(expected_data_list): padlen = i - len(expected_data_list) + 1 for j in xrange(0, padlen): expected_data_list.append('\0') expected_data_list[i] = c i += 1 ret...
identifier_body
syndicate-create-write-read.py
#!/usr/bin/env python """ Copyright 2016 The Trustees of Princeton University 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 Unle...
rg_exitcode, rg_out = testlib.stop_gateway( rg_proc, rg_out_path ) testlib.save_output( output_dir, "syndicate-rg", rg_out ) if rg_exitcode != 0: raise Exception("%s exited %s" % (RG_PATH, rg_exitcode)) sys.exit(0)
testlib.clear_cache( config_dir, volume_id=volume_id, gateway_id=read_gateway_id ) # do each read twice--once uncached, and one cached for i in xrange(0, 2): exitcode, out = testlib.run( READ_PATH, '-d2', '-f', '-c', os.path.join(config_dir, 'syndicate.conf'), ...
conditional_block
hero-detail.component.ts
import { OnInit,Input, Component} from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import 'rxjs/add/operator/switchMap'; import { HeroService } from './hero.service'; @Component({ moduleId: module.id, selector: 'my-hero-detail', templateUrl...
import {Hero} from './hero';
random_line_split
hero-detail.component.ts
import {Hero} from './hero'; import { OnInit,Input, Component} from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import 'rxjs/add/operator/switchMap'; import { HeroService } from './hero.service'; @Component({ moduleId: module.id, selector: '...
(): void { this.route.params .switchMap((params: Params) => this.heroService.getHero(+params['id'])) .subscribe(hero => this.hero = hero); } goBack(): void{ this.location.back(); } save(): void { this.heroService.update(this.hero) .then(() => this.goBack()); } }
ngOnInit
identifier_name
hero-detail.component.ts
import {Hero} from './hero'; import { OnInit,Input, Component} from '@angular/core'; import { ActivatedRoute, Params } from '@angular/router'; import { Location } from '@angular/common'; import 'rxjs/add/operator/switchMap'; import { HeroService } from './hero.service'; @Component({ moduleId: module.id, selector: '...
ngOnInit(): void { this.route.params .switchMap((params: Params) => this.heroService.getHero(+params['id'])) .subscribe(hero => this.hero = hero); } goBack(): void{ this.location.back(); } save(): void { this.heroService.update(this.hero) .then(() => this.goBack()); } }
{}
identifier_body
long-live-the-unsized-temporary.rs
#![allow(incomplete_features)] #![feature(unsized_locals, unsized_fn_params)] use std::fmt; fn gen_foo() -> Box<fmt::Display> { Box::new(Box::new("foo")) } fn foo(x: fmt::Display) { assert_eq!(x.to_string(), "foo"); } fn foo_indirect(x: fmt::Display) { foo(x); } fn main()
{ foo(*gen_foo()); foo_indirect(*gen_foo()); { let x: fmt::Display = *gen_foo(); foo(x); } { let x: fmt::Display = *gen_foo(); let y: fmt::Display = *gen_foo(); foo(x); foo(y); } { let mut cnt: usize = 3; let x = loop { ...
identifier_body
long-live-the-unsized-temporary.rs
#![allow(incomplete_features)] #![feature(unsized_locals, unsized_fn_params)] use std::fmt; fn gen_foo() -> Box<fmt::Display> { Box::new(Box::new("foo")) } fn foo(x: fmt::Display) { assert_eq!(x.to_string(), "foo"); }
fn foo_indirect(x: fmt::Display) { foo(x); } fn main() { foo(*gen_foo()); foo_indirect(*gen_foo()); { let x: fmt::Display = *gen_foo(); foo(x); } { let x: fmt::Display = *gen_foo(); let y: fmt::Display = *gen_foo(); foo(x); foo(y); } { ...
random_line_split
long-live-the-unsized-temporary.rs
#![allow(incomplete_features)] #![feature(unsized_locals, unsized_fn_params)] use std::fmt; fn gen_foo() -> Box<fmt::Display> { Box::new(Box::new("foo")) } fn foo(x: fmt::Display) { assert_eq!(x.to_string(), "foo"); } fn foo_indirect(x: fmt::Display) { foo(x); } fn main() { foo(*gen_foo()); foo...
}; foo(x); } { let x: fmt::Display = *gen_foo(); let x = if true { x } else { *gen_foo() }; foo(x); } }
{ cnt -= 1; }
conditional_block
long-live-the-unsized-temporary.rs
#![allow(incomplete_features)] #![feature(unsized_locals, unsized_fn_params)] use std::fmt; fn gen_foo() -> Box<fmt::Display> { Box::new(Box::new("foo")) } fn
(x: fmt::Display) { assert_eq!(x.to_string(), "foo"); } fn foo_indirect(x: fmt::Display) { foo(x); } fn main() { foo(*gen_foo()); foo_indirect(*gen_foo()); { let x: fmt::Display = *gen_foo(); foo(x); } { let x: fmt::Display = *gen_foo(); let y: fmt::Displa...
foo
identifier_name
test.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
else { delta = abs( y - expected[ i ] ); tol = 300.0 * EPS * abs( expected[ i ] ); t.ok( delta <= tol, 'within tolerance. k: '+k[i]+'. lambda: '+lambda[i]+'. y: '+y+'. E: '+expected[ i ]+'. Δ: '+delta+'. tol: '+tol+'.' ); } } t.end(); });
{ t.equal( y, expected[i], 'k: '+k[i]+', lambda: '+lambda[i]+', y: '+y+', expected: '+expected[i] ); }
conditional_block
test.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by a...
// MODULES // var tape = require( 'tape' ); var abs = require( '@stdlib/math/base/special/abs' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var PINF = require( '@stdlib/constants/float64/pinf' ); var NINF = require( '@stdlib/constants/float64/ninf' ); var EPS = require( '@stdlib/constants/float64/eps'...
'use strict';
random_line_split
hash-navigation.js
import { window, document } from 'ssr-window'; import $ from '../../utils/dom'; import Utils from '../../utils/utils'; const HashNavigation = { onHashCange() { const swiper = this; const newHash = document.location.hash.replace('#', ''); const activeSlideHash = swiper.slides.eq(swiper.activeIndex).attr('...
() { const swiper = this; if (!swiper.hashNavigation.initialized || !swiper.params.hashNavigation.enabled) return; if (swiper.params.hashNavigation.replaceState && window.history && window.history.replaceState) { window.history.replaceState(null, null, (`#${swiper.slides.eq(swiper.activeIndex).attr('d...
setHash
identifier_name
hash-navigation.js
import { window, document } from 'ssr-window'; import $ from '../../utils/dom'; import Utils from '../../utils/utils'; const HashNavigation = { onHashCange() { const swiper = this; const newHash = document.location.hash.replace('#', ''); const activeSlideHash = swiper.slides.eq(swiper.activeIndex).attr('...
const swiper = this; if (swiper.params.hashNavigation.enabled) { swiper.hashNavigation.destroy(); } }, transitionEnd() { const swiper = this; if (swiper.hashNavigation.initialized) { swiper.hashNavigation.setHash(); } }, }, };
} }, destroy() {
random_line_split
hash-navigation.js
import { window, document } from 'ssr-window'; import $ from '../../utils/dom'; import Utils from '../../utils/utils'; const HashNavigation = { onHashCange() { const swiper = this; const newHash = document.location.hash.replace('#', ''); const activeSlideHash = swiper.slides.eq(swiper.activeIndex).attr('...
, init() { const swiper = this; if (!swiper.params.hashNavigation.enabled || (swiper.params.history && swiper.params.history.enabled)) return; swiper.hashNavigation.initialized = true; const hash = document.location.hash.replace('#', ''); if (hash) { const speed = 0; for (let i = 0, le...
{ const swiper = this; if (!swiper.hashNavigation.initialized || !swiper.params.hashNavigation.enabled) return; if (swiper.params.hashNavigation.replaceState && window.history && window.history.replaceState) { window.history.replaceState(null, null, (`#${swiper.slides.eq(swiper.activeIndex).attr('data...
identifier_body
loginRedirectProvider.ts
module app.security { "use strict"; class LoginRedirectProvider implements ng.IServiceProvider { constructor() { } public loginUrl:string = "/login"; public lastPath:string; public defaultPath:string = "/"; public setLoginUrl = (value) => { ...
httpProvider) { $httpProvider.interceptors.push("loginRedirect"); } }
nfig($
identifier_name
loginRedirectProvider.ts
module app.security { "use strict"; class LoginRedirectProvider implements ng.IServiceProvider { constructor() { } public loginUrl:string = "/login"; public lastPath:string; public defaultPath:string = "/"; public setLoginUrl = (value) => { ...
$location.path(this.lastPath); this.lastPath = ""; } else { $location.path(this.defaultPath); } } }; }] } angular.module("app.security").provider("lo...
redirectPreLogin: () => { if (this.lastPath) {
random_line_split
loginRedirectProvider.ts
module app.security { "use strict"; class LoginRedirectProvider implements ng.IServiceProvider { constructor() { } public loginUrl:string = "/login"; public lastPath:string; public defaultPath:string = "/"; public setLoginUrl = (value) => { ...
lse { $location.path(this.defaultPath); } } }; }] } angular.module("app.security").provider("loginRedirect", [LoginRedirectProvider]) .config(["$httpProvider", config]); function config($httpProvider) { ...
$location.path(this.lastPath); this.lastPath = ""; } e
conditional_block
loginRedirectProvider.ts
module app.security { "use strict"; class LoginRedirectProvider implements ng.IServiceProvider { constructor() { } public loginUrl:string = "/login"; public lastPath:string; public defaultPath:string = "/"; public setLoginUrl = (value) => { ...
$httpProvider.interceptors.push("loginRedirect"); } }
identifier_body
jy_serv.py
#!/usr/bin/env jython import sys #sys.path.append("/usr/share/java/itextpdf-5.4.1.jar") sys.path.append("itextpdf-5.4.1.jar") #sys.path.append("/usr/share/java/itext-2.0.7.jar") #sys.path.append("/usr/share/java/xercesImpl.jar") #sys.path.append("/usr/share/java/xml-apis.jar") from java.io import FileOutputStream fro...
st.setFormFlattening(True) st.close() t1=time.time() #print "finished in %.2fs"%(t1-t0) return True def pdf_merge(pdf1,pdf2): #print "pdf_merge",orig_pdf,vals t0=time.time() pdf=pdf1 t1=time.time() #print "finished in %.2fs"%(t1-t0) return pdf serv=SimpleXMLRPCServer(("loc...
try: form.setFieldProperty(k,"textfont",font,None) form.setField(k,v.decode('utf-8')) except Exception,e: raise Exception("Field %s: %s"%(k,str(e)))
conditional_block
jy_serv.py
#!/usr/bin/env jython import sys #sys.path.append("/usr/share/java/itextpdf-5.4.1.jar") sys.path.append("itextpdf-5.4.1.jar") #sys.path.append("/usr/share/java/itext-2.0.7.jar") #sys.path.append("/usr/share/java/xercesImpl.jar") #sys.path.append("/usr/share/java/xml-apis.jar") from java.io import FileOutputStream fro...
(pdf1,pdf2): #print "pdf_merge",orig_pdf,vals t0=time.time() pdf=pdf1 t1=time.time() #print "finished in %.2fs"%(t1-t0) return pdf serv=SimpleXMLRPCServer(("localhost",9999)) serv.register_function(pdf_fill,"pdf_fill") serv.register_function(pdf_merge,"pdf_merge") print "waiting for requests......
pdf_merge
identifier_name
jy_serv.py
#!/usr/bin/env jython import sys #sys.path.append("/usr/share/java/itextpdf-5.4.1.jar") sys.path.append("itextpdf-5.4.1.jar") #sys.path.append("/usr/share/java/itext-2.0.7.jar") #sys.path.append("/usr/share/java/xercesImpl.jar") #sys.path.append("/usr/share/java/xml-apis.jar") from java.io import FileOutputStream fro...
#print t0 st=PdfStamper(rd,FileOutputStream(new_pdf)) font=BaseFont.createFont("/usr/share/fonts/truetype/thai/Garuda.ttf",BaseFont.IDENTITY_H,BaseFont.EMBEDDED) form=st.getAcroFields() for k,v in vals.items(): try: form.setFieldProperty(k,"textfont",font,None) form.s...
#print new_pdf
random_line_split
jy_serv.py
#!/usr/bin/env jython import sys #sys.path.append("/usr/share/java/itextpdf-5.4.1.jar") sys.path.append("itextpdf-5.4.1.jar") #sys.path.append("/usr/share/java/itext-2.0.7.jar") #sys.path.append("/usr/share/java/xercesImpl.jar") #sys.path.append("/usr/share/java/xml-apis.jar") from java.io import FileOutputStream fro...
serv=SimpleXMLRPCServer(("localhost",9999)) serv.register_function(pdf_fill,"pdf_fill") serv.register_function(pdf_merge,"pdf_merge") print "waiting for requests..." serv.serve_forever()
t0=time.time() pdf=pdf1 t1=time.time() #print "finished in %.2fs"%(t1-t0) return pdf
identifier_body
humancapitalsearch.py
import functools import os import numpy as np import pygmo as pg from simulation import simulate, statistical from solving import value_function_list from util import constants as cs, param_type class HumanCapitalSearchProblem(object):
def calculate_criterion(simulate_coefficients, data_coefficients, weights): cutoff = 155 try: squared_coeff_diffs = (data_coefficients[:cutoff] - simulate_coefficients[:cutoff])**2 return np.sum(squared_coeff_diffs * weights[:cutoff]**2) excep...
def fitness(self, params_nparray, gradient_eval=False): params_paramtype = param_type.transform_array_to_paramstype(params_nparray) optimal_value_functions = value_function_list.backwards_iterate(params_paramtype) # if display_plots: # plotting.plot_valuefunctions(optimal_value_funct...
identifier_body
humancapitalsearch.py
import functools import os import numpy as np import pygmo as pg from simulation import simulate, statistical from solving import value_function_list from util import constants as cs, param_type class HumanCapitalSearchProblem(object): def fitness(self, params_nparray, gradient_eval=False): params_param...
return np.array([criterion_value]) def get_name(self): return 'Human Capital Search Problem' def get_bounds(self): lowerbounds, upperbounds, _ = param_type.gen_initial_point() return (lowerbounds, upperbounds) def gradient(self, x): grad_fitness = functools.partia...
print('within_val {0}:'.format(os.getpid()), repr(params_nparray), repr(np.array([criterion_value])))
conditional_block
humancapitalsearch.py
import functools import os import numpy as np import pygmo as pg from simulation import simulate, statistical from solving import value_function_list from util import constants as cs, param_type class HumanCapitalSearchProblem(object): def fitness(self, params_nparray, gradient_eval=False): params_param...
(hours): seconds = 60 * 60 * hours return int(seconds) if __name__ == '__main__': x0 = np.array([ 3.50002199e-03, 6.51848176e-03, 1.51129690e-02, 5.44408669e-01, 4.00993663e-01, 6.55844833e-02, 6.07802957e+00, 1.60167206e+00, 5.01869425e+00, 4.72961572e+00, 9.38466...
convert_hours_to_seconds
identifier_name
humancapitalsearch.py
import functools import os import numpy as np import pygmo as pg from simulation import simulate, statistical from solving import value_function_list from util import constants as cs, param_type class HumanCapitalSearchProblem(object): def fitness(self, params_nparray, gradient_eval=False): params_param...
print(archi.get_champions_x()) print(archi.get_champions_f())
while archi.status is pg.core._evolve_status.busy: time.sleep(120) print(archi) archi.wait_check()
random_line_split
building.d.ts
declare namespace AMap { namespace Buildings { interface Options extends Layer.Options { /** * 可见级别范围 */ zooms?: [number, number]; /** * 不透明度 */ opacity?: number; /** * 高度比例系数,可控制3D视图...
@param opts 图层选项 */ constructor(opts?: Buildings.Options); /** * 按区域设置楼块的颜色 * @param style 颜色设置 */ setStyle(style: Buildings.Style): void; } }
*
identifier_name
building.d.ts
declare namespace AMap { namespace Buildings { interface Options extends Layer.Options { /** * 可见级别范围 */ zooms?: [number, number]; /** * 不透明度 */ opacity?: number; /**
* 是否可见 */ visible?: boolean; /** * 层级 */ zIndex?: number; // inner merge?: boolean; sort?: boolean; } interface AreaStyle { color1: string; path: Locat...
* 高度比例系数,可控制3D视图下的楼块高度 */ heightFactor?: number; /**
random_line_split
word_cluster.py
from sklearn.cluster import MiniBatchKMeans import numpy as np import json import os from texta.settings import MODELS_DIR class WordCluster(object): """ WordCluster object to cluster Word2Vec vectors using MiniBatchKMeans. : param embedding : Word2Vec object : param n_clusters, int, number of cluster...
return True def query(self, word): try: return self.cluster_dict[self.word_to_cluster_dict[word]] except: return [] def text_to_clusters(self, text): text = [str(self.word_to_cluster_dict[word]) for word in text if word in self.word_to_...
word = vocab[i] etalon = embedding.wv.most_similar(positive=[clustering.cluster_centers_[cluster_label]])[0][0] if etalon not in self.cluster_dict: self.cluster_dict[etalon] = [] self.cluster_dict[etalon].append(word) self.wor...
conditional_block
word_cluster.py
from sklearn.cluster import MiniBatchKMeans import numpy as np import json import os from texta.settings import MODELS_DIR class WordCluster(object): """ WordCluster object to cluster Word2Vec vectors using MiniBatchKMeans. : param embedding : Word2Vec object : param n_clusters, int, number of cluster...
def query(self, word): try: return self.cluster_dict[self.word_to_cluster_dict[word]] except: return [] def text_to_clusters(self, text): text = [str(self.word_to_cluster_dict[word]) for word in text if word in self.word_to_cluster_dict] return ...
vocab = list(embedding.wv.vocab.keys()) vocab_vectors = np.array([embedding[word] for word in vocab]) if not n_clusters: # number of clusters = 10% of embedding vocabulary # if larger than 1000, limit to 1000 n_clusters = int(len(vocab) * 0.1) if ...
identifier_body
word_cluster.py
from sklearn.cluster import MiniBatchKMeans import numpy as np import json import os from texta.settings import MODELS_DIR
class WordCluster(object): """ WordCluster object to cluster Word2Vec vectors using MiniBatchKMeans. : param embedding : Word2Vec object : param n_clusters, int, number of clusters in output """ def __init__(self): self.word_to_cluster_dict = {} self.cluster_dict = {} de...
random_line_split
word_cluster.py
from sklearn.cluster import MiniBatchKMeans import numpy as np import json import os from texta.settings import MODELS_DIR class WordCluster(object): """ WordCluster object to cluster Word2Vec vectors using MiniBatchKMeans. : param embedding : Word2Vec object : param n_clusters, int, number of cluster...
(self, text): text = [str(self.word_to_cluster_dict[word]) for word in text if word in self.word_to_cluster_dict] return ' '.join(text) def save(self, file_path): try: data = {"word_to_cluster_dict": self.word_to_cluster_dict, "cluster_dict": self.cluster_dict} with ...
text_to_clusters
identifier_name
auth.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { tokenNotExpired } from 'angular2-jwt'; import { environment } from '../../environments/environment'; const apiUrl = environment.apiUrl; @Injectable() export class AuthService { authTo...
(private http: Http) { } registerUser (user) { let headers = new Headers(); headers.append('Content-Type', 'application/json'); return this.http.post(apiUrl + 'users/register', user, {headers: headers}) .map(res => res.json()); } authenticateUser (user) { let headers = new Headers(); h...
constructor
identifier_name
auth.service.ts
import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; import { tokenNotExpired } from 'angular2-jwt'; import { environment } from '../../environments/environment'; const apiUrl = environment.apiUrl; @Injectable() export class AuthService { authTo...
this.user = null; localStorage.clear(); } }
logout () { this.authToken = null;
random_line_split
feed.ts
import { Comment } from './comment' export class
{ id:number; body:string; mlink:string; is_system:string; is_edited:boolean; is_ack:boolean; feed_type:string; feed_status_type:string; category:string; full_details_mobile_url:string; group_id:string; group_name:string; group_privacy:string; group_sub_type:string; has_guest:boolean; ...
Feed
identifier_name
feed.ts
import { Comment } from './comment' export class Feed { id:number; body:string; mlink:string; is_system:string; is_edited:boolean; is_ack:boolean; feed_type:string; feed_status_type:string; category:string; full_details_mobile_url:string; group_id:string; group_name:string; group_privacy:...
superlike_count:number; haha_count:number; yay_count:number; wow_count:number; sad_count:number; comment_count:number; attachment_count:number; platform:string; liked:boolean; superliked:boolean; haha:boolean; yay:boolean; wow:boolean; sad:boolean; watched:boolean; unread:boolean; ...
has_guest:boolean; like_count:number;
random_line_split
mod.rs
//! Sends an email using the client use std::string::String; use std::net::{SocketAddr, ToSocketAddrs}; use openssl::ssl::{SslContext, SslMethod}; use transport::error::{EmailResult, Error}; use transport::smtp::extension::{Extension, ServerInfo}; use transport::smtp::client::Client; use transport::smtp::authenticat...
(mut self, enable: bool) -> SmtpTransportBuilder { self.connection_reuse = enable; self } /// Set the maximum number of emails sent using one connection pub fn connection_reuse_count_limit(mut self, limit: u16) -> SmtpTransportBuilder { self.connection_reuse_count_limit = limit; ...
connection_reuse
identifier_name
mod.rs
//! Sends an email using the client use std::string::String; use std::net::{SocketAddr, ToSocketAddrs}; use openssl::ssl::{SslContext, SslMethod}; use transport::error::{EmailResult, Error}; use transport::smtp::extension::{Extension, ServerInfo}; use transport::smtp::client::Client; use transport::smtp::authenticat...
/// Require SSL/TLS using STARTTLS /// /// Incompatible with `ssl_wrapper()`` pub fn encrypt(mut self) -> SmtpTransportBuilder { self.security_level = SecurityLevel::AlwaysEncrypt; self } /// Require SSL/TLS using STARTTLS /// /// Incompatible with `encrypt()` pub ...
{ self.security_level = level; self }
identifier_body
mod.rs
//! Sends an email using the client use std::string::String; use std::net::{SocketAddr, ToSocketAddrs}; use openssl::ssl::{SslContext, SslMethod}; use transport::error::{EmailResult, Error}; use transport::smtp::extension::{Extension, ServerInfo}; use transport::smtp::client::Client; use transport::smtp::authenticat...
pub mod client; // Registrated port numbers: // https://www.iana. // org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml /// Default smtp port pub static SMTP_PORT: u16 = 25; /// Default submission port pub static SUBMISSION_PORT: u16 = 587; // Useful strings and characters /// The word sep...
random_line_split
mod.rs
//! Sends an email using the client use std::string::String; use std::net::{SocketAddr, ToSocketAddrs}; use openssl::ssl::{SslContext, SslMethod}; use transport::error::{EmailResult, Error}; use transport::smtp::extension::{Extension, ServerInfo}; use transport::smtp::client::Client; use transport::smtp::authenticat...
result } /// Closes the inner connection fn close(&mut self) { self.client.close(); } }
{ self.reset(); }
conditional_block
test_benchmark_mem.py
# -*- coding: utf-8 -*- # # Copyright 2015 Red Hat, Inc. # All Rights Reserved. # # 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...
def test_mem_perf_bytes(self, mock_popen, mock_cpu_socket, mock_get_memory): mock_get_memory.return_value = 123456789012 mock_popen.return_value = mock.Mock( stdout=SYSBENCH_OUTPUT.encode().splitlines()) mock_cpu_socket.return_value = range(2) ...
super(TestBenchmarkMem, self).setUp() self.hw_data = [('cpu', 'logical', 'number', 2), ('cpu', 'physical', 'number', 2)]
identifier_body
test_benchmark_mem.py
# -*- coding: utf-8 -*- # # Copyright 2015 Red Hat, Inc. # All Rights Reserved. # # 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...
(self, mock_popen, mock_cpu_socket, mock_get_memory): mock_get_memory.return_value = 123456789012 mock_popen.return_value = mock.Mock( stdout=SYSBENCH_OUTPUT.encode().splitlines()) hw_dat...
test_run_sysbench_memory_threaded_bytes
identifier_name
test_benchmark_mem.py
# -*- coding: utf-8 -*- # # Copyright 2015 Red Hat, Inc. # All Rights Reserved. # # 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...
def test_run_sysbench_memory_threaded_bytes(self, mock_popen, mock_cpu_socket, mock_get_memory): mock_get_memory.return_value = 123456789012 mock_popen.return_value = mock.Mock( stdout=SYSBEN...
hw_data)
random_line_split
test_benchmark_mem.py
# -*- coding: utf-8 -*- # # Copyright 2015 Red Hat, Inc. # All Rights Reserved. # # 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...
# Low memory mock_get_memory.return_value = 1 for block_size in block_size_list: self.assertFalse(mem.check_mem_size(block_size, 2)) def test_run_sysbench_memory_forked_bytes(self, mock_popen, mock_cpu_socket, ...
self.assertTrue(mem.check_mem_size(block_size, 2))
conditional_block
index.tsx
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import {createStore, applyMiddleware, compose} from 'redux'; import {Provider...
() { const hide = this.props.player.playerStatus.name === ''; if (hide) return null; const dead = this.props.player.playerStatus.blood.current <= 0 || this.props.player.playerStatus.health[BodyParts.Torso].current <= 0; return ( <div className={`Playerhealth ${this.props.containerClass}`} ...
render
identifier_name
index.tsx
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import {createStore, applyMiddleware, compose} from 'redux'; import {Provider...
onClick={() => hasClientAPI() || dead ? '' : this.props.dispatch(doThing())}> <PlayerStatusComponent containerClass='PlayerHealth' playerStatus={this.props.player.playerStatus} events={this.props.player.events} /> </div> ); } public componentDidMount...
{ const hide = this.props.player.playerStatus.name === ''; if (hide) return null; const dead = this.props.player.playerStatus.blood.current <= 0 || this.props.player.playerStatus.health[BodyParts.Torso].current <= 0; return ( <div className={`Playerhealth ${this.props.containerClass}`}
identifier_body
index.tsx
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import * as React from 'react'; import {createStore, applyMiddleware, compose} from 'redux'; import {Provider...
const dead = this.props.player.playerStatus.blood.current <= 0 || this.props.player.playerStatus.health[BodyParts.Torso].current <= 0; return ( <div className={`Playerhealth ${this.props.containerClass}`} onClick={() => hasClientAPI() || dead ? '' : this.props.dispatch(doThing())}> <...
public render() { const hide = this.props.player.playerStatus.name === ''; if (hide) return null;
random_line_split
test_stale_read.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::atomic::*; use std::sync::{mpsc, Arc, Mutex}; use std::time::Duration; use std::{mem, thread}; use kvproto::metapb::{Peer, Region}; use raft::eraftpb::MessageType; use pd_client::PdClient; use raftstore::store::Callback; use test_rafts...
( cluster: &mut Cluster<NodeCluster>, key: &[u8], value: &[u8], read_quorum: bool, old_region: &Region, old_leader: &Peer, new_region: &Region, new_leader: &Peer, ) { let value1 = read_on_peer( cluster, old_leader.clone(), old_region.clone(), key, ...
must_not_eq_on_key
identifier_name
test_stale_read.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::atomic::*; use std::sync::{mpsc, Arc, Mutex}; use std::time::Duration; use std::{mem, thread}; use kvproto::metapb::{Peer, Region}; use raft::eraftpb::MessageType; use pd_client::PdClient; use raftstore::store::Callback; use test_rafts...
; // Get the new region. let region2 = cluster.get_region_with(stale_key, |region| region != &region1); // Get the leader of the new region. let leader2 = cluster.leader_of_region(region2.get_id()).unwrap(); assert_ne!(leader1.get_store_id(), leader2.get_store_id()); must_not_stale_read( ...
{ key2 }
conditional_block
test_stale_read.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::atomic::*; use std::sync::{mpsc, Arc, Mutex}; use std::time::Duration; use std::{mem, thread}; use kvproto::metapb::{Peer, Region}; use raft::eraftpb::MessageType; use pd_client::PdClient; use raftstore::store::Callback; use test_rafts...
.get_peers() .iter() .find(|p| p.get_id() == 3) .unwrap() .clone(); cluster.must_transfer_leader(region1.get_id(), peer3.clone()); // Get the current leader. let leader1 = peer3; // Pause the apply worker of peer 3. let apply_split = "apply_before_split_1_3"...
let region1 = region_left; assert_eq!(region1.get_id(), 1); let peer3 = region1
random_line_split
test_stale_read.rs
// Copyright 2018 TiKV Project Authors. Licensed under Apache-2.0. use std::sync::atomic::*; use std::sync::{mpsc, Arc, Mutex}; use std::time::Duration; use std::{mem, thread}; use kvproto::metapb::{Peer, Region}; use raft::eraftpb::MessageType; use pd_client::PdClient; use raftstore::store::Callback; use test_rafts...
/// In previous implementation, we suspect the leader lease at the position of `leader_commit_prepare_merge` /// failpoint when `PrepareMerge` log is committed, which is too late to prevent stale read. #[test] fn test_stale_read_during_merging_2() { let mut cluster = new_node_cluster(0, 3); let pd_client = cl...
{ let mut cluster = new_node_cluster(0, 3); let pd_client = cluster.pd_client.clone(); // Disable default max peer number check. pd_client.disable_default_operator(); let r1 = cluster.run_conf_change(); // Add 2 peers. for i in 2..4 { pd_client.must_add_peer(r1, new_peer(i, i)); ...
identifier_body
singleCourse.ts
import { ActivatedRoute, Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { coursesActions } from '../../Store/actions'; export abstract class AbstractCourseDetailed { public abstract pageType : string; public currentCourse$ : any; protected abstract get activatedRoute() : ActivatedR...
return duration ? `${hours || ''} ${hours ? 'hour' : ''}${hours > 1 ? 's' : ''} ${minutes || '0'} min.` : 'not specified'; } }
random_line_split
singleCourse.ts
import { ActivatedRoute, Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { coursesActions } from '../../Store/actions'; export abstract class AbstractCourseDetailed { public abstract pageType : string; public currentCourse$ : any; protected abstract get activatedRoute() : ActivatedR...
() { let sub = this.activatedRoute.params.subscribe(({id}) => { if(id) { this.store.dispatch(new coursesActions.FetchingSingleCourse({id})) } else { this.store.dispatch(new coursesActions.EmptyCourse()) } }); this.store.select('currentCourse').subscribe(course => { t...
ngOnInit
identifier_name
singleCourse.ts
import { ActivatedRoute, Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { coursesActions } from '../../Store/actions'; export abstract class AbstractCourseDetailed { public abstract pageType : string; public currentCourse$ : any; protected abstract get activatedRoute() : ActivatedR...
else { this.store.dispatch(new coursesActions.EmptyCourse()) } }); this.store.select('currentCourse').subscribe(course => { this.currentCourse$ = course; }); } get prettyCourseDuration(): string { const {duration} = this.currentCourse$, hours = Math.floor(duration / 60),...
{ this.store.dispatch(new coursesActions.FetchingSingleCourse({id})) }
conditional_block
singleCourse.ts
import { ActivatedRoute, Router } from '@angular/router'; import { Store } from '@ngrx/store'; import { coursesActions } from '../../Store/actions'; export abstract class AbstractCourseDetailed { public abstract pageType : string; public currentCourse$ : any; protected abstract get activatedRoute() : ActivatedR...
get prettyCourseDuration(): string { const {duration} = this.currentCourse$, hours = Math.floor(duration / 60), minutes = duration % 60; return duration ? `${hours || ''} ${hours ? 'hour' : ''}${hours > 1 ? 's' : ''} ${minutes || '0'} min.` : 'not specified'; } }
{ let sub = this.activatedRoute.params.subscribe(({id}) => { if(id) { this.store.dispatch(new coursesActions.FetchingSingleCourse({id})) } else { this.store.dispatch(new coursesActions.EmptyCourse()) } }); this.store.select('currentCourse').subscribe(course => { this...
identifier_body
test_del_10gig_hardware.py
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
def test_700_delmachines(self): for i in range(0, 8) + range(9, 17): machine = "evm%d" % (10 + i) self.noouttest(["del", "machine", "--machine", machine]) def test_800_verifydelmachines(self): for i in range(0, 18): machine = "evm%d" % (10 + i) ...
for i in range(1, 25): hostname = "evh%d-e1.aqd-unittest.ms.com" % (i + 50) self.dsdb_expect_delete(self.net.vm_storage_net[0].usable[i - 1]) command = ["del", "auxiliary", "--auxiliary", hostname] (out, err) = self.successtest(command) self.assertEmptyOut(out...
identifier_body
test_del_10gig_hardware.py
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
command = "show machine --machine %s" % machine self.notfoundtest(command.split(" ")) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestDel10GigHardware) unittest.TextTestRunner(verbosity=2).run(suite)
def test_800_verifydelmachines(self): for i in range(0, 18): machine = "evm%d" % (10 + i)
random_line_split
test_del_10gig_hardware.py
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
else: net_index = ((i - 9) % 4) + 6 usable_index = (i - 9) / 4 ip = self.net.unknown[net_index].usable[usable_index] self.dsdb_expect_delete(ip) (out, err) = self.successtest(command.split(" ")) self.assertEmptyOut(out, comman...
net_index = (i % 4) + 2 usable_index = i / 4
conditional_block
test_del_10gig_hardware.py
#!/usr/bin/env python2.6 # -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2012,2013 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # Y...
(TestBrokerCommand): def test_200_del_hosts(self): for i in range(0, 8) + range(9, 17): hostname = "ivirt%d.aqd-unittest.ms.com" % (1 + i) command = "del_host --hostname %s" % hostname if i < 9: net_index = (i % 4) + 2 usable_index = i / ...
TestDel10GigHardware
identifier_name
schedule.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
() { let s1 = Schedule::new_frontier(); let s2 = Schedule::new_homestead(); // To optimize division we assume 2**9 for quad_coeff_div assert_eq!(s1.quad_coeff_div, 512); assert_eq!(s2.quad_coeff_div, 512); }
schedule_evm_assumptions
identifier_name
schedule.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 200, sstore_set_gas: 20000, sstore_reset_gas: 5000, sstore_refund_gas: 15000, jumpdest_gas: 1, log_gas: 375, log_data_gas: 8, log_topic_gas: 375, create_gas: 32000, call_gas: 700, call_stipend: 2300, call_value_transfer_gas: 9000, ...
{10}
conditional_block
schedule.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
/// If Some(x): let limit = GAS * (x - 1) / x; let CALL's gas = min(requested, limit). let CREATE's gas = limit. /// If None: let CALL's gas = (requested > GAS ? [OOG] : GAS). let CREATE's gas = GAS pub sub_gas_cap_divisor: Option<usize>, /// Don't ever make empty accounts; contracts start with nonce=1. Also, don't...
/// Amount of additional gas to pay when SUICIDE credits a non-existant account pub suicide_to_new_account_cost: usize,
random_line_split
schedule.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version....
} #[test] #[cfg(test)] fn schedule_evm_assumptions() { let s1 = Schedule::new_frontier(); let s2 = Schedule::new_homestead(); // To optimize division we assume 2**9 for quad_coeff_div assert_eq!(s1.quad_coeff_div, 512); assert_eq!(s2.quad_coeff_div, 512); }
{ Schedule { exceptional_failed_code_deposit: efcd, have_delegate_call: hdc, stack_limit: 1024, max_depth: 1024, tier_step_gas: [0, 2, 3, 5, 8, 10, 20, 0], exp_gas: 10, exp_byte_gas: 10, sha3_gas: 30, sha3_word_gas: 6, sload_gas: 50, sstore_set_gas: 20000, sstore_reset_gas: 5000, ...
identifier_body
__init__.py
# -*- coding: UTF-8 -*- # COPYRIGHT (c) 2016 Cristóbal Ganter # # GNU AFFERO GENERAL PUBLIC LICENSE # Version 3, 19 November 2007 # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, eit...
# along with this program. If not, see <http://www.gnu.org/licenses/>. from controller import MSGHandler from src.load import load_wsclasses load_wsclasses(__name__, MSGHandler)
# GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License
random_line_split
lib.rs
#[derive(Debug)] pub struct Rectangle { length: u32, width: u32, } impl Rectangle { pub fn can_hold(&self, other: &Rectangle) -> bool { self.length > other.length && self.width > other.width } } #[cfg(test)] mod tests { use super::*; #[test] fn
() { let larger = Rectangle { length: 8, width: 7, }; let smaller = Rectangle { length: 5, width: 1, }; assert!(larger.can_hold(&smaller)); } #[test] fn smaller_can_hold_larger() { let larger = Rectangle { ...
larger_can_hold_smaller
identifier_name
lib.rs
#[derive(Debug)] pub struct Rectangle { length: u32, width: u32, } impl Rectangle { pub fn can_hold(&self, other: &Rectangle) -> bool { self.length > other.length && self.width > other.width } } #[cfg(test)] mod tests { use super::*; #[test] fn larger_can_hold_smaller() { ...
width: 7, }; let smaller = Rectangle { length: 5, width: 1, }; assert!(!smaller.can_hold(&larger)); } }
random_line_split
test.rs
extern crate couch; extern crate http; extern crate serialize; #[cfg(test)] mod test { use couch::{Server,Document}; #[deriving(Encodable,Decodable)] struct TestDocument { _id: String, body: String } impl Document for TestDocument { fn id(&self) -> String
} #[test] fn speak_to_the_couch() { let server = Server::new(String::from_str("http://localhost:5984")); let info = server.info(); assert_eq!(info.message(), "Welcome".to_owned()); } #[test] fn create_database() { let mut server = Server::new(String::from_str("http://localhost:5984")); ...
{ self._id.clone() }
identifier_body
test.rs
extern crate couch; extern crate http; extern crate serialize; #[cfg(test)] mod test { use couch::{Server,Document}; #[deriving(Encodable,Decodable)] struct TestDocument { _id: String, body: String } impl Document for TestDocument { fn id(&self) -> String { self._id.clone() } } #...
() { let mut server = Server::new(String::from_str("http://localhost:5984")); server.delete_database("created_by_couch".to_owned()); let database = server.create_database("created_by_couch".to_owned()); assert_eq!(database.name(), "created_by_couch".to_owned()); } #[test] fn create_document() { ...
create_database
identifier_name
test.rs
extern crate couch; extern crate http; extern crate serialize;
#[deriving(Encodable,Decodable)] struct TestDocument { _id: String, body: String } impl Document for TestDocument { fn id(&self) -> String { self._id.clone() } } #[test] fn speak_to_the_couch() { let server = Server::new(String::from_str("http://localhost:5984")); let info...
#[cfg(test)] mod test { use couch::{Server,Document};
random_line_split
Add.tsx
import { randomUUID } from 'node:crypto'; import { Fragment, useState, type ReactElement, type ReactNode, type Dispatch as D, type SetStateAction as S, type ChangeEvent, type MouseEvent } from 'react'; import { useDispatch } from 'react-redux'; import type { Dispatch } from '@reduxjs/toolkit'; import { ...
nloadUrl: Array<DownloadUrlItem>): Array<ReactNode> { return downloadUrl.map((item: DownloadUrlItem, index: number): ReactElement => { return <Select.Option key={ item.label + item.value } value={ item.value }>{ item.label }</Select.Option>; }); } /* 获取和下载链接 */ function Add(props: {}): ReactElement { const d...
ctOptionsRender(dow
identifier_name
Add.tsx
import { randomUUID } from 'node:crypto'; import { Fragment, useState, type ReactElement, type ReactNode, type Dispatch as D, type SetStateAction as S, type ChangeEvent, type MouseEvent } from 'react'; import { useDispatch } from 'react-redux'; import type { Dispatch } from '@reduxjs/toolkit'; import { ...
: Dispatch = useDispatch(); const [urlValue, setUrlValue]: [string, D<S<string>>] = useState(''); const [getUrlLoading, setGetUrlLoading]: [boolean, D<S<boolean>>] = useState(false); const [visible, setVisible]: [boolean, D<S<boolean>>] = useState(false); // 弹出层的显示隐藏 const [downloadUrl, setDownloadUrl]: [Downlo...
identifier_body
Add.tsx
import { randomUUID } from 'node:crypto'; import { Fragment, useState, type ReactElement, type ReactNode, type Dispatch as D, type SetStateAction as S, type ChangeEvent, type MouseEvent } from 'react'; import { useDispatch } from 'react-redux'; import type { Dispatch } from '@reduxjs/toolkit'; import { ...
alse); } return ( <Fragment> <Input className={ style.input } value={ urlValue } placeholder="请输入视频ID" onChange={ (event: ChangeEvent<HTMLInputElement>): void => setUrlValue(event.target.value) } /> <Button loading={ getUrlLoading } onClick={ handleGetVideoUrlClick }>获...
ror(err); message.error('视频地址解析失败!'); } setGetUrlLoading(f
conditional_block
Add.tsx
import { randomUUID } from 'node:crypto'; import { Fragment, useState, type ReactElement, type ReactNode, type Dispatch as D, type SetStateAction as S, type ChangeEvent, type MouseEvent } from 'react'; import { useDispatch } from 'react-redux'; import type { Dispatch } from '@reduxjs/toolkit'; import { ...
> <Select className={ style.urlSelect } value={ selectedUrl } onSelect={ (value: string): void => setSelectedUrl(value) } > { selectOptionsRender(downloadUrl) } </Select> </Modal> </Fragment> ); } export default Add;
destroyOnClose={ true } closable={ false } afterClose={ afterClose } onOk={ handleAddClick } onCancel={ (event: MouseEvent<HTMLButtonElement>): void => setVisible(false) }
random_line_split
test_availability_zone.py
# Copyright 2013 IBM Corp. # # 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 t...
(self): response = self._do_get('os-availability-zone') self._verify_response('availability-zone-list-resp', {}, response, 200) def test_availability_zone_detail(self): response = self._do_get('os-availability-zone/detail') self._verify_response('availability-zone-detail-resp', {}, ...
test_availability_zone_list
identifier_name
test_availability_zone.py
# Copyright 2013 IBM Corp. # # 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 t...
def test_availability_zone_list(self): response = self._do_get('os-availability-zone') self._verify_response('availability-zone-list-resp', {}, response, 200) def test_availability_zone_detail(self): response = self._do_get('os-availability-zone/detail') self._verify_response(...
f = super(AvailabilityZoneJsonTest, self)._get_flags() f['osapi_compute_extension'] = CONF.osapi_compute_extension[:] f['osapi_compute_extension'].append( 'nova.api.openstack.compute.contrib.availability_zone.' 'Availability_zone') return f
identifier_body
test_availability_zone.py
# Copyright 2013 IBM Corp. # # 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 t...
def test_availability_zone_list(self): response = self._do_get('os-availability-zone') self._verify_response('availability-zone-list-resp', {}, response, 200) def test_availability_zone_detail(self): response = self._do_get('os-availability-zone/detail') self._verify_response('a...
random_line_split
stage_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * 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 agr...
expect(stage.toApiPayload().approval.type).toBe("manual"); stage.approval().state(true); expect(stage.toApiPayload().approval.type).toBe("success"); }); it("should serialize correctly", () => { const stage = new Stage("foo", [validJob()]); expect(stage.toApiPayload()).toEqual({ name: "fo...
random_line_split
stage_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * 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 agr...
it("should include a name", () => { let stage = new Stage("foo", [validJob()]); expect(stage.isValid()).toBe(true); expect(stage.errors().count()).toBe(0); stage = new Stage("", [validJob()]); expect(stage.isValid()).toBe(false); expect(stage.errors().count()).toBe(1); expect(stage.erro...
{ return new Job("name", [new ExecTask("ls", ["-lA"])]); }
identifier_body
stage_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * 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 agr...
() { return new Job("name", [new ExecTask("ls", ["-lA"])]); } it("should include a name", () => { let stage = new Stage("foo", [validJob()]); expect(stage.isValid()).toBe(true); expect(stage.errors().count()).toBe(0); stage = new Stage("", [validJob()]); expect(stage.isValid()).toBe(false)...
validJob
identifier_name
utils.py
"""Helper functions and view derivers for spynl.main.""" import json import logging import traceback import sys import os import contextlib from functools import wraps from inspect import isclass, getfullargspec import yaml from tld import get_tld from tld.exceptions import TldBadUrl, TldDomainNotFound from pyramid....
(doc_str, load_yaml=True): """ Load the YAML part (after "---") from the docstring of a Spynl view. if load_yaml is True, return the result of yaml.load, otherwise return as string. """ if doc_str: yaml_sep = doc_str.find('---') else: yaml_sep = -1 if yaml_sep != -1: ...
get_yaml_from_docstring
identifier_name
utils.py
"""Helper functions and view derivers for spynl.main.""" import json import logging import traceback import sys import os import contextlib from functools import wraps from inspect import isclass, getfullargspec import yaml from tld import get_tld from tld.exceptions import TldBadUrl, TldDomainNotFound from pyramid....
filters = config.get_settings().get('jinja2.filters', {}) filters.update(new_filters) config.add_settings({'jinja2.filters': filters})
random_line_split
utils.py
"""Helper functions and view derivers for spynl.main.""" import json import logging import traceback import sys import os import contextlib from functools import wraps from inspect import isclass, getfullargspec import yaml from tld import get_tld from tld.exceptions import TldBadUrl, TldDomainNotFound from pyramid....
else: request.parsed_body = {} if not request.body else json.loads(request.body) else: # disregard any body content if not a POST of PUT request request.parsed_body = {} return request.parsed_body def unify_args(request): """ Make one giant args dictonary from GET...
request.parsed_body = body_parser(request)
conditional_block
utils.py
"""Helper functions and view derivers for spynl.main.""" import json import logging import traceback import sys import os import contextlib from functools import wraps from inspect import isclass, getfullargspec import yaml from tld import get_tld from tld.exceptions import TldBadUrl, TldDomainNotFound from pyramid....
def unify_args(request): """ Make one giant args dictonary from GET, POST, headers and cookies and return it. On the way, create r.parsed_body and r.parsed_get as well. It is possible to provide a custom parser for the POST body in the settings. Complex data can be given via GET as a JSON string...
"""Return the body of the request parsed if request was POST or PUT.""" settings = get_settings() body_parser = settings.get('spynl.post_parser') if request.method in ('POST', 'PUT'): if body_parser: request.parsed_body = body_parser(request) else: request.parsed_bod...
identifier_body
objpool.rs
/* Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, th...
} pub struct ObjPoolMutIdxIterator<'a, T: 'a> { inner_iter: IterMut<'a, T>, current_idx: usize, } impl<'a, T> Iterator for ObjPoolMutIdxIterator<'a, T> { type Item = (ObjPoolIndex<T>, &'a mut T); fn next(&mut self) -> Option<Self::Item> { let next = self.inner_iter.next(); match next...
{ if self.current_idx == self.pool.storage.len() { None } else { let ret = ObjPoolIndex::<T> {i: self.current_idx, type_marker: PhantomData}; self.current_idx += 1; Some(ret) } }
identifier_body
objpool.rs
/* Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, th...
} } pub struct ObjPoolMutIdxIterator<'a, T: 'a> { inner_iter: IterMut<'a, T>, current_idx: usize, } impl<'a, T> Iterator for ObjPoolMutIdxIterator<'a, T> { type Item = (ObjPoolIndex<T>, &'a mut T); fn next(&mut self) -> Option<Self::Item> { let next = self.inner_iter.next(); matc...
{ let ret = ObjPoolIndex::<T> {i: self.current_idx, type_marker: PhantomData}; self.current_idx += 1; Some(ret) }
conditional_block
objpool.rs
/* Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, th...
(&self, other: &ObjPoolIndex<T>) -> bool { self.i == other.i } } impl<T> Eq for ObjPoolIndex<T> { } impl<T> Hash for ObjPoolIndex<T> { fn hash<H: Hasher>(&self, state: &mut H) { self.i.hash(state); } } impl<T> ObjPoolIndex<T> { pub fn get_raw_i(&self) -> usize { self.i } }...
eq
identifier_name
objpool.rs
/* Copyright (c) 2016-2017, Robert Ou <rqou@robertou.com> and contributors All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, th...
let next = self.inner_iter.next(); match next { None => None, Some(x) => { let ret = ObjPoolIndex::<T> {i: self.current_idx, type_marker: PhantomData}; self.current_idx += 1; Some((ret, x)) } } } } #[cfg(tes...
fn next(&mut self) -> Option<Self::Item> {
random_line_split
sysoptions.py
"""Options list for system config.""" import os from collections import OrderedDict from lutris import runners from lutris.util import display, system def get_optirun_choices(): """Return menu choices (label, value) for Optimus""" choices = [("Off", "off")] if system.find_executable("primusrun"): ...
"option": "disable_runtime", "type": "bool", "label": "Disable Lutris Runtime", "default": False, "help": ( "The Lutris Runtime loads some libraries before running the " "game. Which can cause some incompatibilities in some cases. " "Check this...
{
random_line_split
sysoptions.py
"""Options list for system config.""" import os from collections import OrderedDict from lutris import runners from lutris.util import display, system def get_optirun_choices():
system_options = [ # pylint: disable=invalid-name { "option": "game_path", "type": "directory_chooser", "label": "Default installation folder", "default": os.path.expanduser("~/Games"), "scope": ["runner", "system"], "help": "The default folder where you install y...
"""Return menu choices (label, value) for Optimus""" choices = [("Off", "off")] if system.find_executable("primusrun"): choices.append(("primusrun", "primusrun")) if system.find_executable("optirun"): choices.append(("optirun/virtualgl", "optirun")) return choices
identifier_body
sysoptions.py
"""Options list for system config.""" import os from collections import OrderedDict from lutris import runners from lutris.util import display, system def get_optirun_choices(): """Return menu choices (label, value) for Optimus""" choices = [("Off", "off")] if system.find_executable("primusrun"): ...
return choices system_options = [ # pylint: disable=invalid-name { "option": "game_path", "type": "directory_chooser", "label": "Default installation folder", "default": os.path.expanduser("~/Games"), "scope": ["runner", "system"], "help": "The default folder ...
choices.append(("optirun/virtualgl", "optirun"))
conditional_block
sysoptions.py
"""Options list for system config.""" import os from collections import OrderedDict from lutris import runners from lutris.util import display, system def get_optirun_choices(): """Return menu choices (label, value) for Optimus""" choices = [("Off", "off")] if system.find_executable("primusrun"): ...
(runner_slug): """Return system options updated with overrides from given runner.""" options = system_options try: runner = runners.import_runner(runner_slug) except runners.InvalidRunner: return options if not getattr(runner, "system_options_override"): runner = runner() ...
with_runner_overrides
identifier_name
trait-inheritance2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
trait Bar { fn g(&self) -> int; } trait Baz { fn h(&self) -> int; } trait Quux: Foo + Bar + Baz { } struct A { x: int } impl Foo for A { fn f(&self) -> int { 10 } } impl Bar for A { fn g(&self) -> int { 20 } } impl Baz for A { fn h(&self) -> int { 30 } } impl Quux for A {} fn f<T:Quux + Foo + Bar + Baz>(a: &T) { ...
// option. This file may not be copied, modified, or distributed // except according to those terms. trait Foo { fn f(&self) -> int; }
random_line_split
trait-inheritance2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&self) -> int { 30 } } impl Quux for A {} fn f<T:Quux + Foo + Bar + Baz>(a: &T) { assert_eq!(a.f(), 10); assert_eq!(a.g(), 20); assert_eq!(a.h(), 30); } pub fn main() { let a = &A { x: 3 }; f(a); }
h
identifier_name
trait-inheritance2.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl Bar for A { fn g(&self) -> int { 20 } } impl Baz for A { fn h(&self) -> int { 30 } } impl Quux for A {} fn f<T:Quux + Foo + Bar + Baz>(a: &T) { assert_eq!(a.f(), 10); assert_eq!(a.g(), 20); assert_eq!(a.h(), 30); } pub fn main() { let a = &A { x: 3 }; f(a); }
{ 10 }
identifier_body