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 |
|---|---|---|---|---|
application.py | ():
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 | # HBar Graph per la paga oraria provinciale a seconda del livello di istruzione
if(request.args['graph'] == "pagaOra"):
return make_response(render_template("graphs/pagaOra.html"))
# Line Graph per gli iscritti alle università nel veneto per anno
eli... | 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 | ("templates/" + dir)):
if('year' in request.args):
return make_response(render_template(dir, year=int(request.args['year'])))
else:
return make_response(render_template(dir, year=0))
# Polar Area Graph per gli stu... | ppend(str(row[10]))
| conditional_block | |
task4-main.py | .485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# Preprocess the image
image_tensor = transformation(image).float()
# Add an extra batch dimension since pytorch treats all images as batches
image_tensor = image_tensor.unsqueeze_(0)
if torch.cuda.is_available():
image_tensor.cuda()
... | 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 |
'''
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 | 2.putText(image8,value,(50,30),cv2.FONT_HERSHEY_SIMPLEX,0.8,(0,0,0),2)
#cv2.imshow('images',image)
#cv2.imshow('track',image[2055:2200,120+u:265+v,:])
#cv2.waitKey(0)
#cv2.destroyAllWindows()
# print(value,pred)
position.append(value)
aposition.append(value)
... | 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 | (value)
aposition.append(value)
name.append(pred)
aname.append(pred)
dicto=dict(zip(position,name))
animalliston=dict(zip(aposition,aname))
u=u+1936
v=v+1937
#top to bottom contour find drawing and detection
a=0
b=0
k=0
x=0
for j in range(0,4):
c=0
d=0
f... | Diff | identifier_name | |
lib.rs | > tell us what your website is. You can just put your name in for now. Once you get a key, its what
//! > uniquely identifies you when accessing our WebAPI calls.
//!
//! In your `main.rs` or anywhere you intend to use the library create a non-mutable string of
//! you token pass first to use the library, there is no ... |
}
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 | //! > tell us what your website is. You can just put your name in for now. Once you get a key, its what
//! > uniquely identifies you when accessing our WebAPI calls.
//!
//! In your `main.rs` or anywhere you intend to use the library create a non-mutable string of
//! you token pass first to use the library, there is ... | 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 | _live_league_games::*,
get_rarities::*, get_top_live_game::*, get_tournament_prize_pool::*,
};
/// language macro for easy implementation in various builder struct
///
/// The language to retrieve results in (default is en_us) (see http://en.wikipedia.org/wiki/ISO_639-1 for
/// the language codes (first two charac... | match_id | identifier_name | |
lib.rs | > tell us what your website is. You can just put your name in for now. Once you get a key, its what
//! > uniquely identifies you when accessing our WebAPI calls.
//!
//! In your `main.rs` or anywhere you intend to use the library create a non-mutable string of
//! you token pass first to use the library, there is no ... |
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 | //!
//! Not running any extractors is also supported:
//!
//! ```rust
//! use axum::{
//! Router,
//! BoxError,
//! response::IntoResponse,
//! http::StatusCode,
//! routing::get,
//! };
//! use tower::{ServiceBuilder, timeout::error::Elapsed};
//! use std::time::Duration;
//! use axum_handle_error_... | 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 | //!
//! Not running any extractors is also supported:
//!
//! ```rust
//! use axum::{
//! Router,
//! BoxError,
//! response::IntoResponse,
//! http::StatusCode,
//! routing::get,
//! };
//! use tower::{ServiceBuilder, timeout::error::Elapsed};
//! use std::time::Duration;
//! use axum_handle_error_... | (&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 | TreeSet<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,
#[serde(default, skip_serializing_if = "BTreeMap::is... | <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 | TreeSet<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,
#[serde(default, skip_serializing_if = "BTreeMap::is... |
}
/// 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 | 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 | TreeSet<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,
#[serde(default, skip_serializing_if = "BTreeMap::is... |
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 | .YAGCommand{
Name: "Create",
CmdCategory: categoryRoleMenu,
Aliases: []string{"c"},
Description: "Set up a role menu.",
LongDescription: reqPerms + "Specify a message with -m to use an existing message instead of having the bot make one\n\n" + msgIDDocs,
Requir... | 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 | .YAGCommand{
Name: "Create",
CmdCategory: categoryRoleMenu,
Aliases: []string{"c"},
Description: "Set up a role menu.",
LongDescription: reqPerms + "Specify a message with -m to use an existing message instead of having the bot make one\n\n" + msgIDDocs,
Requir... | 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 | .YAGCommand{
Name: "Create",
CmdCategory: categoryRoleMenu,
Aliases: []string{"c"},
Description: "Set up a role menu.",
LongDescription: reqPerms + "Specify a message with -m to use an existing message instead of having the bot make one\n\n" + msgIDDocs,
Requir... | {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 | after updating it.\n\n" + msgIDDocs,
RequireDiscordPerms: []int64{discordgo.PermissionManageServer},
RequiredArgs: 1,
Arguments: []*dcmd.ArgDef{
{Name: "Message-ID", Type: dcmd.BigInt},
},
RunFunc: cmdFuncRoleMenuResetReactions,
}
cmdEditOption := &commands.YAGCommand{
Name: "Ed... | 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 | ) -> Self::IntoIter {
BorrowedVectorIterator {
vector: &self,
index: -1isize as usize,
index_back: self.size,
}
}
}
impl<'a, T> IntoIterator for &'a mut Vector<T> {
type Item = &'a mut T;
type IntoIter = BorrowedVectorIteratorMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
let size = self.size;... |
///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 | (self) -> Self::IntoIter {
BorrowedVectorIterator {
vector: &self,
index: -1isize as usize,
index_back: self.size,
}
}
}
impl<'a, T> IntoIterator for &'a mut Vector<T> {
type Item = &'a mut T;
type IntoIter = BorrowedVectorIteratorMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
let size = self.... | (&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 | pub fn reserve_additional(&mut self, additional: usize) {
if mem::size_of::<T>() == 0 {
return;
}
let new_cap = self
.capacity
.checked_add(additional)
.expect("New size overflowed usize");
new_cap
.checked_mul(mem::size_of::<T>())
.expect("New size overflowed usize");
self.reserve(new_cap)... |
self.data.map(|p| p.as_ptr())
}
| conditional_block | |
lib.rs | (self) -> Self::IntoIter {
BorrowedVectorIterator {
vector: &self,
index: -1isize as usize,
index_back: self.size,
}
}
}
impl<'a, T> IntoIterator for &'a mut Vector<T> {
type Item = &'a mut T;
type IntoIter = BorrowedVectorIteratorMut<'a, T>;
fn into_iter(self) -> Self::IntoIter {
let size = self.... | 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 | "job_role": "Operator"
// },
// {
// "id": 38,
// "first_name": "Brenda",
// "last_name": "Perry",
// "email": "bperry11@google.ru",
// "gender": "Female",
// "address": "9407 6th Hill",
// "job_role": "Environmental Tech"
// },
// {
// "id": 39,
// "first_name": "Rebecca",
// "las... | {
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 | "email": "egrayz@dedecms.com",
// "gender": "Female",
// "address": "15125 Utah Circle",
// "job_role": "Structural Engineer"
// },
// {
// "id": 37,
// "first_name": "Wayne",
// "last_name": "Martinez",
// "email": "wmartinez10@constantcontact.com",
// "gender": "Male",
// "address": "60... | filterEmployees | identifier_name | |
data.ts | 6 Briar Crest Place",
// "job_role": "Food Chemist"
// },
// {
// "id": 33,
// "first_name": "Christopher",
// "last_name": "Reed",
// "email": "creedw@examiner.com",
// "gender": "Male",
// "address": "19798 Lakewood Gardens Avenue",
// "job_role": "Media Manager III"
// },
// {
// "... | {
resolve({ success: false, errorMessage: "Inloggen mislukt. " + data["errorMessage"] });
} | conditional_block | |
data.ts | "job_role": "Structural Engineer"
// },
// {
// "id": 37,
// "first_name": "Wayne",
// "last_name": "Martinez",
// "email": "wmartinez10@constantcontact.com",
// "gender": "Male",
// "address": "6056 Clyde Gallagher Circle",
// "job_role": "Operator"
// },
// {
// "id": 38,
// "first_... | 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 | , s, ns):
rospy.loginfo(self.build(s, ns))
def d(self, s, ns):
rospy.logdebug(self.build(s, ns))
def e(self, s, ns):
rospy.logerr(self.build(s, ns))
def c(self, s, ns):
rospy.logwarn(self.build(s, ns))
def build(self, s, ns):
return "\x1B[1m[{}]\x1B[0m {}".format(... | """ | random_line_split | |
leap_tracker.py | :
"""
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 | "on_disconnect")
def on_exit(self, controller):
LOG.v("END", "on_exit")
def on_frame(self, controller):
# Get the most recent frame and fill data structures
frame = controller.frame()
selected_finger = None
if not frame.hands.is_empty:
# Get the fi... | 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 | for i in range(5)}
# Initialize joint names for JointState messages
self.joint_names = []
# Initialize node
rospy.init_node('hand_tracker', anonymous=True)
# Initialize publishers
self.js_pub = rospy.Publisher(JS_TOPIC, JointState, queue_size=1... | lf.t = 0.0
| conditional_block | |
en.ts | voting for less than 36.",
"voting-rules-2": "Each voting transaction costs only a small fee of 0.0004 ELA.",
"voting-rules-3": "There is no lock in period. However, if you send coins out of your wallet your votes will be cancelled and you will need to vote again.",
"voting-rules-4": "As an incentive to vo... | "node-state-text": "State", | random_line_split | |
practice.js | return false;
}
// const testOne = areThereDuplicates(1, 2, 3);
// console.log(testOne);
// const testTwo = areThereDuplicates(1, 2, 2);
// console.log(testTwo);
const testThree = areThereDuplicates("a", "b", "c", "a");
//console.log(testThree);
//areThereDuplicates One Liner Solution
function areThereDuplicates() {... |
//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 | return false;
}
// const testOne = areThereDuplicates(1, 2, 3);
// console.log(testOne);
// const testTwo = areThereDuplicates(1, 2, 2);
// console.log(testTwo);
const testThree = areThereDuplicates("a", "b", "c", "a");
//console.log(testThree);
//areThereDuplicates One Liner Solution
function areThereDuplicates() ... | ////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 | return false;
}
// const testOne = areThereDuplicates(1, 2, 3);
// console.log(testOne);
// const testTwo = areThereDuplicates(1, 2, 2);
// console.log(testTwo);
const testThree = areThereDuplicates("a", "b", "c", "a");
//console.log(testThree);
//areThereDuplicates One Liner Solution
function areThereDuplicates() {... |
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 | return false;
}
// const testOne = areThereDuplicates(1, 2, 3);
// console.log(testOne);
// const testTwo = areThereDuplicates(1, 2, 2);
// console.log(testTwo);
const testThree = areThereDuplicates("a", "b", "c", "a");
//console.log(testThree);
//areThereDuplicates One Liner Solution
function areThereDuplicates() {... | (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 | js);
Ok(())
})
}
};
}
extern_case!(snudown_js, "js/snudown.js");
case!(
basic,
r#"
function f(x) {
while (true);
x = y.bar;
z.foo = x ? true : 'hi';
return +[1 || x, { x }, f + 1, ++g];
}
f(1), true;
"#,
@r###"
(function f() ... | };
"###);
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 | p' as an argument. Additionally, if you would like to clean all
generated files, you can call this script with the argument 'clean'.
"""
import distutils.spawn
import glob
import os
import platform
import subprocess
import sys
# The project root directory, which is one level up from this script's
# directory.
PROJECT... |
# 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 | p' as an argument. Additionally, if you would like to clean all
generated files, you can call this script with the argument 'clean'.
"""
import distutils.spawn
import glob
import os
import platform
import subprocess
import sys
# The project root directory, which is one level up from this script's
# directory.
PROJECT... | # 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 | p' as an argument. Additionally, if you would like to clean all
generated files, you can call this script with the argument 'clean'.
"""
import distutils.spawn
import glob
import os
import platform
import subprocess
import sys
# The project root directory, which is one level up from this script's
# directory.
PROJECT... |
# 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 | 'Debug'),
os.path.join(PREBUILTS_ROOT, 'libwebp',
'%s-x86' % platform.system().lower(),
'libwebp-0.4.1-%s-x86-32' % platform.system().lower(), 'bin'),
os.path.dirname(CWEBP_BINARY_IN_PATH) if CWEBP_BINARY_IN_PATH else '',
]
# Directory to place processed assets.
ASSETS_PATH =... | main | identifier_name | |
bcfw_diffrac.py | (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 | = gaps / gaps.sum()
return np.random.choice(len(gaps), 1, p=gap_prob)[0]
def display_information(iter,
max_iter,
gaps,
eval_metric,
objective_value=None,
verbose='silent',
... | 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 | bias_value=bias_value))
# Compute X^TX
print('Computing xtx...')
x_t_x = np.zeros([d, d])
N = 0
for i in tqdm(range(len(feats))):
x = get_feat_block(feats, i, memory_mode, bias_value=bias_value)
x_t_x += np.dot(np.transpose(x), x)
N += x.shape[0]
# Compute P
p_matr... |
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 | bias_value=bias_value))
# Compute X^TX
print('Computing xtx...')
x_t_x = np.zeros([d, d])
N = 0
for i in tqdm(range(len(feats))):
x = get_feat_block(feats, i, memory_mode, bias_value=bias_value)
x_t_x += np.dot(np.transpose(x), x)
N += x.shape[0]
# Compute P
p_matr... | 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 | .Base0C,
"0D": s.Base0D,
"0E": s.Base0E,
"0F": s.Base0F,
} {
vars[fmt.Sprintf("base%s-hex", base)] = color
vars[fmt.Sprintf("base%s-hex-r", base)] = color[0:2]
vars[fmt.Sprintf("base%s-rgb-r", base)] = toRGB(color[0:2])
vars[fmt.Sprintf("base%s-dec-r", base)] = toDec(color[0:2])
vars[fmt.Sprintf("bas... | {
return nil, wrap(err, "reading response")
} | conditional_block | |
main.go | string `yaml:"output"`
} | 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 | 2 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 string `yaml:"base09"`
Base0A string `yaml:"base0A"`
Base0B string `yaml:"base0B"`
Base0C string `... | {
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 | .Sprintf("base%s-dec-r", base)] = toDec(color[0:2])
vars[fmt.Sprintf("base%s-hex-g", base)] = color[2:4]
vars[fmt.Sprintf("base%s-rgb-g", base)] = toRGB(color[2:4])
vars[fmt.Sprintf("base%s-dec-g", base)] = toDec(color[2:4])
vars[fmt.Sprintf("base%s-hex-r", base)] = color[4:6]
vars[fmt.Sprintf("base%s-rgb-r... | githubFileURL | identifier_name | |
storage.rs | , BTreeMap<String, f64>>; 2],
pub nr_reports: (u64, u64),
}
impl StorageJob {
pub fn parse(spec: &JobSpec) -> Result<StorageJob> {
let mut job = StorageJob::default();
for (k, v) in spec.props[0].iter() {
match k.as_str() {
"apply" => job.apply = v.len() == 0 || v.p... | <'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 | _err = (self.mem_usage as f64 - mem.target as f64) / mem.target as f64;
}
// Abort early iff we go over. Memory usage may keep rising
// through refine stages, so we'll check for going under
// after run completion.
if mem_avail_err > self... | random_line_split | ||
storage.rs | job.loops = v.parse::<u32>()?,
"rps-max" => job.rps_max = Some(v.parse::<u32>()?),
"hash-size" => job.hash_size = Some(parse_size(v)? as usize),
"chunk-pages" => job.chunk_pages = Some(v.parse::<usize>()?),
"log-bps" => job.log_bps = parse_size(v)?,
... | {
HASHD_SYSREQS.clone()
} | identifier_body | |
storage.rs | may keep rising
// through refine stages, so we'll check for going under
// after run completion.
if mem_avail_err > self.mem_avail_err_max
&& rep.bench_hashd.phase > rd_hashd_intf::Phase::BenchMemBisect
{
return tr... | {
self.prev_mem_avail = 0;
self.first_try = false;
} | conditional_block | |
phrases_or_entities_over_time_first.py | dataframe.
years = ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017']
# zscores for years are 10 columns, 1st column is cluster number
col_list = ['cluster_number'].extend(years)
centres_df = pd.read_csv('centres_df.tsv', sep='\t', names=col_list)
centres_df = centres_df.set_inde... |
@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 | dataframe.
years = ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017']
# zscores for years are 10 columns, 1st column is cluster number
col_list = ['cluster_number'].extend(years)
centres_df = pd.read_csv('centres_df.tsv', sep='\t', names=col_list)
centres_df = centres_df.set_inde... | (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 | dataframe.
years = ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017']
# zscores for years are 10 columns, 1st column is cluster number
col_list = ['cluster_number'].extend(years)
centres_df = pd.read_csv('centres_df.tsv', sep='\t', names=col_list)
centres_df = centres_df.set_inde... |
# 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 | dataframe.
years = ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017']
# zscores for years are 10 columns, 1st column is cluster number
col_list = ['cluster_number'].extend(years)
centres_df = pd.read_csv('centres_df.tsv', sep='\t', names=col_list)
centres_df = centres_df.set_inde... |
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 | .5, 0.0, 1.0, 0.0, 0.0]
//! // &[1.5, 1.0, 0.0, 1.5, 0.0, 0.0, 1.0, 0.0]
//! // &[1.5, 0.0, 1.0, 1.5, 0.0, 0.0, 0.0, 1.0]
//! ```
use std::iter;
use crate::error::Failed;
use crate::linalg::Matrix;
use crate::preprocessing::data_traits::{CategoricalFloat, Categorizable};
use crate::preprocessing::series_encoder... | {
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 | .5, 0.0, 1.0, 0.0, 0.0]
//! // &[1.5, 1.0, 0.0, 1.5, 0.0, 0.0, 1.0, 0.0]
//! // &[1.5, 0.0, 1.0, 1.5, 0.0, 0.0, 0.0, 1.0]
//! ```
use std::iter;
use crate::error::Failed;
use crate::linalg::Matrix;
use crate::preprocessing::data_traits::{CategoricalFloat, Categorizable};
use crate::preprocessing::series_encoder... | 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 | 5, 0.0, 1.0, 0.0, 0.0]
//! // &[1.5, 1.0, 0.0, 1.5, 0.0, 0.0, 1.0, 0.0]
//! // &[1.5, 0.0, 1.0, 1.5, 0.0, 0.0, 0.0, 1.0]
//! ```
use std::iter;
use crate::error::Failed;
use crate::linalg::Matrix;
use crate::preprocessing::data_traits::{CategoricalFloat, Categorizable};
use crate::preprocessing::series_encoder:... |
}
/// 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 |
// 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;
use fidl_fuchsia_ui_input;
use fidl_fuchsia_ui_scenic::{SessionListenerMarker, SessionListenerRequest};
use fidl_fuchsia_ui_viewsv1... | {
match view_msg {
ViewMessages::Update => {
self.update();
}
}
} | conditional_block | |
view.rs | 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;
use fidl_fuchsia_ui_input;
use fidl_fuchsia_ui_... | };
self.assistant
.handle_input_event(&mut context, &event)
.unwrap_or_else(|e| eprintln!("handle_event: {:?}", e));
for msg in context.messages {
self.send_message(&msg);
}
self.u... | {
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 | 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;
use fidl_fuchsia_ui_input;
use fidl_fuchsia_ui_... | (
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 | 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;
use fidl_fuchsia_ui_input;
use fidl_fuch... | 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 | sprite::{SpriteRender, SpriteSheet, SpriteSheetFormat, SpriteSheetHandle},
types::DefaultBackend,
GraphCreator,
RenderingSystem,
Texture,
},
ui::UiBundle,
utils::{application_root_dir, scene::BasicScenePrefab},
window::{ScreenDimensions, Window, WindowBundle},
};
use ame... | (
&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 | sprite::{SpriteRender, SpriteSheet, SpriteSheetFormat, SpriteSheetHandle},
types::DefaultBackend,
GraphCreator,
RenderingSystem,
Texture,
},
ui::UiBundle,
utils::{application_root_dir, scene::BasicScenePrefab},
window::{ScreenDimensions, Window, WindowBundle},
};
use ame... | .start();
let app_root = application_root_dir()?;
// display configuration
let display_config_path = app_root.join("examples/resources/display_config.ron");
// key bindings
let key_bindings_path = app_root.join("examples/resources/input.ron");
let game_data = GameDataBuilder::default... | {
//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 | 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 | sprite::{SpriteRender, SpriteSheet, SpriteSheetFormat, SpriteSheetHandle},
types::DefaultBackend,
GraphCreator,
RenderingSystem,
Texture,
},
ui::UiBundle,
utils::{application_root_dir, scene::BasicScenePrefab},
window::{ScreenDimensions, Window, WindowBundle},
};
use ame... |
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 | AWSClients struct {
session *session.Session
cleanup *cleanup.Cleanup
pollInterval time.Duration
accountID oncecache.StringCache
myToken string
mu sync.Mutex
}
func (a *AWSClients) token() string {
a.mu.Lock()
defer a.mu.Unlock()
if a.myToken == "" {
a.myToken = strconv.FormatInt(time.N... | 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 | "..", ".")
s = stringsReplaceAllRepeated(s, ".-", "-")
s = stringsReplaceAllRepeated(s, "-.", "-")
return s
}
func (a *AWSClients) FixTemplateBody(ctx context.Context, in *cloudformation.CreateChangeSetInput, bucket string, logger *logger.Logger) error {
if in.TemplateBody == nil {
return nil
}
tb := *in.Temp... | emptyOnNil | identifier_name | |
awscache.go | AWSClients struct {
session *session.Session
cleanup *cleanup.Cleanup
pollInterval time.Duration
accountID oncecache.StringCache
myToken string
mu sync.Mutex
}
func (a *AWSClients) token() string {
a.mu.Lock()
defer a.mu.Unlock()
if a.myToken == "" {
a.myToken = strconv.FormatInt(time.N... |
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 | AWSClients struct {
session *session.Session
cleanup *cleanup.Cleanup
pollInterval time.Duration
accountID oncecache.StringCache
myToken string
mu sync.Mutex
}
func (a *AWSClients) token() string {
a.mu.Lock()
defer a.mu.Unlock()
if a.myToken == "" {
a.myToken = strconv.FormatInt(time.N... | }
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 | genre and get mean for each genre and each variable, divide by 1 mio for clarity and better visibility
md_genre_mean = md_split_genres.groupby(['genres']).mean()
md_genre_mean ['profit_million'] = md_genre_mean['profit']/1000000
del md_genre_mean['profit']
md_genre_mean['revenue_million'] = md_genre_mean['revenue']/10... |
# 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 | \n"` and `"world"`. And
//! the rope `"Hello\nworld\n"` has three lines: `"Hello\n"`,
//! `"world\n"`, and `""`.
//!
//! Ropey can be configured at build time via feature flags to recognize
//! different line breaks. Ropey always recognizes:
//!
//! - `U+000A` — LF (Line Feed)
//! - `U+000D` `U+000A` &... | write_range | identifier_name | |
lib.rs | _idx));
//!
//! // Write the file back out to disk.
//! text.write_to(
//! BufWriter::new(File::create("my_great_book.txt")?)
//! )?;
//! # Ok(())
//! # }
//! # do_stuff().unwrap();
//! ```
//!
//! More examples can be found in the `examples` directory of the git
//! repository. Many of those examples demonstrate ... | {
""
} | identifier_body | |
lib.rs | //! text.remove(start_idx..end_idx);
//!
//! // ...and replace it with something better.
//! text.insert(start_idx, "The flowers are... so... dunno.\n");
//!
//! // Print the changes, along with the previous few lines for context.
//! let start_idx = text.line_to_char(511);
//! let end_idx = text.line_to_char(516);
//!... | /// 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 | the following are also recognized:
//!
//! - `U+000D` — CR (Carriage Return)
//!
//! With the `unicode_lines` feature, in addition to all of the
//! above, the following are also recognized (bringing Ropey into
//! conformance with
//! [Unicode Annex #14](https://www.unicode.org/reports/tr14/#BK)):
//!
... | {
write!(f, "{}..{}", start, end)
} | conditional_block | |
my_functions.py | a_1 = 0.5*(-(-p_prime[0, 0]-p_prime[1, 0]) + np.sqrt((-p_prime[0, 0]-p_prime[1, 0])**2 - 4*(p_prime[0, 0]*p_prime[1, 0] - p_prime[2, 0]**2/4) + 0j))
a_2 = 0.5*(-(-p_prime[0, 0]-p_prime[1, 0]) - np.sqrt((-p_prime[0, 0]-p_prime[1, 0])**2 - 4*(p_prime[0, 0]*p_prime[1, 0] - p_prime[2, 0]**2/4) + 0j))
a_1 = np.r... | (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 | a_1 = 0.5*(-(-p_prime[0, 0]-p_prime[1, 0]) + np.sqrt((-p_prime[0, 0]-p_prime[1, 0])**2 - 4*(p_prime[0, 0]*p_prime[1, 0] - p_prime[2, 0]**2/4) + 0j))
a_2 = 0.5*(-(-p_prime[0, 0]-p_prime[1, 0]) - np.sqrt((-p_prime[0, 0]-p_prime[1, 0])**2 - 4*(p_prime[0, 0]*p_prime[1, 0] - p_prime[2, 0]**2/4) + 0j))
a_1 = np.r... |
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 | a_1 = 0.5*(-(-p_prime[0, 0]-p_prime[1, 0]) + np.sqrt((-p_prime[0, 0]-p_prime[1, 0])**2 - 4*(p_prime[0, 0]*p_prime[1, 0] - p_prime[2, 0]**2/4) + 0j))
a_2 = 0.5*(-(-p_prime[0, 0]-p_prime[1, 0]) - np.sqrt((-p_prime[0, 0]-p_prime[1, 0])**2 - 4*(p_prime[0, 0]*p_prime[1, 0] - p_prime[2, 0]**2/4) + 0j))
a_1 = np.r... | 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 |
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 | 6]
time_1 = float(self.data_in[idx, 3])
time_2 = float(self.data_in[idx, 7])
audio1, sr = librosa.load(audio_dir_1, mono=False)
# find time of click's peak?
start_1 = 10925 + np.argmax(abs(audio1[1 , 10925 : 11035])) # why dim 1 and not 0?
... | 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 | , 1), stride=(2, 1),
padding=(8, 0))
self.batchnorm3 = nn.BatchNorm2d(64, eps=1e-5, momentum=0.1)
self.relu3 = nn.ReLU(True)
self.conv4 = nn.Conv2d(64, 128, kernel_size=(8, 1), stride=(2, 1),
padding=(4, 0))
self.batchnorm4 =... | fn += 1 | conditional_block | |
click_differentiator_test_mode.py |
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 | 6]
time_1 = float(self.data_in[idx, 3])
time_2 = float(self.data_in[idx, 7])
audio1, sr = librosa.load(audio_dir_1, mono=False)
# find time of click's peak?
start_1 = 10925 + np.argmax(abs(audio1[1 , 10925 : 11035])) # why dim 1 and not 0?
... | (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 | (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 | 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 empty, have one element, or have
// many... | if left.read(&mut buf).is_err() {
break;
}
}
});
Box::new(right)
}
#[cfg(not(unix))]
{
continue;
... | random_line_split | |
proto_connection.rs | 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 empty, have one element, or have
// many ... | for recv_queue in &[REmpty, RFull] {
let name = format!(
"send_and_receive_request (send {}, recv {})",
match send_queue {
SEmpty => "empty",
SFull => "full",
},
match recv_queue {
... | {
// 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 | {
// We could do precedence-based printing, but let's always put them in...
let mut first = true;
for x in xs.iter() {
write!(f, "{}", if first {'('} else {'|'})?;
first = false;
x.fmt(f)?;
}
... | element.push(partial);
res.push(Match::Concatenation(element));
}
}
res
}
}
}
}
}
////////////////////////////////////////////////////////////////////////
// ... | {
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 | => {
// We could do precedence-based printing, but let's always put them in...
let mut first = true;
for x in xs.iter() {
write!(f, "{}", if first {'('} else {'|'})?;
first = false;
x.fmt(f)?;
}
... | }
}
}
// 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 | => {
// We could do precedence-based printing, but let's always put them in...
let mut first = true;
for x in xs.iter() {
write!(f, "{}", if first {'('} else {'|'})?;
first = false;
x.fmt(f)?;
}
... | (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(). | count_long | identifier_name |
precheck.go | requirements.`,
Example: ` # Verify that Istio can be installed or upgraded
istioctl x precheck
# Check only a single namespace
istioctl x precheck --namespace default`,
RunE: func(cmd *cobra.Command, args []string) (err error) {
cli, err := ctx.CLIClientWithRevision(opts.Revision)
if err != nil {
... |
// 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 | name: "ValidatingWebhookConfiguration",
},
}
msgs := diag.Messages{}
for _, r := range Resources {
err := checkCanCreateResources(cli, r.namespace, r.group, r.version, r.name)
if err != nil {
msgs.Add(msg.NewInsufficientPermissions(&resource.Instance{Origin: clusterOrigin{}}, r.name, err.Error()))
}
... | erence() | identifier_name | |
precheck.go | namespace: istioNamespace,
group: "rbac.authorization.k8s.io",
version: "v1",
name: "Role",
},
{
namespace: istioNamespace,
version: "v1",
name: "ServiceAccount",
},
{
namespace: istioNamespace,
version: "v1",
name: "Service",
},
{
namespace: istioNa... | 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 | nil, err
}
sa.AddRunningKubeSource(cli)
cancel := make(chan struct{})
result, err := sa.Analyze(cancel)
if err != nil {
return nil, err
}
if result.Messages != nil {
msgs = append(msgs, result.Messages...)
}
return msgs, nil
}
// Checks that if the user has gateway APIs, they are the minimum version.
//... | // Likely distroless or other custom build without ss. Nothing we can do here...
return nil
}
| conditional_block | |
river.rs | 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 | allows(2),
"rapids" => Rapids(2),
"append. down" => AppendDown,
"bear" => Bear,
"force. field" => ForceField,
"sense" => Sense,
"clone" => Clone,
"young bear" => YoungBear,
"bird" => Bird,
"upstream. killing. dev... | {
use self::NodeType::*;
self.snowy = true;
match self.node_type {
HydroPower => self.destroyed = true,
_ => (),
}
} | identifier_body | |
river.rs | ,
ForceDown,
ForceUp,
Spawn,
PowerInvert,
Current,
Bridge,
Split,
RangeSwitch,
YoungRangeSwitch,
}
impl NodeType {
pub fn from_name(name: &str) -> NodeType {
// unimplemented!();
use self::NodeType::*;
match &name.to_lowercase()[..] {
"hatcher... | (&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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.