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 |
|---|---|---|---|---|
pipeline.py | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from skimage.feature import hog
from helper_func import *
from sklearn.model_selection import GridSearchCV
import pick... | (img):
new_img = cv2.GaussianBlur(img, (3,3), 0)
#new_img = cv2.cvtColor(new_img, cv2.COLOR_YUV2RGB)
new_img = cv2.cvtColor(new_img, cv2.COLOR_RGB2HSV)
new_img = np.array(new_img, dtype = np.float64)
#Generate new random brightness
random_bright = .5+random.uniform(0.3,1.0)
new_img[:,:,2] = random_... | augment_image | identifier_name |
pipeline.py | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from skimage.feature import hog
from helper_func import *
from sklearn.model_selection import GridSearchCV
import pick... |
def main():
ystart = 400
ystop = 656
scale = 1.5
### TRAINING #####
print(len(cars))
#train_model(cars, notcars)
### INFERENCE #####
#myimage = mpimg.imread('./test1.jpg')
myvid = 'project_video.mp4'
find_vehicles_in_video(myvid)
#new_img =find_vehicles_in_frame(myimage)
#plt.imsho... | output = "tracked2_" + video
input_clip = VideoFileClip(video)
clip = input_clip.fl_image(find_vehicles_in_frame)
#clip = input_clip.fl_image(save_image)
clip.write_videofile(output, audio=False) | identifier_body |
pipeline.py | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from skimage.feature import hog
from helper_func import *
from sklearn.model_selection import GridSearchCV
import pick... |
if history:
hist3 = history.popleft()
if history:
hist4 = history.popleft()
if history:
hist5 = history.popleft()
if history:
hist6 = history.popleft()
if history:
hist7 = history.popleft()
heat = hist1 + hist2 + hist3 + hist4 + hist5 + ... | hist2 = history.popleft() | conditional_block |
pipeline.py | import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from skimage.feature import hog
from helper_func import *
from sklearn.model_selection import GridSearchCV
import pick... |
#hot_windows = search_windows(image, windows, svc, X_scaler, color_space=color_space,
# spatial_size=spatial_size, hist_bins=hist_bins,
# orient=orient, pix_per_cell=pix_per_cell,
# cell_per_block=cell_per_block,
# hog_chan... | # image you are searching is a .jpg (scaled 0 to 255)
#image = image.astype(np.float32)/255
#windows = slide_window(image, x_start_stop=[None, None], y_start_stop=y_start_stop,
# xy_window=(96, 96), xy_overlap=(0.5, 0.5)) | random_line_split |
app.rs | use std::cell::RefCell;
use std::error;
use gio::{self, prelude::*};
use gtk::{self, prelude::*};
use crate::utils::*;
use crate::header_bar::*;
use crate::about_dialog::*;
#[derive(Clone)]
pub struct App {
main_window: gtk::ApplicationWindow,
pub header_bar: HeaderBar,
url_input: gtk::Entry
}
#[derive(... |
}
impl Action {
// The full action name as is used in e.g. menu models
pub fn full_name(self) -> &'static str {
match self {
Action::About => "app.about",
Action::Quit => "app.quit",
Action::ClickToggle(_) => "app.toggle",
}
}
// Create our applica... | {
eprintln!("Shutting down the whole thing");
} | identifier_body |
app.rs | use std::cell::RefCell;
use std::error;
use gio::{self, prelude::*};
use gtk::{self, prelude::*};
use crate::utils::*;
use crate::header_bar::*;
use crate::about_dialog::*;
#[derive(Clone)]
pub struct App {
main_window: gtk::ApplicationWindow,
pub header_bar: HeaderBar,
url_input: gtk::Entry
}
#[derive(... | let payload_row = gtk::Box::new(gtk::Orientation::Horizontal, 5);
payload_row.set_sensitive(false);
payload_row.add(&payload_title);
payload_row.pack_start(&payload_input, true, true, 0);
// when POST is selected, activate the payload input box
// TODO: why don't I need ... | let payload_title = gtk::Label::new(None);
payload_title.set_markup("<big>Payload</big>");
let payload_input = gtk::Entry::new();
payload_input.insert_text(r#"ex. {"k": "key","v": "val"}"#, &mut 0);
payload_input.set_sensitive(false); | random_line_split |
app.rs | use std::cell::RefCell;
use std::error;
use gio::{self, prelude::*};
use gtk::{self, prelude::*};
use crate::utils::*;
use crate::header_bar::*;
use crate::about_dialog::*;
#[derive(Clone)]
pub struct App {
main_window: gtk::ApplicationWindow,
pub header_bar: HeaderBar,
url_input: gtk::Entry
}
#[derive(... | (v: &glib::Variant) -> ToggleButtonState {
v.get::<bool>().expect("Invalid record state type").into()
}
}
impl From<bool> for ToggleButtonState {
fn from(v: bool) -> ToggleButtonState {
match v {
false => ToggleButtonState::State1,
true => ToggleButtonState::State2,
... | from | identifier_name |
footprint_analysis.rs | // BSD 2-Clause License
//
// Copyright (c) 2020 Alasdair Armstrong
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyrigh... |
}
impl Cacheable for Footprint {
type Key = Footprintkey;
}
impl Footprint {
fn new() -> Self {
Footprint {
write_data_taints: (HashSet::new(), false),
mem_addr_taints: (HashSet::new(), false),
branch_addr_taints: (HashSet::new(), false),
register_reads... | {
format!("opcode_{}", self.opcode)
} | identifier_body |
footprint_analysis.rs | // BSD 2-Clause License
//
// Copyright (c) 2020 Alasdair Armstrong
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyrigh... | <B: BV>(from: usize, to: usize, instrs: &[B], footprints: &HashMap<B, Footprint>) -> bool {
if from >= to {
return false;
}
let touched = touched_by(from, to, instrs, footprints);
for reg in &footprints.get(&instrs[to]).unwrap().write_data_taints.0 {
if touched.contains(reg) {
... | data_dep | identifier_name |
footprint_analysis.rs | // BSD 2-Clause License
//
// Copyright (c) 2020 Alasdair Armstrong
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyrigh... |
let to_footprint = footprints.get(&instrs[to]).unwrap();
to_footprint.is_exclusive && to_footprint.is_store
}
/// The set of registers that could be (syntactically) touched by the
/// first instruction before reaching the second.
#[allow(clippy::needless_range_loop)]
fn touched_by<B: BV>(
from: usize,
... | random_line_split | |
footprint_analysis.rs | // BSD 2-Clause License
//
// Copyright (c) 2020 Alasdair Armstrong
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyrigh... |
}
let to_footprint = footprints.get(&instrs[to]).unwrap();
to_footprint.is_exclusive && to_footprint.is_store
}
/// The set of registers that could be (syntactically) touched by the
/// first instruction before reaching the second.
#[allow(clippy::needless_range_loop)]
fn touched_by<B: BV>(
from: usi... | {
return false;
} | conditional_block |
express.js | // file: express.js
// start: node express.js
// install: npm i -S express
// to see: in browser, url=localhost:3000
// thx to https://flaviocopes.com/
/** Install
* -----------------
*
* npm init
* npm i -S express
* yarn init
* yarn add express
*/
const express = require('express');
const app = express();
v... | else {
callback(new Error('Not allowed by CORS'))
}
}
}
app.get('/with-cors', cors(corsOptions), (req, res, next) => {
res.json({ msg: 'WHOAH with CORS it works!' });
});
app.listen(3000, () => console.log('Server ready'))
};
eg9_prefligth = () => {
//al... | {
callback(null, true)
} | conditional_block |
express.js | // file: express.js
// start: node express.js
// install: npm i -S express
// to see: in browser, url=localhost:3000
// thx to https://flaviocopes.com/
/** Install
* -----------------
*
* npm init
* npm i -S express
* yarn init
* yarn add express
*/
const express = require('express');
const app = express();
v... | res.end()
});
app.listen(3000)
};
eg3_post_query = () => {
// for Content-Type: application/json
// if header =
app.use(express.json());
// for Content-Type: application/x-www-form-urlencoded
// if header =
app.use(express.urlencoded());
app.post('/form', (req, res) => {
... | console.log('--------------------') | random_line_split |
orchestrator.go | // Package orchestrator is an algorithm that manages the work of a cluster of
// nodes. It ensures each piece of work has a worker assigned to it.
//
// The Orchestrator stores a set of expected tasks. Each term, it reaches out
// to the cluster to gather what each node is working on. These tasks are
// called the actu... |
}
t := Task{Definition: taskDefinition, Instances: 1}
for _, opt := range opts {
opt(&t)
}
o.expectedTasks = append(o.expectedTasks, t)
}
// TaskOption is used to configure a task when it is being added.
type TaskOption func(*Task)
// WithTaskInstances configures the number of tasks. Defaults to 1.
func Wit... | {
return
} | conditional_block |
orchestrator.go | // Package orchestrator is an algorithm that manages the work of a cluster of
// nodes. It ensures each piece of work has a worker assigned to it.
//
// The Orchestrator stores a set of expected tasks. Each term, it reaches out
// to the cluster to gather what each node is working on. These tasks are
// called the actu... |
// ListExpectedTasks returns the current list of the expected tasks.
func (o *Orchestrator) ListExpectedTasks() []Task {
o.mu.Lock()
defer o.mu.Unlock()
return o.expectedTasks
}
// WorkerState stores the state of a worker.
type WorkerState struct {
Worker Worker
// Tasks are the task definitions the worker is ... | {
o.mu.Lock()
defer o.mu.Unlock()
o.expectedTasks = tasks
} | identifier_body |
orchestrator.go | // Package orchestrator is an algorithm that manages the work of a cluster of
// nodes. It ensures each piece of work has a worker assigned to it.
//
// The Orchestrator stores a set of expected tasks. Each term, it reaches out
// to the cluster to gather what each node is working on. These tasks are
// called the actu... | }
o.s(TermStats{
WorkerCount: len(actual),
})
}
// collectActual reaches out to each worker and gets their state of the world.
// Each worker is queried in parallel. If a worker returns an error while
// trying to list the tasks, it will be logged and not considered for what
// workers should be assigned work.
f... | history,
)
} | random_line_split |
orchestrator.go | // Package orchestrator is an algorithm that manages the work of a cluster of
// nodes. It ensures each piece of work has a worker assigned to it.
//
// The Orchestrator stores a set of expected tasks. Each term, it reaches out
// to the cluster to gather what each node is working on. These tasks are
// called the actu... | (x interface{}, y []interface{}) int {
for i, t := range y {
if t == x {
return i
}
}
return -1
}
// containsTask returns the index of the given task name in the tasks. If the
// task is not found, it returns -1.
func containsTask(task interface{}, tasks []Task) int {
for i, t := range tasks {
if t.Defin... | contains | identifier_name |
warnings.go | // Copyright 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.... | func isOldEnough(t time.Time, threshold time.Duration) bool {
return t.UTC().Add(threshold).Before(time.Now().UTC())
}
func completionWarning(credentials string, recommendedCompletionInterval time.Duration) string {
return fmt.Sprintf("the %s rotation initiation was finished more than %s ago and should be completed"... | }
return isOldEnough(lastInitiationFinishedTime.Time, threshold)
}
| random_line_split |
warnings.go | // Copyright 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.... | {
if !helper.IsWorkerless(shoot) && shoot.Spec.Kubernetes.KubeAPIServer != nil {
for _, plugin := range shoot.Spec.Kubernetes.KubeAPIServer.AdmissionPlugins {
if plugin.Name == "PodSecurityPolicy" && pointer.BoolDeref(plugin.Disabled, false) {
return ""
}
}
}
return "you should consider migrating to P... | identifier_body | |
warnings.go | // Copyright 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.... |
return warnings
}
func getWarningsForDueCredentialsRotations(shoot *core.Shoot, credentialsRotationInterval time.Duration) []string {
if !isOldEnough(shoot.CreationTimestamp.Time, credentialsRotationInterval) {
return nil
}
if shoot.Status.Credentials == nil || shoot.Status.Credentials.Rotation == nil {
ret... | {
warnings = append(warnings, fmt.Sprintf("annotation %v is deprecated. Use field `.spec.systemComponents.nodeLocalDNS.forceTCPToUpstreamDNS` in Shoot instead.", v1beta1constants.AnnotationNodeLocalDNSForceTcpToUpstreamDns))
} | conditional_block |
warnings.go | // Copyright 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.... | (shoot *core.Shoot, credentialsRotationInterval time.Duration) []string {
if !isOldEnough(shoot.CreationTimestamp.Time, credentialsRotationInterval) {
return nil
}
if shoot.Status.Credentials == nil || shoot.Status.Credentials.Rotation == nil {
return []string{"you should consider rotating the shoot credentials... | getWarningsForDueCredentialsRotations | identifier_name |
train_gcn.py | #Copyright (C) 2021 Fanwei Kong, Shawn C. Shadden, University of California, Berkeley
#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 req... |
unet_gcn.compile(optimizer=adam, loss=losses,loss_weights=loss_weights, metrics=metrics_losses)
""" Setup model checkpoint """
save_model_path = os.path.join(args.output, "weights_gcn.hdf5")
cp_cd = SaveModelOnCD(metric_key, save_model_path, patience=50)
lr_schedule = tf.keras.callbacks.ReduceLROnPlateau(monitor='... | loss_weights[0] = args.seg_weight | conditional_block |
train_gcn.py | #Copyright (C) 2021 Fanwei Kong, Shawn C. Shadden, University of California, Berkeley
#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 req... | """# Build the model"""
model = DeformNet(args.batch_size, img_shape, mesh_info, amplify_factor=args.amplify_factor,num_mesh=len(args.mesh_ids), num_seg=args.num_seg)
unet_gcn = model.build_keras()
unet_gcn.summary(line_length=150)
adam = Adam(lr=args.lr, beta_1=0.9, beta_2=0.999, epsilon=None, decay=1e-6, amsgrad=Tru... | num_train_examples = train_ds_num[np.argmax(train_data_weights)]/np.max(train_data_weights)
num_val_examples = val_ds_num[np.argmax(val_data_weights)]/np.max(val_data_weights)
print("Number of train, val samples after reweighting: ", num_train_examples, num_val_examples)
| random_line_split |
mod.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... | &self, new_origin: Vector3<f32>) {
self.origin.set(new_origin);
}
pub fn set_left_ear(&self, new_origin: Vector3<f32>) {
self.left_ear.set(new_origin);
}
pub fn set_right_ear(&self, new_origin: Vector3<f32>) {
self.right_ear.set(new_origin);
}
pub fn attenuate(
... | et_origin( | identifier_name |
mod.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... | };
use thiserror::Error;
use chrono::Duration;
pub const DISTANCE_ATTENUATION_FACTOR: f32 = 0.001;
const MAX_ENTITY_CHANNELS: usize = 128;
#[derive(Error, Debug)]
pub enum SoundError {
#[error("No such music track: {0}")]
NoSuchTrack(String),
#[error("I/O error: {0}")]
Io(#[from] io::Error),
#[err... | use cgmath::{InnerSpace, Vector3};
use rodio::{
source::{Buffered, SamplesConverter},
Decoder, OutputStreamHandle, Sink, Source, | random_line_split |
mod.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... |
pub fn start_sound(
&mut self,
src: AudioSource,
time: Duration,
ent_id: Option<usize>,
ent_channel: i8,
volume: f32,
attenuation: f32,
origin: Vector3<f32>,
listener: &Listener,
) {
let chan_id = self.find_free_channel(ent_id, ent... |
let mut oldest = 0;
for (i, channel) in self.channels.iter().enumerate() {
match *channel {
Some(ref chan) => {
// if this channel is free, return it
if !chan.channel.in_use() {
return i;
}
... | identifier_body |
mod.rs | // Copyright © 2018 Cormac O'Brien
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, ... |
// replace sounds on the same entity channel
if ent_channel != 0
&& chan.ent_id == ent_id
&& (chan.ent_channel == ent_channel || ent_channel == -1)
{
return i;
}
... |
return i;
}
| conditional_block |
dropck.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | // definition yields the instantiated assumptions:
//
// ['y : 'z]
//
// We then check all of the predicates of the Drop impl:
//
// ['y:'z, 'x:'y]
//
// and ensure each is in the list of instantiated
// assumptions. Here, `'y:'z` is present, but `'x:'y` is
// absent.... | // self_to_impl_substs = {'c => 'z, 'b => 'y, 'a => 'x}
//
// Applying this to the predicates (i.e. assumptions) provided by the item | random_line_split |
dropck.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
/// Confirms that every predicate imposed by dtor_predicates is
/// implied by assuming the predicates attached to self_type_did.
fn ensure_drop_predicates_are_implied_by_item_defn<'a, 'tcx>(
ccx: &CrateCtxt<'a, 'tcx>,
drop_impl_did: DefId,
dtor_predicates: &ty::GenericPredicates<'tcx>,
self_type_did:... | {
let tcx = ccx.tcx;
let drop_impl_node_id = tcx.map.as_local_node_id(drop_impl_did).unwrap();
let self_type_node_id = tcx.map.as_local_node_id(self_type_did).unwrap();
// check that the impl type can be made to match the trait type.
let impl_param_env = ty::ParameterEnvironment::for_item(tcx, sel... | identifier_body |
dropck.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | <'tcx> {
Overflow(TypeContext, ty::Ty<'tcx>),
}
#[derive(Copy, Clone)]
enum TypeContext {
Root,
ADT {
def_id: DefId,
variant: ast::Name,
field: ast::Name,
}
}
struct DropckContext<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> {
rcx: &'a mut RegionCtxt<'b, 'gcx, 'tcx>,
/// types ... | Error | identifier_name |
dropck.rs | // Copyright 2014-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
ty::TyTrait(..) | ty::TyProjection(..) | ty::TyAnon(..) => {
debug!("ty: {:?} isn't known, and therefore is a dropck type", ty);
true
},
_ => false
}
}
| {
def.is_dtorck(tcx)
} | conditional_block |
views.py | from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.db.models import Count
from django.db.models import F
from django.db import transaction
from bs4 import BeautifulSoup
from django.contrib.auth.decorators import login_required
from django.core.mail import send_m... | if ret: # 用户存在
auth.login(request, ret) # 当前登录对象
resopnse['user'] = user
else:
resopnse['msg'] = 'username or password is wromg!'
else:
resopnse['msg'] = 'valid code error!'
return JsonResponse(resopnse)
retur... | if validcode.upper() == valid_code.upper(): # 首先校验验证码,验证码不区分大小写
ret = auth.authenticate(username=user, password=pwd) | random_line_split |
views.py | from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.db.models import Count
from django.db.models import F
from django.db import transaction
from bs4 import BeautifulSoup
from django.contrib.auth.decorators import login_required
from django.core.mail import send_m... | .filter(user_id=user_id, article_id=article_id).first()
response = {'state': False, 'msg': None}
if not obj: # 该用户没对本文章进行操作
ArticleUpDown.objects.create(is_up=is_up, article_id=article_id, user_id=user_id)
queryset = Article.objects.filter(pk=article_id)
if is_up: # 更新文章的数据
... | render(request, 'article_detail.html', locals())
def digg(request):
"""
点赞
:param request:
:return:
"""
is_up = json.loads(request.POST.get('is_up')) # 反序列化
user_id = request.user.pk
article_id = request.POST.get('article_id')
obj = ArticleUpDown.objects | identifier_body |
views.py | from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.db.models import Count
from django.db.models import F
from django.db import transaction
from bs4 import BeautifulSoup
from django.contrib.auth.decorators import login_required
from django.core.mail import send_m... | ticle_edit(request, article_id):
"""
编辑修改某一篇文章
:param request:
:return:
"""
article_id = article_id
article_obj = Article.objects.filter(nid=article_id).first()
return render(request, 'article_edit.html', locals())
def article_update(request):
username = request.user.username
i... |
def ar | identifier_name |
views.py | from django.shortcuts import render, HttpResponse, redirect
from django.http import JsonResponse
from django.db.models import Count
from django.db.models import F
from django.db import transaction
from bs4 import BeautifulSoup
from django.contrib.auth.decorators import login_required
from django.core.mail import send_m... | conditional_block | ||
ui.rs | use failure::{bail, ensure, format_err, Error, Fallible};
use std::cell::{RefCell, RefMut};
use std::io::Read;
use std::rc::Rc;
use crate::terminal::{set_stdin_echo, TERMINAL_CLEAR_LINE};
use crate::util::to_hex_string;
use crate::{Reader, ReaderFactory, Writer};
const ERROR_VERBOSITY: i32 = -1;
const INTERACTIVE_VER... |
Ok(())
}
fn println_interactive(&self, message: &str) -> Fallible<()> {
if self.will_print(INTERACTIVE_VERBOSITY) {
writeln!(self.output.borrow_mut(), "{}", message)?;
}
Ok(())
}
fn println_progress(&self, verbosity: i32, message: &str, finish: bool) -> Fal... | {
writeln!(self.output.borrow_mut(), "{}: {}", self.program_name, err)?;
} | conditional_block |
ui.rs | use failure::{bail, ensure, format_err, Error, Fallible};
use std::cell::{RefCell, RefMut};
use std::io::Read;
use std::rc::Rc;
use crate::terminal::{set_stdin_echo, TERMINAL_CLEAR_LINE};
use crate::util::to_hex_string;
use crate::{Reader, ReaderFactory, Writer};
const ERROR_VERBOSITY: i32 = -1;
const INTERACTIVE_VER... |
pub fn expect_prompt(
self,
matcher: impl AsRef<str>,
reply: Result<impl AsRef<str>, Error>,
) -> Self {
self.prompt_replies.borrow_mut().push_back((
Some(matcher.as_ref().to_string()),
reply.map(|s| s.as_ref().to_string()... | {
TestUI {
..Default::default()
}
} | identifier_body |
ui.rs | use failure::{bail, ensure, format_err, Error, Fallible};
use std::cell::{RefCell, RefMut};
use std::io::Read;
use std::rc::Rc;
use crate::terminal::{set_stdin_echo, TERMINAL_CLEAR_LINE};
use crate::util::to_hex_string;
use crate::{Reader, ReaderFactory, Writer};
const ERROR_VERBOSITY: i32 = -1;
const INTERACTIVE_VER... | }
}
impl UI for TestUI {
fn set_verbosity(&mut self, _verbosity: i32) {}
fn set_progress_enabled(&mut self, _enabled: bool) {}
fn program_name(&self) -> &str {
"rypt"
}
// Write interface
fn will_print(&self, _verbosity: i32) -> bool {
... | }
printed_lines.extend(line_tuples);
Ok(()) | random_line_split |
ui.rs | use failure::{bail, ensure, format_err, Error, Fallible};
use std::cell::{RefCell, RefMut};
use std::io::Read;
use std::rc::Rc;
use crate::terminal::{set_stdin_echo, TERMINAL_CLEAR_LINE};
use crate::util::to_hex_string;
use crate::{Reader, ReaderFactory, Writer};
const ERROR_VERBOSITY: i32 = -1;
const INTERACTIVE_VER... | (&self) -> bool {
self.input.borrow().is_some()
&& self.input_is_tty
&& self.output_is_tty
&& self.will_print(INTERACTIVE_VERBOSITY)
}
fn read_prompt(&self, prompt: &str) -> Fallible<String> {
ensure!(self.can_read(), "Can't read from a non-TTY input");
... | can_read | identifier_name |
electronics.py | #! python3.4
from __future__ import division, print_function
import pygame as P
from random import randint, choice
from os.path import join
from functools import reduce
if __name__ == "__main__":
import sys
sys.path.append("..")
from vec2d import vec2d
from Engine.effects import repeated_surface as repeat... |
ys = min(levels)
ye = size[1]#max(levels)+chiplength
bar = repeat(tilemap["v"], (5, ye-ys+minstraight))
for x in barlines:
self.surface.blit(bar, (x-1, ys-minstraight))
######Chips######
[self.surface.blit(chip.surface, pos) for pos in self.chipposs]
... | self.surface.blit(bar, (xs-minstraight, y-1)) | conditional_block |
electronics.py | #! python3.4
from __future__ import division, print_function
import pygame as P
from random import randint, choice
from os.path import join
from functools import reduce
if __name__ == "__main__":
import sys
sys.path.append("..")
from vec2d import vec2d
from Engine.effects import repeated_surface as repeat... | def save_images(self):
for name, surface in self.tiles.items():
P.image.save(surface, "_test_"+name+".png")
def draw_line(self, surface, start, end):
dif_x = end[0]-start[0]
dif_y = end[1]-start[1]
if not abs(dif_x) == abs(dif_y) and dif_y and dif_x:
... |
def __getitem__(self, key):
return self.tiles[key]
| random_line_split |
electronics.py | #! python3.4
from __future__ import division, print_function
import pygame as P
from random import randint, choice
from os.path import join
from functools import reduce
if __name__ == "__main__":
import sys
sys.path.append("..")
from vec2d import vec2d
from Engine.effects import repeated_surface as repeat... |
class Fizzle():
"""electric fizzle on the Grid"""
def __init__(self, surface, connection, speed = 1):
self.connection = connection
self.surface = surface
self.pos = connection.start
self.direction = self.end-self.start
self.time = connection.time
class An... | def __init__(self, length, connector, innercolor = P.Color(50,50,50), deviation = 3, bordercolor = P.Color(150,150,150)):
size = length,length
rect = P.Rect((0,0), size)
innerrect = rect.inflate(-connector.indent*2,-connector.indent*2)
self.surface = P.Surface(size, flags = P.SR... | identifier_body |
electronics.py | #! python3.4
from __future__ import division, print_function
import pygame as P
from random import randint, choice
from os.path import join
from functools import reduce
if __name__ == "__main__":
import sys
sys.path.append("..")
from vec2d import vec2d
from Engine.effects import repeated_surface as repeat... | ():
def __init__(self, grid,amount, speed, color = (250,250,100)):
self.grid = grid
connections = []
for node in grid.nodes.values():
connections.extend(node.connections)
for c in connections:
c.direction.length = speed
c.scale_time(speed)... | AnimFizzle | identifier_name |
SL1_ImportData.py |
# Importing Data
'''
Description:
This file provide some function that are toe used for importing data .
Function this file Contains:
- ImportData: Used to import data either from BQ or from Storage.
'''
# ----------------------------------------------- Loading Libraries -------------------------------------... |
# -------------------------------------------------- ImportData --------------------------------------------------- #
def ImportData(config):
"""
Can be used to import data from either storage or BQ
Extracts any size data from any SID of any number of days.
Works in Two Configuration(c... | '''
Incase if dataset size is too large then this function will enable the extraction of whole dataset by getting the data in chunks
'''
# -----------<<< Setting constant values that are to be used inside function >>>----------- #
ModuleSetting = config['Config']['ModuleSettingRuleName']
BQ_Cred =... | identifier_body |
SL1_ImportData.py | # Importing Data
'''
Description:
This file provide some function that are toe used for importing data .
Function this file Contains:
- ImportData: Used to import data either from BQ or from Storage.
'''
# ----------------------------------------------- Loading Libraries --------------------------------------... | StaDataWindow = ast.literal_eval(config['IfStatic']['DataGrabWindow_Days'])
elif DataGrabMethodology == 'dynamic':
DynDataWindow = int(ast.literal_eval(config['IfDynamic']['DataGrabWindow_Hr']))
else:
txt = 'Exception: Wrong Configuration has been passed in "UseStaticOrDynamicCurrentDay"... | DataGrabMethodology = config['DomainConfig']['UseStaticOrDynamicCurrentDay']
LevBasedPrint('Inside "'+GenerateTableNames.__name__+'" function and configurations for this has been set.',3,1)
LevBasedPrint('Data collection methodology that has been selected : ' + str(DataGrabMethodology),3)
if DataGrabMet... | random_line_split |
SL1_ImportData.py |
# Importing Data
'''
Description:
This file provide some function that are toe used for importing data .
Function this file Contains:
- ImportData: Used to import data either from BQ or from Storage.
'''
# ----------------------------------------------- Loading Libraries -------------------------------------... | (config):
"""
Can be used to import data from either storage or BQ
Extracts any size data from any SID of any number of days.
Works in Two Configuration(config['IterationAim']['CycleType']), namely 'TrainTest' & 'GlTest'
'TrainTest' is for models training purpose where This Dataset is... | ImportData | identifier_name |
SL1_ImportData.py |
# Importing Data
'''
Description:
This file provide some function that are toe used for importing data .
Function this file Contains:
- ImportData: Used to import data either from BQ or from Storage.
'''
# ----------------------------------------------- Loading Libraries -------------------------------------... |
except Exception as error:
txt = 'Exception: In importing data from BQ was thrown!\nLimit used: ' + str(i) + '\n' + str(error)
LevBasedPrint(txt, 2)
AddRecommendation(txt, config)
# raise Exception(txt)
# ----------------------------... | LevBasedPrint('Setting used in extracting data from BQ:\tNo. of obs. extracted per cycle (limit) = ' + str(i) + '\tOffset = ' + str(offcurr),2)
QueryToUse = query.format(BinToUse = GroupsToInclude, TableToInclude = TableToInclude, lim = str(i), off = str(offcurr))
tempDF = Exec_B... | conditional_block |
resnet.rs | use plant::*;
use std::{rc::Rc, time::Instant, env, cmp::Ordering::*};
macro_rules! read { ($s: expr, $($arg:tt)*) => { ArrayInit::Data(&std::fs::read(&format!(concat!("resnet_data/", $s), $($arg)*)).unwrap()) }; }
type M = Slice<u8, usize>;
static TILE_MAP: [([u32; 6], [u32; 12]); 26] = [
// resnet18, 34
([3, 6... | pl Fn(M), M) {
let expansion = if bottleneck { 4 } else { 1 };
let mut layers = Vec::with_capacity(blocks as _);
layers.push(block(inplanes, planes, size, stride, bottleneck));
for _ in 1..blocks {
layers.push(block(planes * expansion, planes, size / stride, 1, bottleneck));
}
let b = layers.last().unwr... | > (im | identifier_name |
resnet.rs | use plant::*;
use std::{rc::Rc, time::Instant, env, cmp::Ordering::*};
macro_rules! read { ($s: expr, $($arg:tt)*) => { ArrayInit::Data(&std::fs::read(&format!(concat!("resnet_data/", $s), $($arg)*)).unwrap()) }; }
type M = Slice<u8, usize>;
static TILE_MAP: [([u32; 6], [u32; 12]); 26] = [
// resnet18, 34
([3, 6... | let b_init = f.comp("B_init", x![chan,], x!(0));
let b = f.comp("B", x![chan, size, size], x!(a(i0, i1, i2) + buf_b(i0)));
let b_final = f.comp("B_final", x![chan,], x!(buf_b(i0) / ((size * size))));
b_init.before(b, 1).before(b_final, 1);
b_init.store(buf_b);
b.store_at(buf_b, x![i0,]);
b_final.store(buf... | let f = Func::new("avgpool");
let a = f.buf("A", F32, In, x![chan, size, size]);
let buf_b = f.buf("B", F32, Out, x![chan,]); | random_line_split |
resnet.rs | use plant::*;
use std::{rc::Rc, time::Instant, env, cmp::Ordering::*};
macro_rules! read { ($s: expr, $($arg:tt)*) => { ArrayInit::Data(&std::fs::read(&format!(concat!("resnet_data/", $s), $($arg)*)).unwrap()) }; }
type M = Slice<u8, usize>;
static TILE_MAP: [([u32; 6], [u32; 12]); 26] = [
// resnet18, 34
([3, 6... | let (f1, b1) = conv(inplanes, planes, size, 1, stride, 0, 0, 1);
let (f2, b2) = conv(planes, planes, size / stride, 3, 1, 1, 0, 1);
let (f3, b3) = conv(planes, planes * expansion, size / stride, 1, 1, 0, 1, 1);
let f4 = if downsample { Some(conv(inplanes, planes * expansion, size, 1, stride, 0, 0, 0)) } els... | conditional_block | |
resnet.rs | use plant::*;
use std::{rc::Rc, time::Instant, env, cmp::Ordering::*};
macro_rules! read { ($s: expr, $($arg:tt)*) => { ArrayInit::Data(&std::fs::read(&format!(concat!("resnet_data/", $s), $($arg)*)).unwrap()) }; }
type M = Slice<u8, usize>;
static TILE_MAP: [([u32; 6], [u32; 12]); 26] = [
// resnet18, 34
([3, 6... | ol) -> (impl Fn(M), M) {
let expansion = if bottleneck { 4 } else { 1 };
let mut layers = Vec::with_capacity(blocks as _);
layers.push(block(inplanes, planes, size, stride, bottleneck));
for _ in 1..blocks {
layers.push(block(planes * expansion, planes, size / stride, 1, bottleneck));
}
let b = layers.l... | anes != planes * expansion;
if bottleneck {
let (f1, b1) = conv(inplanes, planes, size, 1, stride, 0, 0, 1);
let (f2, b2) = conv(planes, planes, size / stride, 3, 1, 1, 0, 1);
let (f3, b3) = conv(planes, planes * expansion, size / stride, 1, 1, 0, 1, 1);
let f4 = if downsample { Some(conv(inplanes, pl... | identifier_body |
ClassifierAdapter.py | import subprocess
import time
from random import random, randint, randrange
import uuid
from bertopic import BERTopic
import numpy as np
from BuisnessLayer.AnalysisManager.DataObjects import AnalyzedTweet, Claim
import pandas as pd
import nltk
# nltk.download('vader_lexicon')
from nltk.sentiment.vader import SentimentI... | (self,text):
emo = te.get_emotion(text)
return max(emo, key=emo.get) # The output we received,
def _trends_to_csv(self, trends_dict, path="C:/fake-news-framework_Py3/data/input/tryout/"):
topics = []
tweets = []
authors = []
topic_tweet_connection = []
for ... | get_emotion | identifier_name |
ClassifierAdapter.py | import subprocess
import time
from random import random, randint, randrange
import uuid
from bertopic import BERTopic
import numpy as np
from BuisnessLayer.AnalysisManager.DataObjects import AnalyzedTweet, Claim
import pandas as pd
import nltk
# nltk.download('vader_lexicon')
from nltk.sentiment.vader import SentimentI... |
def _trends_to_csv(self, trends_dict, path="C:/fake-news-framework_Py3/data/input/tryout/"):
topics = []
tweets = []
authors = []
topic_tweet_connection = []
for trend in trends_dict.keys():
for topic in trends_dict[trend].claims:
topics.append(... | emo = te.get_emotion(text)
return max(emo, key=emo.get) # The output we received, | identifier_body |
ClassifierAdapter.py | import subprocess
import time
from random import random, randint, randrange
import uuid
from bertopic import BERTopic
import numpy as np
from BuisnessLayer.AnalysisManager.DataObjects import AnalyzedTweet, Claim
import pandas as pd
import nltk
# nltk.download('vader_lexicon')
from nltk.sentiment.vader import SentimentI... |
time.sleep(1)
results['pred'] = results['pred'].apply(lambda x:"True" if x else "Fake")
return callback(processed_data, trends_dict,results)
def analyze_snopes(self, data, callback): # data is type of dict {<claim name> : list <tweets>}
# print(data)
# processed_data = {}... | print("start trend {}".format(trend))
if trend not in processed_data:
processed_data[trend] = list()
for topic in trends_dict[trend].claims:
tweets = list()
for tweet in topic.tweets:
rand = randrange(100)
if... | conditional_block |
ClassifierAdapter.py | import subprocess
import time
from random import random, randint, randrange
import uuid
from bertopic import BERTopic
import numpy as np
from BuisnessLayer.AnalysisManager.DataObjects import AnalyzedTweet, Claim
import pandas as pd
import nltk
# nltk.download('vader_lexicon')
from nltk.sentiment.vader import SentimentI... | results['pred'] = results['pred'].apply(lambda x:"True" if x else "Fake")
return callback(processed_data, trends_dict,results)
def analyze_snopes(self, data, callback): # data is type of dict {<claim name> : list <tweets>}
# print(data)
# processed_data = {}
# for key in da... | time.sleep(1) | random_line_split |
MapScreen.js | import React, { Component } from 'react';
import { FlatList, SafeAreaView, Dimensions, StyleSheet, View, Image, TextInput, Modal } from 'react-native';
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { Marker } from "react-native-maps";
import { Text } from ... | () {
const { modalVisible } = this.state;
let button;
button=
<TouchableOpacity style={Buttons.brownbuttonSmall}
onPress={() => this.setModalVisible(!modalVisible)}>
<Text style={{color:'white', alignSelf: "center"}}>Save</Text>
</TouchableOpacity>
return (
<V... | render | identifier_name |
MapScreen.js | import React, { Component } from 'react';
import { FlatList, SafeAreaView, Dimensions, StyleSheet, View, Image, TextInput, Modal } from 'react-native';
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { Marker } from "react-native-maps";
import { Text } from ... | <Text style={styles.pathTitle}>{item.name}</Text>
<Text style={styles.detailsTwo}>{item.description}</Text>
</TouchableOpacity>
)}
keyExtractor={item => (item.id).toString()}
/>
</SafeAreaView>
</View>
</View>
);
}
}
const styles = ... | data={this.state.walks}
renderItem={({item}) => (
<TouchableOpacity style={styles.item}
onPress={() => this.setPremadePath(item)}> | random_line_split |
MapScreen.js | import React, { Component } from 'react';
import { FlatList, SafeAreaView, Dimensions, StyleSheet, View, Image, TextInput, Modal } from 'react-native';
import MapView from 'react-native-maps';
import MapViewDirections from 'react-native-maps-directions';
import { Marker } from "react-native-maps";
import { Text } from ... |
else{
this.setState({
startValue:'Start'
});
this.mapView.fitToCoordinates(this.state.initialCoords,{
edgePadding: {
right: width,
bottom: height,
left: width,
top: height
}
}
);
}
}
// Saves user's walks to da... | {
this.setState({
startValue:'Stop'
});
this.mapView.fitToCoordinates(this.state.forZoom.coordinates,{
edgePadding: {
right: (width / 10),
bottom: (height / 20),
left: (width / 10),
top: (height / 20),
}
}
);
} | conditional_block |
yolov5_trt12.py | """
An example that uses TensorRT's Python api to make inferences.
"""
import ctypes
import os
import random
import sys
import threading
import time
import cv2
import numpy as np
import tensorrt as trt
import torch
import torchvision
from trt_lite2 import TrtLite
INPUT_W = 256
INPUT_H = 256
CONF_THRESH = 0.1
IOU_TH... | shape)
print(io_info)
d_buffers = trt_engine.allocate_io_buffers(i2shape, True)
print(io_info[1][2])
d_buffers[0] = data.cuda()
bindings = [t.data_ptr() for t in d_buffers]
# 进行推理
trt_engine.execute(bindings, i2shape)
#
output_data_trt = d_buff... | ine.get_io_info(i2 | identifier_name |
yolov5_trt12.py | """
An example that uses TensorRT's Python api to make inferences.
"""
import ctypes
import os
import random
import sys
import threading
import time
import cv2
import numpy as np
import tensorrt as trt
import torch
import torchvision
from trt_lite2 import TrtLite
INPUT_W = 256
INPUT_H = 256
CONF_THRESH = 0.1
IOU_TH... | = trt_engine.get_io_info(i2shape)
print(io_info)
d_buffers = trt_engine.allocate_io_buffers(i2shape, True)
print(io_info[1][2])
d_buffers[0] = data.cuda()
bindings = [t.data_ptr() for t in d_buffers]
# 进行推理
trt_engine.execute(bindings, i2shape)
#
... | e preprocess
input_image, image_raw, origin_h, origin_w = self.preprocess_image(image_path)
self.buffers[0] = torch.from_numpy(input_image.ravel()).cuda()
bindings = [t.data_ptr() for t in self.buffers]
self.trt_yolo.execute(bindings, BATCH_SIZE)
host_outputs = self.buffers[... | identifier_body |
yolov5_trt12.py | """
An example that uses TensorRT's Python api to make inferences.
"""
import ctypes
import os
import random
import sys
import threading
import time
import cv2
import numpy as np
import tensorrt as trt
import torch
import torchvision
from trt_lite2 import TrtLite
INPUT_W = 256
INPUT_H = 256
CONF_THRESH = 0.1
IOU_TH... | image_raw = cv2.imread(input_image_path)
h, w, c = image_raw.shape
image = cv2.cvtColor(image_raw, cv2.COLOR_BGR2RGB)
# Calculate widht and height and paddings
r_w = INPUT_W / w
r_h = INPUT_H / h
if r_h > r_w:
tw = INPUT_W
th = int(r_w * h)... | image_raw: the original image
h: original height
w: original width
""" | random_line_split |
yolov5_trt12.py | """
An example that uses TensorRT's Python api to make inferences.
"""
import ctypes
import os
import random
import sys
import threading
import time
import cv2
import numpy as np
import tensorrt as trt
import torch
import torchvision
from trt_lite2 import TrtLite
INPUT_W = 256
INPUT_H = 256
CONF_THRESH = 0.1
IOU_TH... |
draw_bd_handpose(img, pts_hand, 0, 0) # 绘制关键点连线
# ------------- 绘制关键点
for i in range(int(outputs.shape[0] / 2)):
x = (outputs[i * 2 + 0] * float(img_width))
y = (outputs[i * 2 + 1] * float(img_height))
cv2.circle(img, (int(x), int(y)), 3, (255, 50, 60), -1)
cv2.circle(img... | x = (outputs[i * 2 + 0] * float(img_width))
y = (outputs[i * 2 + 1] * float(img_height))
pts_hand[str(i)] = {}
pts_hand[str(i)] = {
"x": x,
"y": y,
} | conditional_block |
game.js | var Game = function(cid, w, h, callback){
var that = this;
var txtColor = "#333"; //default text color
var fps = 30;
// add event listeners, this will store key pressed on key down in an array and remove on keyup
document.addEventListener('keydown', function(e){
var key = e.keyCode;
var index = that.keysPress... | ;
var Level = function(game, s){
/***********************/
/* level class
/***********************/
// map array. This is a 2d array of tiles generated from the platform
// groups created in this.init(). Format = [0,0,0,0,0,1,1,1,1...]
var map = [];
var tileGroup = Math.floor(Math.random() * 2); // d... | { // x, y, sx, sy,
this.s = sprite;
this.frame = 0; // start frame
// movement tick
this.xtick = 0;
this.ytick = 0;
// variables to restrict movement to given platform
// xs = xStart, xe = xEnd. They correspond to tile
// start and tile end positions
this.xs = typeof(group[0]) !== 'number' ? group[... | identifier_body |
game.js | var Game = function(cid, w, h, callback){
var that = this;
var txtColor = "#333"; //default text color
var fps = 30;
// add event listeners, this will store key pressed on key down in an array and remove on keyup
document.addEventListener('keydown', function(e){
var key = e.keyCode;
var index = that.keysPress... | that.cx.fillStyle=txtColor;
that.cx.font = "48px verdana";
that.cx.fillText("Game Over", that.w/2, that.h/2 - 100);
that.cx.font = "16px verdana";
that.cx.fillText("You completed " + (that.currLevel - 1) + " levels in " + (totalTime/1000).toFixed(2) + " seconds.", that.w/2, that.h/2 -50);
that.c... | var scoreMsg = score > 0 ? ". Well done." : ". Opps, better luck next time."
| random_line_split |
game.js | var Game = function(cid, w, h, callback){
var that = this;
var txtColor = "#333"; //default text color
var fps = 30;
// add event listeners, this will store key pressed on key down in an array and remove on keyup
document.addEventListener('keydown', function(e){
var key = e.keyCode;
var index = that.keysPress... | (game, group, sprite){ // x, y, sx, sy,
this.s = sprite;
this.frame = 0; // start frame
// movement tick
this.xtick = 0;
this.ytick = 0;
// variables to restrict movement to given platform
// xs = xStart, xe = xEnd. They correspond to tile
// start and tile end positions
this.xs = typeof(group[0]) ... | Enemy | identifier_name |
game.js | var Game = function(cid, w, h, callback){
var that = this;
var txtColor = "#333"; //default text color
var fps = 30;
// add event listeners, this will store key pressed on key down in an array and remove on keyup
document.addEventListener('keydown', function(e){
var key = e.keyCode;
var index = that.keysPress... | else{
// check collision with object h and object e
var abs = Math.abs;
return (abs(h.x - e.x) * 2 < (1)) && (abs(h.y - e.y) * 2 < (1));
}
};
this.update = function(i){
// add interval to all ticks
this.xTick += i;
this.yTick += i;
this.fireTick += i;
// check if any relevant keys ar... | {
var yBelow = Math.ceil(that.y)-1;
var xBelow1 = Math.floor(that.x);
var xBelow2 = Math.ceil(that.x);
// check collision with tiles below
// and on either side of hero
var tileBelow1 = game.levelObj.getTile(xBelow1, yBelow);
var tileBelow2 = game.levelObj.getTile(xBelow2, yBelow);
if(... | conditional_block |
terminal.rs | use crate::os_glue::Glue;
use crate::{Features, Key, TermOut};
use stakker::{fwd, timer_max, Fwd, MaxTimerKey, Share, CX};
use std::error::Error;
use std::mem;
use std::panic::PanicInfo;
use std::sync::Arc;
use std::time::Duration;
/// Actor that manages the connection to the terminal
pub struct Terminal {
resize:... | termout: Share<TermOut>,
glue: Glue,
disable_output: bool,
paused: bool,
inbuf: Vec<u8>,
check_enable: bool,
force_timer: MaxTimerKey,
check_timer: MaxTimerKey,
cleanup: Vec<u8>,
panic_hook: Arc<Box<dyn Fn(&PanicInfo<'_>) + 'static + Sync + Send>>,
}
impl Terminal {
/// Set ... | random_line_split | |
terminal.rs | use crate::os_glue::Glue;
use crate::{Features, Key, TermOut};
use stakker::{fwd, timer_max, Fwd, MaxTimerKey, Share, CX};
use std::error::Error;
use std::mem;
use std::panic::PanicInfo;
use std::sync::Arc;
use std::time::Duration;
/// Actor that manages the connection to the terminal
pub struct Terminal {
resize:... |
/// Resume terminal output and input handling. Switches to raw
/// mode and sends a resize message to trigger a full redraw.
pub fn resume(&mut self, cx: CX![]) {
if self.paused {
self.paused = false;
self.glue.input(true);
self.termout.rw(cx).discard();
... | {
if !self.paused {
fwd!([self.resize], None);
self.glue.input(false);
self.termout.rw(cx).discard();
self.termout.rw(cx).bytes(&self.cleanup[..]);
self.termout.rw(cx).flush();
self.flush(cx);
self.paused = true;
sel... | identifier_body |
terminal.rs | use crate::os_glue::Glue;
use crate::{Features, Key, TermOut};
use stakker::{fwd, timer_max, Fwd, MaxTimerKey, Share, CX};
use std::error::Error;
use std::mem;
use std::panic::PanicInfo;
use std::sync::Arc;
use std::time::Duration;
/// Actor that manages the connection to the terminal
pub struct Terminal {
resize:... | (&mut self, cx: CX![]) {
if !self.paused {
fwd!([self.resize], None);
self.glue.input(false);
self.termout.rw(cx).discard();
self.termout.rw(cx).bytes(&self.cleanup[..]);
self.termout.rw(cx).flush();
self.flush(cx);
self.paused ... | pause | identifier_name |
terminal.rs | use crate::os_glue::Glue;
use crate::{Features, Key, TermOut};
use stakker::{fwd, timer_max, Fwd, MaxTimerKey, Share, CX};
use std::error::Error;
use std::mem;
use std::panic::PanicInfo;
use std::sync::Arc;
use std::time::Duration;
/// Actor that manages the connection to the terminal
pub struct Terminal {
resize:... |
}
/// Resume terminal output and input handling. Switches to raw
/// mode and sends a resize message to trigger a full redraw.
pub fn resume(&mut self, cx: CX![]) {
if self.paused {
self.paused = false;
self.glue.input(true);
self.termout.rw(cx).discard();
... | {
fwd!([self.resize], None);
self.glue.input(false);
self.termout.rw(cx).discard();
self.termout.rw(cx).bytes(&self.cleanup[..]);
self.termout.rw(cx).flush();
self.flush(cx);
self.paused = true;
self.update_panic_hook();
... | conditional_block |
importNet.js | import _ from 'lodash';
import config from 'grafana/app/core/config';
import locationUtil from '../utils/location_util';
const appCtrl = require('../utils/appCtrl');
const Influx = require('../utils/Influx');
import * as $ from 'jquery';
//const url = "http://localhost:8086/query?db=mydb&q=SELECT+value,region+FROM+cpu... | se if (!inputModel.info) {
inputModel.info = 'Select a ' + input.pluginName + ' data source';
}
inputModel.options = sources.map(val => {
return { text: val.name, value: val.name };
});
}
inputValueChanged() {
this.inputsValid = true;
... | inputModel.info = 'No data sources of type ' + input.pluginName + ' found';
} el | conditional_block |
importNet.js | import _ from 'lodash';
import config from 'grafana/app/core/config';
import locationUtil from '../utils/location_util';
const appCtrl = require('../utils/appCtrl');
const Influx = require('../utils/Influx');
import * as $ from 'jquery';
//const url = "http://localhost:8086/query?db=mydb&q=SELECT+value,region+FROM+cpu... |
this.hasNameValidationError = true;
this.nameValidationError = err.message;
});
}
uidChanged(initial) {
this.uidExists = false;
this.hasUidValidationError = false;
if (initial === true && this.dash.uid) {
... | random_line_split | |
importNet.js | import _ from 'lodash';
import config from 'grafana/app/core/config';
import locationUtil from '../utils/location_util';
const appCtrl = require('../utils/appCtrl');
const Influx = require('../utils/Influx');
import * as $ from 'jquery';
//const url = "http://localhost:8086/query?db=mydb&q=SELECT+value,region+FROM+cpu... |
setDatasourceOptions(input, inputModel) {
const sources = _.filter(config.datasources, val => {
return val.type === input.pluginId;
});
if (sources.length === 0) {
inputModel.info = 'No data sources of type ' + input.pluginName + ' found';
} else i... | this.network = net; //per l'html
//riceverò sempre una net, gli devo aggiungere il template della dashboard
ImportNetCtrl.initProbs(net);
structure.title = net.rete;
structure.network = net; //attacco il pezzo che ricevo al template
console.info("onUpload Rete: ");
... | identifier_body |
importNet.js | import _ from 'lodash';
import config from 'grafana/app/core/config';
import locationUtil from '../utils/location_util';
const appCtrl = require('../utils/appCtrl');
const Influx = require('../utils/Influx');
import * as $ from 'jquery';
//const url = "http://localhost:8086/query?db=mydb&q=SELECT+value,region+FROM+cpu... | {
return this.inputsValid && this.folderId !== null;
}
saveDashboard() {
const inputs = this.inputs.map(input => {
return {
name: input.name,
type: input.type,
pluginId: input.pluginId,
value: input.value,
... | alid() | identifier_name |
dataset_RAF.py | import warnings
warnings.filterwarnings('ignore', category=FutureWarning)
from cv2 import cv2
from tqdm import tqdm
import os
import pickle
import numpy as np
import csv
import sys
from collections import defaultdict
from dataset_utils import *
sys.path.append("../training")
from dataset_tools import enclosing_square... | (gender):
if gender == 'male':
return LABELS["gender"]["male"]
elif gender == 'female':
return LABELS["gender"]["female"]
return MASK_VALUE
def get_age_group_label(age_group_text):
return rafdb_labels["age_group"][age_group_text]
def get_ethnicity_label(ethnicity_text):
return rafd... | get_gender_label | identifier_name |
dataset_RAF.py | import warnings
warnings.filterwarnings('ignore', category=FutureWarning)
from cv2 import cv2
from tqdm import tqdm
import os
import pickle
import numpy as np
import csv
import sys
from collections import defaultdict
from dataset_utils import *
sys.path.append("../training")
from dataset_tools import enclosing_square... |
def test_multi(dataset="test", debug_samples=None):
if dataset.startswith("train") or dataset.startswith("val"):
print(dataset, debug_samples if debug_samples is not None else '')
dt = RAFDBMulti(dataset,
target_shape=(112, 112, 3),
preprocessing='... | def __init__(self,
partition='train',
imagesdir='data/RAF-DB/basic/Image/{aligned}',
csvmeta='data/RAF-DB/basic/multitask/{part}.multitask_rafdb.csv',
target_shape=(112, 112, 3),
augment=True,
custom_augmentation=None,
... | identifier_body |
dataset_RAF.py | import warnings
warnings.filterwarnings('ignore', category=FutureWarning)
from cv2 import cv2
from tqdm import tqdm
import os
import pickle
import numpy as np
import csv
import sys
from collections import defaultdict
from dataset_utils import *
sys.path.append("../training")
from dataset_tools import enclosing_square... | output_dict[row[0]]["gender"] = row[1]
output_dict[row[0]]["age_group"] = row[2]
output_dict[row[0]]["race"] = row[3]
output_dict[row[0]]["emotion"] = row[4]
output_dict[row[0]]["identity"] = row[0].split("_")[1]
def get_partition(identity_label):
global rafDBpartition
... | def _load_meta_from_csv(csv_meta, output_dict):
data = readcsv(csv_meta)
for row in data: | random_line_split |
dataset_RAF.py | import warnings
warnings.filterwarnings('ignore', category=FutureWarning)
from cv2 import cv2
from tqdm import tqdm
import os
import pickle
import numpy as np
import csv
import sys
from collections import defaultdict
from dataset_utils import *
sys.path.append("../training")
from dataset_tools import enclosing_square... |
# Labelling
def get_gender_label(gender):
if gender == 'male':
return LABELS["gender"]["male"]
elif gender == 'female':
return LABELS["gender"]["female"]
return MASK_VALUE
def get_age_group_label(age_group_text):
return rafdb_labels["age_group"][age_group_text]
def get_ethnicity_lab... | print("Gender errors", errors["gender"])
print("Age errors", errors["age"])
print("Ethnicity errors", errors["ethnicity"]) | conditional_block |
mod.rs | //! GPU acceleration for BLAKE3.
//!
//! This module allows accelerating a [`Hasher`] through SPIR-V shaders.
//!
//! [`Hasher`]: ../struct.Hasher.html
use super::*;
use core::mem;
use core::ops::{Deref, DerefMut};
use core::slice;
/// Control uniform for the BLAKE3 shader.
///
/// This uniform contains the informati... | ///
/// [`update`]: #method.update
/// [`update_with_join`]: #method.update_with_join
/// [`GpuControl`]: struct.GpuControl.html
pub fn update_from_gpu<J: Join>(&mut self, chunk_count: u64, parents: &mut [u8]) -> &mut Self {
assert_eq!(self.chunk_state.len(), 0, "leftover buffered bytes");
... | /// same as the chunk counter in the [`GpuControl`] passed to the shader,
/// otherwise it will lead to a wrong hash output.
///
/// Note: on a big-endian host, this method will swap the endianness of the
/// shader output in-place. | random_line_split |
mod.rs | //! GPU acceleration for BLAKE3.
//!
//! This module allows accelerating a [`Hasher`] through SPIR-V shaders.
//!
//! [`Hasher`]: ../struct.Hasher.html
use super::*;
use core::mem;
use core::ops::{Deref, DerefMut};
use core::slice;
/// Control uniform for the BLAKE3 shader.
///
/// This uniform contains the informati... |
/// Returns the SPIR-V code for the chunk shader module.
#[cfg(target_endian = "little")]
pub fn chunk_shader() -> &'static [u8] {
include_bytes!("shaders/blake3-chunk-le.spv")
}
/// Returns the SPIR-V code for the parent shader module.
pub fn parent_shader... | {
include_bytes!("shaders/blake3-chunk-be.spv")
} | identifier_body |
mod.rs | //! GPU acceleration for BLAKE3.
//!
//! This module allows accelerating a [`Hasher`] through SPIR-V shaders.
//!
//! [`Hasher`]: ../struct.Hasher.html
use super::*;
use core::mem;
use core::ops::{Deref, DerefMut};
use core::slice;
/// Control uniform for the BLAKE3 shader.
///
/// This uniform contains the informati... | (&self) -> u8 {
self.d as u8
}
/// Returns the bytes to be copied to the control uniform in the GPU.
///
/// The contents of the returned slice are opaque and should be interpreted
/// only by the shader.
#[inline]
pub fn as_bytes(&self) -> &[u8] {
// According to the specif... | flags | identifier_name |
transfer_leads.py | import json
from simple_salesforce import Salesforce
import os
import boto3
import datetime
def lambda_handler(event, context):
#gathers JSON file from S3 that was posted from Chrome River SFDC via the transfer_leads_trigger lambda function
bucket = event['Records'][0]['s3']['bucket']['name']
key = event... | (lead_dict):
cr_industry = lead_dict.get('Industry')
cert_industry = lead_dict.get('Industry')
if(cr_industry == 'Accounting'):
cert_industry = 'Business Services'
elif(cr_industry == 'Advertising'):
cert_industry = 'Business Services'
elif(cr_industry == 'Apparel'):
cert_ind... | standardize_industry | identifier_name |
transfer_leads.py | import json
from simple_salesforce import Salesforce
import os
import boto3
import datetime
def lambda_handler(event, context):
#gathers JSON file from S3 that was posted from Chrome River SFDC via the transfer_leads_trigger lambda function
bucket = event['Records'][0]['s3']['bucket']['name']
key = event... |
return cert_state
def _publish_alert(alert_message):
data = {'message':alert_message}
json_data = json.dumps(data)
sns = boto3.client('sns')
sns.publish(
TopicArn='arn:aws:sns:us-east-1:374175877904:hamster_alerts',
Message=str(json_data))
| cert_state = None | conditional_block |
transfer_leads.py | import json
from simple_salesforce import Salesforce
import os
import boto3
import datetime
def lambda_handler(event, context):
#gathers JSON file from S3 that was posted from Chrome River SFDC via the transfer_leads_trigger lambda function
bucket = event['Records'][0]['s3']['bucket']['name']
key = event... |
def standardize_state(lead_dict):
cert_country = lead_dict.get('Country')
cr_state = lead_dict.get('State')
cert_state = lead_dict.get('State')
if(cert_country == 'Australia'):
if(cr_state == 'Brisbane'):
cert_state = 'Queensland'
if(cert_country == 'China'):
if(cr_stat... | cr_country = lead_dict.get('Country')
cert_country = lead_dict.get('Country')
if(cr_country == 'Bolivia'):
cert_country = 'Bolivia, Plurinational State of'
elif(cr_country == 'Iran'):
cert_country = 'Iran, Islamic Republic of'
elif(cr_country == 'North Korea'):
cert_country = 'Ko... | identifier_body |
transfer_leads.py | import json
from simple_salesforce import Salesforce
import os
import boto3
import datetime
def lambda_handler(event, context):
#gathers JSON file from S3 that was posted from Chrome River SFDC via the transfer_leads_trigger lambda function
bucket = event['Records'][0]['s3']['bucket']['name']
key = event... | cert_country = 'Saint Martin (French part)'
elif(cr_country == 'Macedonia'):
cert_country = 'Greece'
elif(cr_country == 'Russia'):
cert_country = 'Russian Federation'
elif(cr_country == 'Saint Helena'):
cert_country = 'Saint Helena, Ascension and Tristan da Cunha'
elif(cr... | random_line_split | |
caclient.go | /*
Copyright: Cognition Foundry. All Rights Reserved.
License: Apache License Version 2.0
*/
package gohfc
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
)
// CAClient is common interface for Certificate authority services.
type CACl... | (identity *Identity, request []byte) (string, error) {
encPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: identity.Certificate.Raw})
encCert := base64.StdEncoding.EncodeToString(encPem)
body := base64.StdEncoding.EncodeToString(request)
sigString := body + "." + encCert
sig, err := f.Crypto.Sign(... | createAuthToken | identifier_name |
caclient.go | /*
Copyright: Cognition Foundry. All Rights Reserved.
License: Apache License Version 2.0
*/
package gohfc
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
)
// CAClient is common interface for Certificate authority services.
type CACl... |
return result, nil
}
// Enroll execute enrollment request for registered user in fabric-ca server.
// On success new Identity with ECert is returned
func (f *FabricCAClientImpl) Enroll(enrollmentId, password string) (*Identity, []byte, error) {
if len(enrollmentId) < 1 {
return nil, nil, ErrEnrollmentIdMissing
}... | {
return nil, err
} | conditional_block |
caclient.go | /*
Copyright: Cognition Foundry. All Rights Reserved.
License: Apache License Version 2.0
*/
package gohfc
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
)
// CAClient is common interface for Certificate authority services.
type CACl... | resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
enrResp := new(enrollmentResponse)
if err := json.Unmarshal(body, enrResp); err != nil {
return nil, err
}
if !enrResp.Success {
return n... | random_line_split | |
caclient.go | /*
Copyright: Cognition Foundry. All Rights Reserved.
License: Apache License Version 2.0
*/
package gohfc
import (
"bytes"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"fmt"
"io/ioutil"
"net/http"
)
// CAClient is common interface for Certificate authority services.
type CACl... |
// NewFabricCAClient creates new FabricCAClientImpl
func NewCAClient(path string, transport *http.Transport) (CAClient, error) {
config,err:=NewCAConfig(path)
if err!=nil{
return nil,err
}
var crypto CryptoSuite
switch config.CryptoConfig.Family {
case "ecdsa":
crypto, err = NewECCryptSuiteFromConfig(conf... | {
encPem := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: identity.Certificate.Raw})
encCert := base64.StdEncoding.EncodeToString(encPem)
body := base64.StdEncoding.EncodeToString(request)
sigString := body + "." + encCert
sig, err := f.Crypto.Sign([]byte(sigString), identity.PrivateKey)
if err != n... | identifier_body |
machine_amd64.go | // Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | () error {
var (
kernelSystemRegs systemRegs
kernelUserRegs userRegs
)
// Set base control registers.
kernelSystemRegs.CR0 = c.CR0()
kernelSystemRegs.CR4 = c.CR4()
kernelSystemRegs.EFER = c.EFER()
// Set the IDT & GDT in the registers.
kernelSystemRegs.IDT.base, kernelSystemRegs.IDT.limit = c.IDT()
ker... | initArchState | identifier_name |
machine_amd64.go | // Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
// If tsc scaling is not supported, fallback to legacy mode.
if !c.machine.tscControl {
return c.setSystemTimeLegacy()
}
// First, scale down the clock frequency to the lowest value allowed by
// the API itself. How low we can go depends on the underlying
// hardware, but it is typically ~1/2^48 for Intel, ... | {
return err
} | conditional_block |
machine_amd64.go | // Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... | } else {
info.Code = 2 // SEGV_ACCERR.
}
return accessType, platform.ErrContextSignal
}
//go:nosplit
//go:noinline
func loadByte(ptr *byte) byte {
return *ptr
}
// SwitchToUser unpacks architectural-details.
func (c *vCPU) SwitchToUser(switchOpts ring0.SwitchOpts, info *linux.SignalInfo) (hostarch.AccessType, e... | }
}
if !accessType.Write && !accessType.Execute {
info.Code = 1 // SEGV_MAPERR. | random_line_split |
machine_amd64.go | // Copyright 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agree... |
func (m *machine) mapUpperHalf(pageTable *pagetables.PageTables) {
// Map all the executable regions so that all the entry functions
// are mapped in the upper half.
if err := applyVirtualRegions(func(vr virtualRegion) {
if excludeVirtualRegion(vr) || vr.filename == "[vsyscall]" {
return
}
if vr.accessTy... | {
// Check for canonical addresses.
if regs := switchOpts.Registers; !ring0.IsCanonical(regs.Rip) {
return nonCanonical(regs.Rip, int32(unix.SIGSEGV), info)
} else if !ring0.IsCanonical(regs.Rsp) {
return nonCanonical(regs.Rsp, int32(unix.SIGBUS), info)
} else if !ring0.IsCanonical(regs.Fs_base) {
return nonC... | identifier_body |
main.py | '''
2D Coupled Burgers' system model
===
Distributed by: Notre Dame CICS (MIT Liscense)
- Associated publication:
url: http://www.sciencedirect.com/science/article/pii/S0021999119307612
doi: https://doi.org/10.1016/j.jcp.2019.109056
github: https://github.com/cics-nd/ar-pde-cnn
===
'''
from args import Parser
from nn.d... |
input = input[:,-2*int(args.nic-1):,:].detach()
input0 = uPred.detach()
input = torch.cat([input, input0], dim=1)
return u_out, u_target
def testSample(args, swag_nn, test_loader, tstep=100, n_samples=10, test_every=2):
'''
Tests the samples of the Bayesi... | u_out[bidx*mb_size:(bidx+1)*mb_size, (t_idx+1)//test_every,:,:,:] = uPred | conditional_block |
main.py | '''
2D Coupled Burgers' system model
===
Distributed by: Notre Dame CICS (MIT Liscense)
- Associated publication:
url: http://www.sciencedirect.com/science/article/pii/S0021999119307612
doi: https://doi.org/10.1016/j.jcp.2019.109056
github: https://github.com/cics-nd/ar-pde-cnn
===
'''
from args import Parser
from nn.d... | init_features=args.init_features,
bn_size=args.bn_size,
drop_rate=args.drop_rate,
bottleneck=False,
out_activation=None).to(args.device)
# Bayesian neural network
bayes_nn = BayesNN(args, den... | blocks=args.blocks,
growth_rate=args.growth_rate, | random_line_split |
main.py | '''
2D Coupled Burgers' system model
===
Distributed by: Notre Dame CICS (MIT Liscense)
- Associated publication:
url: http://www.sciencedirect.com/science/article/pii/S0021999119307612
doi: https://doi.org/10.1016/j.jcp.2019.109056
github: https://github.com/cics-nd/ar-pde-cnn
===
'''
from args import Parser
from nn.d... |
if __name__ == '__main__':
# Parse arguements
args = Parser().parse()
use_cuda = "cpu"
if(torch.cuda.is_available()):
use_cuda = "cuda"
args.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
print("Torch device:{}".format(args.device))
# Domain settings,... | '''
Tests the samples of the Bayesian SWAG model
Args:
args (argparse): object with programs arguements
model (PyTorch model): DenseED model to be tested
test_loader (dataloader): dataloader with test cases (use createTestingLoader)
tstep (int): number of timesteps to predict for... | identifier_body |
main.py | '''
2D Coupled Burgers' system model
===
Distributed by: Notre Dame CICS (MIT Liscense)
- Associated publication:
url: http://www.sciencedirect.com/science/article/pii/S0021999119307612
doi: https://doi.org/10.1016/j.jcp.2019.109056
github: https://github.com/cics-nd/ar-pde-cnn
===
'''
from args import Parser
from nn.d... | (args, model, burgerInt, train_loader, optimizer, tsteps, tback, tstart, dt=0.1):
'''
Trains the model
Args:
args (argparse): object with programs arguements
model (PyTorch model): SWAG DenseED model to be tested
burgerInt (BurgerIntegrate): 1D Burger system time integrator
t... | train | identifier_name |
index.js | const Discord = require('discord.js');
const config = require('./config.json');
const nodemailer = require("nodemailer");
const showdown = require('showdown');
const randtoken = require('rand-token');
const Keyv = require('keyv');
const crypto = require('crypto');
const os = require("os");
const hostname = os.hostname... | const welcomeMsg = (guildName) => `Hello! I see you just joined the server **${guildName}**.
You are currently not verified as an ETH student on **${guildName}**, so you only have access to a restricted number of channels.
To verify yourself as an ETH student,
1. please tell me your nethz (i.e ETH username) in the fo... | random_line_split | |
index.js | const Discord = require('discord.js');
const config = require('./config.json');
const nodemailer = require("nodemailer");
const showdown = require('showdown');
const randtoken = require('rand-token');
const Keyv = require('keyv');
const crypto = require('crypto');
const os = require("os");
const hostname = os.hostname... |
}
} else if (command === 'mark') {
if (!args.length) {
return message.channel.send(`You didn't provide any nethz! Usage: e.g \`!mark ${sampleNethz}\``);
} else if (args.length > 1) {
return message.channel.send(`You provided too many arguments... Usage: e.g \`!mark ${sampleNethz}\``);
} else {
... | {
await verifiedNethzHashs.delete(nethzHash);
return message.channel.send(`Unmarked nethz ${nethz} as "already used for verification".`);
} | conditional_block |
index.js | const Discord = require('discord.js');
const config = require('./config.json');
const nodemailer = require("nodemailer");
const showdown = require('showdown');
const randtoken = require('rand-token');
const Keyv = require('keyv');
const crypto = require('crypto');
const os = require("os");
const hostname = os.hostname... | (mention) {
// The id is the first and only match found by the RegEx.
const matches = mention.match(/^<@!?(\d+)>$/);
// If supplied variable was not a mention, matches will be null instead of an array.
if (!matches) return;
// However the first element in the matches array will be the entire mention, not just the ... | getUserFromMention | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.