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
laptop.pb.go
} func (m *Laptop) GetKeyboard() *Keyboard { if m != nil { return m.Keyboard } return nil } type isLaptop_Weight interface { isLaptop_Weight() } type Laptop_WeightKg struct { WeightKg float64 `protobuf:"fixed64,10,opt,name=weight_kg,json=weightKg,proto3,oneof"` } type Laptop_WeightLb struct { WeightLb float...
func (m *CreateLaptopRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_CreateLaptopRequest.Marshal(b, m, deterministic) } func (m *CreateLaptopRequest) XXX_Merge(src proto.Message) { xxx_messageInfo_CreateLaptopRequest.Merge(m, src) } func (m *CreateLaptopRequest) XXX_Size()...
{ return xxx_messageInfo_CreateLaptopRequest.Unmarshal(m, b) }
identifier_body
renderer.rs
> { pub fn new(context: &gpukit::Context, value: T) -> Self { let buffer = context .build_buffer() .with_usage(wgpu::BufferUsages::UNIFORM) .init_with_data(std::slice::from_ref(&value)); UniformBuffer { buffer, value } } fn update(&self, context: &gpukit:...
{ self.vertex_buffer = Self::create_vertex_buffer(&self.context, vertex_count as usize); }
conditional_block
renderer.rs
8Unorm>, } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct ScreenUniforms { width_in_points: f32, height_in_points: f32, pixels_per_point: f32, _padding: u32, } struct UniformBuffer<T: bytemuck::Pod> { buffer: gpukit::Buffer<T>, value: T, } impl<T: bytemuck:...
color_targets: &[wgpu::ColorTargetState { format: target_format, blend: Some(wgpu::BlendState { color: wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::OneMinusSrcAlph...
2 => Uint32, ]], bind_group_layouts: &[&bind_group.layout, &texture_bind_group.layout],
random_line_split
renderer.rs
Unorm>, } #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Pod, bytemuck::Zeroable)] struct ScreenUniforms { width_in_points: f32, height_in_points: f32, pixels_per_point: f32, _padding: u32, } struct UniformBuffer<T: bytemuck::Pod> { buffer: gpukit::Buffer<T>, value: T, } impl<T: bytemuck::...
(context: &gpukit::Context, value: T) -> Self { let buffer = context .build_buffer() .with_usage(wgpu::BufferUsages::UNIFORM) .init_with_data(std::slice::from_ref(&value)); UniformBuffer { buffer, value } } fn update(&self, context: &gpukit::Context) { ...
new
identifier_name
exec.rs
Stream}; use tokio::process::Child; use tokio::sync::oneshot; use tokio::time::{delay_for, timeout, Duration}; // config for executor #[derive(Debug, Clone, Deserialize)] pub struct ExecutorConf { pub path: PathBuf, pub host_ip: Option<String>, pub concurrency: bool, pub memleak_check: bool, pub sc...
(&mut self) { match self.inner { ExecutorImpl::Linux(ref mut e) => e.start().await, ExecutorImpl::Scripy(ref mut e) => e.start().await, } } pub async fn exec(&mut self, p: &Prog, t: &Target) -> Result<ExecResult, Option<Crash>> { match self.inner { Ex...
start
identifier_name
exec.rs
Stream}; use tokio::process::Child; use tokio::sync::oneshot; use tokio::time::{delay_for, timeout, Duration}; // config for executor #[derive(Debug, Clone, Deserialize)] pub struct ExecutorConf { pub path: PathBuf, pub host_ip: Option<String>, pub concurrency: bool, pub memleak_check: bool, pub sc...
target_path: PathBuf::from(&cfg.fots_bin), host_ip, } } pub async fn start(&mut self) { // handle should be set to kill on drop self.exec_handle = None; self.guest.boot().await; self.start_executer().await } pub async fn start_executer(...
{ let guest = Guest::new(cfg); let port = free_ipv4_port() .unwrap_or_else(|| exits!(exitcode::TEMPFAIL, "No Free port for executor driver")); let host_ip = cfg .executor .host_ip .as_ref() .map(String::from) .unwrap_or_else...
identifier_body
exec.rs
Stream}; use tokio::process::Child; use tokio::sync::oneshot; use tokio::time::{delay_for, timeout, Duration}; // config for executor #[derive(Debug, Clone, Deserialize)] pub struct ExecutorConf { pub path: PathBuf, pub host_ip: Option<String>, pub concurrency: bool, pub memleak_check: bool, pub sc...
Ok(conn) => Some(conn.unwrap()), }; } pub async fn exec(&mut self, p: &Prog) -> Result<ExecResult, Option<Crash>> { // send must be success assert!(self.conn.is_some()); if let Err(e) = timeout( Duration::new(15, 0), async_send(p, self.conn.a...
{ self.exec_handle = None; eprintln!("Time out: wait executor connection {}", host_addr); exit(1) }
conditional_block
exec.rs
TcpStream}; use tokio::process::Child; use tokio::sync::oneshot; use tokio::time::{delay_for, timeout, Duration}; // config for executor #[derive(Debug, Clone, Deserialize)] pub struct ExecutorConf { pub path: PathBuf, pub host_ip: Option<String>, pub concurrency: bool, pub memleak_check: bool, pu...
listener = match TcpListener::bind(&host_addr).await { Ok(l) => l, Err(e) => { if e.kind() == AddrInUse && retry != 5 { self.port = free_ipv4_port().unwrap(); retry += 1; continue; ...
let host_addr = format!("{}:{}", self.host_ip, self.port);
random_line_split
PoissonDiscSampleGenerator.py
random sample. (Optional) (Default: None) """ # -------------------------------- # User Parameters # -------------------------------- # Defines self._radius self.radius = radius # Defines self._k self.k = k # Defines both self._extent and self._d...
if seed < 0: raise ValueError("Seed must be non-negative.") self._seed = seed def _clear_previous_samples(self): """Clears grid and samples for generating new samples. """ del self._grid del self._samples # ------------------------------...
raise ValueError("Seed must be integer.")
conditional_block
PoissonDiscSampleGenerator.py
random sample. (Optional) (Default: None) """ # -------------------------------- # User Parameters # -------------------------------- # Defines self._radius self.radius = radius # Defines self._k self.k = k # Defines both self._extent and self._d...
@property def metric(self): """The distance function used to measure the distance between two points. Returns: (function) """ return self._metric @property def seed(self): """The random seed used for generating samples. Returns: ...
"""The number of attempts each active point to make a new point. Returns: (int) """ return self._k
identifier_body
PoissonDiscSampleGenerator.py
random sample. (Optional) (Default: None) """ # -------------------------------- # User Parameters # -------------------------------- # Defines self._radius self.radius = radius # Defines self._k self.k = k # Defines both self._extent and self._d...
(bool) If succeeds, returns True. Otherwise, returns False. """ # -------------------------------- # Check Bounds # -------------------------------- # Get grid point and confirm it is within range coord = self._get_grid_coord(point) if np.logical_or(np...
point (np.ndarray): An array of size (number_of_dimensions,). Returns:
random_line_split
PoissonDiscSampleGenerator.py
random sample. (Optional) (Default: None) """ # -------------------------------- # User Parameters # -------------------------------- # Defines self._radius self.radius = radius # Defines self._k self.k = k # Defines both self._extent and self._d...
(self, active_point): """ Attempts to make a random point in proximity of active_point. Attempts to make a random point around the active_point k times. If the new point is too close to another point, it will discard and try. If it fails k times, the function returns None. Args...
_make_point
identifier_name
Labupdown.py
, :], allfeats=BIGfeat[:, :, s1:s2, :], updown='up'), min=0) VecUp=getVec(allfeats=BIGfeat[:, :, s1:s2, :]) torch.save(VecUp,'./VecUp.pkl') VecUp=torch.load('./VecUp.pkl') project_mapup=torch.clamp(getPmap(features[:, :, s1:s2, :],VecUp), min=0) maxv = project_mapup.view(project_...
project_mapdown1 = torch.zeros(features[:, :, s2:s3, s1:s4].size(0), features[:, :, s2:s3, s1:s4].size(2), features[:, :, s2:s3, s1:s4].size(3)).cuda() elif dr == 1: project_mapdown1 = torch.clamp( pca(features[:, :, s2:s3, s1:s4], allfeats=BIGfeat[...
if dr == 0:
random_line_split
Labupdown.py
def getPmap(features, first_compo): featuresChange=features.permute(1,0,2,3) reshaped_features=featuresChange.reshape(featuresChange.size(0),featuresChange.size(1)*featuresChange.size(2)*featuresChange.size(3)) projected_map = torch.matmul(first_compo.cuda().unsqueeze(0), reshaped_features.cuda()).view...
allfeaturesChange = allfeats.permute(1, 0, 2, 3) allreshaped_features = allfeaturesChange.reshape(allfeaturesChange.size(0), allfeaturesChange.size(1) * allfeaturesChange.size( 2) * allfeaturesChange.size(3...
identifier_body
Labupdown.py
:], allfeats=BIGfeat[:, :, s1:s2, :], updown='up'), min=0) VecUp=getVec(allfeats=BIGfeat[:, :, s1:s2, :]) torch.save(VecUp,'./VecUp.pkl') VecUp=torch.load('./VecUp.pkl') project_mapup=torch.clamp(getPmap(features[:, :, s1:s2, :],VecUp), min=0) maxv = project_mapup.view(project_m...
ClusterFeat = torch.cat((ClusterFeat, SF), 0) cnt = cnt + 1 ClusterFeatmean = torch.mean(ClusterFeat, dim=0) ClusterFeatmean = ClusterFeatmean.unsqueeze(0) ClusterFeatmax = torch.max(ClusterFeat, dim=0) ClusterFeatmax = ClusterFeatmax[0].unsqueeze(0) ...
roject_map[i] Singlefeature = features[i, :, :, :] meanmaskvalue = Sproject_map.sum() / (Sproject_map.size(0) * Sproject_map.size(1)) Sproject_map[Sproject_map < theh] = 0 allcood = torch.nonzero(Sproject_map).cpu().numpy() Sproject_map = Sproject_map.unsqueeze(0) # Smask...
conditional_block
Labupdown.py
(allfeats=None): # features: NCWH allfeaturesChange = allfeats.permute(1, 0, 2, 3) allreshaped_features = allfeaturesChange.reshape(allfeaturesChange.size(0), allfeaturesChange.size(1) * allfeaturesChange.size( ...
getVec
identifier_name
main.rs
config .try_parse_untrusted_http_server_port() .expect("untrusted http server port to be a valid port number"); let initialization_handler_clone = initialization_handler.clone(); tokio_handle.spawn(async move { if let Err(e) = start_is_initialized_server(initialization_handler_clone, untrusted_http_server_p...
{ for evr in &events { debug!("Decoded: phase = {:?}, event = {:?}", evr.phase, evr.event); match &evr.event { Event::Balances(be) => { info!("[+] Received balances event"); debug!("{:?}", be); match &be { pallet_balances::Event::Transfer { from: transactor, to: dest, amount: ...
identifier_body
main.rs
chain(); // ------------------------------------------------------------------------ // initialize teeracle interval #[cfg(feature = "teeracle")] if WorkerModeProvider::worker_mode() == WorkerMode::Teeracle { start_interval_market_update( &node_api, run_config.teeracle_update_interval, enclave.as_ref(),...
//TODO: this should be implemented by parentchain_handler directly, and not via // exposed parentchain_api. Blocked by https://github.com/scs/substrate-api-client/issues/267. parentchain_handler .parentchain_api()
random_line_split
main.rs
ed_header, ) .unwrap(); } // ------------------------------------------------------------------------ // start parentchain syncing loop (subscribe to header updates) thread::Builder::new() .name("parentchain_sync_loop".to_owned()) .spawn(move || { if let Err(e) = subscribe_to_parentchain_n...
we_are_primary_validateer
identifier_name
main.rs
else if matches.is_present("shielding-key") { setup::generate_shielding_key_file(enclave.as_ref()); } else if matches.is_present("signing-key") { setup::generate_signing_key_file(enclave.as_ref()); } else if matches.is_present("dump-ra") { info!("*** Perform RA and dump cert to disk"); enclave.dump_ra_to_dis...
{ start_interval_market_update( &node_api, run_config.teeracle_update_interval, enclave.as_ref(), &teeracle_tokio_handle, ); }
conditional_block
products.page.ts
allSelectedProducts = []// contain all products are selected idAccount: Number newProducts:Products[]= new Array() isPageForUpdateFollowList: boolean categoryProduct: number; nameProduct: string; currentItems =new Array() map= new Map() newListId = [] addProductsToList:boolean typeListId: number; ...
} }); } ngOnInit() { this.idAccount =+ localStorage.getItem('accountId') console.log(this.idAccount) this.getAllProducts() if(this.isPageForUpdateFollowList) this.getSortedFolowList() if(this.addProductsToList) this.GetAllProductsByTypeId() if(this.isF...
this.typeListName = params['typeListName'] if(params['productsInList'] != undefined) { this.allSelectedProducts =(params['productsInList'].split(',')).map(x=>+x);
random_line_split
products.page.ts
allSelectedProducts = []// contain all products are selected idAccount: Number newProducts:Products[]= new Array() isPageForUpdateFollowList: boolean categoryProduct: number; nameProduct: string; currentItems =new Array() map= new Map() newListId = [] addProductsToList:boolean typeListId: number; ...
:number[]) { this.productService.getProductsByIdProduct(res).subscribe(products=>{ this.selectedsArray = [] console.log(products) console.log(Object.values(products)) for (let i = 0; i < this.arrKind.length; i++) { if(Object.values(products).find(group=> group[0].Catego...
electedArray(res
identifier_name
products.page.ts
allSelectedProducts = []// contain all products are selected idAccount: Number newProducts:Products[]= new Array() isPageForUpdateFollowList: boolean categoryProduct: number; nameProduct: string; currentItems =new Array() map= new Map() newListId = [] addProductsToList:boolean typeListId: number; ...
this.selectedsArray.length; i++)// over all Categories for checking which Categories are selected items { if (this.selectedsArray[i] != null)// if seleced items in this Categories so { Object(this.selectedsArray[i]).forEach(pr=> { if(!this.allSelectedProducts.find(item=> ...
follow up list saveList() { // this.allSelectedProducts=[] לבדוק עם מוצרים מהרשימה אם מתווסף או מה for (let i = 0; i <
conditional_block
products.page.ts
allSelectedProducts = []// contain all products are selected idAccount: Number newProducts:Products[]= new Array() isPageForUpdateFollowList: boolean categoryProduct: number; nameProduct: string; currentItems =new Array() map= new Map() newListId = [] addProductsToList:boolean typeListId: number; ...
GetAllProductsByTypeId() { this.listService.GetAllProductsByTypeId(this.typeListId).subscribe(res=> { this.setSelectedArray(res.map(p=>p.ProductId)) }) } setSelectedArray(res:number[]) { this.productService.getProductsByIdProduct(res).subscribe(products=>{ this.selectedsArray...
this.setSelectedArray(this.allSelectedProducts.map(p=>p)) }
identifier_body
material.rs
of the object. albedo: Color, } impl Lambertian { /// Create a new diffuse material from a given intrinsic object color. pub fn new(albedo: Color) -> Self { Lambertian { albedo } } } impl Material<f64> for Lambertian { fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ra...
/// /// In our current design, N is a unit vector, but the same does not have to be true for V. /// Furthermore, V points inwards, so the sign has to be changed. /// All this is encoded in the reflect() function. pub struct Metal { /// Color of the object. albedo: Color, /// Fuziness of the specular reflect...
/// /// Additionally, B is an additional vector for illustration purposes. /// The reflected ray (in between N and B) has the same angle as the incident ray V with regards to // the surface. It can be computed as V + B + B.
random_line_split
material.rs
material. /// /// For smooth metal surfaces, light is not randomly scattered. Instead, the angle of the incident /// ray is equal to that of the specular outgoing ray. /// /// V N ^ ^ /// \ ^ / | /// \ | / | B /// v|/ | /// S ------------x------------ /// ...
and have to reflect) instead!
conditional_block
material.rs
the object. albedo: Color, } impl Lambertian { /// Create a new diffuse material from a given intrinsic object color. pub fn new(albedo: Color) -> Self
} impl Material<f64> for Lambertian { fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f64>, Color)> { // Diffuse reflection: True Lambertian reflection. // We aim for a Lambertian distribution of the reflected rays, which has a distribution of // cos(phi) instead of...
{ Lambertian { albedo } }
identifier_body
material.rs
the object. albedo: Color, } impl Lambertian { /// Create a new diffuse material from a given intrinsic object color. pub fn new(albedo: Color) -> Self { Lambertian { albedo } } } impl Material<f64> for Lambertian { fn scatter(&self, _ray: &Ray<f64>, rec: &HitRecord<f64>) -> Option<(Ray<f...
{ /// Color of the object. albedo: Color, /// Fuziness of the specular reflections. fuzz: f64, } impl Metal { /// Create a new metallic material from a given intrinsic object color. /// /// * `albedo`: Intrinsic surface color. /// * `fuzz`: Fuzziness factor for specular reflection in th...
etal
identifier_name
singleVisit.component.ts
; private accentureOfficeHeight; private mapZoomLevel = 3; private googleMapDesktopAPIKey = 'AIzaSyD5yFBB69RwOsb6sVRsQEapd9ynwCuoBYo'; private googleMapInfoWindow; constructor( private googleMaps: GoogleMaps, private selectvisit: SelectVisitServices, private headerService: HeaderService, private _tran...
{ marker.showInfoWindow(); me.defaultShowInfoWindow = true; }
conditional_block
singleVisit.component.ts
MarkerUrl: Array<string>; public visitStartDate: string; public visitEndDate: string; public selectedMapCityName; private displayVisitLocation: any = []; private displayAccentureOfficeLocation: any = []; private defaultShowInfoWindow; private _apiLoadingPromise: Promise<any>; private visitLocationWidth...
let visitLocationGrouped = _.groupBy(clientvisitLocations[1], function(locationObj: any){ return locationObj.CityName; }); let accentureOffices = []; _.forEach(visitLocationGrouped, function(paramObj, key){ //by default, display first marker position l...
random_line_split
singleVisit.component.ts
Url: Array<string>; public visitStartDate: string; public visitEndDate: string; public selectedMapCityName; private displayVisitLocation: any = []; private displayAccentureOfficeLocation: any = []; private defaultShowInfoWindow; private _apiLoadingPromise: Promise<any>; private visitLocationWidth; pr...
loadMap() { this.selectvisit.getVisitLocationDetails(this.selectvisit.selectedVisitObj.VisitID) .subscribe(locations => this.successLocationCallback(locations), error => this.errorMessage = <any>error); } private successLocationCallback(locations: any[]){ // create a new map ...
{ this.loadMap(); }
identifier_body
singleVisit.component.ts
Url: Array<string>; public visitStartDate: string; public visitEndDate: string; public selectedMapCityName; private displayVisitLocation: any = []; private displayAccentureOfficeLocation: any = []; private defaultShowInfoWindow; private _apiLoadingPromise: Promise<any>; private visitLocationWidth; pr...
() : void{ let me = this, counter = 0; me.displayVisitLocation.map(function(locationObj, key){ if(!counter){ me.selectedMapCityName = locationObj.CityName + ' '+ moment(locationObj.StartDate).format('Do MMM YYYY'); } // create LatLng object ...
addVisitLocationMarker
identifier_name
main.js
// // arrs[3][7] = 2; // squArr = [[1][6],[1][7],[2][7],[3][7]]; // break; // case 3: // // |-字形 // // arrs[1][6] = 2; // // arrs[2][6] = 2; // // arrs[3][6] = 2; // // arrs[2][7] = 2; // squArr = [[1][6],[2][6],[3][6],[2][7]]; // break; // case 4: // // z字形 // // arrs[1][6] = 2; ...
移动 能移动则把移动完数组的值赋给squarr if(canMove()){ squArr = target; //绘出来 block(); } } } } //拿到显示分数的盒子 var scoreBox = document.getElementById("score"); //显示的分数值 var score = 0; //消除的方法 function clear(){ //遍历整个数组 for(var i=22;i>=1;i--){ var isClear = true; for(var j=12;j>=1;j--){ if(arrs[i][j] != 2){ ...
r[i][0], squArr[i][1] + 1]; } else if (direction == "up") { //形状变化 给移动的数组赋变形后的值 change(); //判断是否能
identifier_body
main.js
var j = 0; j < 14; j++) { //当是第一行或者是最后一行或者是第一列或者是最后一列 为墙赋值为1 if (i == 0 || i == 23 || j == 0 || j == 13) { arrs[i][j] = 1; } } } } //先拿到所有的单元格 数组 var tds = document.getElementsByTagName("td"); //控制难度的时间 datatime = 500; //随机生成颜色的方法 function randomColor(){ var r,g,b; r=Math.floor(Math.random()*166+90); g=Ma...
or (
identifier_name
main.js
][0]+1; target[3][1] = squArr[2][1]; break; } break; case 3: // |-字形 //squArr = [[1,6],[2,6],[3,6],[2,7]]; switch(Chgcount%4){ case 0: hidden(); target[0][0] = squArr[1][0]; target[0][1] = squArr[1][1]+1; target[1][0] = squArr[1][0]; target[1][1] = squArr[1][1]; ...
block(); //重新绘图 draw(); timer = setInterval("autoDown()", datatime); isBegin = true; } else { alert("当前游戏已经开始"); } break; //按左箭头的时候 case 37: conso
conditional_block
main.js
] = squArr[2][1]-2; // target[3][0] = squArr[3][0]+3; // target[3][1] = squArr[3][1]-3; if(Chgcount%2){ //当为真的时候 值为1的时候变横条 否则变竖条 //隐藏开始的位置 hidden(); //给变化后的位置赋值 for(var i=0;i<4;i++){ target[i][0] =squArr[0][0]; target[i][1] =squArr[0][1]+i; } }else{ //隐藏开始的位置 ...
block(); //重新绘图 draw();
random_line_split
model.go
Ind *Ind `xml:"w:ind,omitempty"` Jc *Jc `xml:"w:jc,omitempty"` RPr *RPr `xml:"w:rPr,omitempty"` } //Ind 首行:缩进、行高 type Ind struct { XMLName xml.Name `xml:"w:ind"` FirstLineChars int64 `xml:"w:firstLineChars,attr"` //首行缩进字符数,100是一个字符 LeftChars int64 `xml...
e `xml:"w:rPr"` RFonts *RFonts `xml:"w:rFonts,omitempty"` B *Bold `xml:"w:b,omitempty"` // BCs string `xml:"w:bCs,omitempty"` Color *Color `xml:"w:color"` Sz *Sz `xml:"w:sz"` SzCs *SzCs `xml:"w:szCs"` } //Bold 加粗 type Bold struct { XMLName xml.Name `xml:"w:b"` Val string `xml:"w:...
l.Nam
identifier_name
model.go
Ind *Ind `xml:"w:ind,omitempty"` Jc *Jc `xml:"w:jc,omitempty"` RPr *RPr `xml:"w:rPr,omitempty"` } //Ind 首行:缩进、行高 type Ind struct { XMLName xml.Name `xml:"w:ind"` FirstLineChars int64 `xml:"w:firstLineChars,attr"` //首行缩进字符数,100是一个字符 LeftChars int64 `xm...
:"w:rPr"` RFonts *RFonts `xml:"w:rFonts,omitempty"` B *Bold `xml:"w:b,omitempty"` // BCs string `xml:"w:bCs,omitempty"` Color *Color `xml:"w:color"` Sz *Sz `xml:"w:sz"` SzCs *SzCs `xml:"w:szCs"` } //Bold 加粗 type Bold struct { XMLName xml.Name `xml:"w:b"` Val string `xml:"w:val,at...
xml
identifier_body
model.go
Ind *Ind `xml:"w:ind,omitempty"` Jc *Jc `xml:"w:jc,omitempty"` RPr *RPr `xml:"w:rPr,omitempty"` } //Ind 首行:缩进、行高 type Ind struct { XMLName xml.Name `xml:"w:ind"` FirstLineChars int64 `xml:"w:firstLineChars,attr"` //首行缩进字符数,100是一个字符 LeftChars int64 `xml...
XMLName xml.Name `xml:"w:jc"` Val string `xml:"w:val,attr,omitempty"` } //T 文本 type T struct { XMLName xml.Name `xml:"w:t"` Space string `xml:"xml:space,attr,omitempty"` //"preserve" // Space string `xml:"w:space,attr,omitempty"` Text string `xml:",chardata"` } //Drawing 绘图 type Drawing struct { XMLN...
//Jc 对齐方式 <w:jc w:val="left"/> type Jc struct {
random_line_split
minesweeper.py
'X', 'Y', 'Z'] def __init__(self, height, width, mines): """initializes the Minesweeper instance with a width, height, and the number of mines. Sets up a default game table, generates random mine locations and updates another table for the solution.""" self.x = int(width) self.y = ...
return mine_locations def generate_answer(self): ft = deepcopy(self.table_state) for x in range(0, self.x): for y in range(0, self.y): # get the number or mine with neighbours ft[y][x] = self.get_neighbour(y, x) return ft def get_nei...
choice = random.choice(available_places) available_places.remove(choice) mine_locations.append(choice) number -= 1
conditional_block
minesweeper.py
'X', 'Y', 'Z'] def __init__(self, height, width, mines): """initializes the Minesweeper instance with a width, height, and the number of mines. Sets up a default game table, generates random mine locations and updates another table for the solution.""" self.x = int(width) self.y = ...
if self.final_table[ye][xe] == Minesweeper.BOMB and self.table_state[ye][xe] != Minesweeper.FLAG: self.show_answer_board([ye, xe]) print "KABOOM!" return Minesweeper.IS_A_BOMB self.open_neighbours(y, x) self.print_table(self...
x - 1, x + 2) if xe >= 0 for ye in range(y - 1, y + 2) if ye >= 0] for ye, xe in l: if xe >= self.x or ye >= self.y: # do not open out of bounds continue # if it is a bomb but not flagged
random_line_split
minesweeper.py
'X', 'Y', 'Z'] def
(self, height, width, mines): """initializes the Minesweeper instance with a width, height, and the number of mines. Sets up a default game table, generates random mine locations and updates another table for the solution.""" self.x = int(width) self.y = int(height) self.table_st...
__init__
identifier_name
minesweeper.py
'X', 'Y', 'Z'] def __init__(self, height, width, mines): """initializes the Minesweeper instance with a width, height, and the number of mines. Sets up a default game table, generates random mine locations and updates another table for the solution.""" self.x = int(width) self.y = ...
def flags_nearby(self, y, x): """ gets number of flags nearby """ count = 0 l = [[ye, xe] for xe in range( x - 1, x + 2) if xe >= 0 for ye in range(y - 1, y + 2) if ye >= 0] for ye, xe in l: if xe >= self.x or ye >= self.y: continue ...
"""populate answer table with numbers and mines""" if [y, x] in self.mine_locations: return Minesweeper.BOMB count = 0 # (x-1, y-1), (x, y-1), (x+1, y-1), # (x-1, y), (x, y), (x+1, y), # (x-1, y+1), (x, y+1), (x+1, y+1) for xe in range(x - 1, x + 2): ...
identifier_body
IBRAHIM_OLADOKUN.py
AndLoans': 'OpenCredit', 'NumberOfTimes90DaysLate': 'Late90', 'NumberRealEstateLoansOrLines': 'PropLines', 'NumberOfTime60-89DaysPastDueNotWorse': 'Late6089', 'NumberOfDependents': 'De...
if dataset.Late6089[i] >= 3: dataset.Late6089[i] = 3
conditional_block
IBRAHIM_OLADOKUN.py
suspected that other variables contains errors (Age) # In[11]: test.isnull().sum() # The test data also contains several NaN values # # Target distribution # In[13]: ax = sns.countplot(x = train.SeriousDlqin2yrs ,palette="Set3") sns.set(font_scale=1.5) ax.set_ylim(top = 150000) ax.set_xlabel('Financial diffic...
# Interquartile range (IQR) IQR = Q3 - Q1 # outlier step outlier_step = 1.5 * IQR # Determine a list of indices of outliers for feature col outlier_list_col = df[(df[col] < Q1 - outlier_step) | (df[col] > Q3 + outlier_step )].index # app...
Q1 = np.percentile(df[col], 25) # 3rd quartile (75%) Q3 = np.percentile(df[col],75)
random_line_split
IBRAHIM_OLADOKUN.py
that other variables contains errors (Age) # In[11]: test.isnull().sum() # The test data also contains several NaN values # # Target distribution # In[13]: ax = sns.countplot(x = train.SeriousDlqin2yrs ,palette="Set3") sns.set(font_scale=1.5) ax.set_ylim(top = 150000) ax.set_xlabel('Financial difficulty in 2 ...
# select observations containing more than 2 outliers outlier_indices = Counter(outlier_indices) multiple_outliers = list( k for k, v in outlier_indices.items() if v > n ) return multiple_outliers # detect outliers from Age, SibSp , Parch and Fare # These are the numerical features presen...
outlier_indices = [] # iterate over features(columns) for col in features: # 1st quartile (25%) Q1 = np.percentile(df[col], 25) # 3rd quartile (75%) Q3 = np.percentile(df[col],75) # Interquartile range (IQR) IQR = Q3 - Q1 # outlier step ...
identifier_body
IBRAHIM_OLADOKUN.py
that other variables contains errors (Age) # In[11]: test.isnull().sum() # The test data also contains several NaN values # # Target distribution # In[13]: ax = sns.countplot(x = train.SeriousDlqin2yrs ,palette="Set3") sns.set(font_scale=1.5) ax.set_ylim(top = 150000) ax.set_xlabel('Financial difficulty in 2 ...
(df,n,features): outlier_indices = [] # iterate over features(columns) for col in features: # 1st quartile (25%) Q1 = np.percentile(df[col], 25) # 3rd quartile (75%) Q3 = np.percentile(df[col],75) # Interquartile range (IQR) IQR = Q3 - Q1 ...
detect_outliers
identifier_name
putio-ftp-connector.py
): c = self.buffer self.buffer = '' return c def read(self, size=65536): if self.req == None: self.req = urllib2.Request(self.download_url) if self.seekpos: self.req.headers['Range'] = 'bytes=%s-' % (self.seekpos) if self.read_size > self.t...
else: key = '%s/%s' % (pathtoid._utf8(basedir), pathtoid._utf8(i.name)) self.dirlistcache[key] = i print 'key:', key yield ln.encode('utf-8') class HttpOperations(object): '''Storing connection object''' def __init__(self): self.connection = Non...
key = '/%s' % (pathtoid._utf8(i.name))
conditional_block
putio-ftp-connector.py
): c = self.buffer self.buffer = '' return c def read(self, size=65536): if self.req == None: self.req = urllib2.Request(self.download_url) if self.seekpos: self.req.headers['Range'] = 'bytes=%s-' % (self.seekpos) if self.read_size > self.t...
if not username: return False print "> welcome ", username return True def
print "checking user & passwd" username = self.api.get_user_name()
random_line_split
putio-ftp-connector.py
): c = self.buffer self.buffer = '' return c def read(self, size=65536): if self.req == None: self.req = urllib2.Request(self.download_url) if self.seekpos: self.req.headers['Range'] = 'bytes=%s-' % (self.seekpos) if self.read_size > self.t...
(self, filename): if filename in self.dirlistcache: apifile = self.dirlistcache[filename] print 'found........', apifile.id, apifile.name else: if filename == os.path.sep: # items = operations.api.get_items() return False else: ...
_getitem
identifier_name
putio-ftp-connector.py
): c = self.buffer self.buffer = '' return c def read(self, size=65536): if self.req == None: self.req = urllib2.Request(self.download_url) if self.seekpos: self.req.headers['Range'] = 'bytes=%s-' % (self.seekpos) if self.read_size > self.t...
def listdir(self, path): ret = [] try: item = self._getitem(path) except: return [] if not item: items = operations.api.get_items() else: try: items = operations.api.get_items(parent_id=item.id) except: ...
dirs = os.path.split(path) apifile = self._getitem(dirs[0]) if not apifile: #this is root operations.api.create_folder(name = dirs[1], parent_id = 0) else: apifile.create_folder(name=dirs[1]) self.remove_from_cache(path) self.remove_from_cache(dirs[0])
identifier_body
glfw.go
ickyKeysMode) // Value can be either 1 or 0 StickyMouseButtonsInputMode = InputMode(glfw.StickyMouseButtonsMode) // Value can be either 1 or 0 ) // Cursor mode values const ( CursorNormal = CursorMode(glfw.CursorNormal) CursorHidden = CursorMode(glfw.CursorHidden) CursorDisabled = CursorMode(glfw.Curso...
{ // If already in the desired state, nothing to do if w.fullscreen == full { return } // Set window fullscreen on the primary monitor if full { // Save current position and size of the window w.lastX, w.lastY = w.GetPos() w.lastWidth, w.lastHeight = w.GetSize() // Get size of primary monitor mon := g...
identifier_body
glfw.go
= glfw.CreateWindow(width, height, title, nil, nil) if err != nil { return err } w.MakeContextCurrent() // Create OpenGL state w.gls, err = gls.New() if err != nil { return err } // Compute and store scale fbw, fbh := w.GetFramebufferSize() w.scaleX = float64(fbw) / float64(width) w.scaleY = float64(f...
{ w.cursors[key].Destroy() delete(w.cursors, key) }
conditional_block
glfw.go
ModifierKey(glfw.ModSuper) ) // Mouse buttons const ( MouseButton1 = MouseButton(glfw.MouseButton1) MouseButton2 = MouseButton(glfw.MouseButton2) MouseButton3 = MouseButton(glfw.MouseButton3) MouseButton4 = MouseButton(glfw.MouseButton4) MouseButton5 = MouseButton(glfw.MouseButton5) Mou...
FullScreen
identifier_name
glfw.go
this is set, glLineWidth(width) only accepts width=1.0 and generates an error // for any other values although the spec says it should ignore unsupported widths // and generate an error only when width <= 0. if runtime.GOOS == "darwin" { glfw.WindowHint(glfw.OpenGLForwardCompatible, glfw.True) } // Create wind...
} // Create and store cursor w.lastCursorKey += 1 w.cursors[Cursor(w.lastCursorKey)] = glfw.CreateCursor(img, xhot, yhot)
random_line_split
rf_model.py
', \ 'following', 'homeless', 'homeless_trend', 'food_class'] writer.writerow(keys) i = 0 for dic in jsonData: try: # get coordinates if dic['location']['coordinates'] is None: city = dic['location']['place_name'] city = city.rep...
""" --------------------------------------------------------- --------------------- Main Function --------------------- --------------------------------------------------------- """ if __name__ == "__main__": COUCHDB_NAME = sys.argv[1] OUT_COUCHDB_NAME = sys.argv[2] REFORMED_FILE = sys.argv[3] ...
if food in Keywords.fastfood: return "fastfood" if food in Keywords.fruits: return "fruits" if food in Keywords.grains: return "grains" if food in Keywords.meat: return "meat" if food in Keywords.seafood: return "seafood" if food in Keywords.vegetables: ...
identifier_body
rf_model.py
\ 'following', 'homeless', 'homeless_trend', 'food_class'] writer.writerow(keys) i = 0 for dic in jsonData: try: # get coordinates if dic['location']['coordinates'] is None: city = dic['location']['place_name'] city = city.repla...
(food): if food in Keywords.fastfood: return "fastfood" if food in Keywords.fruits: return "fruits" if food in Keywords.grains: return "grains" if food in Keywords.meat: return "meat" if food in Keywords.seafood: return "seafood" if food in Keywords.vegeta...
get_food_group
identifier_name
rf_model.py
("number of rows without homeless information: %d" % df_no_homeless.count()) # transform dataframe into RDD transformed_df_food = df_all_info.rdd.map(lambda row: LabeledPoint(row[-1], Vectors.dense(row[2:-1]))) transformed_df_homeless = df_all_info.rdd.map(lambda row: LabeledPoint(row[-3], Vec...
entry["properties"]["time"] = json_obj["time"]
random_line_split
rf_model.py
', \ 'following', 'homeless', 'homeless_trend', 'food_class'] writer.writerow(keys) i = 0 for dic in jsonData:
home = dic['homeless'] foods = dic['food_list'] if (home is None) and (foods is None or len(foods) == 0): continue # get homeless information if home is None: homeless = -1 homeless_trend = 0 ...
try: # get coordinates if dic['location']['coordinates'] is None: city = dic['location']['place_name'] city = city.replace(" ","%20") coor = cityPos(city) lng = coor['location']['lng'] lat = coor['location']['lat'] ...
conditional_block
actions.rs
Serialize, Deserialize, Debug)] pub struct ActionDisplayInfo { pub name: String, pub health_cost: Cost, pub time_cost: Cost, pub rules_text: String, pub flavor_text: String, } impl Default for ActionDisplayInfo { fn default() -> Self { ActionDisplayInfo { name: "".to_string(), health_cost:...
} #[derive(Clone, PartialEq, Serialize, Deserialize, Debug)] pub struct BuildConveyor { pub allow_splitting: bool, } #[derive(Copy, Clone, PartialEq, Serialize, Deserialize, Debug)] struct BuildConveyorCandidate { position: GridVector, input_side: Facing, } impl BuildConveyorCandidate { fn input_position(&s...
{ draw.rectangle_on_map( 5, game.player.position.containing_tile().to_floating(), TILE_SIZE.to_floating(), "#666", ); }
identifier_body
actions.rs
Serialize, Deserialize, Debug)] pub struct ActionDisplayInfo { pub name: String, pub health_cost: Cost, pub time_cost: Cost, pub rules_text: String, pub flavor_text: String, } impl Default for ActionDisplayInfo { fn default() -> Self { ActionDisplayInfo { name: "".to_string(), health_cost:...
(&self) -> bool { self.progress > self.finish_time() } fn health_to_pay_by(&self, progress: f64) -> f64 { smootherstep(self.startup_time(), self.finish_time(), progress) * self.health_cost() } } impl ActionTrait for SimpleAction { fn update(&mut self, context: ActionUpdateContext) -> ActionStatus { ...
finished
identifier_name
actions.rs
Serialize, Deserialize, Debug)] pub struct ActionDisplayInfo { pub name: String, pub health_cost: Cost, pub time_cost: Cost, pub rules_text: String, pub flavor_text: String, } impl Default for ActionDisplayInfo { fn default() -> Self { ActionDisplayInfo { name: "".to_string(), health_cost:...
} _ => unreachable!(), } } self.simple_action_type.finish(context); } } if self.progress > self.time_cost() || self.cancel_progress > self.cooldown_time() { ActionStatus::Completed } else { ActionStatus::StillGoing } } fn display...
{ context.game.cards.selected_index = Some(index + 1); }
conditional_block
actions.rs
_text: flavor_text.to_string(), }, is_card, simple_action_type, progress: 0.0, cancel_progress: 0.0, } } fn time_cost(&self) -> f64 { match self.display_info.time_cost { Cost::Fixed(cost) => cost as f64, _ => panic!(), } } fn health_cost(&self) -> f64 { ...
}
random_line_split
train.py
train_features, dev_features, test_features): def finetune(features, optimizer, num_epoch, num_steps): best_score = -1 train_dataloader = DataLoader(features, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn, drop_last=True) train_iterator = range(int(num_epoch)) ...
parser.add_argument("--train_batch_size", default=4, type=int, help="Batch size for training.") parser.add_argument("--test_batch_size", default=8, type=int, help="Batch size for testing.") parser.add_argument("--gradient_accumulation_steps", default=1, type=i...
parser = argparse.ArgumentParser() parser.add_argument("--data_dir", default="./dataset/docred", type=str) parser.add_argument("--transformer_type", default="bert", type=str) parser.add_argument("--model_name_or_path", default="bert-base-cased", type=str) parser.add_argument("--train_file", default="t...
identifier_body
train.py
train_features, dev_features, test_features): def finetune(features, optimizer, num_epoch, num_steps): best_score = -1 train_dataloader = DataLoader(features, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn, drop_last=True) train_iterator = range(int(num_epoch)) ...
(args, model, features, tag="dev"): dataloader = DataLoader(features, batch_size=args.test_batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False) preds = [] for batch in dataloader: model.eval() inputs = {'input_ids': batch[0].to(args.device), 'attention_mask'...
evaluate
identifier_name
train.py
train_features, dev_features, test_features): def finetune(features, optimizer, num_epoch, num_steps): best_score = -1 train_dataloader = DataLoader(features, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn, drop_last=True) train_iterator = range(int(num_epoch)) ...
dev_score, dev_output = evaluate(args, model, dev_features, tag="dev") #wandb.log(dev_output, step=num_steps) print(dev_output) if dev_score > best_score: best_score = dev_score pred = report(...
'''
random_line_split
train.py
train_features, dev_features, test_features): def finetune(features, optimizer, num_epoch, num_steps): best_score = -1 train_dataloader = DataLoader(features, batch_size=args.train_batch_size, shuffle=True, collate_fn=collate_fn, drop_last=True) train_iterator = range(int(num_epoch)) ...
output = { tag + "_F1": best_f1 * 100, tag + "_F1_ign": best_f1_ign * 100, } return best_f1, output def report(args, model, features): dataloader = DataLoader(features, batch_size=args.test_batch_size, shuffle=False, collate_fn=collate_fn, drop_last=False) preds = [] for batc...
best_f1, _, best_f1_ign, _ = official_evaluate(ans, args.data_dir)
conditional_block
Set.go
) Remove(removeMem setMember) { delete(s.mem, removeMem) } // ----------------------------------------------------------------------------- // Set equality: Two sets are equal if they have the same elements. func Equals(oneSet, otherSet Set) bool { if len(oneSet.mem) != len(otherSet.mem) { return false } /* ...
() string { mySetSlice := []setMember{} for i := range s.mem { mySetSlice = append(mySetSlice, i) } myString := fmt.Sprint(mySetSlice) return myString } func testSetString(theSetString string, theSet Set) { counter := 0 for i := range theSet.mem { for k := 0; k < len(theSetString); k++ { if fmt.Spri...
SetString
identifier_name
Set.go
Set) Remove(removeMem setMember) { delete(s.mem, removeMem) } // ----------------------------------------------------------------------------- // Set equality: Two sets are equal if they have the same elements. func Equals(oneSet, otherSet Set) bool { if len(oneSet.mem) != len(otherSet.mem) { return false } ...
unionSet := NewSet() for k := range s.mem { unionSet.mem[k] = true } // Adds the elements of the set to the union set. for k := range otherSet.mem { unionSet.mem[k] = true } // Adds the elements of the set in the argument to the union set. return unionSet } // -------------------------------------------...
another set specified in the argument of the function. */ func (s Set) Union(otherSet Set) Set {
random_line_split
Set.go
) Remove(removeMem setMember)
// ----------------------------------------------------------------------------- // Set equality: Two sets are equal if they have the same elements. func Equals(oneSet, otherSet Set) bool { if len(oneSet.mem) != len(otherSet.mem) { return false } /* Obviously, if the sets have different numbers of elements, th...
{ delete(s.mem, removeMem) }
identifier_body
Set.go
) Remove(removeMem setMember) { delete(s.mem, removeMem) } // ----------------------------------------------------------------------------- // Set equality: Two sets are equal if they have the same elements. func Equals(oneSet, otherSet Set) bool { if len(oneSet.mem) != len(otherSet.mem) { return false } /* ...
// Adds the elements of the set in the argument to the union set. return unionSet } // ----------------------------------------------------------------------------- /* The intersection of two sets is the set of members of both sets. This function is a method which acts on a set and returns the intersection of it ...
{ unionSet.mem[k] = true }
conditional_block
gitiles.pb.go
func (*LogResponse) Descriptor() ([]byte, []int) { return fileDescriptor_gitiles_e833c2c096a9c6f8, []int{1} } func (m *LogResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LogResponse.Unmarshal(m, b) } func (m *LogResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_message...
() string { if m != nil { return m.Project } return "" } func (m *RefsRequest) GetRefsPath() string { if m != nil { return m.RefsPath } return "" } // RefsResponse is a response message of Gitiles.Refs RPC. type RefsResponse struct { // revisions maps a ref to a revision. // Git branches have keys start w...
GetProject
identifier_name
gitiles.pb.go
(*LogResponse) Descriptor() ([]byte, []int) { return fileDescriptor_gitiles_e833c2c096a9c6f8, []int{1} } func (m *LogResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LogResponse.Unmarshal(m, b) } func (m *LogResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo...
return out, nil } func (c *gitilesPRPCClient) Refs(ctx context.Context, in *RefsRequest, opts ...grpc.CallOption) (*RefsResponse, error) { out := new(RefsResponse) err := c.client.Call(ctx, "gitiles.Gitiles", "Refs", in, out, opts...) if err != nil { return nil, err } return out, nil } type gitilesClient str...
{ return nil, err }
conditional_block
gitiles.pb.go
func (m *LogRequest) GetTreeDiff() bool { if m != nil { return m.TreeDiff } return false } func (m *LogRequest) GetPageToken() string { if m != nil { return m.PageToken } return "" } func (m *LogRequest) GetPageSize() int32 { if m != nil { return m.PageSize } return 0 } // LogRequest is response mes...
{ if m != nil { return m.Ancestor } return "" }
identifier_body
gitiles.pb.go
func (*LogResponse) Descriptor() ([]byte, []int) { return fileDescriptor_gitiles_e833c2c096a9c6f8, []int{1} } func (m *LogResponse) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_LogResponse.Unmarshal(m, b) } func (m *LogResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_message...
} return "" } func (m *RefsRequest) GetRefsPath() string { if m != nil { return m.RefsPath } return "" } // RefsResponse is a response message of Gitiles.Refs RPC. type RefsResponse struct { // revisions maps a ref to a revision. // Git branches have keys start with "refs/heads/". Revisions map[s...
func (m *RefsRequest) GetProject() string { if m != nil { return m.Project
random_line_split
lib.rs
_mut_passed)] #![warn(clippy::wildcard_in_or_patterns)] #![warn(clippy::crosspointer_transmute)] #![warn(clippy::excessive_precision)] #![warn(clippy::overflow_check_conditional)] #![warn(clippy::as_conversions)] #![warn(clippy::match_overlapping_arm)] #![warn(clippy::zero_divided_by_zero)] #![warn(clippy::must_use_uni...
Database
identifier_name
lib.rs
ting)] #![warn(clippy::suspicious_unary_op_formatting)] #![warn(clippy::mut_mutex_lock)] #![warn(clippy::print_literal)] #![warn(clippy::same_item_push)] #![warn(clippy::useless_format)] #![warn(clippy::write_literal)] #![warn(clippy::redundant_closure)] #![warn(clippy::redundant_closure_call)] #![warn(clippy::unnecess...
pub name: String, pub schema: String, pub fields: Vec<TableField>, }
random_line_split
transaction.rs
_dao = TransactionDao { conn: &conn }; let trans = tran_dao.list(&since_nd, &until_nd); let account_dao = AccountDao { conn: &conn }; let account = account_dao.list().into_iter().find(|acct| { acct.qualified_name() == expense_name }).unwrap(); // :(:( let mut splits = Vec::new(); for ...
#[derive(Debug)] #[derive(Serialize)] pub struct MonthlyTotals { summaries: Vec<MonthTotal>, totalSpent: i64, pub acctSums: Vec<MonthlyExpenseGroup> } #[derive(Debug)] #[derive(Serialize)] pub struct AccountSummary { name: String, monthlyTotals: Vec<MonthlyTotal>, } #[derive(Debug)] #[derive(Ser...
{ let (since_nd, until_nd) = since_until(since, until, months, year); let dao = TransactionDao { conn: &conn }; dao.list(&since_nd, &until_nd) }
identifier_body
transaction.rs
_dao = TransactionDao { conn: &conn }; let trans = tran_dao.list(&since_nd, &until_nd); let account_dao = AccountDao { conn: &conn }; let account = account_dao.list().into_iter().find(|acct| { acct.qualified_name() == expense_name }).unwrap(); // :(:( let mut splits = Vec::new(); for ...
; NaiveDate::from_ymd(curr_year, curr_month, 1) }).collect::<Vec<_>>(); desired_months.insert(0, NaiveDate::from_ymd(until.year(), until.month(), 1)); let mut cloned_expenses = expenses.clone(); (0..cloned_expenses.len()).for_each(|i| { let mut exp = &mut cloned_expenses[i]; ...
{ curr_month -= 1; }
conditional_block
transaction.rs
_dao = TransactionDao { conn: &conn }; let trans = tran_dao.list(&since_nd, &until_nd); let account_dao = AccountDao { conn: &conn }; let account = account_dao.list().into_iter().find(|acct| { acct.qualified_name() == expense_name }).unwrap(); // :(:( let mut splits = Vec::new(); for ...
{ pub name: String, pub total: i64, monthlyTotals: Vec<MonthTotal>, } fn expenses_by_month( transactions: &Vec<Transaction>, accounts: &Vec<Account> ) -> Vec<MonthlyExpenseGroup> { let mut accounts_map = HashMap::new(); for a in accounts { accounts_map.insert(&a.guid, a); } ...
MonthlyExpenseGroup
identifier_name
transaction.rs
tran_dao = TransactionDao { conn: &conn }; let trans = tran_dao.list(&since_nd, &until_nd); let account_dao = AccountDao { conn: &conn }; let account = account_dao.list().into_iter().find(|acct| { acct.qualified_name() == expense_name }).unwrap(); // :(:( let mut splits = Vec::new(); ...
}).collect::<Vec<_>>(); summed.sort_by(|a, b| parse_nd(&b.month).cmp(&parse_nd(&a.month))); let total_spent = summed.iter().map(|m| m.total).sum(); //let mut acct_sums = months.clone(); MonthlyTotals { summaries: summed, totalSpent: total_spent, acctSums: months.clone() ...
month: i, total: month_summary.into_iter().map(|m| m.total).sum() }
random_line_split
glyph_brush.rs
{ fn pixel_bounds_custom_layout<'a, S, L>( &mut self, section: S, custom_layout: &L, ) -> Option<Rect<i32>> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layo...
Ok(None) => None, Ok(Some((tex_coords, pixel_coords))) => { if pixel_coords.min.x as f32 > bounds.max.x || pixel_coords.min.y as f32 > bounds.max.y || bound...
None }
random_line_split
glyph_brush.rs
{ fn pixel_bounds_custom_layout<'a, S, L>( &mut self, section: S, custom_layout: &L, ) -> Option<Rect<i32>> where L: GlyphPositioner + Hash, S: Into<Cow<'a, VariedSection<'a>>>, { let section_hash = self.cache_glyphs(&section.into(), custom_layo...
let verts: Vec<V> = if some_text { let sections: Vec<_> = self .section_buffer .iter() .map(|hash| &self.calculate_glyph_cache[hash]) .collect(); let mut verts = Vec::with_capacity( ...
{ let (width, height) = self.texture_cache.dimensions(); return Err(BrushError::TextureTooSmall { suggested: (width * 2, height * 2), }); }
conditional_block
glyph_brush.rs
).build(); /// glyph_brush.queue(Section { /// text: "Hello glyph_brush", /// ..Section::default() /// }); /// ``` pub fn queue<'a, S>(&mut self, section: S) where S: Into<Cow<'a, VariedSection<'a>>>, { profile_scope!("glyph_brush_queue"); let sect...
{ self.add_font(Font::from_bytes(font_data.into()).unwrap()) }
identifier_body
glyph_brush.rs
= self.section_hasher.build_hasher(); hashable.hash(&mut s); s.finish() } /// Returns the calculate_glyph_cache key for this sections glyphs fn cache_glyphs<L>(&mut self, section: &VariedSection<'_>, layout: &L) -> SectionHash where L: GlyphPositioner, { prof...
keep_cached_custom_layout
identifier_name
main.go
AtWords()) if err != nil { panic(err) } if err := blocksWidget.Write("Latest block height " + networkStatus.Get("result.sync_info.latest_block_height").String() + "\n"); err != nil { panic(err) } // Transaction parsing widget transactionWidget, err := text.New(text.RollContent(), text.WrapAtWords()) if err ...
func getTendermintRPC(endpoint string) string { resp, err := resty.R(). SetHeader("Cache-Control", "no-cache"). SetHeader("Content-Type", "application/json"). Get(tendermintRPC + endpoint) if err != nil { panic(err) } return resp.String() } // writeTime writes the current system time to the timeWidget. /...
}
random_line_split
main.go
Words()) if err != nil { panic(err) } if err := blocksWidget.Write("Latest block height " + networkStatus.Get("result.sync_info.latest_block_height").String() + "\n"); err != nil { panic(err) } // Transaction parsing widget transactionWidget, err := text.New(text.RollContent(), text.WrapAtWords()) if err !=...
ntext, t *text.Text, delay time.Duration) { peers := gjson.Get(getFromRPC("net_info"), "result.n_peers").String() t.Reset() if peers != "" { t.Write(peers) } if err := t.Write(peers); err != nil { panic(err) } ticker := time.NewTicker(delay) defer ticker.Stop() for { select { case <-ticker.C: t.Re...
context.Co
identifier_name
main.go
blocksWidget, err := text.New(text.RollContent(), text.WrapAtWords()) if err != nil { panic(err) } if err := blocksWidget.Write("Latest block height " + networkStatus.Get("result.sync_info.latest_block_height").String() + "\n"); err != nil { panic(err) } // Transaction parsing widget transactionWidget, err ...
{ view() connectionSignal := make(chan string) t, err := termbox.New() if err != nil { panic(err) } defer t.Close() flag.Parse() networkInfo := getFromRPC("status") networkStatus := gjson.Parse(networkInfo) if !networkStatus.Exists() { panic("Application not running on localhost:" + fmt.Sprintf("%s", *g...
identifier_body
main.go
AtWords()) if err != nil { panic(err) } if err := blocksWidget.Write("Latest block height " + networkStatus.Get("result.sync_info.latest_block_height").String() + "\n"); err != nil { panic(err) } // Transaction parsing widget transactionWidget, err := text.New(text.RollContent(), text.WrapAtWords()) if err ...
return resp.String() } // writeTime writes the current system time to the timeWidget. // Exits when the context expires. func writeTime(ctx context.Context, t *text.Text, delay time.Duration) { ticker := time.NewTicker(delay) defer ticker.Stop() for { select { case <-ticker.C: currentTime := time.Now() t...
panic(err) }
conditional_block
shared.rs
]; /// the root of AsRef,Borrow and Deref. fn get_slice(&self) -> &[u8]; } //////////////////// // public methods // //////////////////// impl Nbstr { #[cfg(feature="unstable")] /// Get the max length a Nbstr can store, /// as some compile-time features might limit it. pub const MAX_LENG...
fn boxed() { let b: Box<str> = STR.to_string().into_boxed_str(); let len = b.len(); let ptr = b.as_ptr();
random_line_split
shared.rs
use std::{mem,slice,ptr, fmt,hash}; use std::borrow::{Borrow,Cow}; /// Protected methods used by the impls below. pub trait Protected { /// create new of this variant with possibly uninitialized data fn new(u8) -> Self; /// store this str, which is either &'static or boxed fn with_pointer(u8, &str) ...
impl From<Nbstr> for Box<str> { fn from(mut z: Nbstr) -> Box<str> { take_box(&mut z).unwrap_or_else(|| z.deref().to_owned().into_boxed_str() ) } } impl From<Nbstr> for String { fn from(mut z: Nbstr) -> String { take_box(&mut z) .map(|b| b.into_string() ) .unwrap_or_e...
if z.variant() == BOX { // I asked on #rust, and transmuting from & to mut is apparently undefined behaviour. // Is it really in this case? let s: *mut str = unsafe{ mem::transmute(z.get_slice()) }; // Cannot just assign default; then rust tries to drop the previous value! /...
identifier_body
shared.rs
use std::{mem,slice,ptr, fmt,hash}; use std::borrow::{Borrow,Cow}; /// Protected methods used by the impls below. pub trait Protected { /// create new of this variant with possibly uninitialized data fn new(u8) -> Self; /// store this str, which is either &'static or boxed fn with_pointer(u8, &str) ...
s: &'static str) -> Self { Self::with_pointer(LITERAL, s) } } impl Nbstr { fn try_stack(s: &str) -> Option<Self> {match s.len() as u8 { // Cannot have stack str with length 0, as variant might be NonZero 0 => Some(Self::default()), 1...MAX_STACK => { let mut z = Self:...
rom(
identifier_name
packfile.rs
{ entry.encode_to(&mut buf)?; } // footer buf.extend_from_slice(&sha1::Sha1::digest(&buf[..])); original_buf.unsplit(buf); Ok(()) } } #[derive(Debug)] pub struct Commit<'a> { pub tree: GenericArray<u8, <Sha1 as FixedOutputDirty>::OutputSize>, // [u8; 20],...
} #[derive(Debug)] pub enum TreeItemKind { File, Directory, } impl TreeItemKind { #[must_use] pub const fn mode(&self) -> &'static str { match self { Self::File => "100644", Self::Directory => "40000", } } } #[derive(Debug)] pub struct TreeItem<'a> { pu...
+ " +0000".len() }
random_line_split
packfile.rs
a013f96a3550374e3 | gzip -dc // commit 1068tree 0d586b48bc42e8591773d3d8a7223551c39d453c // parent c2a862612a14346ae95234f26efae1ee69b5b7a9 // author Jordan Doyle <jordan@doyle.la> 1630244577 +0100 // committer Jordan Doyle <jordan@doyle.la> 1630244577 +0100 // gpgsig -----BEGIN PGP SIGNATURE----- ...
for item in items { item.encod
conditional_block
packfile.rs
pub fn encode_to(&self, original_buf: &mut BytesMut) -> Result<(), anyhow::Error> { let mut buf = original_buf.split_off(original_buf.len()); buf.reserve(Self::header_size() + Self::footer_size()); // header buf.extend_from_slice(b"PACK"); // magic header buf.put_u32(2); /...
{ 20 }
identifier_body
packfile.rs
{ entry.encode_to(&mut buf)?; } // footer buf.extend_from_slice(&sha1::Sha1::digest(&buf[..])); original_buf.unsplit(buf); Ok(()) } } #[derive(Debug)] pub struct Commit<'a> { pub tree: GenericArray<u8, <Sha1 as FixedOutputDirty>::OutputSize>, // [u8; 20],...
(&self) -> usize { self.kind.mode().len() + " ".len() + self.name.len() + "\0".len() + self.hash.len() } } #[derive(Debug)] pub enum PackFileEntry<'a> { // jordan@Jordans-MacBook-Pro-2 0d % printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" | cat - f5/473259d9674ed66239766a013f96a3550374e3 | gzip -dc // com...
size
identifier_name
poll.rs
file descriptor is ready. /// /// [`read`]: tcp/struct.TcpStream.html#method.read /// [`register`]: #method.register /// [`reregister`]: #method.reregister /// /// # Examples /// /// A basic example -- establishing a `TcpStream` connection. /// /// ```no_run /// # extern crate mio; /// # extern crate mio_pool; /// # u...
/// # } /// ``` /// /// # Exclusive access /// /// Since this `Poll` implementation is optimized for worker-pool style use-cases, all file /// descriptors are registered using `EPOLL_ONESHOT`. This means that once an event has been issued /// for a given descriptor, not more events will be issued for that descriptor un...
/// # fn main() { /// # try_main().unwrap();
random_line_split
poll.rs
wrapper around `usize`, and is used as an argument to /// [`Poll::register`] and [`Poll::reregister`]. /// /// See [`Poll`] for more documentation on polling. You will likely want to use something like /// [`slab`] for creating and managing these. /// /// [`Poll`]: struct.Poll.html /// [`Poll::register`]: struct.Poll....
{ // events beyond .1 are old return None; }
conditional_block
poll.rs
/// } /// } /// } /// # Ok(()) /// # } /// # /// # fn main() { /// # try_main().unwrap(); /// # } /// ``` /// /// # Exclusive access /// /// Since this `Poll` implementation is optimized for worker-pool style use-cases, all file /// descriptors are registered using `EPOLL_ONESHOT`. This means that o...
EventsIterator
identifier_name
poll.rs
Poll`] for more documentation on polling. You will likely want to use something like /// [`slab`] for creating and managing these. /// /// [`Poll`]: struct.Poll.html /// [`Poll::register`]: struct.Poll.html#method.register /// [`Poll::reregister`]: struct.Poll.html#method.reregister /// [`slab`]: https://crates.io/crat...
{ let at = &mut self.at; if *at >= self.events.current { // events beyond .1 are old return None; } self.events.all.get(*at).map(|e| { *at += 1; Token(e.data() as usize) }) }
identifier_body