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
application.py
from flask import Flask, render_template, jsonify, request, make_response #BSD License import requests #Apache 2.0 #StdLibs import json from os import path import csv ################################################### #Programmato da Alex Prosdocimo e Matteo Mirandola# ###################################...
(): return make_response(render_template("index.html")) @application.route("/getGraph", methods=["POST", "GET"]) def getgraph(): #Metodo POST: responsabile di ottnere i dati in formato json dal server. #Il server si aspetta un campo data che contenga il nome di un file esistente nel server nella c...
index
identifier_name
application.py
from flask import Flask, render_template, jsonify, request, make_response #BSD License import requests #Apache 2.0 #StdLibs import json from os import path import csv ################################################### #Programmato da Alex Prosdocimo e Matteo Mirandola# ###################################...
#Per aggiornare i dataset: #A causa di un errore nella creazione del file riguardante gli iscritti per ogni ateneo da parte del MIUR il file #riguardante gli iscritti per ateneo non sono scaricabili dinamicamente e va sostituito manualmente. #Allo stesso modo, i dati ottenuti tramite l'istat non sono scaricabili di...
if request.method == "POST": if('data' in request.form): if(path.exists("static/jsons/" + request.form['data'] + ".json")): with open("static/jsons/" + request.form['data'] + ".json", "r") as file: jsonStr = file.read() jsonStr = json.loads(js...
identifier_body
application.py
from flask import Flask, render_template, jsonify, request, make_response #BSD License import requests #Apache 2.0 #StdLibs import json from os import path import csv ################################################### #Programmato da Alex Prosdocimo e Matteo Mirandola# ###################################...
else: lavoro[row[1]].append(str(row[8]) + ';' + str(row[10])) for key in lavoro.keys(): tmp = lavoro[key][0] + ';' + lavoro[key][2] tmp2 = lavoro[key][1] + ';' + lavoro[key][3] lavoro[key].clear() lavoro[key].append(tmp) la...
ppend(str(row[10]))
conditional_block
task4-main.py
''' Team Id: HC#145 Author List: Sujan Bag Filename: task4.py Theme: Homecoming (HC) Functions: findhabit(image),findanimal(image),Hpredict_image(image_path,model),Apredict_image(image_path,model),Diff(li1,li2) Global Variables: position=[],hposition=[],aposition=[],name=[],hname=[],aname=[],dicto={},anim...
else: value='F6' cv2.putText(image11,value,(50,30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,0),2) #cv2.imshow('track',image) #cv2.imshow('im',image[120:265,120+u:264+v,:]) #cv2.waitKey(0) #cv2.destroyAllWindows() #print(value,pred) position.append(val...
random_line_split
task4-main.py
''' Team Id: HC#145 Author List: Sujan Bag Filename: task4.py Theme: Homecoming (HC) Functions: findhabit(image),findanimal(image),Hpredict_image(image_path,model),Apredict_image(image_path,model),Diff(li1,li2) Global Variables: position=[],hposition=[],aposition=[],name=[],hname=[],aname=[],dicto={},anim...
''' Function name : Hpredict_image(image_path,model) input : image path and model output : predicted class name index of Habitat image call example : a=Hpredict_image(image_path,model1) ''' def Hpredict_image(image_path,model1): #print("Prediction in progress") image=image_p...
image=Image.fromarray(image,'RGB') index=Apredict_image(image,Amodel1) prediction=Aclass_name[index] return prediction
identifier_body
task4-main.py
''' Team Id: HC#145 Author List: Sujan Bag Filename: task4.py Theme: Homecoming (HC) Functions: findhabit(image),findanimal(image),Hpredict_image(image_path,model),Apredict_image(image_path,model),Diff(li1,li2) Global Variables: position=[],hposition=[],aposition=[],name=[],hname=[],aname=[],dicto={},anim...
else: j=0 while(j<len(animal[i])): habitatloc.append(habit[i][j]) j=j+1 i=i+1 t=0 while(t<len(animal)): for j in range(0,len(animal[t])): animalloc.append(animal[t][j]) t=t+1 dictokey=[] for key in habitatlist: dictokey.append(key) def Diff(li...
j=0 # print('animal greater') while(j<len(habit[i])): habitatloc.append(habit[i][j]) j=j+1 k=0 while(k<(len(animal[i])-len(habit[i]))): habitatloc.append(habit[i][0]) k=k+1 i=i+1
conditional_block
task4-main.py
''' Team Id: HC#145 Author List: Sujan Bag Filename: task4.py Theme: Homecoming (HC) Functions: findhabit(image),findanimal(image),Hpredict_image(image_path,model),Apredict_image(image_path,model),Diff(li1,li2) Global Variables: position=[],hposition=[],aposition=[],name=[],hname=[],aname=[],dicto={},anim...
(li1, li2): return (list(set(li1) - set(li2))) habitat_loc=Diff(dictokey,habitatloc) invalid_habitat=[] for i in range(0,len(habitat_loc)): invalid_habitat.append([habitat_loc[i],habitatlist[habitat_loc[i]]]) valid_habitat=[] for i in range(0,len(habitatloc)): valid_habitat.append([habitatloc[i],habitat...
Diff
identifier_name
lib.rs
//! The crate serves as an bindings to the official (outdated) //! [dota2 webapi](https://dev.dota2.com/forum/dota-2/spectating/replays/webapi/60177-things-you-should-know-before-starting?t=58317) //! The crate has been made so you can call make calls directly and get a result back in a Struct. //! //! Read the full li...
} impl From<serde_json::Error> for Error { fn from(e: serde_json::Error) -> Error { Error::Json(e) } } /// The main `Dota2Api` of you library works by saving states of all the invoked URLs (you only call the one you need) /// language macro for easy implementation in various builder struct /// /// Th...
{ Error::Http(e) }
identifier_body
lib.rs
//! The crate serves as an bindings to the official (outdated) //! [dota2 webapi](https://dev.dota2.com/forum/dota-2/spectating/replays/webapi/60177-things-you-should-know-before-starting?t=58317) //! The crate has been made so you can call make calls directly and get a result back in a Struct. //! //! Read the full li...
self.$builder = $build::build(&*self.key); &mut self.$builder } }; } /// A `get!` macro to get our `get` functions macro_rules! get { ($func: ident, $return_type: ident, $builder: ident, $result: ident) => { pub fn $func(&mut self) -> Result<$return_type, Error> { ...
pub fn $func(&mut self) -> &mut $build {
random_line_split
lib.rs
//! The crate serves as an bindings to the official (outdated) //! [dota2 webapi](https://dev.dota2.com/forum/dota-2/spectating/replays/webapi/60177-things-you-should-know-before-starting?t=58317) //! The crate has been made so you can call make calls directly and get a result back in a Struct. //! //! Read the full li...
(&mut self, param_value: usize) -> &mut Self { self.url.push_str(&*format!("match_id={}&", param_value)); self } } builder!( GetTopLiveGameBuilder, "http://api.steampowered.com/IDOTA2Match_570/GetTopLiveGame/v1/?key={}&" ); impl GetTopLiveGameBuilder { language!(); /// Which partne...
match_id
identifier_name
lib.rs
//! The crate serves as an bindings to the official (outdated) //! [dota2 webapi](https://dev.dota2.com/forum/dota-2/spectating/replays/webapi/60177-things-you-should-know-before-starting?t=58317) //! The crate has been made so you can call make calls directly and get a result back in a Struct. //! //! Read the full li...
let _ = response.read_to_string(&mut temp); Ok(temp) } } //============================================================================== //IEconDOTA2_570 //============================================================================== builder!( GetHeroesBuilder, "http://api.steampowered....
{ return Err(Error::Forbidden( "Access is denied. Retrying will not help. Please check your API key.", )); }
conditional_block
lib.rs
//! Error handling layer for axum that supports extractors and async functions. //! //! This crate provides [`HandleErrorLayer`] which works similarly to //! [`axum::error_handling::HandleErrorLayer`] except that it supports //! extractors and async functions: //! //! ```rust //! use axum::{ //! Router, //! Box...
clippy::suboptimal_flops, clippy::lossy_float_literal, clippy::rest_pat_in_fully_bound_structs, clippy::fn_params_excessive_bools, clippy::exit, clippy::inefficient_to_string, clippy::linkedlist, clippy::macro_use_imports, clippy::option_option, clippy::verbose_file_reads, cl...
clippy::imprecise_flops,
random_line_split
lib.rs
//! Error handling layer for axum that supports extractors and async functions. //! //! This crate provides [`HandleErrorLayer`] which works similarly to //! [`axum::error_handling::HandleErrorLayer`] except that it supports //! extractors and async functions: //! //! ```rust //! use axum::{ //! Router, //! Box...
(&self) -> Self { Self { f: self.f.clone(), _extractor: PhantomData, } } } impl<F, E> fmt::Debug for HandleErrorLayer<F, E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HandleErrorLayer") .field("f", &format_args!("{}",...
clone
identifier_name
manifest.rs
//! Reproducible package manifest data. pub use self::sources::Source; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use toml::de::Error as DeserializeError; use self::outputs::Outpu...
<T, U>(name: T, version: T, default_output_hash: T, refs: U) -> ManifestBuilder where T: AsRef<str>, U: IntoIterator<Item = OutputId>, { ManifestBuilder::new(name, version, default_output_hash, refs) } /// Computes the content-addressable ID of this manifest. /// /// # E...
build
identifier_name
manifest.rs
//! Reproducible package manifest data. pub use self::sources::Source; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use toml::de::Error as DeserializeError; use self::outputs::Outpu...
} /// Builder for creating new `Manifest`s. #[derive(Clone, Debug)] pub struct ManifestBuilder { package: Result<Package, ()>, env: BTreeMap<String, String>, sources: Sources, outputs: Result<Outputs, ()>, } impl ManifestBuilder { /// Creates a `Manifest` with the given name, version, default out...
{ toml::from_str(s) }
identifier_body
manifest.rs
//! Reproducible package manifest data. pub use self::sources::Source; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use toml::de::Error as DeserializeError; use self::outputs::Outpu...
name: Name, version: String, dependencies: BTreeSet<ManifestId>, build_dependencies: BTreeSet<ManifestId>, dev_dependencies: BTreeSet<ManifestId>, } /// A reproducible package manifest. #[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)] pub struct Manifest { package: Package, ...
struct Package {
random_line_split
manifest.rs
//! Reproducible package manifest data. pub use self::sources::Source; use std::collections::{BTreeMap, BTreeSet}; use std::fmt::{Display, Error as FmtError, Formatter, Result as FmtResult}; use std::str::FromStr; use serde::{Deserialize, Serialize}; use toml::de::Error as DeserializeError; use self::outputs::Outpu...
self } /// Adds a build dependency on `id`. /// /// # Laziness /// /// This kind of dependency is only downloaded when the package is being built from source. /// Otherwise, the dependency is ignored. Artifacts from build dependencies cannot be linked to /// at runtime. pub...
{ p.dependencies.insert(id); }
conditional_block
bot.go
package rolecommands import ( "context" "database/sql" "github.com/mrbentarikau/pagst/analytics" "github.com/mrbentarikau/pagst/bot/eventsystem" "github.com/mrbentarikau/pagst/commands" "github.com/mrbentarikau/pagst/common" "github.com/mrbentarikau/pagst/common/pubsub" "github.com/mrbentarikau/pagst/common/s...
return err.Error(), nil } if code, msg := common.DiscordError(err); code != 0 { if code == discordgo.ErrCodeMissingPermissions { return "The bot is below the role, contact the server admin", err } else if code == discordgo.ErrCodeMissingAccess { return "Bot does not have enough permissions to assign you th...
return roleError.PrettyError(guild.Roles), nil }
conditional_block
bot.go
package rolecommands import ( "context" "database/sql" "github.com/mrbentarikau/pagst/analytics" "github.com/mrbentarikau/pagst/bot/eventsystem" "github.com/mrbentarikau/pagst/commands" "github.com/mrbentarikau/pagst/common" "github.com/mrbentarikau/pagst/common/pubsub" "github.com/mrbentarikau/pagst/common/s...
rsed *dcmd.Data) (interface{}, error) { if parsed.Args[0].Value == nil { return CmdFuncListCommands(parsed) } given, err := FindToggleRole(parsed.Context(), parsed.GuildData.MS, parsed.Args[0].Str()) if err != nil { if err == sql.ErrNoRows { resp, err := CmdFuncListCommands(parsed) if v, ok := resp.(stri...
FuncRole(pa
identifier_name
bot.go
package rolecommands import ( "context" "database/sql" "github.com/mrbentarikau/pagst/analytics" "github.com/mrbentarikau/pagst/bot/eventsystem" "github.com/mrbentarikau/pagst/commands" "github.com/mrbentarikau/pagst/common" "github.com/mrbentarikau/pagst/common/pubsub" "github.com/mrbentarikau/pagst/common/s...
{Name: "skip", Help: "Number of roles to skip", Default: 0, Type: dcmd.Int}, }, RunFunc: cmdFuncRoleMenuCreate, } cmdRemoveRoleMenu := &commands.YAGCommand{ Name: "Remove", CmdCategory: categoryRoleMenu, Aliases: []string{"rm"}, Description: "Removes a roleme...
ArgSwitches: []*dcmd.ArgDef{ {Name: "m", Help: "Message ID", Type: dcmd.BigInt}, {Name: "nodm", Help: "Disable DM"}, {Name: "rr", Help: "Remove role on reaction removed"},
random_line_split
bot.go
package rolecommands import ( "context" "database/sql" "github.com/mrbentarikau/pagst/analytics" "github.com/mrbentarikau/pagst/bot/eventsystem" "github.com/mrbentarikau/pagst/commands" "github.com/mrbentarikau/pagst/common" "github.com/mrbentarikau/pagst/common/pubsub" "github.com/mrbentarikau/pagst/common/s...
ype CacheKey struct { GuildID int64 MessageID int64 } var menuCache = common.CacheSet.RegisterSlot("rolecommands_menus", nil, int64(0)) func GetRolemenuCached(ctx context.Context, gs *dstate.GuildSet, messageID int64) (*models.RoleMenu, error) { result, err := menuCache.GetCustomFetch(CacheKey{ GuildID: gs.I...
dataCast := data.(*ScheduledMemberRoleRemoveData) err = common.BotSession.GuildMemberRoleRemove(dataCast.GuildID, dataCast.UserID, dataCast.RoleID) if err != nil { return scheduledevents2.CheckDiscordErrRetry(err), err } // remove the reaction menus, err := models.RoleMenus( qm.Where("role_group_id = ? AND gu...
identifier_body
lib.rs
use std::{ alloc, alloc::Layout, fmt, fmt::Debug, iter::FromIterator, mem, ops::{Index, IndexMut}, ptr, ptr::NonNull, }; #[cfg(test)] pub mod test_box; #[cfg(test)] pub mod test_i32; #[cfg(test)] pub mod test_zst; pub mod iterator; use iterator::{BorrowedVectorIterator, BorrowedVectorIteratorMut, VectorIte...
///Gets a mutable reference to the element at index's position. /// /// Returns `None` if index is greater than the length of the vector. Has complexity O(1). pub fn get_mut(&mut self, idx: usize) -> Option<&mut T> { if idx >= self.size { return None; } //Safety: Index is already checked. unsafe { self...
{ if idx >= self.size { return None; } //Safety: Index is already checked. unsafe { self.as_ptr()?.add(idx).as_ref() } }
identifier_body
lib.rs
use std::{ alloc, alloc::Layout, fmt, fmt::Debug, iter::FromIterator, mem, ops::{Index, IndexMut}, ptr, ptr::NonNull, }; #[cfg(test)] pub mod test_box; #[cfg(test)] pub mod test_i32; #[cfg(test)] pub mod test_zst; pub mod iterator; use iterator::{BorrowedVectorIterator, BorrowedVectorIteratorMut, VectorIte...
(&mut self, idx: usize, elem: T) { if idx == self.size { return self.push(elem); } if self.size == self.capacity { if self.capacity == usize::MAX { panic!("Overflow"); } self.reserve( (self.capacity as f64 * GROWTH_RATE) .ceil() .min(usize::MAX as f64) as usize, ); } else if se...
insert
identifier_name
lib.rs
use std::{ alloc, alloc::Layout, fmt, fmt::Debug, iter::FromIterator, mem, ops::{Index, IndexMut}, ptr, ptr::NonNull, }; #[cfg(test)] pub mod test_box; #[cfg(test)] pub mod test_i32; #[cfg(test)] pub mod test_zst; pub mod iterator; use iterator::{BorrowedVectorIterator, BorrowedVectorIteratorMut, VectorIte...
} ///Removes any element which does not fulfill the requirement passed. /// It is recommended to use this over `remove` in a loop due to time /// complexity and fewer moves. /// /// Has complexity O(n) pub fn retain(&mut self, f: fn(&T) -> bool) { if mem::size_of::<T>() == 0 { for i in (0..self.size).rev()...
self.data.map(|p| p.as_ptr()) }
conditional_block
lib.rs
use std::{ alloc, alloc::Layout, fmt, fmt::Debug, iter::FromIterator, mem, ops::{Index, IndexMut}, ptr, ptr::NonNull, }; #[cfg(test)] pub mod test_box; #[cfg(test)] pub mod test_i32; #[cfg(test)] pub mod test_zst; pub mod iterator; use iterator::{BorrowedVectorIterator, BorrowedVectorIteratorMut, VectorIte...
self.as_ptr_mut() .expect("Above assertion failed?") .add(self.size) .write(elem) }; self.size += 1; } ///Gets a reference to the element at index's position. /// /// Returns `None` if index is greater than the length of the vector. Has complexity O(1). pub fn get(&self, idx: usize) -> Option<&...
random_line_split
data.ts
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { Http } from '@angular/http'; @Injectable() export class Data { private storage = new Storage(); private http: Http; private employees; // hardcoded data // private defaultEmployees = [ // { // "id": 1, // "firs...
cloneObject(obj) { var copy; // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { c...
{ return this.employees.filter(employee => { // search fullName and filter jobRole let retVal = true; let employeeFullName = employee.first_name + employee.last_name; if(fullName){ if(employeeFullName.toLowerCase().indexOf(fullName.toLowerCase()) == -1){ retVal = false; } } if(jo...
identifier_body
data.ts
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { Http } from '@angular/http'; @Injectable() export class Data { private storage = new Storage(); private http: Http; private employees; // hardcoded data // private defaultEmployees = [ // { // "id": 1, // "firs...
(fullName, jobRole){ return this.employees.filter(employee => { // search fullName and filter jobRole let retVal = true; let employeeFullName = employee.first_name + employee.last_name; if(fullName){ if(employeeFullName.toLowerCase().indexOf(fullName.toLowerCase()) == -1){ retVal = false; ...
filterEmployees
identifier_name
data.ts
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { Http } from '@angular/http'; @Injectable() export class Data { private storage = new Storage(); private http: Http; private employees; // hardcoded data // private defaultEmployees = [ // { // "id": 1, // "firs...
} else { resolve({ success: false, errorMessage: "Inloggen mislukt. Geen gegevens."}); } }, error => { resolve({ success: false, errorMessage: "Inloggen mislukt. " + error }); }); }); } getEmployees() { // get Employees from local storage. Load from server if there are none return new P...
{ resolve({ success: false, errorMessage: "Inloggen mislukt. " + data["errorMessage"] }); }
conditional_block
data.ts
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; import { Http } from '@angular/http'; @Injectable() export class Data { private storage = new Storage(); private http: Http; private employees; // hardcoded data // private defaultEmployees = [ // { // "id": 1, // "firs...
if(fullName){ if(employeeFullName.toLowerCase().indexOf(fullName.toLowerCase()) == -1){ retVal = false; } } if(jobRole){ if(employee.job_role.toLowerCase().indexOf(jobRole.toLowerCase()) == -1 ){ retVal = false; } else if(fullName && !retVal){ retVal = false; } else { ...
filterEmployees(fullName, jobRole){ return this.employees.filter(employee => { // search fullName and filter jobRole let retVal = true; let employeeFullName = employee.first_name + employee.last_name;
random_line_split
leap_tracker.py
#!/usr/bin/env python # coding:utf8 """ @package leap_tracker @file leap_tracker.py @brief LEAP Motion for ROS. This package provides a tracking server for a LEAP Motion device. It constantly listens to the controller for new frames and processes the hands and fingers tracking data. It publishes ROS's own Joint...
t = self.t # Cyclic functions for orientation and position values delta = math.sin(t) * 1000 alpha = math.cos(t) * math.pi * 2 # Default values x = 0 y = 0 z = 0 pitch = 0 yaw = 0 roll = 0 # assig...
"""
random_line_split
leap_tracker.py
#!/usr/bin/env python # coding:utf8 """ @package leap_tracker @file leap_tracker.py @brief LEAP Motion for ROS. This package provides a tracking server for a LEAP Motion device. It constantly listens to the controller for new frames and processes the hands and fingers tracking data. It publishes ROS's own Joint...
: """ Fixes libraries path to properly import the LEAP Motion controller and its Python wrapper """ import sys, os, struct bit_size = struct.calcsize("P") * 8 ARCH = '/x86' if bit_size == 32 else '/x64' LEAP_PATH = os.path.dirname(__file__) + '/leap' sys.path.extend([LEAP_PATH, LEA...
x_import_path()
identifier_name
leap_tracker.py
#!/usr/bin/env python # coding:utf8 """ @package leap_tracker @file leap_tracker.py @brief LEAP Motion for ROS. This package provides a tracking server for a LEAP Motion device. It constantly listens to the controller for new frames and processes the hands and fingers tracking data. It publishes ROS's own Joint...
if __name__ == '__main__': main()
ap_server = LeapServer() controller = Leap.Controller() # Have the sample listener receive events from the controller controller.add_listener(leap_server) # Keep this process running until quit from client or Ctrl^C LOG.v("Press ^C to quit...", "main") try: # Start communication ...
identifier_body
leap_tracker.py
#!/usr/bin/env python # coding:utf8 """ @package leap_tracker @file leap_tracker.py @brief LEAP Motion for ROS. This package provides a tracking server for a LEAP Motion device. It constantly listens to the controller for new frames and processes the hands and fingers tracking data. It publishes ROS's own Joint...
return ((x, y, z), (pitch, yaw, roll)) def main(): # Init the server and controller leap_server = LeapServer() controller = Leap.Controller() # Have the sample listener receive events from the controller controller.add_listener(leap_server) # Keep this process runn...
lf.t = 0.0
conditional_block
en.ts
export const en = { // Splashscreen "splash-loading": "", // Nav Tabs "Supernodes": "Supernodes", "rewards-tab": "Rewards", "analytics-tab": "Analytics", "staking-tab": "Staking", "settings-tab": "Settings", // About Page "about-title": "About", "version-text": "Version", ...
"node-of-votes-text": "of Votes", "node-payout-text": "Payout", "node-location-text": "Location", "node-reward-text": "Daily Reward", "node-return-text": "Annual Return", "node-about-text": "About", "show-more-text": "...show more", "show-less-text": "...show less", // Rewards Chart...
"node-state-text": "State",
random_line_split
practice.js
function sameFrequency(num1, num2) { // good luck. Add any arguments you deem necessary. let numOne = num1.toString(); let numTwo = num2.toString(); console.log(numOne, numTwo); if (numOne.length !== numTwo.length) return false; let numOneMap = {}; for (let i = 0; i < numOne.length; i++) { let letter...
//FIBONACCI SOLUTION function fib(n) { if (n <= 2) return 1; return fib(n - 1) + fib(n - 2); } // REVERSE function reverse(str) { // add whatever parameters you deem necessary - good luck! let lastChar = str.charAt(str.length - 1); let withoutLastChar = str.substring(0, str.length - 1); console.log(lastCha...
{ if (x === 0) return 0; return x + recursiveRange(x - 1); }
identifier_body
practice.js
function sameFrequency(num1, num2) { // good luck. Add any arguments you deem necessary. let numOne = num1.toString(); let numTwo = num2.toString(); console.log(numOne, numTwo); if (numOne.length !== numTwo.length) return false; let numOneMap = {}; for (let i = 0; i < numOne.length; i++) { let letter...
////PRODUCT OF ARRAY SOLUTION function productOfArray(arr) { if (arr.length === 0) { return 1; } return arr[0] * productOfArray(arr.slice(1)); } //RECURSIVE RANGE SOLUTION function recursiveRange(x) { if (x === 0) return 0; return x + recursiveRange(x - 1); } //FIBONACCI SOLUTION function fib(n) { if (n...
function factorial(x) { if (x < 0) return 0; if (x <= 1) return 1; return x * factorial(x - 1); }
random_line_split
practice.js
function sameFrequency(num1, num2) { // good luck. Add any arguments you deem necessary. let numOne = num1.toString(); let numTwo = num2.toString(); console.log(numOne, numTwo); if (numOne.length !== numTwo.length) return false; let numOneMap = {}; for (let i = 0; i < numOne.length; i++) { let letter...
return arr[0] * productOfArray(arr.slice(1)); } //RECURSIVE RANGE SOLUTION function recursiveRange(x) { if (x === 0) return 0; return x + recursiveRange(x - 1); } //FIBONACCI SOLUTION function fib(n) { if (n <= 2) return 1; return fib(n - 1) + fib(n - 2); } // REVERSE function reverse(str) { // add whateve...
{ return 1; }
conditional_block
practice.js
function sameFrequency(num1, num2) { // good luck. Add any arguments you deem necessary. let numOne = num1.toString(); let numTwo = num2.toString(); console.log(numOne, numTwo); if (numOne.length !== numTwo.length) return false; let numOneMap = {}; for (let i = 0; i < numOne.length; i++) { let letter...
(arr) { let foundSmaller; for (let i = 0; i < arr.length; i++) { let lowest = i; for (let j = i + 1; j < arr.length; j++) { if (arr[lowest] > arr[j]) { lowest = j; foundSmaller = true; } } if (foundSmaller) { let temp = arr[i]; arr[i] = arr[lowest]; arr[...
selectionSort
identifier_name
all_phases.rs
use crate::ast2ir; use crate::emit; use crate::err::NiceError; use crate::ir2ast; use crate::opt; use crate::opt_ast; use crate::parse; use crate::swc_globals; macro_rules! case { ( $name:ident, $string:expr, @ $expected:literal ) => { #[test] fn $name() -> Result<(), NiceError> { swc_g...
}; "###); case!( snudown_js_like2, r#" var o, c = {}, s = {}; for (o in c) c.hasOwnProperty(o) && (s[o] = c[o]); var u = console.log.bind(console), b = console.warn.bind(console); for (o in s) s.hasOwnProperty(o) && (c[o] = s[o]); s = null; var k, v, d, h = 0, w = !1; k = c.buffer ?...
return z + 2;
random_line_split
build_assets.py
#!/usr/bin/python # Copyright 2014 Google 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 # # Unless required by a...
# If not found, just assume it's in the PATH. return name # Location of FlatBuffers compiler. FLATC = find_executable(FLATC_EXECUTABLE_NAME, FLATBUFFERS_PATHS) # Location of webp compression tool. CWEBP = find_executable(CWEBP_EXECUTABLE_NAME, CWEBP_PATHS) class BuildError(Exception): """Error indicating th...
return full_path
conditional_block
build_assets.py
#!/usr/bin/python # Copyright 2014 Google 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 # # Unless required by a...
# A list of json files and their schemas that will be converted to binary files # by the flatbuffer compiler. FLATBUFFERS_CONVERSION_DATA = [ FlatbuffersConversionData( schema=os.path.join(SCHEMA_PATH, 'config.fbs'), input_files=[os.path.join(RAW_ASSETS_PATH, 'config.json')], output_path=ASS...
random_line_split
build_assets.py
#!/usr/bin/python # Copyright 2014 Google 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 # # Unless required by a...
# A list of json files and their schemas that will be converted to binary files # by the flatbuffer compiler. FLATBUFFERS_CONVERSION_DATA = [ FlatbuffersConversionData( schema=os.path.join(SCHEMA_PATH, 'config.fbs'), input_files=[os.path.join(RAW_ASSETS_PATH, 'config.json')], output_path=...
"""Holds data needed to convert a set of json files to flatbuffer binaries. Attributes: schema: The path to the flatbuffer schema file. input_files: A list of input files to convert. output_path: The path to the output directory where the converted files will be placed. """ def __init__(self...
identifier_body
build_assets.py
#!/usr/bin/python # Copyright 2014 Google 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 # # Unless required by a...
(argv): """Builds or cleans the assets needed for the game. To build all assets, either call this script without any arguments. Or alternatively, call it with the argument 'all'. To just convert the flatbuffer json files, call it with 'flatbuffers'. Likewise to convert the png files to webp files, call it wi...
main
identifier_name
bcfw_diffrac.py
""" Implements BCFW for DIFFRAC objectives. """ import numpy as np import os from tqdm import tqdm from numpy.linalg import norm as matrix_norm import time def
(feats, block_idx, memory_mode, bias_value=-1.0): """Get feature for a given block.""" if memory_mode == 'RAM': feat = feats[block_idx] elif memory_mode == 'disk': feat = np.load(feats[block_idx]) else: raise ValueError( 'Memory mode {} is not supported.'.format(memor...
get_feat_block
identifier_name
bcfw_diffrac.py
""" Implements BCFW for DIFFRAC objectives. """ import numpy as np import os from tqdm import tqdm from numpy.linalg import norm as matrix_norm import time def get_feat_block(feats, block_idx, memory_mode, bias_value=-1.0): """Get feature for a given block.""" if memory_mode == 'RAM': feat = feats[bl...
display_information(t, n_iterations, gaps, eval_metric, objective_value, verbose) return asgn, weights
x = get_feat_block( feats, block_idx, memory_mode, bias_value=bias_value) gaps[block_idx] = compute_gap(x, asgn[block_idx], weights, n_feats, cstrs[block_idx], cstrs_solver)
conditional_block
bcfw_diffrac.py
""" Implements BCFW for DIFFRAC objectives. """ import numpy as np import os from tqdm import tqdm from numpy.linalg import norm as matrix_norm import time def get_feat_block(feats, block_idx, memory_mode, bias_value=-1.0): """Get feature for a given block.""" if memory_mode == 'RAM': feat = feats[bl...
def save_xw_block(path_save_asgn, block_idx, x, weights, t): np.save( os.path.join(path_save_asgn, 'xw_{0}_{1:05d}.npy'.format(block_idx, t)), np.dot(x, weights)) def save_gt_block(path_save_asgn, block_idx, gts): np.save( ...
np.save( os.path.join(path_save_asgn, '{0}_{1:05d}.npy'.format(block_idx, t)), asgn[block_idx])
identifier_body
bcfw_diffrac.py
""" Implements BCFW for DIFFRAC objectives. """ import numpy as np import os from tqdm import tqdm from numpy.linalg import norm as matrix_norm import time def get_feat_block(feats, block_idx, memory_mode, bias_value=-1.0): """Get feature for a given block.""" if memory_mode == 'RAM': feat = feats[bl...
d, _ = np.shape(get_p_block(p_matrix, 0, memory_mode)) _, k = np.shape(asgn[0]) weights = np.zeros([d, k]) print('Computing weights from scratch...') for i in tqdm(range(len(p_matrix))): weights += np.dot(get_p_block(p_matrix, i, memory_mode), asgn[i]) return weights def compute_obj...
random_line_split
main.go
package main import ( "bufio" "bytes" "fmt" "io/ioutil" "net/http" "os" "os/exec" "strconv" "strings" "github.com/OpenPeeDeeP/xdg" "github.com/hoisie/mustache" "github.com/inconshreveable/log15" "gopkg.in/yaml.v2" ) type Configuration struct { Scheme string `yaml:"scheme"` SchemeRepositor...
if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("unexpected response (status=%d body=%s)", res.StatusCode, string(body)) } return body, nil } func loadYAMLFile(url string, dest interface{}) error { body, err := loadFile(url) if err != nil { return wrap(err, "loading file") } err = yaml.Unmar...
{ return nil, wrap(err, "reading response") }
conditional_block
main.go
package main import ( "bufio" "bytes" "fmt" "io/ioutil" "net/http" "os" "os/exec" "strconv" "strings" "github.com/OpenPeeDeeP/xdg" "github.com/hoisie/mustache" "github.com/inconshreveable/log15" "gopkg.in/yaml.v2" ) type Configuration struct { Scheme string `yaml:"scheme"` SchemeRepositor...
Author string `yaml:"author"` Base00 string `yaml:"base00"` Base01 string `yaml:"base01"` Base02 string `yaml:"base02"` Base03 string `yaml:"base03"` Base04 string `yaml:"base04"` Base05 string `yaml:"base05"` Base06 string `yaml:"base06"` Base07 string `yaml:"base07"` Base08 string `yaml:"base08"` Base09 st...
type ColorScheme struct { Name string `yaml:"scheme"`
random_line_split
main.go
package main import ( "bufio" "bytes" "fmt" "io/ioutil" "net/http" "os" "os/exec" "strconv" "strings" "github.com/OpenPeeDeeP/xdg" "github.com/hoisie/mustache" "github.com/inconshreveable/log15" "gopkg.in/yaml.v2" ) type Configuration struct { Scheme string `yaml:"scheme"` SchemeRepositor...
func loadScheme(log log15.Logger, config Configuration) (ColorScheme, error) { var scheme ColorScheme if len(config.SchemeRepositoryURL) == 0 { log.Debug("retrieving schemes list", "url", config.SchemesListURL) var schemes map[string]string err := loadYAMLFile(config.SchemesListURL, &schemes) if err != nil...
{ var config Configuration // Set the defaults here so they can be omitted from the actual // configuration. config.SchemesListURL = githubFileURL("chriskempson", "base16-schemes-source", "list.yaml") config.TemplatesListURL = githubFileURL("chriskempson", "base16-templates-source", "list.yaml") raw, err := iou...
identifier_body
main.go
package main import ( "bufio" "bytes" "fmt" "io/ioutil" "net/http" "os" "os/exec" "strconv" "strings" "github.com/OpenPeeDeeP/xdg" "github.com/hoisie/mustache" "github.com/inconshreveable/log15" "gopkg.in/yaml.v2" ) type Configuration struct { Scheme string `yaml:"scheme"` SchemeRepositor...
(user, repository, file string) string { return fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/master/%s", user, repository, file) } func expandPath(path string) string { if len(path) != 0 && path[0] == '~' { path = "$HOME" + path[1:] } return os.Expand(path, os.Getenv) }
githubFileURL
identifier_name
storage.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::*; use rd_agent_intf::{HashdKnobs, HASHD_BENCH_SVC_NAME, ROOT_SLICE}; use std::collections::{BTreeMap, VecDeque}; #[derive(Clone)] pub struct StorageJob { pub apply: bool, pub commit: bool, pub loops: u32, pub rps_max: Option<u32>, pub ...
<'a>( &self, out: &mut Box<dyn Write + 'a>, rec: &StorageRecord, res: &StorageResult, ) { write!( out, "Memory offloading: factor={:.3}@{} ", res.mem_offload_factor, rec.mem.profile ) .unwrap(); if self.loops > 1 { ...
format_mem_summary
identifier_name
storage.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::*; use rd_agent_intf::{HashdKnobs, HASHD_BENCH_SVC_NAME, ROOT_SLICE}; use std::collections::{BTreeMap, VecDeque}; #[derive(Clone)] pub struct StorageJob { pub apply: bool, pub commit: bool, pub loops: u32, pub rps_max: Option<u32>, pub ...
continue 'outer; } else { continue 'inner; } } else { self.prev_mem_avail = 0; self.first_try = false; } final_mem_probe_periods.push((self.mem...
random_line_split
storage.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::*; use rd_agent_intf::{HashdKnobs, HASHD_BENCH_SVC_NAME, ROOT_SLICE}; use std::collections::{BTreeMap, VecDeque}; #[derive(Clone)] pub struct StorageJob { pub apply: bool, pub commit: bool, pub loops: u32, pub rps_max: Option<u32>, pub ...
fn run(&mut self, rctx: &mut RunCtx) -> Result<serde_json::Value> { rctx.set_prep_testfiles() .disable_zswap() .start_agent(vec![])?; // Depending on mem-profile, we might be using a large balloon which // can push down available memory below workload's memory.low ...
{ HASHD_SYSREQS.clone() }
identifier_body
storage.rs
// Copyright (c) Facebook, Inc. and its affiliates. use super::*; use rd_agent_intf::{HashdKnobs, HASHD_BENCH_SVC_NAME, ROOT_SLICE}; use std::collections::{BTreeMap, VecDeque}; #[derive(Clone)] pub struct StorageJob { pub apply: bool, pub commit: bool, pub loops: u32, pub rps_max: Option<u32>, pub ...
final_mem_probe_periods.push((self.mem_probe_at, unix_now())); mem_usages.push(self.mem_usage as f64); mem_sizes.push(mem_size as f64); info!( "storage: Supportable memory footprint {}", format_size(mem_size) ...
{ self.prev_mem_avail = 0; self.first_try = false; }
conditional_block
phrases_or_entities_over_time_first.py
""" This module is used to visualize the monthly doc frequencies (no. of docs in which a phrase is present per month) and phrase frequencies (no. of times a phrase is present per month) of noun phrase(s) chosen by the user in a Dash user interface. A Solr query is made for the query/queries, results are aggregated mont...
@app.callback( Output('output1', 'children'), [Input('type_of_term', 'value'), Input('time_period', 'value'), Input('submit-button', 'n_clicks')], [State('npinput1-state', 'value')]) def create_graph(termtype, timeperiod, n_clicks, input_box): """ Wrapped function which takes user input in a t...
""" Sets input placeholder based on the radio buttons selected""" placeholder = 'E.g. search: "machine learning, model validation"' if termtype == 'Noun phrases'\ else 'E.g. search: "machine learning, model validation": each search term will automatically be converted to http://en.wikipedia.org/wiki/<se...
identifier_body
phrases_or_entities_over_time_first.py
""" This module is used to visualize the monthly doc frequencies (no. of docs in which a phrase is present per month) and phrase frequencies (no. of times a phrase is present per month) of noun phrase(s) chosen by the user in a Dash user interface. A Solr query is made for the query/queries, results are aggregated mont...
(termtype, timeperiod, n_clicks, input_box): """ Wrapped function which takes user input in a text box, and 2 radio buttons, returns the appropriate graph if the query produces a hit in Solr, returns an error message otherwise. ARGUMENTS: n_clicks: a parameter of the HTML button which indicates it has ...
create_graph
identifier_name
phrases_or_entities_over_time_first.py
""" This module is used to visualize the monthly doc frequencies (no. of docs in which a phrase is present per month) and phrase frequencies (no. of times a phrase is present per month) of noun phrase(s) chosen by the user in a Dash user interface. A Solr query is made for the query/queries, results are aggregated mont...
# Add the default Dash CSS, and some custom (very simple) CSS to remove the undo button # app.css.append_css({'external_url': 'https://www.jsdelivr.com/package/npm/normalize.css'}) #app.css.append_css({'external_url': 'https://unpkg.com/sakura.css/css/sakura.css'}) app.css.append_css({'external_url': 'https://codepen....
style={'color': colours['text']} ) app = dash.Dash(__name__)
random_line_split
phrases_or_entities_over_time_first.py
""" This module is used to visualize the monthly doc frequencies (no. of docs in which a phrase is present per month) and phrase frequencies (no. of times a phrase is present per month) of noun phrase(s) chosen by the user in a Dash user interface. A Solr query is made for the query/queries, results are aggregated mont...
if termtype == 'Entity mentions' and timeperiod == 'Yearly': return emvy.show_graph_unique_not_callback(n_clicks, input_box) if termtype == 'Clusters': # !!! DO NOT modify global variables phrases_df_copy = phrases_df.copy() # Add a new column which is 1 only for the cluster in ...
return npvy.show_graph_unique_not_callback(n_clicks, input_box)
conditional_block
categorical.rs
//! # One-hot Encoding For [RealNumber](../../math/num/trait.RealNumber.html) Matricies //! Transform a data [Matrix](../../linalg/trait.BaseMatrix.html) by replacing all categorical variables with their one-hot equivalents //! //! Internally OneHotEncoder treats every categorical column as a series and transforms it u...
{ category_mappers: Vec<CategoryMapper<CategoricalFloat>>, col_idx_categorical: Vec<usize>, } impl OneHotEncoder { /// Create an encoder instance with categories infered from data matrix pub fn fit<T, M>(data: &M, params: OneHotEncoderParams) -> Result<OneHotEncoder, Failed> where T: Categ...
OneHotEncoder
identifier_name
categorical.rs
//! # One-hot Encoding For [RealNumber](../../math/num/trait.RealNumber.html) Matricies //! Transform a data [Matrix](../../linalg/trait.BaseMatrix.html) by replacing all categorical variables with their one-hot equivalents //! //! Internally OneHotEncoder treats every categorical column as a series and transforms it u...
let repeats = cat_idx.scan(0, |a, v| { let im = v + 1 - *a; *a = v; Some(im) }); // Calculate the offset to parameter idx due to newly intorduced one-hot vectors let offset_ = cat_sizes.iter().scan(0, |a, &v| { *a = *a + v - 1; Some(*a) }); let offset = (...
let cat_idx = cat_idxs.iter().copied().chain((num_params..).take(1)); // Offset is constant between two categorical values, here we calculate the number of steps // that remain constant
random_line_split
categorical.rs
//! # One-hot Encoding For [RealNumber](../../math/num/trait.RealNumber.html) Matricies //! Transform a data [Matrix](../../linalg/trait.BaseMatrix.html) by replacing all categorical variables with their one-hot equivalents //! //! Internally OneHotEncoder treats every categorical column as a series and transforms it u...
} /// Calculate the offset to parameters to due introduction of one-hot encoding fn find_new_idxs(num_params: usize, cat_sizes: &[usize], cat_idxs: &[usize]) -> Vec<usize> { // This functions uses iterators and returns a vector. // In case we get a huge amount of paramenters this might be a problem // tod...
{ Self { col_idx_categorical: Some(categorical_params.to_vec()), infer_categorical: false, } }
identifier_body
view.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{app::App, geometry::Size}; use failure::Error; use fidl::endpoints::{create_endpoints, create_proxy, ServerEnd}; use fidl_fuchsia_ui_gfx as gfx...
else { self.assistant.handle_message(msg); } } }
{ match view_msg { ViewMessages::Update => { self.update(); } } }
conditional_block
view.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{app::App, geometry::Size}; use failure::Error; use fidl::endpoints::{create_endpoints, create_proxy, ServerEnd}; use fidl_fuchsia_ui_gfx as gfx...
fn present(&self) { fasync::spawn_local( self.session .lock() .present(0) .map_ok(|_| ()) .unwrap_or_else(|e| panic!("present error: {:?}", e)), ); } fn handle_properties_changed(&mut self, properties: &fidl_fuchs...
{ events.iter().for_each(|event| match event { fidl_fuchsia_ui_scenic::Event::Gfx(gfx::Event::Metrics(event)) => { self.metrics = Size::new(event.metrics.scale_x, event.metrics.scale_y); self.logical_size = Size::new( self.physical_size.width * sel...
identifier_body
view.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{app::App, geometry::Size}; use failure::Error; use fidl::endpoints::{create_endpoints, create_proxy, ServerEnd}; use fidl_fuchsia_ui_gfx as gfx...
( key: ViewKey, session_listener_request: ServerEnd<SessionListenerMarker>, ) -> Result<(), Error> { fasync::spawn_local( session_listener_request .into_stream()? .map_ok(move |request| match request { SessionListenerRequest::On...
setup_session_listener
identifier_name
view.rs
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::{app::App, geometry::Size}; use failure::Error; use fidl::endpoints::{create_endpoints, create_proxy, ServerEnd}; use fidl_fuchsia_ui_gfx as gfx...
view_listener, theirs, None, )?; let (session_listener, session_listener_request) = create_endpoints()?; let (session_proxy, session_request) = create_proxy()?; app.scenic.create_session(session_request, Some(session_listener))?; let session =...
view_token.value,
random_line_split
main.rs
#[macro_use] extern crate log; use std::sync::Arc; use amethyst::{ assets::{AssetStorage, Loader, PrefabLoader, PrefabLoaderSystem, Processor, RonFormat}, core::{ bundle::SystemBundle, math::Vector3, transform::{Transform, TransformBundle}, Float, }, ecs::{ Disp...
( &mut self, texture_path: &str, ron_path: &str, world: &mut World, ) -> SpriteSheetHandle { // Load the sprite sheet necessary to render the graphics. // The texture is the pixel data // `sprite_sheet` is the layout of the sprites on the image // `tex...
load_sprite_sheet
identifier_name
main.rs
#[macro_use] extern crate log; use std::sync::Arc; use amethyst::{ assets::{AssetStorage, Loader, PrefabLoader, PrefabLoaderSystem, Processor, RonFormat}, core::{ bundle::SystemBundle, math::Vector3, transform::{Transform, TransformBundle}, Float, }, ecs::{ Disp...
// This graph structure is used for creating a proper `RenderGraph` for // rendering. A renderGraph can be thought of as the stages during a render // pass. In our case, we are only executing one subpass (DrawFlat2D, or the // sprite pass). This graph also needs to be rebuilt whenever the window is // resized, so the...
{ //amethyst::start_logger(Default::default()); amethyst::Logger::from_config(Default::default()) .level_for("gfx_backend_vulkan", amethyst::LogLevelFilter::Warn) .level_for("rendy_factory::factory", amethyst::LogLevelFilter::Warn) .level_for( "rendy_memory::allocator::dynami...
identifier_body
main.rs
#[macro_use] extern crate log; use std::sync::Arc; use amethyst::{ assets::{AssetStorage, Loader, PrefabLoader, PrefabLoaderSystem, Processor, RonFormat}, core::{ bundle::SystemBundle, math::Vector3, transform::{Transform, TransformBundle}, Float, }, ecs::{ Disp...
prelude::*, renderer::{ formats::texture::ImageFormat, pass::{DrawDebugLinesDesc, DrawFlat2DDesc}, rendy::{ factory::Factory, graph::{ render::{RenderGroupDesc, SubpassBuilder}, GraphBuilder, }, hal::{format:...
System, SystemData, WriteStorage, }, input::{InputBundle, InputHandler, StringBindings},
random_line_split
main.rs
#[macro_use] extern crate log; use std::sync::Arc; use amethyst::{ assets::{AssetStorage, Loader, PrefabLoader, PrefabLoaderSystem, Processor, RonFormat}, core::{ bundle::SystemBundle, math::Vector3, transform::{Transform, TransformBundle}, Float, }, ecs::{ Disp...
Trans::None } } impl<'a, 'b> GameState<'a, 'b> { fn load_sprite_sheet( &mut self, texture_path: &str, ron_path: &str, world: &mut World, ) -> SpriteSheetHandle { // Load the sprite sheet necessary to render the graphics. // The texture is the pixel ...
{ dispatcher.dispatch(&data.world.res); }
conditional_block
awscache.go
package awscache import ( "context" "fmt" "strconv" "strings" "sync" "time" "github.com/cep21/cfmanage/internal/aimd" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/...
else { logger.Log(1, "Bucket created with URL %s", *out.Location) } } uploader := s3manager.NewUploader(a.session) itemKey := fmt.Sprintf("cfmanage_%s_%s", *in.StackName, time.Now().UTC()) out, err := uploader.UploadWithContext(ctx, &s3manager.UploadInput{ Bucket: &bucket, Key: &itemKey, Body: stri...
{ if !isAWSError(err, "BucketAlreadyOwnedByYou") { return errors.Wrapf(err, "unable to create bucket %s correctly", bucket) } logger.Log(1, "bucket already owend by you") }
conditional_block
awscache.go
package awscache import ( "context" "fmt" "strconv" "strings" "sync" "time" "github.com/cep21/cfmanage/internal/aimd" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/...
(s *string) string { if s == nil { return "" } return *s }
emptyOnNil
identifier_name
awscache.go
package awscache import ( "context" "fmt" "strconv" "strings" "sync" "time" "github.com/cep21/cfmanage/internal/aimd" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/...
func (a *AWSClients) AccountID() (string, error) { return a.accountID.Do(func() (string, error) { stsClient := sts.New(a.session) out, err := stsClient.GetCallerIdentity(&sts.GetCallerIdentityInput{}) if err != nil { return "", errors.Wrap(err, "unable to fetch identity ID") } return *out.Account, nil ...
{ return *a.session.Config.Region }
identifier_body
awscache.go
package awscache import ( "context" "fmt" "strconv" "strings" "sync" "time" "github.com/cep21/cfmanage/internal/aimd" "github.com/aws/aws-sdk-go/aws/awserr" "github.com/aws/aws-sdk-go/service/s3" "github.com/aws/aws-sdk-go/service/s3/s3manager" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/...
} func (a *AWSClients) AccountID() (string, error) { return a.accountID.Do(func() (string, error) { stsClient := sts.New(a.session) out, err := stsClient.GetCallerIdentity(&sts.GetCallerIdentityInput{}) if err != nil { return "", errors.Wrap(err, "unable to fetch identity ID") } return *out.Account, nil ...
return *a.session.Config.Region
random_line_split
movie-data-analysis.py
# Movie Data Analysis using TMDb dataset ## Table of Contents <ul> <li><a href="#intro">Introduction</a></li> <li><a href="#wrangling">Data Wrangling</a></li> <li><a href="#eda">Exploratory Data Analysis</a></li> <li><a href="#conclusions">Conclusions</a></li> </ul> <a id='intro'></a> ## Introduction In this project ...
# Display in bar chart md_genre['original_title'].plot.barh(title = 'Movies per Genre',color='DarkBlue', figsize=(10, 9)); The most common genres are Drama (4672 movies, 17.6%) , Comedy (3750 movies, 14.2%) and Thriller (2841 movies, 10.7%). <a id='q2'></a> #### Q2. Which genres have high avg. budget and revenue? ...
md_genre['original_title'].plot.pie(title= 'Movies per Genre in %', figsize=(10,10), autopct='%1.1f%%',fontsize=15);
random_line_split
lib.rs
//! Ropey is a utf8 text rope for Rust. It is fast, robust, and can handle //! huge texts and memory-incoherent edits with ease. //! //! Ropey's atomic unit of text is Unicode scalar values (or `char`s in Rust) //! encoded as utf8. All of Ropey's editing and slicing operations are done //! in terms of char indices, w...
( f: &mut std::fmt::Formatter<'_>, start_idx: Option<usize>, end_idx: Option<usize>, ) -> std::fmt::Result { match (start_idx, end_idx) { (None, None) => { write!(f, "..") } (Some(start), None) => { write!(f, "{}..", start) } (None, Some(...
write_range
identifier_name
lib.rs
//! Ropey is a utf8 text rope for Rust. It is fast, robust, and can handle //! huge texts and memory-incoherent edits with ease. //! //! Ropey's atomic unit of text is Unicode scalar values (or `char`s in Rust) //! encoded as utf8. All of Ropey's editing and slicing operations are done //! in terms of char indices, w...
// Deprecated in std. fn cause(&self) -> Option<&dyn std::error::Error> { None } } impl std::fmt::Debug for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match *self { Error::ByteIndexOutOfBounds(index, len) => { write!( ...
{ "" }
identifier_body
lib.rs
//! Ropey is a utf8 text rope for Rust. It is fast, robust, and can handle //! huge texts and memory-incoherent edits with ease. //! //! Ropey's atomic unit of text is Unicode scalar values (or `char`s in Rust) //! encoded as utf8. All of Ropey's editing and slicing operations are done //! in terms of char indices, w...
/// Indicates that the passed char index was out of bounds. /// /// Contains the index attempted and the actual length of the /// `Rope`/`RopeSlice` in chars, in that order. CharIndexOutOfBounds(usize, usize), /// Indicates that the passed line index was out of bounds. /// /// Contains ...
random_line_split
lib.rs
//! Ropey is a utf8 text rope for Rust. It is fast, robust, and can handle //! huge texts and memory-incoherent edits with ease. //! //! Ropey's atomic unit of text is Unicode scalar values (or `char`s in Rust) //! encoded as utf8. All of Ropey's editing and slicing operations are done //! in terms of char indices, w...
} } //============================================================== // Range handling utilities. #[inline(always)] pub(crate) fn start_bound_to_num(b: Bound<&usize>) -> Option<usize> { match b { Bound::Included(n) => Some(*n), Bound::Excluded(n) => Some(*n + 1), Bound::Unbounded => N...
{ write!(f, "{}..{}", start, end) }
conditional_block
my_functions.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.odr as odr import scipy.optimize as optimize from sympy import solve, solveset, var import sympy as sp from scipy.io import loadmat from copy import deepcopy import time import os from scipy.stats import truncnorm def get_truncated_no...
(init, *data): """biconical model; inital guess: init=[a',b',d',u',v',w'], data to fit to: data= [x_i,y_i,z_i]""" data = data[0] c = (init[3]*data[0, :]**2 + init[4]*data[1, :]**2 + init[5]*data[0, :]*data[1, :])/(init[0]*data[0, :]**2 + init[1]*data[1, :]**2 + init[2]*data[0, :]*data[1, :]) return np.s...
f_biconic_model
identifier_name
my_functions.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.odr as odr import scipy.optimize as optimize from sympy import solve, solveset, var import sympy as sp from scipy.io import loadmat from copy import deepcopy import time import os from scipy.stats import truncnorm def get_truncated_no...
def circ_fit(data): x = np.reshape(data[:, 0], [len(data[:, 0]), 1]) y = np.reshape(data[:, 1], [len(data[:, 0]), 1]) init = np.array([7.6, 0]) res = optimize.least_squares(f_circ, init, args=np.array([x, y])) return res.x def keratometry(self, mode='biconic'): # Coordinates of surface ...
data = np.array(data[0:2])[:, :, 0] x = data[0, :] y = data[1, :] return (-init[0]**2 + x**2 + (y-init[1])**2)**2
identifier_body
my_functions.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.odr as odr import scipy.optimize as optimize from sympy import solve, solveset, var import sympy as sp from scipy.io import loadmat from copy import deepcopy import time import os from scipy.stats import truncnorm def get_truncated_no...
a_2 = np.round(a_2, decimals=5) p = np.zeros([5,1]) if a_1 > 0 and (p_prime[0] - a_1) / (p_prime[0] + p_prime[1] - 2 * a_1) >= 0: p[0] = np.real(a_1) elif a_2 > 0 and (p_prime[0] - a_2) / (p_prime[0] + p_prime[1] - 2 * a_2) >= 0: p[0] = np.real(a_2) else: p[0] = np.inf p[...
a_1 = np.round(a_1, decimals=5)
random_line_split
my_functions.py
import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.odr as odr import scipy.optimize as optimize from sympy import solve, solveset, var import sympy as sp from scipy.io import loadmat from copy import deepcopy import time import os from scipy.stats import truncnorm def get_truncated_no...
f.write("\t</Parameters>\n") f.write("</febio_spec>") f.close() def pre_stretch(ite_max, tol_error, path=''): if not path == '': os.chdir(path) error = np.inf # [mm] i = 0 # os.system('cp geometry_init.feb geometry_opt.feb') X_aim = np.asarray(load_feb_file_nodes('geometry_in...
f.write("\t\t<param name=\"" + parm_name[i] + "\">" + str(param) + "</param>\n") i += 1
conditional_block
click_differentiator_test_mode.py
import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import numpy as np import io, os from torch.utils.data import Dataset, DataLoader import pickle from IPython import embed from tensorboardX import SummaryWriter import argparse import random import torch from torch.autograd import Var...
label = 0 ## return audio, label, click_1_file_dir, click_1_time, click_2_file_dir, click_2_time return (audio, label, audio_dir_1, time_1, audio_dir_2, time_2) ###### Model ################################# class SoundNet(nn.Module): def __init__(self): ...
random_line_split
click_differentiator_test_mode.py
import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import numpy as np import io, os from torch.utils.data import Dataset, DataLoader import pickle from IPython import embed from tensorboardX import SummaryWriter import argparse import random import torch from torch.autograd import Var...
print('accuracy: ', acc / labels_out.shape[0]) print("Number of pairs same whale: ", np.sum(label)) print("Percentage of same whale: ", np.sum(label) / len(label) * 100) print('TP: ', tp) print('TN: ', tn) print('FP: ', fp) print('FN...
fn += 1
conditional_block
click_differentiator_test_mode.py
import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import numpy as np import io, os from torch.utils.data import Dataset, DataLoader import pickle from IPython import embed from tensorboardX import SummaryWriter import argparse import random import torch from torch.autograd import Var...
def __getitem__(self, idx): ## only for test mode audio_dir_1, label_1 = self.data_in[idx, 0], self.data_in[idx, 2] audio_dir_2, label_2 = self.data_in[idx, 4], self.data_in[idx, 6] time_1 = float(self.data_in[idx, 3]) time_2 = float(self.data_in[idx, ...
return len(self.data_in)
identifier_body
click_differentiator_test_mode.py
import torch.nn as nn from torch.autograd import Variable import torch.optim as optim import numpy as np import io, os from torch.utils.data import Dataset, DataLoader import pickle from IPython import embed from tensorboardX import SummaryWriter import argparse import random import torch from torch.autograd import Var...
(self, waveform): x = self.conv1(waveform.unsqueeze(1).permute(0,1,3,2)) x = self.batchnorm1(x) x = self.relu1(x) x = self.maxpool1(x) x = self.conv2(x) x = self.batchnorm2(x) x = self.relu2(x) x = self.maxpool2(x) x = self.conv3(x) x = s...
forward
identifier_name
proto_connection.rs
//! Benchmark the `x11rb_protocol::Connection` type's method, at varying levels of //! capacity. use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion}; use std::{ io::{Read, Write}, mem::{replace, size_of}, net::{TcpListener, TcpStream}, thread, }; use x11rb_protocol::{ ...
(i: i32, p: i32) -> i32 { let mut result = 1; for _ in 0..p { result *= i; } result } fn enqueue_packet_test(c: &mut Criterion) { // take the cartesian product of the following conditions: // - the packet is an event, a reply, or an error // - pending_events and pending_replies are ...
pow
identifier_name
proto_connection.rs
//! Benchmark the `x11rb_protocol::Connection` type's method, at varying levels of //! capacity. use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion}; use std::{ io::{Read, Write}, mem::{replace, size_of}, net::{TcpListener, TcpStream}, thread, }; use x11rb_protocol::{ ...
if left.read(&mut buf).is_err() { break; } } }); Box::new(right) } #[cfg(not(unix))] { continue; ...
random_line_split
proto_connection.rs
//! Benchmark the `x11rb_protocol::Connection` type's method, at varying levels of //! capacity. use criterion::{black_box, criterion_group, criterion_main, BatchSize, Criterion}; use std::{ io::{Read, Write}, mem::{replace, size_of}, net::{TcpListener, TcpStream}, thread, }; use x11rb_protocol::{ ...
fn try_parse_small_struct(c: &mut Criterion) { // xproto::Rectangle is a pointer wide on 64-bit, use that c.bench_function("try_parse an xproto::Rectangle", |b| { let packet = [0x42u8; size_of::<Rectangle>()]; b.iter(|| Rectangle::try_parse(black_box(&packet))) }); } fn try_parse_large_st...
{ // permutations: // - send queue is empty or very full // - receive queue is empty of very full enum SendQueue { SEmpty, SFull, } enum RecvQueue { REmpty, RFull, } use RecvQueue::*; use SendQueue::*; let mut group = c.benchmark_group("send_and...
identifier_body
main.rs
use std::collections::HashMap; use std::collections::HashSet; use std::io; use std::io::Read; use std::iter::Peekable; use std::slice::Iter; #[derive(Clone)] enum Match { Literal(char), Alternation(Vec<Match>), Concatenation(Vec<Match>), } impl std::fmt::Debug for Match { fn fmt(&self, f: &mut std::fmt::...
//////////////////////////////////////////////////////////////////////// // Generate all the possible strings. // fn generate_all(m: &Match) -> HashSet<String> { let mut res: HashSet<String> = HashSet::new(); match m { Match::Literal(x) => { res.insert(x.to_string()); () ...
{ match m { Match::Alternation(xs) => { let mut res = Vec::new(); for alternative in xs.iter() { res.extend(get_partials(alternative).into_iter()); } res } // A single literal will have no backtrackable parts. Match::Lit...
identifier_body
main.rs
use std::collections::HashMap; use std::collections::HashSet; use std::io; use std::io::Read; use std::iter::Peekable; use std::slice::Iter; #[derive(Clone)] enum Match { Literal(char), Alternation(Vec<Match>), Concatenation(Vec<Match>), } impl std::fmt::Debug for Match { fn fmt(&self, f: &mut std::fmt::...
} } } // Is this an empty match? Used by opt_empties. fn is_empty(m: &Match) -> bool { match m { Match::Literal(_) => false, Match::Concatenation(xs) => xs.iter().all(is_empty), Match::Alternation(xs) => xs.len() > 0 && xs.iter().all(is_empty), } } // And this removes alter...
random_line_split
main.rs
use std::collections::HashMap; use std::collections::HashSet; use std::io; use std::io::Read; use std::iter::Peekable; use std::slice::Iter; #[derive(Clone)] enum Match { Literal(char), Alternation(Vec<Match>), Concatenation(Vec<Match>), } impl std::fmt::Debug for Match { fn fmt(&self, f: &mut std::fmt::...
(l: usize, mapping: &HashMap<(i32, i32), usize>) -> usize { mapping.iter().filter(|(_, l2)| **l2 >= l).count() } fn main() { let mut buffer = String::new(); io::stdin().read_to_string(&mut buffer).expect("Read error"); let chars = buffer.replace('^', "").replace('$', "").trim().chars().collect::<Vec<_>...
count_long
identifier_name
precheck.go
// Copyright © 2021 NAME HERE <EMAIL ADDRESS> // // 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 ...
// TODO: add more checks sa := local.NewSourceAnalyzer( analysis.Combine("upgrade precheck", &maturity.AlphaAnalyzer{}), resource.Namespace(ctx.Namespace()), resource.Namespace(ctx.IstioNamespace()), nil, ) if err != nil { return nil, err } sa.AddRunningKubeSource(cli) cancel := make(chan struct{}) ...
msgs = append(msgs, gwMsg...)
random_line_split
precheck.go
// Copyright © 2021 NAME HERE <EMAIL ADDRESS> // // 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 ...
resource.Reference { return nil } func (o clusterOrigin) FieldMap() map[string]int { return make(map[string]int) }
erence()
identifier_name
precheck.go
// Copyright © 2021 NAME HERE <EMAIL ADDRESS> // // 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 ...
ype bindStatus struct { Lo bool Wildcard bool Explicit bool } func (b bindStatus) Any() bool { return b.Lo || b.Wildcard || b.Explicit } func (b bindStatus) String() string { res := []string{} if b.Lo { res = append(res, "Localhost") } if b.Wildcard { res = append(res, "Wildcard") } if b.Explicit ...
ports := map[int]bindStatus{} cd := &admin.ConfigDump{} if err := protomarshal.Unmarshal(configdump, cd); err != nil { return nil, err } for _, cdump := range cd.Configs { clw := &admin.ClustersConfigDump_DynamicCluster{} if err := cdump.UnmarshalTo(clw); err != nil { return nil, err } cl := &cluster.C...
identifier_body
precheck.go
// Copyright © 2021 NAME HERE <EMAIL ADDRESS> // // 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 ...
fmt.Println("failed to get listener state: ", err) return nil } for _, ss := range strings.Split(out, "\n") { if len(ss) == 0 { continue } bind, port, err := net.SplitHostPort(getColumn(ss, 3)) if err != nil { fmt.Println("failed to get parse state: ", err) continue } ...
// Likely distroless or other custom build without ss. Nothing we can do here... return nil }
conditional_block
river.rs
#[cfg(test)] extern crate gag; use std::rc::{Rc, Weak}; use std::cell::{RefCell, RefMut, Ref}; use tick::Tick; use salmon::{Salmon, Age, Direction}; use split_custom_escape::HomespringSplit; use program::Program; #[derive(Debug, PartialEq, Eq)] pub enum NodeType { Other(String), Hatchery, HydroPower, ...
InverseLock, YoungSense, Switch, YoungSwitch, Narrows, AppendUp, YoungRangeSense, Net, ForceDown, ForceUp, Spawn, PowerInvert, Current, Bridge, Split, RangeSwitch, YoungRangeSwitch, } impl NodeType { pub fn from_name(name: &str) -> NodeType { ...
random_line_split
river.rs
#[cfg(test)] extern crate gag; use std::rc::{Rc, Weak}; use std::cell::{RefCell, RefMut, Ref}; use tick::Tick; use salmon::{Salmon, Age, Direction}; use split_custom_escape::HomespringSplit; use program::Program; #[derive(Debug, PartialEq, Eq)] pub enum NodeType { Other(String), Hatchery, HydroPower, ...
pub fn become_watered(&mut self) { self.watered = true; } pub fn is_powered(&self) -> bool { if self.block_power { false } else if self.powered { true } else { self.children.iter().any(|c| { c.borrow_mut().is_powered() ...
{ use self::NodeType::*; self.snowy = true; match self.node_type { HydroPower => self.destroyed = true, _ => (), } }
identifier_body
river.rs
#[cfg(test)] extern crate gag; use std::rc::{Rc, Weak}; use std::cell::{RefCell, RefMut, Ref}; use tick::Tick; use salmon::{Salmon, Age, Direction}; use split_custom_escape::HomespringSplit; use program::Program; #[derive(Debug, PartialEq, Eq)] pub enum NodeType { Other(String), Hatchery, HydroPower, ...
(&self, name: &str) -> bool { let len = self.children.len(); if len > 0 { match self.borrow_child(0).find_node(name) { true => return true, false => (), } } if self.name == name { return true; } if len > 1 { for ...
find_node
identifier_name