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 |
|---|---|---|---|---|
script.js |
var width = 818,
height = 800;
var svg = d3.select("#map")
.append("svg")
.attr("width", width)
.attr("height", height - 150);
var tiler = d3.geo.tile()
.size([width, height - 200]);
var vector;
var map = dc.geoChoroplethChart(svg); //focus chart
// var timeline = dc... | (evt) {
var oldFilterMetric = filterMetric;
filterMetric = evt.target.id;
if (filterMetric !== "mhi" && filterMetric !== "mgr") {
filterYear = +(filterMetric.split("_")[1]);
filterMetric = oldFilterMetric;
metricChange(true);
var titleMetric = maptitle.innerHTML.split(" ").slice(0, 3);
titleMe... | clickedOn | identifier_name |
script.js |
var width = 818,
height = 800;
var svg = d3.select("#map")
.append("svg")
.attr("width", width)
.attr("height", height - 150);
var tiler = d3.geo.tile()
.size([width, height - 200]);
var vector;
var map = dc.geoChoroplethChart(svg); //focus chart
// var timeline = dc... |
function sort_group(group, order) {
return {
all: function() {
var g = group.all(), map = {};
g.forEach(function(kv) {
map[kv.key] = kv.value;
});
return order.map(function(k) {
return {key: k, value: map[k]};
});
... | {
if (error)
throw error;
sf_topojson = topojson.feature(tracts, tracts.objects.sf).features;
filterMetric = "mgr";
filterYear = 2014;
svg.style("stroke", "black").style("fill", "lightgrey").style("stroke-width", "1px");
var dateFormat;
data.forEach(function(d) {
dateFormat = d3.time.format('%Y... | identifier_body |
script.js | var width = 818,
height = 800;
var svg = d3.select("#map")
.append("svg")
.attr("width", width)
.attr("height", height - 150);
var tiler = d3.geo.tile()
.size([width, height - 200]);
var vector;
var map = dc.geoChoroplethChart(svg); //focus chart
// var timeline = dc.... | return +d.mgr;
}
});
return year_grouped;
}
function metricYearChange_map() {
var metric_grouped = tractDim.group(function(id) { return id;}).reduce(
function(p, v) {
if (v.year.getFullYear() === filterYear) {
p.mhi += +v.mhi;
p.mgr += +v.mgr;
p.year = v.ye... | } else { //default on mgr | random_line_split |
step4_fit_prior_fast.py | '''STEP 4 fit a deep empirical Bayes prior model via SGD.
Builds an empirical Bayes model to predict the prior over the dose-response
mean-effect curve.
TODO: Generative model description.
We use a neural network to model, trained with stochastic gradient descent.
The features are the mutation, copy number, and gene... | print('3', loss)
print('3 nans: {}'.format(np.isnan(loss.data.numpy()).sum()))
return loss
def fit_mu(self, verbose=False, **kwargs):
self.models = []
self.train_folds = []
self.validation_folds = []
for fold_idx, fold in enumerate(self.folds):
if... | print('2 nans: {}'.format(np.isnan(loss.data.numpy()).sum()))
print()
print('shape', loss.shape)
loss = loss.sum(dim=1) / self.tObsMask[tidx].max(dim=-1).values.sum(dim=-1) | random_line_split |
step4_fit_prior_fast.py | '''STEP 4 fit a deep empirical Bayes prior model via SGD.
Builds an empirical Bayes model to predict the prior over the dose-response
mean-effect curve.
TODO: Generative model description.
We use a neural network to model, trained with stochastic gradient descent.
The features are the mutation, copy number, and gene... | (self, X):
fwd = self.fc_in(X).reshape(-1, self.ndrugs, self.ndoses)
# Enforce monotonicity
mu = torch.cat([fwd[:,:,0:1], fwd[:,:,0:1] + self.softplus(fwd[:,:,1:]).cumsum(dim=2)], dim=2)
# Do we want gradients or just predictions?
if self.training:
# Reparameterizat... | forward | identifier_name |
step4_fit_prior_fast.py | '''STEP 4 fit a deep empirical Bayes prior model via SGD.
Builds an empirical Bayes model to predict the prior over the dose-response
mean-effect curve.
TODO: Generative model description.
We use a neural network to model, trained with stochastic gradient descent.
The features are the mutation, copy number, and gene... | for j in range(5):
ebo._predict_mu_insample(0,i,j) | conditional_block | |
step4_fit_prior_fast.py | '''STEP 4 fit a deep empirical Bayes prior model via SGD.
Builds an empirical Bayes model to predict the prior over the dose-response
mean-effect curve.
TODO: Generative model description.
We use a neural network to model, trained with stochastic gradient descent.
The features are the mutation, copy number, and gene... |
if __name__ == '__main__':
import matplotlib
matplotlib.use('Agg')
import matplotlib.pylab as plt
import argparse
parser = argparse.ArgumentParser(description='Deep empirical Bayes dose-response model fitting.')
# Experiment settings
parser.add_argument('name', default='gdsc', help='The... | print('Loading genomic features')
X = load_dataset(genomic_features, index_col=0)
# Remove any features not specified (this is useful for ablation studies)
for ftype in ['MUT', 'CNV', 'EXP', 'TISSUE']:
if ftype not in feature_types:
select = [c for c in X.columns if not c.startswith(fty... | identifier_body |
simulating_agent_model_2D.py | # Author : Ali Snedden
# Date : 4/12/20
# License: MIT
# Purpose:
# This code attmpts to follow https://www.youtube.com/watch?v=gxAaO2rsdIs and try to
# mimic his plots
#
#
# Notes :
#
# References :
# 1. https://idi.osu.edu/assets/pdfs/covid_response_white_paper.pdf
# 2. https://mbi.osu.edu/events/... | (Agent1=None, Agent2=None):
"""
ARGS:
RETURN:
DESCRIPTION:
Gives displacement between two agents.
DEBUG:
FUTURE:
"""
if(type(Agent1) == AGENT):
x1=Agent1.posL[0]
y1=Agent1.posL[1]
elif(type(Agent1) == list):
x1=Agent1[0]
y1=Agent1[1]
else:
... | displacement | identifier_name |
simulating_agent_model_2D.py | # Author : Ali Snedden
# Date : 4/12/20
# License: MIT
# Purpose:
# This code attmpts to follow https://www.youtube.com/watch?v=gxAaO2rsdIs and try to
# mimic his plots
#
#
# Notes :
#
# References :
# 1. https://idi.osu.edu/assets/pdfs/covid_response_white_paper.pdf
# 2. https://mbi.osu.edu/events/... |
### With many root solvers, it requires that f(a)*f(b) < 0. However,
### fsolve doesn't care. It just needs bounds to look
xroots = optimize.fsolve(f, [xc-r, xc+r])
# If there are two roots, which do i pick? Pick closest to Agent
if(len(... | y = m*x+b
return( (x-xc)**2 + (y-yc)**2 - r**2) | identifier_body |
simulating_agent_model_2D.py | # Author : Ali Snedden
# Date : 4/12/20
# License: MIT
# Purpose:
# This code attmpts to follow https://www.youtube.com/watch?v=gxAaO2rsdIs and try to
# mimic his plots
#
#
# Notes :
#
# References :
# 1. https://idi.osu.edu/assets/pdfs/covid_response_white_paper.pdf | #
#
#
import sys
import numpy as np
import time
import pandas as pd
from matplotlib import pyplot as plt
from matplotlib.patches import Circle
from error import exit_with_error
from scipy import optimize
import random
random.seed(42) # Change later
from classes import AGENT
def print_help(ExitCode):
"""
... | # 2. https://mbi.osu.edu/events/seminar-grzegorz-rempala-mathematical-models-epidemics-tracking-coronavirus-using-dynamic
#
# Future: | random_line_split |
simulating_agent_model_2D.py | # Author : Ali Snedden
# Date : 4/12/20
# License: MIT
# Purpose:
# This code attmpts to follow https://www.youtube.com/watch?v=gxAaO2rsdIs and try to
# mimic his plots
#
#
# Notes :
#
# References :
# 1. https://idi.osu.edu/assets/pdfs/covid_response_white_paper.pdf
# 2. https://mbi.osu.edu/events/... |
startTime = time.time()
print("{} \n".format(sys.argv),flush=True)
print(" Start Time : {}".format(time.strftime("%a, %d %b %Y %H:%M:%S ",
time.localtime())),flush=True)
### Parameters to Change
N = 200 # Number of Agents
nDays = 100 ... | quarantine = True | conditional_block |
dashapp.py | # -*- coding: utf-8 -*-
import os
import sys
import glob
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import ujson
import xlrd
import plotly.graph_objects as go
import time
from scipy.signal import ... | fit_name = 'fitted_data\\fitted_' + excel_file[5:] + '.json'
print(fit_name)
if fit_name in dir_fit_files:
return 'Fit available. Automatically choosing the fit file', fit_name, True
else:
return 'Fit not available. Press fit now to fit this new file. Then refresh page to see the fitted ... | [Input('select_excel','value')]
)
def fit_file(excel_file): | random_line_split |
dashapp.py | # -*- coding: utf-8 -*-
import os
import sys
import glob
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import ujson
import xlrd
import plotly.graph_objects as go
import time
from scipy.signal import ... | (x,a1,c1,w1,a2,c2,w2,a3,c3,w3):
""" For fitting three gaussian peaks """
return gaussian(x,a1,c1,w1)+gaussian(x,a2,c2,w2)+gaussian(x,a3,c3,w3)
# No need to re-run this again if data.json is already built
def fit_and_write_json(excel_file):
"""
This function reads upon the excel file data and writes jso... | gauss3 | identifier_name |
dashapp.py | # -*- coding: utf-8 -*-
import os
import sys
import glob
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import ujson
import xlrd
import plotly.graph_objects as go
import time
from scipy.signal import ... |
# Stack with the cummulative y built till now
else:
y = np.hstack((y, df_data.to_numpy()))
# Ideally x_array should be (481, 1), and y should be (481, 169)
return x_array, y
def gaussian(x, amp, cen, width):
"""1-d gaussian: gaussian(x, amp, cen, width... | y = df_data.to_numpy() | conditional_block |
dashapp.py | # -*- coding: utf-8 -*-
import os
import sys
import glob
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import ujson
import xlrd
import plotly.graph_objects as go
import time
from scipy.signal import ... |
def gauss2(x,a1,c1,w1,a2,c2,w2):
""" For fitting two gaussian peaks """
return gaussian(x,a1,c1,w1)+gaussian(x,a2,c2,w2)
def gauss3(x,a1,c1,w1,a2,c2,w2,a3,c3,w3):
""" For fitting three gaussian peaks """
return gaussian(x,a1,c1,w1)+gaussian(x,a2,c2,w2)+gaussian(x,a3,c3,w3)
# No need to re-run this a... | """1-d gaussian: gaussian(x, amp, cen, width)
x: independent variable
amp: amplitude/height of the curve
cen: mean or peak position
width: standard deviation/ spread of the curve
"""
return (amp / (np.sqrt(2*np.pi) * width)) * np.exp(-(x-cen)**2 / (2*width**2)) | identifier_body |
warm_start.py | # %%
import numpy as np
from numpy import sin, cos, pi
import gym
import seagul.envs
from seagul.integration import rk4,euler
from control import lqr, ctrb
from torch.multiprocessing import Pool
import matplotlib.pyplot as plt
import matplotlib
#matplotlib.use('Qt5Agg')
import time
global_start = time.time()
# %%
... |
for i in range(env.num_steps):
actions = np.clip(np.asarray(control(obs)), -max_torque, max_torque)
obs, reward, done, _ = env.step(actions)
local_reward_hist[i, :] = np.copy(reward)
if done:
break
return local_reward_hist, i
# %%b
start = time.time()
config = {"i... | x, trial_num = args
th1, th2, dth1, dth2 = x
np.random.seed(trial_num)
local_reward_hist = np.ones((env.num_steps, 1)) * -1
obs = env.reset(init_vec=[th1, th2, dth1, dth2]) | random_line_split |
warm_start.py | # %%
import numpy as np
from numpy import sin, cos, pi
import gym
import seagul.envs
from seagul.integration import rk4,euler
from control import lqr, ctrb
from torch.multiprocessing import Pool
import matplotlib.pyplot as plt
import matplotlib
#matplotlib.use('Qt5Agg')
import time
global_start = time.time()
# %%
... |
def do_rollout(trial_num):
np.random.seed(trial_num)
act_hold = 20
hold_count = 0
obs = env.reset()
local_lqr = False
actions = np.random.randn(1) * 3
local_state_hist = np.zeros((env.num_steps, env.observation_space.shape[0]))
local_reward_hist = np.zeros((env.num_steps, 1))
l... | reward = np.sin(s[0]) + 2 * np.sin(s[0] + s[1])
return reward, False | identifier_body |
warm_start.py | # %%
import numpy as np
from numpy import sin, cos, pi
import gym
import seagul.envs
from seagul.integration import rk4,euler
from control import lqr, ctrb
from torch.multiprocessing import Pool
import matplotlib.pyplot as plt
import matplotlib
#matplotlib.use('Qt5Agg')
import time
global_start = time.time()
# %%
... |
preds = sig(net(coords.reshape(-1, 4)).reshape(n_th, n_th).detach())
end = time.time()
print(end - start)
fig, ax = plt.subplots(n_thdot, n_thdot, figsize=(8, 8))
# generate 2 2d grids for the x & y bounds
x, y = np.meshgrid(th1dot_vals, th2dot_vals)
z = preds
# x and y are bounds, so z should be the value *inside... | coords[j, i, :] = np.array([pi/2, 0, th1dot_vals[i], th2dot_vals[j]]) | conditional_block |
warm_start.py | # %%
import numpy as np
from numpy import sin, cos, pi
import gym
import seagul.envs
from seagul.integration import rk4,euler
from control import lqr, ctrb
from torch.multiprocessing import Pool
import matplotlib.pyplot as plt
import matplotlib
#matplotlib.use('Qt5Agg')
import time
global_start = time.time()
# %%
... | (q):
gs = np.array([pi / 2, 0, 0, 0])
return -k.dot(q - gs)
def reward_fn(s, a):
reward = np.sin(s[0]) + 2 * np.sin(s[0] + s[1])
done = reward < 2
return reward, done
def do_rollout(args):
x, trial_num = args
th1, th2, dth1, dth2 = x
np.random.seed(trial_num)
local_reward_hist = ... | control | identifier_name |
fetch.rs | use futures::{
future,
sync::{mpsc, oneshot},
};
use crate::msg;
use flatbuffers::FlatBufferBuilder;
use crate::js::*;
use crate::runtime::{Runtime, EVENT_LOOP};
use crate::utils::*;
use libfly::*;
use crate::errors::{FlyError, FlyResult};
use crate::get_next_stream_id;
use hyper::body::Payload;
use hyper:... |
pub fn op_http_response(rt: &mut Runtime, base: &msg::Base, raw: fly_buf) -> Box<Op> {
debug!("handling http response");
let msg = base.msg_as_http_response().unwrap();
let req_id = msg.id();
let status = match StatusCode::from_u16(msg.status()) {
Ok(s) => s,
Err(e) => return odd_futu... | {
let cmd_id = base.cmd_id();
let msg = base.msg_as_http_request().unwrap();
let url = msg.url().unwrap();
if url.starts_with("file://") {
return file_request(rt, cmd_id, url);
}
let ptr = rt.ptr;
let req_id = msg.id();
let http_uri: hyper::Uri = match url.parse() {
O... | identifier_body |
fetch.rs | use futures::{
future,
sync::{mpsc, oneshot},
};
use crate::msg;
use flatbuffers::FlatBufferBuilder;
use crate::js::*;
use crate::runtime::{Runtime, EVENT_LOOP};
use crate::utils::*;
use libfly::*;
use crate::errors::{FlyError, FlyResult};
use crate::get_next_stream_id;
use hyper::body::Payload;
use hyper:... | status: res.status.as_u16(),
has_body: res.body.is_some(),
..Default::default()
},
);
if let Some(stream) = res.body {
send_body_stream(ptr, req_id, stream);
}
Ok(serialize_respons... | headers: Some(res_headers), | random_line_split |
fetch.rs | use futures::{
future,
sync::{mpsc, oneshot},
};
use crate::msg;
use flatbuffers::FlatBufferBuilder;
use crate::js::*;
use crate::runtime::{Runtime, EVENT_LOOP};
use crate::utils::*;
use libfly::*;
use crate::errors::{FlyError, FlyResult};
use crate::get_next_stream_id;
use hyper::body::Payload;
use hyper:... | (rt: &mut Runtime, base: &msg::Base, raw: fly_buf) -> Box<Op> {
debug!("handling http response");
let msg = base.msg_as_http_response().unwrap();
let req_id = msg.id();
let status = match StatusCode::from_u16(msg.status()) {
Ok(s) => s,
Err(e) => return odd_future(format!("{}", e).into(... | op_http_response | identifier_name |
treeFactory.js | const data = {
name: '地点',
id: '1',
children: [{
name: '欧洲游',
id: '11',
children: [{
name: '挪威游',
id: '111'
}, {
name: '冰岛游',
id: '112'
}]
}, {
name: '北美游',
id: '12',
children: [{
name: '美国游',
id: '121',
children: [{
name: '加州游',
... | ata;
this.initRoot(data);
this.initSVG();
if (this.root) {
this.render(this.root)
}
}
/************************************************************
* 初始化root
************************************************************/
initRoot() {
const root = d3.hierarchy(this.data).count();
... | /
init(data) {
this.data = d | identifier_body |
treeFactory.js | const data = {
name: '地点',
id: '1',
children: [{
name: '欧洲游',
id: '11',
children: [{
name: '挪威游',
id: '111'
}, {
name: '冰岛游',
id: '112'
}]
}, {
name: '北美游',
id: '12',
children: [{
name: '美国游',
id: '121',
children: [{
name: '加州游',
... | **************************************************/
// 节点点击事件
handleNodeClick(d) {
// toggle toolkit
this.toggleToolkit(d);
this.render(d);
}
// 编辑
handleEditClick(d) {
const editFnArr = this.eventEmitter.edit;
if (editFnArr) {
editFnArr.forEach(fn => fn.call(null, d))
}
}
/... | ****** | identifier_name |
treeFactory.js | const data = {
name: '地点',
id: '1',
children: [{
name: '欧洲游',
id: '11',
children: [{
name: '挪威游',
id: '111'
}, {
name: '冰岛游',
id: '112'
}]
}, {
name: '北美游',
id: '12',
children: [{
name: '美国游',
id: '121',
children: [{
name: '加州游',
... | ************************************************************/
// 节点点击事件
handleNodeClick(d) {
// toggle toolkit
this.toggleToolkit(d);
this.render(d);
}
// 编辑
handleEditClick(d) {
const editFnArr = this.eventEmitter.edit;
if (editFnArr) {
editFnArr.forEach(fn => fn.call(null, d))
... | }
}
/************************************************************
* 事件处理函数,可提取出去 | random_line_split |
treeFactory.js | const data = {
name: '地点',
id: '1',
children: [{
name: '欧洲游',
id: '11',
children: [{
name: '挪威游',
id: '111'
}, {
name: '冰岛游',
id: '112'
}]
}, {
name: '北美游',
id: '12',
children: [{
name: '美国游',
id: '121',
children: [{
name: '加州游',
... | = d3.hierarchy(this.data).count();
root.x0 = dy / 2;
root.y0 = 0;
root.descendants().forEach((d, i) => {
d.id = d.data.id ? d.data.id : i;
d._children = d.children;
});
this.root = root;
}
/************************************************************
* 初始化SVG
**************... | ***/
initRoot() {
const root | conditional_block |
SpinConfig.py | #!/usr/bin/env python
# Copyright (c) 2015 SpinPunch. All rights reserved.
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file.
import re, os
import time, calendar, urllib
import SpinJSON
# regular expression that matches C++-style comments (see gamedata/preprocess.p... | config = load(os.path.join(gameserver_dir(), 'config.json'))
def reload():
# reload config file
global config
try:
new_config = load(os.path.join(gameserver_dir(), 'config.json'))
config = new_config
except:
pass
# return identifier for this game (e.g. "mf" or "tr")
def game(ov... | e = os.getenv('SPIN_GAMESERVER')
if e: return e
return '../gameserver'
# global, used by code that imports SpinConfig | random_line_split |
SpinConfig.py | #!/usr/bin/env python
# Copyright (c) 2015 SpinPunch. All rights reserved.
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file.
import re, os
import time, calendar, urllib
import SpinJSON
# regular expression that matches C++-style comments (see gamedata/preprocess.p... |
# global, used by code that imports SpinConfig
config = load(os.path.join(gameserver_dir(), 'config.json'))
def reload():
# reload config file
global config
try:
new_config = load(os.path.join(gameserver_dir(), 'config.json'))
config = new_config
except:
pass
# return identif... | e = os.getenv('SPIN_GAMESERVER')
if e: return e
return '../gameserver' | identifier_body |
SpinConfig.py | #!/usr/bin/env python
# Copyright (c) 2015 SpinPunch. All rights reserved.
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file.
import re, os
import time, calendar, urllib
import SpinJSON
# regular expression that matches C++-style comments (see gamedata/preprocess.p... | (dbname, cfg):
dbname = cfg.get('dbname', dbname)
if 'credentials' in cfg:
username, password = get_credentials(cfg['credentials'])
else:
username = cfg['username']
password = cfg['password']
port = cfg.get('port',5432)
table_prefix = cfg.get('table_prefix', '')
return {'... | parse_pgsql_config | identifier_name |
SpinConfig.py | #!/usr/bin/env python
# Copyright (c) 2015 SpinPunch. All rights reserved.
# Use of this source code is governed by an MIT-style license that can be
# found in the LICENSE file.
import re, os
import time, calendar, urllib
import SpinJSON
# regular expression that matches C++-style comments (see gamedata/preprocess.p... |
ret += '%02dm%02ds' % (m, sec)
return ret
# find current PvP season/week/day based on gamedata
# "seasons" = gamedata['matchmaking']['season_starts']
# t = time you want to find the season for
def get_pvp_season(seasons, t):
for i in xrange(len(seasons)):
if seasons[i] > t:
return i
... | ret += '%02dh' % h | conditional_block |
chaintool.py | import time, os, hashlib, threading, socket, select
from ecdsa import SigningKey, VerifyingKey, NIST384p
ips=['127.0.0.1','192.168.1.132', '68.4.20.23']
ports=[19200]#, 19201] # a common baud rate XD
node_limit=20
hashrate=0
can_mine=False
save_main=False# save main blockchain?
save_sub=False # save daughter blocks?
fu... | self.inUse=True
else:
info(" Node discovered: "+ip+':'+str(port))
self.inUse=False
if running_node:
self.inUse=True # stop polling processes
self.avsend(b'IAMNODE')
self.conn.recv(2)
self.inUse=False... | if self.conn.recv(4).decode()!='OK':
error(str(ip)+" is not a node.")
self.conn.close() | random_line_split |
chaintool.py | import time, os, hashlib, threading, socket, select
from ecdsa import SigningKey, VerifyingKey, NIST384p
ips=['127.0.0.1','192.168.1.132', '68.4.20.23']
ports=[19200]#, 19201] # a common baud rate XD
node_limit=20
hashrate=0
can_mine=False
save_main=False# save main blockchain?
save_sub=False # save daughter blocks?
fu... | (cs, ip):
global solved, ls_sub_blk
index=0
while True:
data=b''
length=0
try:
tmp=cs.recv(8)
if not tmp:
break
elif tmp==b'PING':
data=b'PING'
else:
length= int.from_bytes(tmp,'little')
... | client_thread | identifier_name |
chaintool.py | import time, os, hashlib, threading, socket, select
from ecdsa import SigningKey, VerifyingKey, NIST384p
ips=['127.0.0.1','192.168.1.132', '68.4.20.23']
ports=[19200]#, 19201] # a common baud rate XD
node_limit=20
hashrate=0
can_mine=False
save_main=False# save main blockchain?
save_sub=False # save daughter blocks?
fu... |
class Client():
def __init__(self, ip, port):
self.ip=ip
info("Connecting to "+str(ip)+':'+str(port)+"...")
self.conn=socket.socket()
self.conn.connect((ip, port))
self.conn.sendall(b"PING")
if self.conn.recv(4).decode()!='OK':
error(str(ip)+" is not a no... | global running_node, cs_list
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# bind the socket to a public host, and a well-known port
try:
s.bind(('', port))
info("Node on port "+str(port)+" started.")
running_node=True
except:
error("Cannot run 2 nodes on same mac... | identifier_body |
chaintool.py | import time, os, hashlib, threading, socket, select
from ecdsa import SigningKey, VerifyingKey, NIST384p
ips=['127.0.0.1','192.168.1.132', '68.4.20.23']
ports=[19200]#, 19201] # a common baud rate XD
node_limit=20
hashrate=0
can_mine=False
save_main=False# save main blockchain?
save_sub=False # save daughter blocks?
fu... |
elif data==b"GBLK":
info("["+ip+"] Block requested.")
if len(blocks)>index:
chunk=blocks[index].pack()
else:
chunk=b"NONE"
reply=chunk
reply=len(reply).to_bytes(8, 'little')+reply
elif data[:4]==b'FSB?':
... | data=data[2:]
index=int.from_bytes(data[:8],"little")
reply=b'DONE'
info("["+ip+"] I set to "+str(index)) | conditional_block |
parsers.py | # -*- coding: utf-8 -*-
"""
pywebcopy.parsers
~~~~~~~~~~~~~~~~~
Custom HTML parsers used in pywebcopy.
"""
import os
import io
import re
import sys
import requests
import bs4
import lxml
from bs4 import UnicodeDammit
from lxml import html, etree
from lxml.html import tostring
from lxml.html.clean import Cleaner
fro... |
class Element(BaseParser):
"""An element of HTML.
:param element: The element from which to base the parsing upon.
:param url: The URL from which the HTML originated, used for ``absolute_links``.
:param default_encoding: Which encoding to default to.
"""
def __init__(self, element, url, defa... | self.lxml.getroottree().write(self.url_obj.file_path, method="html")
self._lxml = None # reset the tree | random_line_split |
parsers.py | # -*- coding: utf-8 -*-
"""
pywebcopy.parsers
~~~~~~~~~~~~~~~~~
Custom HTML parsers used in pywebcopy.
"""
import os
import io
import re
import sys
import requests
import bs4
import lxml
from bs4 import UnicodeDammit
from lxml import html, etree
from lxml.html import tostring
from lxml.html.clean import Cleaner
fro... | (self):
attrs = ['{}={}'.format(attr, repr(self.attrs[attr])) for attr in self.attrs]
return "<Element {} {}>".format(repr(self.element.tag), ' '.join(attrs))
@property
def attrs(self):
"""Returns a dictionary of the attributes of the :class:`Element <Element>`
(`learn more <htt... | __repr__ | identifier_name |
parsers.py | # -*- coding: utf-8 -*-
"""
pywebcopy.parsers
~~~~~~~~~~~~~~~~~
Custom HTML parsers used in pywebcopy.
"""
import os
import io
import re
import sys
import requests
import bs4
import lxml
from bs4 import UnicodeDammit
from lxml import html, etree
from lxml.html import tostring
from lxml.html.clean import Cleaner
fro... |
def default_handler(self, elem, attr, url, pos):
"""Handles any link type <a> <link> <script> <style> <style url>.
Note: Default handler function structures makes use of .rel_path attribute
which is completely internal and any usage depending on this attribute
may not work properly... | """Can handle <img>, <link>, <script> :class: `lxml.html.Element` object."""
LOGGER.debug("Handling url %s" % url)
if url.startswith(u"#") or url.startswith(u"data:") or url.startswith(u'javascript'):
return None # not valid link
try:
if elem.tag == 'link':
... | identifier_body |
parsers.py | # -*- coding: utf-8 -*-
"""
pywebcopy.parsers
~~~~~~~~~~~~~~~~~
Custom HTML parsers used in pywebcopy.
"""
import os
import io
import re
import sys
import requests
import bs4
import lxml
from bs4 import UnicodeDammit
from lxml import html, etree
from lxml.html import tostring
from lxml.html.clean import Cleaner
fro... |
# Scan meta tags for charset.
if self._html:
self._encoding = html_to_unicode(self.default_encoding, self._html)[0]
# Fall back to requests' detected encoding if decode fails.
try:
self.raw_html.decode(self.encoding, errors='replace')
exc... | return self._encoding | conditional_block |
blockchain1.py | import datetime # to add timestamps on every block in blockchain
import hashlib # library that is ued to hash the block
import json # to communicate in json data
# Flask to implement webservices jsonify to see the jsop message/response
# request help us to connect all the nodes of the blockchain together froming the... |
# functions used to get add the transactions to the lists
def add_transaction(self, senders, receiver, amount):
self.transactions.append({
'senders': senders,
'receiver': receiver,
'amount': amount
})
previous_block = self.get_previous_block()
... | previous_block = chain[0]
block_index = 1 # required for iteration
while block_index < len(chain):
block = chain[block_index] # cuurent block
# checking weather the refernce stored in property previus_hash is currently matched or not with the hash of previous block using hash f... | identifier_body |
blockchain1.py | import datetime # to add timestamps on every block in blockchain
import hashlib # library that is ued to hash the block
import json # to communicate in json data
# Flask to implement webservices jsonify to see the jsop message/response
# request help us to connect all the nodes of the blockchain together froming the... | (self):
# this variable help us to find the length of longest chain among different network
max_length = len(self.chain)
longest_chain = None
network = self.nodes # this variable will hold the address of all the nodes in network
for node in network:
# we know the nod... | replace_chain | identifier_name |
blockchain1.py | import datetime # to add timestamps on every block in blockchain
import hashlib # library that is ued to hash the block
import json # to communicate in json data
# Flask to implement webservices jsonify to see the jsop message/response
# request help us to connect all the nodes of the blockchain together froming the... | t= '0.0.0.0' specifies that it is available publicily
app.run(host='0.0.0.0', port=5001)
| ne.',
'actual_chain': blockchain.chain}
return jsonify(response), 200
# Running the app
# hos | conditional_block |
blockchain1.py | import datetime # to add timestamps on every block in blockchain
import hashlib # library that is ued to hash the block
import json # to communicate in json data
# Flask to implement webservices jsonify to see the jsop message/response
# request help us to connect all the nodes of the blockchain together froming the... | response = {'message': 'All the nodes are now connected. The Whalecoin 🐳🐳🐳🐳🐳🐳 Blockchain now contains the following nodes:',
'total_nodes': list(blockchain.nodes)}
return jsonify(response), 201
# Replacing the chain by the longest chain if needed
# this function will present in every nod... | blockchain.add_node(node) # add our nodes to network | random_line_split |
AgentConsole.controller.js | sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"com/deloitte/smartservice/SMARTSERVICE/model/models"
], function(Controller, JSONModel, models) {
"use strict";
var AgentConController;
var worker;
var taskQueue;
var marker;
var workspace;
return Controller.extend("com.deloitte.... | },
onClickCallPopUp: function() {
models.fetchCustomerDetails(this.getOwnerComponent());
if (!this._custDetPopover) {
this._custDetPopover = sap.ui.xmlfragment("com.deloitte.smartservice.SMARTSERVICE.fragments.CustomerDetail", this);
this.getView().addDependent(this._custDetPopover);
}
this._cust... | var today = new Date();
AgentConController.getView().byId("dr_fromTo").setSecondDateValue(today);
var oneWeekAgo = new Date();
oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);
AgentConController.getView().byId("dr_fromTo").setDateValue(oneWeekAgo);
AgentConController.initialized = true;
Agent... | conditional_block |
AgentConsole.controller.js | sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/model/json/JSONModel",
"com/deloitte/smartservice/SMARTSERVICE/model/models"
], function(Controller, JSONModel, models) {
"use strict";
var AgentConController;
var worker;
var taskQueue;
var marker;
var workspace;
return Controller.extend("com.deloitte.... | AgentConController.map = new google.maps.Map(AgentConController.getView().byId("map_canvas").getDomRef(), mapOptions);
}
}
},
onClickCallPopUp: function() {
models.fetchCustomerDetails(this.getOwnerComponent());
if (!this._custDetPopover) {
this._custDetPopover = sap.ui.xmlfragment("com.deloi... | zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
}; | random_line_split |
CS3243_P1_41_2.py | # INFORMED SEARCH 1: Manhattan Distance
import os
import sys
import math
import heapq
from time import time # assumes Unix-based system; switch to clock if on Windows
class Node(object):
def __init__(self, orientation):
|
def __lt__(self, other):
if (self.current_cost + self.heuristic_value) == (other.current_cost + other.heuristic_value):
if (self.current_cost == other.current_cost):
return (self.id > other.id)
return (self.current_cost > other.current_cost)
return (self... | self.state = orientation # a list of lists corresponding to the orientation of the tiles
self.current_cost = float('inf')
self.heuristic_value = float('inf')
self.previous_action = "START"
self.previous_node = None
self.id = 0 # id of the node inserted (later nodes have a higher ... | identifier_body |
CS3243_P1_41_2.py | # INFORMED SEARCH 1: Manhattan Distance
import os
import sys
import math
import heapq
from time import time # assumes Unix-based system; switch to clock if on Windows
class Node(object):
def __init__(self, orientation):
self.state = orientation # a list of lists corresponding to the orientation of the til... | (self):
return self.previous_node
def set_id(self, next_id):
self.id = next_id
class Puzzle(object):
def __init__(self, init_state, goal_state):
# you may add more attributes if you think is useful
self.name = "Manhattan Distance"
self.size = len(init_state)
sel... | get_previous_node | identifier_name |
CS3243_P1_41_2.py | # INFORMED SEARCH 1: Manhattan Distance
import os
import sys
import math
import heapq
from time import time # assumes Unix-based system; switch to clock if on Windows
class Node(object):
def __init__(self, orientation):
self.state = orientation # a list of lists corresponding to the orientation of the til... | coord_in_goal = self.search_in_goal(curr);
count += (abs(coord_in_goal[0]-i) + abs(coord_in_goal[1]-j))
return count
def search_in_goal(self, query):
return ((query - 1) // self.size, (query - 1) % self.size)
def generate_possibilities(self, node):
blank... | for i in range(self.size):
for j in range(self.size):
curr = node.state[i][j]
if curr == 0:
continue | random_line_split |
CS3243_P1_41_2.py | # INFORMED SEARCH 1: Manhattan Distance
import os
import sys
import math
import heapq
from time import time # assumes Unix-based system; switch to clock if on Windows
class Node(object):
def __init__(self, orientation):
self.state = orientation # a list of lists corresponding to the orientation of the til... | if len(sys.argv) != 3:
raise ValueError("Wrong number of arguments!")
try:
f = open(sys.argv[1], 'r')
except IOError:
raise IOError("Input file not found!")
lines = f.readlines()
# n = num rows in input file
n = len(lines)
# max_num = n to the power of 2 - 1
ma... | conditional_block | |
handlers_events.go | package monitor
import (
"context"
"math/big"
"strings"
aobjs "github.com/MadBase/MadNet/application/objs"
"github.com/MadBase/MadNet/blockchain/dkg"
"github.com/MadBase/MadNet/blockchain/tasks/dkgtasks"
"github.com/MadBase/MadNet/consensus/objs"
"github.com/MadBase/MadNet/constants"
"github.com/MadBase/MadN... |
// ProcessShareDistribution accumulates everyones shares ETHDKG
func (svcs *Services) ProcessShareDistribution(state *State, log types.Log) error {
logger := svcs.logger
logger.Info(strings.Repeat("-", 60))
logger.Info("ProcessShareDistribution()")
logger.Info(strings.Repeat("-", 60))
if !ETHDKGInProgress(stat... | {
eth := svcs.eth
c := eth.Contracts()
logger := svcs.logger
event, err := c.Ethdkg.ParseRegistrationOpen(log)
if err != nil {
return err
}
if ETHDKGInProgress(state.ethdkg, log.BlockNumber) {
logger.Warnf("Received RegistrationOpen event while ETHDKG in progress. Aborting old round.")
AbortETHDKG(state... | identifier_body |
handlers_events.go | package monitor
import (
"context"
"math/big"
"strings"
aobjs "github.com/MadBase/MadNet/application/objs"
"github.com/MadBase/MadNet/blockchain/dkg"
"github.com/MadBase/MadNet/blockchain/tasks/dkgtasks"
"github.com/MadBase/MadNet/consensus/objs"
"github.com/MadBase/MadNet/constants"
"github.com/MadBase/MadN... |
return svcs.dph.Add(txn, svcs.chainID, depositNonce, event.Amount, owner)
})
}
// ProcessSnapshotTaken handles receiving snapshots
func (svcs *Services) ProcessSnapshotTaken(state *State, log types.Log) error {
eth := svcs.eth
c := eth.Contracts()
logger := svcs.logger
callOpts := eth.GetCallOpts(context.TODO... | {
logger.Debugf("Error in Services.ProcessDepositReceived at owner.New: %v", err)
return err
} | conditional_block |
handlers_events.go | package monitor
import (
"context"
"math/big"
"strings"
aobjs "github.com/MadBase/MadNet/application/objs"
"github.com/MadBase/MadNet/blockchain/dkg"
"github.com/MadBase/MadNet/blockchain/tasks/dkgtasks"
"github.com/MadBase/MadNet/consensus/objs"
"github.com/MadBase/MadNet/constants"
"github.com/MadBase/MadN... | (state *State, log types.Log) error {
eth := svcs.eth
c := eth.Contracts()
event, err := c.Ethdkg.ParseValidatorMember(log)
if err != nil {
return err
}
epoch := uint32(event.Epoch.Int64())
index := uint8(event.Index.Uint64()) - 1
v := Validator{
Account: event.Account,
Index: index,
SharedKe... | ProcessValidatorMember | identifier_name |
handlers_events.go | package monitor
import (
"context"
"math/big"
"strings"
aobjs "github.com/MadBase/MadNet/application/objs"
"github.com/MadBase/MadNet/blockchain/dkg"
"github.com/MadBase/MadNet/blockchain/tasks/dkgtasks"
"github.com/MadBase/MadNet/consensus/objs"
"github.com/MadBase/MadNet/constants"
"github.com/MadBase/MadN... |
updatedState := state
event, err := c.Ethdkg.ParseValidatorSet(log)
if err != nil {
return err
}
epoch := uint32(event.Epoch.Int64())
vs := state.ValidatorSets[epoch]
vs.NotBeforeMadNetHeight = event.MadHeight
vs.ValidatorCount = event.ValidatorCount
vs.GroupKey[0] = *event.GroupKey0
vs.GroupKey[1] = *e... | eth := svcs.eth
c := eth.Contracts() | random_line_split |
migrations.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | traits::{GetStorageVersion, PalletInfoAccess},
};
#[cfg(feature = "try-runtime")]
use sp_io::hashing::twox_128;
pub struct MigrateToV11<T, P, N>(sp_std::marker::PhantomData<(T, P, N)>);
impl<T: Config, P: GetStorageVersion + PalletInfoAccess, N: Get<&'static str>> OnRuntimeUpgrade
for MigrateToV11<T, P, N>
{... | use super::*;
use frame_support::{
storage::migration::move_pallet, | random_line_split |
migrations.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | <T>(sp_std::marker::PhantomData<T>);
impl<T: Config> OnRuntimeUpgrade for MigrateToV12<T> {
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
frame_support::ensure!(
StorageVersion::<T>::get() == ObsoleteReleases::V11_0_0,
"Expected v11 before upgrading to v12"
);... | MigrateToV12 | identifier_name |
migrations.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... | else {
log!(
warn,
"InjectValidatorsIntoVoterList being executed on the wrong storage \
version, expected ObsoleteReleases::V8_0_0"
);
T::DbWeight::get().reads(1)
}
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
frame_support::ensure!(
... | {
let prev_count = T::VoterList::count();
let weight_of_cached = Pallet::<T>::weight_of_fn();
for (v, _) in Validators::<T>::iter() {
let weight = weight_of_cached(&v);
let _ = T::VoterList::on_insert(v.clone(), weight).map_err(|err| {
log!(warn, "failed to insert {:?} into VoterList: {:?}",... | conditional_block |
migrations.rs | // This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// 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.a... |
fn on_runtime_upgrade() -> Weight {
let current = Pallet::<T>::current_storage_version();
let onchain = StorageVersion::<T>::get();
if current == 13 && onchain == ObsoleteReleases::V12_0_0 {
StorageVersion::<T>::kill();
current.put::<Pallet<T>>();
log!(info, "v13 applied successfully");
T... | {
frame_support::ensure!(
StorageVersion::<T>::get() == ObsoleteReleases::V12_0_0,
"Required v12 before upgrading to v13"
);
Ok(Default::default())
} | identifier_body |
exec.go | package command
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/agent/internal"
"github.com/evergreen-ci/evergreen/agent/internal/client"
agentutil "github.com/evergreen-ci/evergreen/agent/util"
"github.... | (params map[string]interface{}) error {
err := mapstructure.Decode(params, c)
if err != nil {
return errors.Wrap(err, "decoding mapstructure params")
}
if c.Command != "" {
if c.Binary != "" || len(c.Args) > 0 {
return errors.New("must specify command as either binary and arguments, or a command string, but... | ParseParams | identifier_name |
exec.go | package command
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/agent/internal"
"github.com/evergreen-ci/evergreen/agent/internal/client"
agentutil "github.com/evergreen-ci/evergreen/agent/util"
"github.... |
func (c *subprocessExec) Execute(ctx context.Context, comm client.Communicator, logger client.LoggerProducer, conf *internal.TaskConfig) error {
var err error
if err = c.doExpansions(conf.Expansions); err != nil {
return errors.Wrap(err, "expanding command parameters")
}
logger.Execution().WarningWhen(
filep... | return exec.LookPath(c.Binary)
} | random_line_split |
exec.go | package command
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/agent/internal"
"github.com/evergreen-ci/evergreen/agent/internal/client"
agentutil "github.com/evergreen-ci/evergreen/agent/util"
"github.... |
func (c *subprocessExec) Name() string { return "subprocess.exec" }
func (c *subprocessExec) ParseParams(params map[string]interface{}) error {
err := mapstructure.Decode(params, c)
if err != nil {
return errors.Wrap(err, "decoding mapstructure params")
}
if c.Command != "" {
if c.Binary != "" || len(c.Args)... | { return &subprocessExec{} } | identifier_body |
exec.go | package command
import (
"context"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"github.com/evergreen-ci/evergreen"
"github.com/evergreen-ci/evergreen/agent/internal"
"github.com/evergreen-ci/evergreen/agent/internal/client"
agentutil "github.com/evergreen-ci/evergreen/agent/util"
"github.... |
cmdPath := c.Env["PATH"]
// For non-Windows platforms, the filepath.Separator is always '/'. However,
// for Windows, Go accepts both '\' and '/' as valid file path separators,
// even though the native filepath.Separator for Windows is really '\'. This
// detects both '\' and '/' as valid Windows file path sepa... | {
return c.Binary, err
} | conditional_block |
Randomizer.py | # import modules
import cv2
import glob
import os
import datetime
from datetime import date
from PIL import Image as Img
from PIL import ImageTk
from random import randint
from Tkinter import *
import Tkinter,tkFileDialog, tkMessageBox
# setting dictionaries and keys for fast conversions
song_mode_dict = {
"Singles":... | (self,parent):
# button function: saves winner to class variable and closes popup
def return_value(event='<Button-1>'):
# if button is selected
if winner.get() != 0:
# if not a draw
if winner.get() != 3:
Selector_Screen.match_winner = Selector_Screen.player_array[winner.get() -... | Prompt_Winner | identifier_name |
Randomizer.py | # import modules
import cv2
import glob
import os
import datetime
from datetime import date
from PIL import Image as Img
from PIL import ImageTk
from random import randint
from Tkinter import *
import Tkinter,tkFileDialog, tkMessageBox
# setting dictionaries and keys for fast conversions
song_mode_dict = {
"Singles":... |
# if a draw
else:
Selector_Screen.match_winner = "Draw"
# close popup
self.win.destroy()
# creates popop window
self.win = Toplevel(parent)
self.win.wm_title("Select Winner")
# button images
self.Continue = Tkinter.PhotoImage(file="./Graphics/Continue.gif"... | Selector_Screen.match_winner = Selector_Screen.player_array[winner.get() - 1] | conditional_block |
Randomizer.py | # import modules
import cv2
import glob
import os
import datetime
from datetime import date
from PIL import Image as Img
from PIL import ImageTk
from random import randint
from Tkinter import *
import Tkinter,tkFileDialog, tkMessageBox
# setting dictionaries and keys for fast conversions
song_mode_dict = {
"Singles":... | winner.set(0)
# construct frame for widgets
self.Inner_Frame = Frame(self.win)
self.Inner_Frame.grid(row=0,column=0)
# asks who the winner is
Winner_Label = Label(self.Inner_Frame, text="The winner is:")
Winner_Label.grid(row=0, column=0,columnspan=2)
Winner_Label.configure(font=("TkDefa... |
# initialize winner radio button variable
winner = IntVar() | random_line_split |
Randomizer.py | # import modules
import cv2
import glob
import os
import datetime
from datetime import date
from PIL import Image as Img
from PIL import ImageTk
from random import randint
from Tkinter import *
import Tkinter,tkFileDialog, tkMessageBox
# setting dictionaries and keys for fast conversions
song_mode_dict = {
"Singles":... |
# asks for winner and saves match information in tournament log file
def Report_Match(self,event='<Button-1'):
# if there isn't a song selected, do nothing
if not Selector_Screen.report_mode:
return
# initialize the time of the match
time_of_match = str(datetime.datetime.now().time()).... | def return_value(event='<Button-1>'):
# if button is selected
if winner.get() != 0:
# if not a draw
if winner.get() != 3:
Selector_Screen.match_winner = Selector_Screen.player_array[winner.get() - 1]
# if a draw
else:
Selector_Screen.match_winner = "Draw"
... | identifier_body |
list.go | // Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gui
import (
"github.com/g3n/engine/window"
)
// List represents a list GUI element
type List struct {
ItemScroller // Embedded scrolle... |
// SetItemPadLeftAt sets the additional left padding for this item
// It is used mainly by the tree control
func (li *List) SetItemPadLeftAt(pos int, pad float32) {
if pos < 0 || pos >= len(li.items) {
return
}
litem := li.items[pos].(*ListItem)
litem.padLeft = pad
litem.update()
}
// selNext selects or high... | {
if pos < 0 || pos >= len(li.items) {
return
}
litem := li.items[pos].(*ListItem)
if litem.selected == state {
return
}
litem.SetSelected(state)
li.update()
li.Dispatch(OnChange, nil)
} | identifier_body |
list.go | // Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gui
import (
"github.com/g3n/engine/window"
)
// List represents a list GUI element
type List struct {
ItemScroller // Embedded scrolle... | (state bool) {
litem.highlighted = state
//litem.item.SetHighlighted2(state)
}
// updates the list item visual style accordingly to its current state
func (litem *ListItem) update() {
list := litem.list
if litem.selected && !litem.highlighted {
litem.applyStyle(&list.styles.Item.Selected)
return
}
if !lite... | SetHighlighted | identifier_name |
list.go | // Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gui
import (
"github.com/g3n/engine/window"
)
// List represents a list GUI element
type List struct {
ItemScroller // Embedded scrolle... |
// onCursor receives subscribed cursor events over the list item
func (litem *ListItem) onCursor(evname string, ev interface{}) {
if litem.list.dropdown {
litem.list.setSelection(litem, true, true, false)
return
}
}
// SetSelected sets this item selected state
func (litem *ListItem) SetSelected(state bool) {
... | }
if litem.list.dropdown {
litem.list.SetVisible(false)
}
} | random_line_split |
list.go | // Copyright 2016 The G3N Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package gui
import (
"github.com/g3n/engine/window"
)
// List represents a list GUI element
type List struct {
ItemScroller // Embedded scrolle... |
}
//
// ListItem methods
//
func newListItem(list *List, item IPanel) *ListItem {
litem := new(ListItem)
litem.Panel.Initialize(litem, 0, 0)
litem.item = item
litem.list = list
litem.Panel.Add(item)
litem.SetContentWidth(item.GetPanel().Width())
litem.SetContentHeight(item.GetPanel().Height())
// If this li... | {
item.(*ListItem).update()
} | conditional_block |
test_network_moreMeasures.py | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 19:13:50 2019
@author: darya
"""
#from os import chdir
#chdir(cur_dir)
#CLAHE = 0 # didn't have this variable from running main_Unet for some reason
import tensorflow as tf
from matplotlib import *
import numpy as np
from PIL import Image
from os import listdir... | try:
tf.reset_default_graph() # necessary?
# Variable Declaration
x = tf.placeholder('float32', shape=[None, len_x, width_x, channels], name='InputImage')
y_ = tf.placeholder('float32', shape=[None, len_x, width_x, 2], name='CorrectLabel')
training = tf.placeholder(t... | identifier_body | |
test_network_moreMeasures.py | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 19:13:50 2019
@author: darya
"""
#from os import chdir
#chdir(cur_dir)
#CLAHE = 0 # didn't have this variable from running main_Unet for some reason
import tensorflow as tf
from matplotlib import *
import numpy as np
from PIL import Image
from os import listdir... |
import copy
copy_list = copy.deepcopy(list_M_cells)
""" associate fibers to masked """
sort_mask = sort_max_fibers(masked, list_M_cells)
""" Then add to all the cells that have no_overlap """
all_... | for T in range(len(overlap_coords)):
no_overlap[overlap_coords[T,0], overlap_coords[T,1]] = seg_im[overlap_coords[T,0], overlap_coords[T,1]] | conditional_block |
test_network_moreMeasures.py | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 19:13:50 2019
@author: darya
"""
#from os import chdir
#chdir(cur_dir)
#CLAHE = 0 # didn't have this variable from running main_Unet for some reason
import tensorflow as tf
from matplotlib import *
import numpy as np
from PIL import Image
from os import listdir... | onlyfiles_mask.sort(key = natsort_key1)
counter = list(range(len(onlyfiles_mask))) # create a counter, so can randomize it
""" Load avg_img and std_img from TRAINING SET """
mean_arr = 0; std_arr = 0;
with open('./Data_functions/mean_arr.pkl', 'rb') as f: # Py... | onlyfiles_mask = [ f for f in listdir(input_path) if isfile(join(input_path,f))]
natsort_key1 = natsort_keygen(key = lambda y: y.lower()) # natural sorting order | random_line_split |
test_network_moreMeasures.py | # -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 19:13:50 2019
@author: darya
"""
#from os import chdir
#chdir(cur_dir)
#CLAHE = 0 # didn't have this variable from running main_Unet for some reason
import tensorflow as tf
from matplotlib import *
import numpy as np
from PIL import Image
from os import listdir... | (s_path, sav_dir, input_path, checkpoint,
im_scale, minLength, minSingle, minLengthDuring, radius,
len_x, width_x, channels, CLAHE, rotate, jacc_test, rand_rot, rolling_ball, resize,
debug):
try:
tf.reset_default_graph() # necessary?
# ... | run_analysis | identifier_name |
filter_jpeg.js |
'use strict';
const filterExif = require('./filter_exif');
///////////////////////////////////////////////////////////////////////
// JPEG parser
//
// Parser states
//
const FILE_START = 0; // start of the file, read signature (FF)
const FILE_START_FF = 1; // start of the file, read signature (D... |
// Perform a shallow copy of a buffer or typed array
//
function slice(buf, start, end) {
if (buf.slice && buf.copy && buf.writeDoubleBE) {
//
// Looks like node.js buffer
//
// - we use buf.slice() in node.js buffers because
// buf.subarray() is not a buffer
//
// - we use buf.subarr... | {
let n = number.toString(16).toUpperCase();
for (let i = 2 - n.length; i > 0; i--) n = '0' + n;
return '0x' + n;
} | identifier_body |
filter_jpeg.js |
'use strict';
const filterExif = require('./filter_exif');
///////////////////////////////////////////////////////////////////////
// JPEG parser
//
// Parser states
//
const FILE_START = 0; // start of the file, read signature (FF)
const FILE_START_FF = 1; // start of the file, read signature (D... | (number) {
let n = number.toString(16).toUpperCase();
for (let i = 2 - n.length; i > 0; i--) n = '0' + n;
return '0x' + n;
}
// Perform a shallow copy of a buffer or typed array
//
function slice(buf, start, end) {
if (buf.slice && buf.copy && buf.writeDoubleBE) {
//
// Looks like node.js buffer
... | toHex | identifier_name |
filter_jpeg.js | 'use strict';
const filterExif = require('./filter_exif');
///////////////////////////////////////////////////////////////////////
// JPEG parser
//
// Parser states
//
const FILE_START = 0; // start of the file, read signature (FF)
const FILE_START_FF = 1; // start of the file, read signature (D8... | buf[3] === 0x66 && buf[4] === 0x00 && buf[5] === 0x00) {
// EXIF
if (this._removeExif) {
buf = null;
} else {
try {
buf = filterExif(buf, {
maxEntrySize: this._maxEntrySize,
onIFDEntry: t... | random_line_split | |
filter_jpeg.js |
'use strict';
const filterExif = require('./filter_exif');
///////////////////////////////////////////////////////////////////////
// JPEG parser
//
// Parser states
//
const FILE_START = 0; // start of the file, read signature (FF)
const FILE_START_FF = 1; // start of the file, read signature (D... |
// unknown markers
this._error('unknown marker: ' + toHex(b) +
' (offset ' + toHex(this._bytesRead + i) + ')',
'EBADDATA');
return; // return after error, not break
// read segment length (2 bytes total)
case SEGMENT_LENGTH:
while (t... | {
// padding byte, skip it
i++;
break;
} | conditional_block |
ptsrc_gibbs.py | import numpy as np, argparse, sys, itertools, os, errno, warnings
from mpi4py import MPI
from enlib import enmap as en, powspec, utils
from enlib.degrees_of_freedom import DOF, Arg
from enlib.cg import CG
warnings.filterwarnings("ignore")
#from matplotlib.pylab import *
parser = argparse.ArgumentParser()
parser.add_ar... | (self, verbose=False):
"""Draw a new, uncorrelated sample."""
for i in range(self.nsamp): self.subsample(verbose)
return self.amps, self.pos, self.irads
class ShapeSamplerMulti:
def __init__(self, maps, inoise, model, amps, pos, pos0, irads, nsamp=1500, stepsize=0.02, maxdist=1.5*np.pi/180/60):
self.samplers ... | sample | identifier_name |
ptsrc_gibbs.py | import numpy as np, argparse, sys, itertools, os, errno, warnings
from mpi4py import MPI
from enlib import enmap as en, powspec, utils
from enlib.degrees_of_freedom import DOF, Arg
from enlib.cg import CG
warnings.filterwarnings("ignore")
#from matplotlib.pylab import *
parser = argparse.ArgumentParser()
parser.add_ar... |
class GibbsSampler:
def __init__(self, maps, inoise, ps, pos0, amp0, irads0, cmb0):
self.maps = maps
self.inoise = inoise
self.ps = ps
self.src_model = PtsrcModel(maps)
self.pos, self.amp, self.irads, self.cmb = pos0, amp0, irads0, cmb0
self.pos0 = pos0
self.cmb_sampler = CMBSampler(maps, inois... | def __init__(self, maps, inoise, model, amps, pos, pos0, irads, nsamp=1500, stepsize=0.02, maxdist=1.5*np.pi/180/60):
self.samplers = [ShapeSampler(maps, inoise, model, amp1, pos1, pos01, irads1, nsamp=1, stepsize=stepsize, maxdist=maxdist) for amp1, pos1, pos01, irads1 in zip(amps, pos, pos0, irads)]
self.nsamp ... | identifier_body |
ptsrc_gibbs.py | import numpy as np, argparse, sys, itertools, os, errno, warnings
from mpi4py import MPI
from enlib import enmap as en, powspec, utils
from enlib.degrees_of_freedom import DOF, Arg
from enlib.cg import CG
warnings.filterwarnings("ignore")
#from matplotlib.pylab import *
parser = argparse.ArgumentParser()
parser.add_ar... |
return nmat
def parse_floats(strs): return np.array([float(w) for w in strs.split(",")])
def apodize(m, rad, apod_fun):
scale = m.extent()/m.shape[-2:]
y = np.arange(m.shape[-2])*scale[0]
x = np.arange(m.shape[-1])*scale[1]
yfun = apod_fun(y, rad)*apod_fun(y[-1]-y, rad)
xfun = apod_fun(x, rad)*apod_fun(x[-1]-x... | raise ValueError("Noise and maps have inconsistent shape!") | conditional_block |
ptsrc_gibbs.py | import numpy as np, argparse, sys, itertools, os, errno, warnings
from mpi4py import MPI
from enlib import enmap as en, powspec, utils
from enlib.degrees_of_freedom import DOF, Arg
from enlib.cg import CG
warnings.filterwarnings("ignore")
#from matplotlib.pylab import *
parser = argparse.ArgumentParser()
parser.add_ar... | lik = self.getlik(self.amps, self.pos, irads)
if np.random.uniform() < np.exp(self.lik-lik):
self.irads, self.lik = irads, lik
amps = self.newamp(self.amps)
lik = self.getlik(amps, self.pos, self.irads)
if np.random.uniform() < np.exp(self.lik-lik):
self.amps, self.lik = amps, lik
if verbose:
sigma... | if np.random.uniform() < np.exp(self.lik-lik):
self.pos, self.lik = pos, lik
irads = self.newshape(self.irads) | random_line_split |
day20.rs | #![allow(dead_code)]
use std::collections::HashMap;
mod lib;
// Width (and height) of each tile.
const SIZE: usize = 10;
// One row/side of each tile.
type Line = u16;
#[derive(PartialEq, Eq, Debug, Clone, Hash, Default)]
struct Tile {
id: usize,
rows: Vec<Line>,
flipped: bool,
rotated: u32,
}
fn ... |
fn west_edge(self: &Self) -> Line {
self.rotate_cw().rows[0]
}
fn east_edge(self: &Self) -> Line {
self.rotate_cw().rotate_cw().rotate_cw().rows[0]
}
fn south_edge(self: &Self) -> Line {
self.rotate_cw().rotate_cw().rows[0]
}
fn get_edges(self: &Self) -> [Line; 4]... | self.rows[0]
} | random_line_split |
day20.rs | #![allow(dead_code)]
use std::collections::HashMap;
mod lib;
// Width (and height) of each tile.
const SIZE: usize = 10;
// One row/side of each tile.
type Line = u16;
#[derive(PartialEq, Eq, Debug, Clone, Hash, Default)]
struct Tile {
id: usize,
rows: Vec<Line>,
flipped: bool,
rotated: u32,
}
fn ... | (self: &Self) -> MergedTiles {
MergedTiles {
rows: self.rows.iter().cloned().rev().collect(),
}
}
}
fn main() {
let contents = std::fs::read_to_string("input/20.txt").expect("read failed");
let mut bag = TileBag::parse(&contents);
// Part 1: find corners, multiply their ids... | mirror_vertical | identifier_name |
day20.rs | #![allow(dead_code)]
use std::collections::HashMap;
mod lib;
// Width (and height) of each tile.
const SIZE: usize = 10;
// One row/side of each tile.
type Line = u16;
#[derive(PartialEq, Eq, Debug, Clone, Hash, Default)]
struct Tile {
id: usize,
rows: Vec<Line>,
flipped: bool,
rotated: u32,
}
fn ... |
#[test]
fn test_invert() {
assert_eq!(invert(1), 512);
assert_eq!(invert(512), 1);
assert_eq!(invert(2), 256);
}
}
impl std::fmt::Display for Tile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut first = true;
for line in self.rows... | {
assert_eq!(line_to_string(1), ".........#");
assert_eq!(line_to_string(391), ".##....###");
} | identifier_body |
noise.go | // Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package controlclient
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"io"
"math"
"net/http"
"net/url"
"sync"
"time"
"golang.org/x/net/http2"
"tailscale.com/control/controlbase"
"tailscale.com/contro... |
return nil, nil, errors.New("[unexpected] failed to reserve a request on a connection")
}
// contextErr is an error that wraps another error and is used to indicate that
// the error was because a context expired.
type contextErr struct {
err error
}
func (e contextErr) Error() string {
return e.err.Error()
}
fu... | {
conn, err := nc.getConn(ctx)
if err != nil {
return nil, nil, err
}
earlyPayloadMaybeNil, err := conn.getEarlyPayload(ctx)
if err != nil {
return nil, nil, err
}
if conn.h2cc.ReserveNewRequest() {
return conn, earlyPayloadMaybeNil, nil
}
} | conditional_block |
noise.go | // Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package controlclient
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"io"
"math"
"net/http"
"net/url"
"sync"
"time"
"golang.org/x/net/http2"
"tailscale.com/control/controlbase"
"tailscale.com/contro... | }
ncc := &noiseConn{
Conn: clientConn.Conn,
id: connID,
pool: nc,
earlyPayloadReady: make(chan struct{}),
}
h2cc, err := nc.h2t.NewClientConn(ncc)
if err != nil {
return nil, err
}
ncc.h2cc = h2cc
nc.mu.Lock()
defer nc.mu.Unlock()
mak.Set(&nc.connPool, ncc... | }).Dial(ctx)
if err != nil {
return nil, err | random_line_split |
noise.go | // Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package controlclient
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"io"
"math"
"net/http"
"net/url"
"sync"
"time"
"golang.org/x/net/http2"
"tailscale.com/control/controlbase"
"tailscale.com/contro... |
// The first 9 bytes from the server to client over Noise are either an HTTP/2
// settings frame (a normal HTTP/2 setup) or, as we added later, an "early payload"
// header that's also 9 bytes long: 5 bytes (earlyPayloadMagic) followed by 4 bytes
// of length. Then that many bytes of JSON-encoded tailcfg.EarlyNoise.
... | {
select {
case <-c.earlyPayloadReady:
return c.earlyPayload, c.earlyPayloadErr
case <-ctx.Done():
return nil, ctx.Err()
}
} | identifier_body |
noise.go | // Copyright (c) Tailscale Inc & AUTHORS
// SPDX-License-Identifier: BSD-3-Clause
package controlclient
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"errors"
"io"
"math"
"net/http"
"net/url"
"sync"
"time"
"golang.org/x/net/http2"
"tailscale.com/control/controlbase"
"tailscale.com/contro... | () error {
if err := c.Conn.Close(); err != nil {
return err
}
c.pool.connClosed(c.id)
return nil
}
// NoiseClient provides a http.Client to connect to tailcontrol over
// the ts2021 protocol.
type NoiseClient struct {
// Client is an HTTP client to talk to the coordination server.
// It automatically makes a ... | Close | identifier_name |
write.rs | use crate::attributes;
use crate::back::bytecode;
use crate::back::lto::ThinBuffer;
use crate::base;
use crate::consts;
use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
use crate::llvm_util;
use crate::ModuleLlvm;
use crate::type_::Type;
use crate::context::{is_pie_binary, get_reloc_model};
use crate... | diag_handler.err(&msg);
}
}
} else if config.embed_bitcode_marker {
embed_bitcode(cgcx, llcx, llmod, None);
}
time_ext(config.time_passes, &format!("codegen passes [{}]", module_name.unwrap()),
|| -> Result<(), FatalError> ... | let msg = format!("failed to write bytecode to {}: {}", dst.display(), e); | random_line_split |
write.rs | use crate::attributes;
use crate::back::bytecode;
use crate::back::lto::ThinBuffer;
use crate::base;
use crate::consts;
use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
use crate::llvm_util;
use crate::ModuleLlvm;
use crate::type_::Type;
use crate::context::{is_pie_binary, get_reloc_model};
use crate... | (cgcx: &CodegenContext<LlvmCodegenBackend>,
msg: &str,
cookie: c_uint) {
cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned());
}
unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic,
... | report_inline_asm | identifier_name |
write.rs | use crate::attributes;
use crate::back::bytecode;
use crate::back::lto::ThinBuffer;
use crate::base;
use crate::consts;
use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
use crate::llvm_util;
use crate::ModuleLlvm;
use crate::type_::Type;
use crate::context::{is_pie_binary, get_reloc_model};
use crate... | else {
"\x01__imp_"
};
unsafe {
let i8p_ty = Type::i8p_llcx(llcx);
let globals = base::iter_globals(llmod)
.filter(|&val| {
llvm::LLVMRustGetLinkage(val) == llvm::Linkage::ExternalLinkage &&
llvm::LLVMIsDeclaration(val) == 0
}... | {
"\x01__imp__"
} | conditional_block |
write.rs | use crate::attributes;
use crate::back::bytecode;
use crate::back::lto::ThinBuffer;
use crate::base;
use crate::consts;
use crate::llvm::{self, DiagnosticInfo, PassManager, SMDiagnostic};
use crate::llvm_util;
use crate::ModuleLlvm;
use crate::type_::Type;
use crate::context::{is_pie_binary, get_reloc_model};
use crate... |
pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize)
{
use self::config::OptLevel::*;
match cfg {
No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone),
Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone),
Default => (l... | {
target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)()
.unwrap_or_else(|err| {
llvm_err(tcx.sess.diagnostic(), &err).raise()
})
} | identifier_body |
lib.rs | //! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a on... | lse {
let mut scheduler_state = state_lock.lock();
if let SchedulerState::PauseTime(_) = *scheduler_state {
let peeked = locked_heap.peek().expect("Expected heap to be filled.");
if task.context.time < peeked.context.time {
let left = task.co... | *scheduler_state = SchedulerState::new_pause_time(left);
notifier.notify_one();
}
} e | conditional_block |
lib.rs | //! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a on... | scheduler exists on two levels: The handle, granting you the
/// ability of adding new tasks, and the executor, dating and executing these
/// tasks when specified time is met.
///
/// **Info**: This scheduler may not be precise due to anomalies such as
/// preemption or platform differences.
pub struct Scheduler {
... | hedulerState::PauseTime(
duration
.to_std()
.unwrap_or_else(|_| StdDuration::from_millis(0)),
)
}
}
/// This | identifier_body |
lib.rs | //! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a on... | DateTime<Utc>,
}
/// Every task will return this `enum`.
pub enum DateResult {
/// The task is considered finished and can be fully removed.
Done,
/// The task will be scheduled for a new date on passed `DateTime<Utc>`.
Repeat(DateTime<Utc>),
}
/// Every job gets a planned `Date` with the scheduler.
... | time: | identifier_name |
lib.rs | //! *“I'm late! I'm late! For a very important date!”*
//! *by “The White Rabbit”* 『Alice's Adventures in Wonderland』
//!
//! `white_rabbit` schedules your tasks and can repeat them!
//!
//! One funny use case are chat bot commands: Imagine a *remind me*-command,
//! the command gets executed and you simply create a on... |
}
#[must_use]
enum Break {
Yes,
No,
}
#[inline]
fn process_states(state_lock: &Mutex<SchedulerState>, notifier: &Condvar) -> Break {
let mut scheduler_state = state_lock.lock();
while let SchedulerState::PauseEmpty = *scheduler_state {
notifier.wait(&mut scheduler_state);
}
while le... | *state = SchedulerState::new_pause_time(left);
_push_and_notfiy(date, &mut heap_lock, ¬ifier);
} | random_line_split |
project.py | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 4 15:35:34 2017
@author: Anirudh
"""
from skimage.feature import hog
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from scipy.ndimage.measurements import label
from sklearn.metrics... |
if __name__ == "__main__":
#Test()
svc, _, _, _, _ = BuildAClassifier()
det = Vehicle_Detect()
ProcessVideo() | self.prev_rects.append(rects)
if len(self.prev_rects) > 15:
# throw out oldest rectangle set(s)
self.prev_rects = self.prev_rects[len(self.prev_rects)-15:] | identifier_body |
project.py | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 4 15:35:34 2017
@author: Anirudh
"""
from skimage.feature import hog
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from scipy.ndimage.measurements import label
from sklearn.metrics... | (heatmap, threshold):
# Zero out pixels below the threshold
heatmap[heatmap <= threshold] = 0
# Return thresholded map
return heatmap
def LabelImage(heatmap_img):
ThresholdImage(heatmap_img, 1)
labels = label(heatmap_img)
return labels
def DrawFinal(img, labels):
# Iterate through all ... | ThresholdImage | identifier_name |
project.py | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 4 15:35:34 2017
@author: Anirudh
"""
from skimage.feature import hog
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from scipy.ndimage.measurements import label
from sklearn.metrics... | # apply color conversion if other than 'RGB'
if cspace != 'RGB':
if cspace == 'HSV':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
elif cspace == 'LUV':
feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV)
elif cspace == 'HLS... | features = []
# Iterate through the list of images
for file in imgs:
# Read in each one by one
image = mpimg.imread(file) | random_line_split |
project.py | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 4 15:35:34 2017
@author: Anirudh
"""
from skimage.feature import hog
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from scipy.ndimage.measurements import label
from sklearn.metrics... |
for xb in range(nxsteps):
for yb in range(nysteps):
ypos = yb*cells_per_step
xpos = xb*cells_per_step
# Extract HOG for this patch
hog_feat1 = hog1[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel()
if hog_channel == 'ALL':
... | hog2 = getHOG(ch2, orient, pix_per_cell, cell_per_block, feature_vec=False)
hog3 = getHOG(ch3, orient, pix_per_cell, cell_per_block, feature_vec=False) | conditional_block |
storage_service.go | /*
* @Description:
* @version:
* @Company: iwhalecloud
* @Author: ddh
* @Date: 2021-02-07 16:32:07
* @LastEditors: ddh
* @LastEditTime: 2021-02-07 16:32:07
*/
package service
import (
"DBaas/models"
"DBaas/utils"
"DBaas/x/response"
"encoding/json"
"errors"
"fmt"
"github.com/go-xorm/xorm"
"github.com/k... | if userId > 0 {
su = append(su, models.ScUser{UserId: userId, ScId: sc.Id})
}
if len(su) > 0 {
_, _ = ss.Engine.Insert(&su)
}
return sc, nil
}
func (ss *storageService) Update(id int, remake string, nodeNum int) error {
sc := models.Sc{
Id: id,
Describe: remake,
NodeNum: nodeNum,
}
_, err := ... | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.