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 |
|---|---|---|---|---|
polynom.py | """
Modular arithmetic
"""
from collections import defaultdict
import numpy as np
class ModInt:
"""
Integers of Z/pZ
"""
def __init__(self, a, n):
self.v = a % n
self.n = n
def __eq__(a, b):
if isinstance(b, ModInt):
|
else:
return NotImplemented
def __hash__(self):
return hash((self.v, self.n))
def __bool__(self):
return bool(self.v)
def __add__(a, b):
assert isinstance(b, ModInt)
assert a.n == b.n
return ModInt(a.v + b.v, a.n)
def __radd__(a, b):
... | return not bool(a - b) | conditional_block |
polynom.py | """
Modular arithmetic
"""
from collections import defaultdict
import numpy as np
class ModInt:
"""
Integers of Z/pZ
"""
def __init__(self, a, n):
self.v = a % n
self.n = n
def __eq__(a, b):
if isinstance(b, ModInt):
return not bool(a - b)
else:
... | (A, B):
Q = [0 * B[0]] * max(0, len(A) - len(B) + 1)
while len(A.C) >= len(B.C):
Q[len(A.C) - len(B.C)] = A[-1] / B[-1]
A -= B.shift(len(A) - len(B)) * (A[-1] / B[-1])
return Polynomial(Q), A
def __floordiv__(A, B):
assert isinstance(B, Polynomial)
re... | euclidean_division | identifier_name |
models.go | package accesscontrol
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/util/errutil"
)
var ErrInternal = errutil.NewBase(... | () bool {
return strings.HasPrefix(r.Name, FixedRolePrefix)
}
func (r *RoleDTO) IsPlugin() bool {
return strings.HasPrefix(r.Name, PluginRolePrefix)
}
func (r *RoleDTO) IsBasic() bool {
return strings.HasPrefix(r.Name, BasicRolePrefix) || strings.HasPrefix(r.UID, BasicRoleUIDPrefix)
}
func (r *RoleDTO) IsExternal... | IsFixed | identifier_name |
models.go | package accesscontrol
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/util/errutil"
)
var ErrInternal = errutil.NewBase(... |
dedupMap[cmd.Permissions[i]] = true
dedup = append(dedup, cmd.Permissions[i])
}
cmd.Permissions = dedup
if cmd.ServiceAccountID <= 0 {
return fmt.Errorf("invalid service account id %d", cmd.ServiceAccountID)
}
return nil
}
const (
GlobalOrgID = 0
FixedRolePrefix = "fixed:"... | {
continue
} | conditional_block |
models.go | package accesscontrol
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/util/errutil"
)
var ErrInternal = errutil.NewBase(... | }
type SaveExternalServiceRoleCommand struct {
OrgID int64
Global bool
ExternalServiceID string
ServiceAccountID int64
Permissions []Permission
}
func (cmd *SaveExternalServiceRoleCommand) Validate() error {
if cmd.ExternalServiceID == "" {
return errors.New("external service id ... | BuiltinRole string `json:"builtInRole,omitempty"`
Permission string `json:"permission"` | random_line_split |
models.go | package accesscontrol
import (
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"github.com/grafana/grafana/pkg/infra/slugify"
"github.com/grafana/grafana/pkg/services/annotations"
"github.com/grafana/grafana/pkg/services/org"
"github.com/grafana/grafana/pkg/util/errutil"
)
var ErrInternal = errutil.NewBase(... |
func (r *RoleDTO) IsFixed() bool {
return strings.HasPrefix(r.Name, FixedRolePrefix)
}
func (r *RoleDTO) IsPlugin() bool {
return strings.HasPrefix(r.Name, PluginRolePrefix)
}
func (r *RoleDTO) IsBasic() bool {
return strings.HasPrefix(r.Name, BasicRolePrefix) || strings.HasPrefix(r.UID, BasicRoleUIDPrefix)
}
f... | {
return strings.HasPrefix(r.Name, ManagedRolePrefix)
} | identifier_body |
hslcolor.rs | //! This file implements what I refer to as HSL but which would precisely be called sHSL: a simple
//! transformation of sRGB that creates a cylindrical space. HSL has the same problems with
//! perceptual uniformity and general unsuitability for exact psychophysically-accurate
//! representation as color as sRGB does,... |
#[test]
fn test_hsl_rgb_conversion() {
let red_rgb = RGBColor {
r: 1.,
g: 0.,
b: 0.,
};
let red_hsl: HSLColor = red_rgb.convert();
assert!(red_hsl.h.abs() <= 0.0001);
assert!((red_hsl.s - 1.0) <= 0.0001);
assert!((red_hsl.l - 0... | random_line_split | |
hslcolor.rs | //! This file implements what I refer to as HSL but which would precisely be called sHSL: a simple
//! transformation of sRGB that creates a cylindrical space. HSL has the same problems with
//! perceptual uniformity and general unsuitability for exact psychophysically-accurate
//! representation as color as sRGB does,... |
}
impl From<HSLColor> for Coord {
fn from(val: HSLColor) -> Self {
Coord {
x: val.h,
y: val.s,
z: val.l,
}
}
}
impl Bound for HSLColor {
fn bounds() -> [(f64, f64); 3] {
[(0., 360.), (0., 1.), (0., 1.)]
}
}
impl FromStr for HSLColor {
t... | {
HSLColor {
h: c.x,
s: c.y,
l: c.z,
}
} | identifier_body |
hslcolor.rs | //! This file implements what I refer to as HSL but which would precisely be called sHSL: a simple
//! transformation of sRGB that creates a cylindrical space. HSL has the same problems with
//! perceptual uniformity and general unsuitability for exact psychophysically-accurate
//! representation as color as sRGB does,... | else if self.h <= 180.0 {
(0.0, chroma, x)
} else if self.h <= 240.0 {
(0.0, x, chroma)
} else if self.h <= 300.0 {
(x, 0.0, chroma)
} else {
(chroma, 0.0, x)
};
// now we add the right value to each component to get the correct li... | {
(x, chroma, 0.0)
} | conditional_block |
hslcolor.rs | //! This file implements what I refer to as HSL but which would precisely be called sHSL: a simple
//! transformation of sRGB that creates a cylindrical space. HSL has the same problems with
//! perceptual uniformity and general unsuitability for exact psychophysically-accurate
//! representation as color as sRGB does,... | () {
let red_rgb = RGBColor {
r: 1.,
g: 0.,
b: 0.,
};
let red_hsl: HSLColor = red_rgb.convert();
assert!(red_hsl.h.abs() <= 0.0001);
assert!((red_hsl.s - 1.0) <= 0.0001);
assert!((red_hsl.l - 0.5) <= 0.0001);
assert!(red_hsl.dis... | test_hsl_rgb_conversion | identifier_name |
channel_layout.rs | use std::{array, ffi::CString, fmt, mem, ptr, slice};
use crate::{
ffi::{AVChannel, AVChannelOrder, *},
Error,
};
// new channel layout since 5.1
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(i32)]
pub enum Channel {
None = AVChannel::AV_CHAN_NONE.0,
FrontLeft = AVChannel::AV_CHAN_FRONT_LEFT.0,
FrontRight... | {
order: u32,
mask: Option<u64>,
map: Option<Vec<CustomChannel>>,
}
#[derive(Deserialize)]
#[serde(untagged, crate = "serde_")]
enum VersionedLayout {
Old(OldLayout),
New(NewLayout),
}
let (order, u, nb_channels);
match VersionedLayout::deserialize(deserializer)? {
Vers... | NewLayout | identifier_name |
channel_layout.rs | use std::{array, ffi::CString, fmt, mem, ptr, slice};
use crate::{
ffi::{AVChannel, AVChannelOrder, *},
Error,
};
// new channel layout since 5.1
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(i32)]
pub enum Channel {
None = AVChannel::AV_CHAN_NONE.0,
FrontLeft = AVChannel::AV_CHAN_FRONT_LEFT.0,
FrontRight... |
#[test]
fn old_format() {
let x: ChannelLayout = serde_json::from_str(r#"{ "bits": 31 }"#).unwrap();
assert_eq!(x.0.order, AVChannelOrder::AV_CHANNEL_ORDER_NATIVE);
assert_eq!(x.0.nb_channels, 5);
assert_eq!(unsafe { x.0.u.mask }, 31);
}
}
}
| {
round_trip_debug(ChannelLayout::native(&[Channel::StereoRight, Channel::LowFrequency]));
round_trip_debug(ChannelLayout::custom(&[
CustomChannel::new(Channel::LowFrequency, Some("low-freq")),
CustomChannel::new(Channel::BackCenter, None),
]));
} | identifier_body |
channel_layout.rs | use std::{array, ffi::CString, fmt, mem, ptr, slice};
use crate::{
ffi::{AVChannel, AVChannelOrder, *},
Error,
};
// new channel layout since 5.1
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(i32)]
pub enum Channel {
None = AVChannel::AV_CHAN_NONE.0,
FrontLeft = AVChannel::AV_CHAN_FRONT_LEFT.0,
FrontRight... | }
d.field("opaque", &self.0.opaque);
d.finish()
}
}
impl PartialEq for ChannelLayout {
fn eq(&self, other: &ChannelLayout) -> bool {
unsafe {
let ord = av_channel_layout_compare(self.as_ptr(), other.as_ptr());
match ord {
// negative return values for invalid layouts
..=-1 => false,
0 =>... | } | random_line_split |
homework1.py | '''
@Author: Shihan Ran
@Date: 2019-10-06 12:08:55
@LastEditors: Shihan Ran
@LastEditTime: 2019-10-13 13:29:02
@Email: rshcaroline@gmail.com
@Software: VSCode
@License: Copyright(C), UCSD
@Description:
'''
#%% [markdown]
# # Task -- Regression
# First, let’s see how ratings can be predicted as a function of (a) wheth... | atureNames, labelName):
train = data[:int(len(data)*ratio)]
test = data[int(len(data)*ratio):]
print("================ For ratio ", ratio, "================")
myRegression(featureNames, labelName, train, test)
#%%
trainByRatio(0.9, data, featureNames, labelName)
#%% [markdown]
# ## Problem 6
# R... | taTrain[labelName]
theta, residuals, rank, s = np.linalg.lstsq(X, y)
print("================ Training ================")
MSE = ((y - np.dot(X, theta))**2).mean()
for i in range(len(theta)):
print("Theta%1d: %.5f" % (i, theta[i]))
print("MSE: %.3f" % MSE)
print("================ Testing =... | identifier_body |
homework1.py | '''
@Author: Shihan Ran
@Date: 2019-10-06 12:08:55
@LastEditors: Shihan Ran
@LastEditTime: 2019-10-13 13:29:02
@Email: rshcaroline@gmail.com
@Software: VSCode
@License: Copyright(C), UCSD
@Description:
'''
#%% [markdown]
# # Task -- Regression
# First, let’s see how ratings can be predicted as a function of (a) wheth... | ain = data[:int(len(data)*ratio)]
test = data[int(len(data)*ratio):]
print("================ For ratio ", ratio, "================")
myClassification(featureNames, labelName, train, test)
featureNames = ['theta_zero', 'star_rating', 'review_body_length']
labelName = 'verified_purchase_int'
ratio = 0.9
trai... | ame):
tr | identifier_name |
homework1.py | '''
@Author: Shihan Ran
@Date: 2019-10-06 12:08:55
@LastEditors: Shihan Ran
@LastEditTime: 2019-10-13 13:29:02
@Email: rshcaroline@gmail.com
@Software: VSCode
@License: Copyright(C), UCSD
@Description:
'''
#%% [markdown]
# # Task -- Regression
# First, let’s see how ratings can be predicted as a function of (a) wheth... |
#%% [markdown]
# ## Problem 3
# Train a simple predictor to predict the star rating using two features:
#
# star_rating ≃ θ0 + θ1 × [review is verified] + θ2 × [review length].
#
# Report the values of θ0, θ1, and θ2. Briefly describe your interpretation of these values, i.e., what do θ0, θ1, and θ2 represent? Explain... |
#%% [markdown]
# We can see from the above plot and printout that most of ratings are 5-star (87%) while the least rating is 2-star (only 1%), which means this dataset is extremely unbalanced.
#
# The dataset only has 6 rows containing NA value and we decide to remove them from the data. | random_line_split |
homework1.py | '''
@Author: Shihan Ran
@Date: 2019-10-06 12:08:55
@LastEditors: Shihan Ran
@LastEditTime: 2019-10-13 13:29:02
@Email: rshcaroline@gmail.com
@Software: VSCode
@License: Copyright(C), UCSD
@Description:
'''
#%% [markdown]
# # Task -- Regression
# First, let’s see how ratings can be predicted as a function of (a) wheth... | [markdown]
# We can see from the above plot and printout that most of ratings are 5-star (87%) while the least rating is 2-star (only 1%), which means this dataset is extremely unbalanced.
#
# The dataset only has 6 rows containing NA value and we decide to remove them from the data.
#%% [markdown]
# ## Problem 3
# T... | "The percent of %1d-star: %.1f%%" % (i, (len(data[data['star_rating']==i])/len(data)*100)))
#%% | conditional_block |
page-email-management.js | 'use strict';
vm.currentMenu('Email Management');
vm.currentTitle("Email Management");
vm.breadcrumb([{ title: 'Operational', href: '#' },{ title: 'Email Management', href: viewModel.appName + 'page/emailmanagement' }]);
viewModel.Email = new Object();
var em = viewModel.Email;
em.templateEmail = {
_id: "",
... | em.isInterval(true);
}
});
var catVal = $('#categoryList').data('kendoDropDownList').value();
if(catVal == "alarm01") {
$('#templateMail').html(em.TemplateMailList().alarmTemplate)
} else {
$('#templateMail').html(em.TemplateMailList().dataTemplate)
}
}
em.reset... | em.isAlarmCode(true);
} else if(val.indexOf("isInterval") >= 0) { | random_line_split |
page-email-management.js | 'use strict';
vm.currentMenu('Email Management');
vm.currentTitle("Email Management");
vm.breadcrumb([{ title: 'Operational', href: '#' },{ title: 'Email Management', href: viewModel.appName + 'page/emailmanagement' }]);
viewModel.Email = new Object();
var em = viewModel.Email;
em.templateEmail = {
_id: "",
... |
}
};
em.checkCategory = function() {
em.showHide($('#categoryList').data('kendoDropDownList').value());
}
em.showHide = function(category) {
var resObj = em.CategoryMailList().filter(function(obj) {
return obj.value == category;
});
var condition = resObj[0].condition.split(",");
em.i... | {
(function () {
var idtemp = '';
$('.deletecheck').each(function (index) {
$(this).prop("checked", false);
idtemp = $(this).attr('idcheck');
em.tempCheckIdDelete.remove(function (item) {
retu... | conditional_block |
binary_search_tree1.py | # 来源知乎 https://zhuanlan.zhihu.com/p/51987247
# 博客 https://www.cnblogs.com/yangecnu/p/Introduce-Binary-Search-Tree.html
"""
二叉查找树 (Binary Search Tree, BST)
特点 : left < root < right
若任意节点的左子树不空,则左子树上所有结点的 值均小于它的根结点的值;
若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树;
没有键值相等的节点(no ... | ly one child or no child 的情形
if node.left and node.right:
# find the largest in the left subtree as successor
tmp = self._find_extremum(node.left) # default by max
# Copy the inorder successor's content to this node
node.d... | 个或零个节点
### 所以转化成了前边 Node with on | identifier_body |
binary_search_tree1.py | # 来源知乎 https://zhuanlan.zhihu.com/p/51987247
# 博客 https://www.cnblogs.com/yangecnu/p/Introduce-Binary-Search-Tree.html
"""
二叉查找树 (Binary Search Tree, BST)
特点 : left < root < right
若任意节点的左子树不空,则左子树上所有结点的 值均小于它的根结点的值;
若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树;
没有键值相等的节点(no ... | an the root's key
# then it lies in right subtree
elif value > node.data:
node.right = self._delete(value, node.right)
# If key is same as root's key, then this is the node
# to be deleted
else: # step2
# Node with two childr... | ter th | identifier_name |
binary_search_tree1.py | # 来源知乎 https://zhuanlan.zhihu.com/p/51987247
# 博客 https://www.cnblogs.com/yangecnu/p/Introduce-Binary-Search-Tree.html
"""
二叉查找树 (Binary Search Tree, BST)
特点 : left < root < right
若任意节点的左子树不空,则左子树上所有结点的 值均小于它的根结点的值;
若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树;
没有键值相等的节点(no ... | # is_left 作用跟踪是否为左子节点
is_left = True
elif value > node.data:
node = node.right
is_left = False
# while 循环完没找到,则node is None
# while 循环完找到的话,则node is not None 跳过if,return 找到的node
if alert and node is None: # alert and (node is None)... | and value != node.data:
# _pre_node 作用跟踪父节点
_pre_node = node
if value < node.data:
node = node.left
| conditional_block |
binary_search_tree1.py | # 来源知乎 https://zhuanlan.zhihu.com/p/51987247
# 博客 https://www.cnblogs.com/yangecnu/p/Introduce-Binary-Search-Tree.html
"""
二叉查找树 (Binary Search Tree, BST)
特点 : left < root < right
若任意节点的左子树不空,则左子树上所有结点的 值均小于它的根结点的值;
若任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树;
没有键值相等的节点(no ... | if result.left is None:
# print('---')
# print(id(result),id(result.right)) # 46446408 1352705168
result = result.right
# print(id(result)) # 1352705168
else:
result = result.left
# 将 result 赋成 pre_node ... | # 有1个或者没有
else: | random_line_split |
new_solver_4.py | # -*- coding: mbcs -*-
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from optimization import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
i... |
#list_vertices_left = []
for k in network.boundary_nodes_left:
ridge=list_nodes_ridges[k]
#print(ridge)
instancename = 'Part-' + str(ridge[0]+1) + '-1'
try:
coords = (vertices[k][0],vertices[k][1],vertices[k][2])
except IndexError:
coords = (verti... | myModel.DisplacementBC(amplitude=UNSET, createStepName='Step-1', distributionType=UNIFORM, fieldName='', fixed=OFF, localCsys=None, name='BC-'+str(ridge[0]+1), region=Region(vertices=mdb.models['Model-1'].rootAssembly.instances[instancename].vertices[1:]), u1=traction_distance, u2=0.0,u3=0.0,ur3=UNSET)
... | conditional_block |
new_solver_4.py | # -*- coding: mbcs -*-
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from optimization import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
i... | (network): ## can be changed with the node label list
#list_vertices_right = []
for k in network.boundary_nodes_right:
ridge=list_nodes_ridges[k]
#print(ridge)
instancename = 'Part-' + str(ridge[0]+1) + '-1'
try:
coords = (vertices[k][0],vertices[k][1],vertices[k][2])... | set_boundary_conditions | identifier_name |
new_solver_4.py | # -*- coding: mbcs -*-
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from optimization import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
i... | vertice1 = myModel.rootAssembly.instances[instancename1].vertices.findAt(coords)
vertice2 = myModel.rootAssembly.instances[instancename2].vertices.findAt(coords)
connector_list.append((vertice1, vertice2))
myModel.rootAssembly.WirePolyLine(mergeType=IMPRINT, meshable=OFF
, points=tuple(connector_list)... | for i in range(len(list_ridge)-1):
instancename1='Part-'+str(list_ridge[i]+1)+'-1'
instancename2='Part-'+str(list_ridge[i+1]+1)+'-1' | random_line_split |
new_solver_4.py | # -*- coding: mbcs -*-
from part import *
from material import *
from section import *
from assembly import *
from step import *
from interaction import *
from load import *
from mesh import *
from optimization import *
from job import *
from sketch import *
from visualization import *
from connectorBehavior import *
i... |
list_nodes_ridges=[[] for i in range(len(vertices))]
for i in range(len(ridge_vertices)):
list_nodes_ridges[ridge_vertices[i][0]].append(i)
list_nodes_ridges[ridge_vertices[i][1]].append(i)
def create_connectors(network):
connector_list=[]
for k in range(len(list_nodes_ridges)):
if int(network.dimension)==2... | number_elements = []
for i in range(len(ridge_vertices)):
instancename = 'Part-' + str(i+1) + '-1'
#myModel.rootAssembly.setElementType(elemTypes=(ElemType(
# elemCode=B21, elemLibrary=STANDARD), ), regions=(
# myModel.rootAssembly.instances[instancename].edges.getSequenceFromMask(
# mask=('[#1 ]', ), ), ))
... | identifier_body |
analysis.py | # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from kde import kde
from mpld3 import plugins
import tsne as lib_tsne
import util
from util import CYTOF_LENGTH_NAMES
# backgating in tsne
from scipy.spatial import cKDTree ... |
else:
ax.set_title(titles[0])
return fig
def hist2(datasets, axis1, axis2, bins = None,
xmin = None, xmax = None, ymin = None, ymax = None, range_ = None,
axes = None, transform = None):
datax = util.extract_data(datasets, axis1)
datay = util.extract_data(datasets, a... | ax.legend() | conditional_block |
analysis.py | # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from kde import kde
from mpld3 import plugins
import tsne as lib_tsne
import util
from util import CYTOF_LENGTH_NAMES
# backgating in tsne
from scipy.spatial import cKDTree ... | for pts in points:
if sample < pts.shape[0]:
# If we have enough points to subsample
sample_masks.append(np.random.choice(pts.shape[0], sample, replace = False))
else:
# Otherwise we add all the points
sample_masks.append(np.array(range(pts.shape[0])))... | # Randomly sample to reduce the number of points
sample_masks = [] | random_line_split |
analysis.py | # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from kde import kde
from mpld3 import plugins
import tsne as lib_tsne
import util
from util import CYTOF_LENGTH_NAMES
# backgating in tsne
from scipy.spatial import cKDTree ... | (df, cmap ='RdBu' ):
"""Draw a heatmap table.
"""
# TODO: mpld3 does not display axis labels properly
# TODO: Replace with an interactive plot, see bokeh:
# http://bokeh.pydata.org/docs/gallery/les_mis.html
fig, ax = plt.subplots()
data = df.as_matrix()
if isinstance(cmap, str):... | heatmap | identifier_name |
analysis.py | # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from kde import kde
from mpld3 import plugins
import tsne as lib_tsne
import util
from util import CYTOF_LENGTH_NAMES
# backgating in tsne
from scipy.spatial import cKDTree ... |
def percent_matrix(datasets, label, relative_to = None):
"""Precentage of events with a given label.
Args:
dataset (list): List of FlowData objects
label (list or string): name(s) of boolean columns in datasets
"""
if relative_to is None:
fn = lambda fd, la: fd[fd[la]].s... | """Counts the events in the given label.
Args:
dataset (list): List of FlowData objects
label (list or string): name(s) of boolean columns in datasets
"""
fn = lambda fd, axis: fd.shape[0]
return fn_matrix(datasets, fn, axes = None, label = labels) | identifier_body |
main.rs | #![forbid(unsafe_code)]
mod certificates;
mod codes;
mod metadata;
use codes::*;
use metadata::{FileOptions, PresetMeta};
use {
once_cell::sync::Lazy,
percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS},
rcgen::{Certificate, CertificateParams, DnType},
rustls::server::ServerConf... |
// correct host
if let Some(domain) = url.domain() {
// because the gemini scheme is not special enough for WHATWG, normalize
// it ourselves
let host = Host::parse(
&percent_decode_str(domain)
.decode_utf8()
.o... | // no userinfo and no fragment
if url.password().is_some() || !url.username().is_empty() || url.fragment().is_some() {
return Err((BAD_REQUEST, "URL contains fragment or userinfo"));
} | random_line_split |
main.rs | #![forbid(unsafe_code)]
mod certificates;
mod codes;
mod metadata;
use codes::*;
use metadata::{FileOptions, PresetMeta};
use {
once_cell::sync::Lazy,
percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS},
rcgen::{Certificate, CertificateParams, DnType},
rustls::server::ServerConf... | else {
// already listening on the other unspecified address
log::warn!("Could not start listener on {}, but already listening on another unspecified address. Probably your system automatically listens in dual stack?", addr);
continue;... | {
panic!("Failed to listen on {addr}: {e}")
} | conditional_block |
main.rs | #![forbid(unsafe_code)]
mod certificates;
mod codes;
mod metadata;
use codes::*;
use metadata::{FileOptions, PresetMeta};
use {
once_cell::sync::Lazy,
percent_encoding::{percent_decode_str, percent_encode, AsciiSet, CONTROLS},
rcgen::{Certificate, CertificateParams, DnType},
rustls::server::ServerConf... | <T> {
stream: TlsStream<T>,
local_port_check: Option<u16>,
log_line: String,
metadata: Arc<Mutex<FileOptions>>,
}
impl RequestHandle<TcpStream> {
/// Creates a new request handle for the given stream. If establishing the TLS
/// session fails, returns a corresponding log line.
async fn new(... | RequestHandle | identifier_name |
certificate_manager.rs | // Copyright (c) Microsoft. All rights reserved.
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use futures::future::Either;
#[cfg(unix)]
use openssl::pkcs12::Pkcs12;
#[cfg(unix)]
use openssl::pkey::PKey;
#[cfg(unix)]
use openssl::stack::Stack;
#[cfg(unix)]
use openssl::x509::X509;
use tokio::prelu... | use edgelet_core::CertificateProperties;
use failure::ResultExt;
pub use crate::error::{Error, ErrorKind};
pub struct CertificateManager<C: CreateCertificate + Clone> {
certificate: Arc<RwLock<Option<Certificate>>>,
crypto: C,
props: CertificateProperties,
creation_time: Instant,
}
#[derive(Clone)]
s... |
use edgelet_core::crypto::{
Certificate as CryptoCertificate, CreateCertificate, KeyBytes, PrivateKey, Signature,
}; | random_line_split |
certificate_manager.rs | // Copyright (c) Microsoft. All rights reserved.
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use futures::future::Either;
#[cfg(unix)]
use openssl::pkcs12::Pkcs12;
#[cfg(unix)]
use openssl::pkey::PKey;
#[cfg(unix)]
use openssl::stack::Stack;
#[cfg(unix)]
use openssl::x509::X509;
use tokio::prelu... |
}
}
#[derive(Clone)]
struct TestCrypto {
created: bool,
}
impl TestCrypto {
pub fn new() -> Result<Self, CoreError> {
Ok(Self { created: true })
}
}
impl CoreCreateCertificate for TestCrypto {
type Certificate = TestCertificate;
... | {
if let ErrorKind::CertificateTimerCreationError = err.kind() {
assert_eq!(true, true);
} else {
panic!(
"Expected a CertificteTimerCreationError type, but got {:?}",
err
);
... | conditional_block |
certificate_manager.rs | // Copyright (c) Microsoft. All rights reserved.
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use futures::future::Either;
#[cfg(unix)]
use openssl::pkcs12::Pkcs12;
#[cfg(unix)]
use openssl::pkey::PKey;
#[cfg(unix)]
use openssl::stack::Stack;
#[cfg(unix)]
use openssl::x509::X509;
use tokio::prelu... | {}
impl CoreCertificate for TestCertificate {
type Buffer = String;
type KeyBuffer = Vec<u8>;
fn pem(&self) -> Result<Self::Buffer, CoreError> {
Ok("test".to_string())
}
fn get_private_key(&self) -> Result<Option<CorePrivateKey<Self::KeyBuffer>>, CoreError> {
... | TestCertificate | identifier_name |
certificate_manager.rs | // Copyright (c) Microsoft. All rights reserved.
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use futures::future::Either;
#[cfg(unix)]
use openssl::pkcs12::Pkcs12;
#[cfg(unix)]
use openssl::pkey::PKey;
#[cfg(unix)]
use openssl::stack::Stack;
#[cfg(unix)]
use openssl::x509::X509;
use tokio::prelu... |
fn get_private_key(&self) -> Result<Option<CorePrivateKey<Self::KeyBuffer>>, CoreError> {
Ok(Some(PrivateKey::Key(KeyBytes::Pem(
"akey".to_string().as_bytes().to_vec(),
))))
}
fn get_valid_to(&self) -> Result<DateTime<Utc>, CoreError> {
Ok(D... | {
Ok("test".to_string())
} | identifier_body |
huifushishichang.js | var HFSSCTotal = doc.getElementById("HFSSCTotal"),
HFSSCTotalPage = 0,
HFSSCnumPerPage = doc.getElementById("HFSSCnumPerPage"),
HFSSCnumPer = 20,
HFSSCassignPage = doc.getElementById("HFSSCassignPage"),
HFSSCconfirm = doc.getElementById("HFSSCconfirm");
var HFSSCloadpage = 1,
HFSSCdataSource = [],
HFSS... | ******before detail a, now with td
// add data rows
for(var i=0;i<HFSSCdataSource.length;i++){
var tr = doc.createElement("tr");
var td = doc.createElement('td'),
span = doc.createElement('span');
span.innerHTML = '🔝';
td.appendChild(span);
td.style.width = '2%';
tr.appendChild(td);
tr.o... | Child(tr);
}
// ********* | conditional_block |
huifushishichang.js | var HFSSCTotal = doc.getElementById("HFSSCTotal"),
HFSSCTotalPage = 0,
HFSSCnumPerPage = doc.getElementById("HFSSCnumPerPage"),
HFSSCnumPer = 20,
HFSSCassignPage = doc.getElementById("HFSSCassignPage"),
HFSSCconfirm = doc.getElementById("HFSSCconfirm");
var HFSSCloadpage = 1,
HFSSCdataSource = [],
HFSS... | etElementById("HFSSCPageBefore"),
HFSSCnextPage = doc.getElementById("HFSSCPageNext"),
HFSSCPageNum = doc.getElementById("HFSSCPageNum");
HFSSCbeforePage.onclick = function(){
if(HFSSCloadpage==1){alert("已经是第一页");}
else{
HFSSCloadpage --;
//console.log(HFSSCloadpage);
var url2 = "http://123.20... | {
var table = doc.getElementById("HFSSC_table");
var thead = doc.getElementById("HFSSC_table_head");
table.innerHTML = '';
thead.innerHTML = '';
//add table head
var top = doc.getElementById('HFSSC_table_top');
if(HFSSCloadpage != 1){
top.style.display = 'none';
}else{
top.style.display = 'block... | identifier_body |
huifushishichang.js | var HFSSCTotal = doc.getElementById("HFSSCTotal"),
HFSSCTotalPage = 0,
HFSSCnumPerPage = doc.getElementById("HFSSCnumPerPage"),
HFSSCnumPer = 20,
HFSSCassignPage = doc.getElementById("HFSSCassignPage"),
HFSSCconfirm = doc.getElementById("HFSSCconfirm");
var HFSSCloadpage = 1,
HFSSCdataSource = [],
HFSS... | HFSSCTotalPage = data.pageCount;
HFSSCPageNum.placeholder = HFSSCloadpage;
insertHFSSCTable();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}else{
HFSSCloadpage = tempPage;
alert('超出页数上限,请重新选择页数');
}
}else{
alert('请... | success: function (data) {
HFSSCdataSource = data.data;
HFSSCdataTitle = data.header;
| random_line_split |
huifushishichang.js | var HFSSCTotal = doc.getElementById("HFSSCTotal"),
HFSSCTotalPage = 0,
HFSSCnumPerPage = doc.getElementById("HFSSCnumPerPage"),
HFSSCnumPer = 20,
HFSSCassignPage = doc.getElementById("HFSSCassignPage"),
HFSSCconfirm = doc.getElementById("HFSSCconfirm");
var HFSSCloadpage = 1,
HFSSCdataSource = [],
HFSS... | onfirm.onclick = function(){
tempPage = HFSSCloadpage;
HFSSCloadpage = parseFloat(HFSSCassignPage.value);
if(isInteger(HFSSCloadpage)){
console.log(HFSSCloadpage);
if(HFSSCloadpage <= HFSSCTotalPage){
var url2 = "http://123.206.134.34:8080/Medicals_war/recovery/morethan1hour?rowCount="+ HFSSCnumPer +"&p... |
HFSSCc | identifier_name |
device-stats.js | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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/li... |
if (ws) {
ws.onmessage = function (event) {
var dataPoint = JSON.parse(event.data);
if (dataPoint) {
var time = parseInt(dataPoint[4]) / 1000;
switch (dataPoint[typeId]) {
case "battery":
graphUpdate(batteryData, time, dataPoint[batteryId]);
graphMap["battery"].updat... | {
console.log('WebSocket is not supported by this browser.');
} | conditional_block |
device-stats.js | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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/li... |
var graphMap = {};
var graphSettingsMap = {};
var palette = new Rickshaw.Color.Palette({scheme: "munin"});
var elemTop;
$(window).load(function () {
graphMap["battery"]=lineGraph("battery", batteryData);
graphMap["light"]=lineGraph("light", lightData);
graphMap["pressure"]=lineGraph("pressure", pressureData);
... | var rotation_xData = [];
var rotation_yData = [];
var rotation_zData = []; | random_line_split |
device-stats.js | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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/li... |
function lineGraph(type, chartData) {
var tNow = new Date().getTime() / 1000;
for (var i = 0; i < 30; i++) {
chartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
}
var $elem = $("#chart-" + type);
var graph = new Rickshaw.Graph({
element: $elem[0],
width: $elem.width() - 100,
height: ... | {
var tNow = new Date().getTime() / 1000;
for (var i = 0; i < 30; i++) {
xChartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
yChartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
zChartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
}
var $elem = $("#ch... | identifier_body |
device-stats.js | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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/li... | (chartData, xValue, yValue) {
chartData.push({
x: parseInt(xValue),
y: parseFloat(yValue)
});
chartData.shift();
}
function disconnect() {
if (ws != null) {
ws.close();
ws = null;
}
}
function maximizeGraph(graph, width,height){
graphSettingsMap[graph.element.id] = {'width': graph.width, 'height': graph... | graphUpdate | identifier_name |
db_helpher.go | /**************************************************************
【提交类型】:BUG/新功能/需求修改/版本制作/代码整理/解决编译不过
【问题描述】:db模块代码
【修改内容】:初次提交
【提交人】:failymao
【评审人】:
***************************************************************/
package db
import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"regexp"
"strc... | }
for key, value := range param {
keys = append(keys, key)
switch value.(type) {
case int, int64, int32:
values = append(values, strconv.FormatInt(int64(value.(int)), 10))
case uint64, uint32:
values = append(values, strconv.FormatUint(value.(uint64), 10))
case string:
values = append(values, "'" ... | var keys []string
var values []string
if len(m.pk) != 0 {
delete(param, m.pk) | random_line_split |
db_helpher.go | /**************************************************************
【提交类型】:BUG/新功能/需求修改/版本制作/代码整理/解决编译不过
【问题描述】:db模块代码
【修改内容】:初次提交
【提交人】:failymao
【评审人】:
***************************************************************/
package db
import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"regexp"
"strc... | angwj 交易明细表增加以太坊交易hash值
n,err := Connect.SetTable(TransactionDetail).Insert(value)
if err != nil {
fmt.Println("UpdateBalance insert value to transaction_detail failed:", err)
return err
}
fmt.Println("UpdateBalance effected rows quantity is :", n)
return err
}
//用户间转账
func TransBetweenUsers (serialNum stri... | unt
value[TXStatus] = MSG_AWAIT_CONFIRM
value["Txhash"] = txhash //add 2018-7-4 sh | identifier_body |
db_helpher.go | /**************************************************************
【提交类型】:BUG/新功能/需求修改/版本制作/代码整理/解决编译不过
【问题描述】:db模块代码
【修改内容】:初次提交
【提交人】:failymao
【评审人】:
***************************************************************/
package db
import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"regexp"
"strc... | s.Join([]string{info[AppID] + ":" + info[PassWord]+ ":" + info[TimeStamp]}, "")
hash := sha256.New()
hash.Write([]byte(plaintext))
md := hash.Sum(nil)
mdStr := hex.EncodeToString(md)
if sign != mdStr {
fmt.Println("Verification failed!")
return MSG_VERIFY_FAILED
}
fmt.Println("Verification success!")
retur... | xt := string | identifier_name |
db_helpher.go | /**************************************************************
【提交类型】:BUG/新功能/需求修改/版本制作/代码整理/解决编译不过
【问题描述】:db模块代码
【修改内容】:初次提交
【提交人】:failymao
【评审人】:
***************************************************************/
package db
import (
"database/sql"
"errors"
"fmt"
_ "github.com/go-sql-driver/mysql"
"regexp"
"strc... | 库中读取用户信息并加密,判断解析后的公共参数是否与从数据库取出并加密后的哈希值相等,相等则鉴权成功
plaintext := strings.Join([]string{info[AppID] + ":" + info[PassWord]+ ":" + info[TimeStamp]}, "")
hash := sha256.New()
hash.Write([]byte(plaintext))
md := hash.Sum(nil)
mdStr := hex.EncodeToString(md)
if sign != mdStr {
fmt.Println("Verification failed!")
re... | n")
return MSG_INVALID_INPUTINFO
}
//不能从缓存中取,否则造成eth和db的循环引用
//从数据 | conditional_block |
server.py | __author__ = 'Wade Pentz'
import os
import time
import logging
import asyncore
import asynchat
import socket
from config import config
from client_api import client_api
from logs import server_log, file_formatter
"""server.py
The Server class uses the asyncore library to set up a local, asynchronous se... |
def handle_ready(self):
server_log.info(str(self.client_id) + ': Client ready, sending test request')
self.push(client_api["run_tests"] + client_api["terminator"])
def handle_start(self):
server_log.info(str(self.client_id) + ': Client started running tests')
self.stat... | server_log.info(str(self.client_id) + ': Sending client id')
self.push(client_api["set_client_id"] + client_api["delimiter"] + str(self.client_id) + client_api["terminator"]) | identifier_body |
server.py | __author__ = 'Wade Pentz'
import os
import time
import logging
import asyncore
import asynchat
import socket
from config import config
from client_api import client_api
from logs import server_log, file_formatter
"""server.py
The Server class uses the asyncore library to set up a local, asynchronous se... |
else:
return True
def write_report(self):
"""Writes out a report that displays data for all clients that ran."""
self.end_time = time.strftime('%Y-%m-%d_%H:%M:%S')
server_log.info('')
server_log.info('=====================================================... | return False | conditional_block |
server.py | __author__ = 'Wade Pentz'
import os
import time
import logging
import asyncore
import asynchat
import socket
from config import config
from client_api import client_api
from logs import server_log, file_formatter
"""server.py
The Server class uses the asyncore library to set up a local, asynchronous se... | (self):
server_log.info(str(self.client_id) + ': File rolled over')
self.files_written += 1
if __name__ == '__main__':
server = None
try:
server = Server(config["host"], config["port"])
server.start_server()
except KeyboardInterrupt:
server_log.info('Keyb... | handle_file_rollover | identifier_name |
server.py | __author__ = 'Wade Pentz'
import os
import time
import logging
import asyncore
import asynchat
import socket
from config import config
from client_api import client_api
from logs import server_log, file_formatter
"""server.py
The Server class uses the asyncore library to set up a local, asynchronous se... | except KeyError as e:
server_log.info('Unhandled command received from client id {}: {}'.format(self.client_id, cmd))
except Exception as e:
server_log.info('Exception raised in server when receiving message from client: {!r}'.format(e))
raise e
finally:
... | self.msg = ''.join(self.msg_buffer)
self.msg_split = self.msg.split(client_api["delimiter"])
cmd = self.msg_split[0]
try:
self.msg_handler[cmd]()
| random_line_split |
model_new2_plot.py | from dolfin import *
import numpy as np
import scipy.sparse as sp
import scipy.interpolate
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from datetime import date
import os
import math
import sys
import h5py
impo... | # ##############
dt = 10
time_axis = range(0,t_final+dt,dt)
time_axis = np.array(time_axis)
def retrieve_result( filename_lin, filename_final ):
fdata = h5py.File( filename_lin, "r" )
n_f = fdata[ "n_f" ].value
n_t = fdata[ "n_t" ].value
n_u = fdata[ "n_u" ].value
n_p = fdata[ "n_p" ].value
num_... | T = FunctionSpace(mesh, "CG", 1)
t_final = 300
# ##############
# t_final = t_final/3 # only works for MPC | random_line_split |
model_new2_plot.py | from dolfin import *
import numpy as np
import scipy.sparse as sp
import scipy.interpolate
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from datetime import date
import os
import math
import sys
import h5py
impo... | ( filename_lin, filename_final ):
fdata = h5py.File( filename_lin, "r" )
n_f = fdata[ "n_f" ].value
n_t = fdata[ "n_t" ].value
n_u = fdata[ "n_u" ].value
n_p = fdata[ "n_p" ].value
num_t = fdata[ "num_t" ].value
num_u = fdata[ "num_u" ].value
num_p = fdata[ "num_p" ].value
n_e1 = fda... | retrieve_result | identifier_name |
model_new2_plot.py | from dolfin import *
import numpy as np
import scipy.sparse as sp
import scipy.interpolate
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from datetime import date
import os
import math
import sys
import h5py
impo... |
( n_f, n_t, n_u, n_p,
num_t, num_u, num_p,
n_e1, n_e2, n_e3,
t_range, v_range, p_range,
vbc_point, vbc_point2, vbc2_point, vbc2_point2,
tq_point, tq_point2, tq_point3,
final_array ) = retrieve_result( "model_new2_lin.data",
(drt + "/results1.npy") )
final_array2 = np.... | fdata = h5py.File( filename_lin, "r" )
n_f = fdata[ "n_f" ].value
n_t = fdata[ "n_t" ].value
n_u = fdata[ "n_u" ].value
n_p = fdata[ "n_p" ].value
num_t = fdata[ "num_t" ].value
num_u = fdata[ "num_u" ].value
num_p = fdata[ "num_p" ].value
n_e1 = fdata[ "n_e1" ].value
n_e2 = fdata[ "... | identifier_body |
model_new2_plot.py | from dolfin import *
import numpy as np
import scipy.sparse as sp
import scipy.interpolate
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
from datetime import date
import os
import math
import sys
import h5py
impo... |
Ux = scipy.interpolate.Rbf(xu_cor, yu_cor, u_x, function='linear')
Uy = scipy.interpolate.Rbf(xu_cor, yu_cor, u_y, function='linear')
u_xi = Ux(xm, ym)
u_yi = Uy(xm, ym)
# speed = np.sqrt( u_xi*u_xi + u_yi*u_yi )
( fig, ax ) = plt.subplots( num = 1,
# figsize=(6,3),
dpi=150 )
q_plot = plt.quiver( xm, ym, u_xi... | u_x[i] = np.sign( u_x[i] ) * abs( u_x[i] )**(0.7)
u_y[i] = np.sign( u_y[i] ) * abs( u_y[i] )**(0.7) | conditional_block |
full_section_then_mfovs_thumbs_blobs.py | import cv2
import os
import numpy as np
from mb_aligner.common.detectors.blob_detector_2d import BlobDetector2D
from mb_aligner.common.matcher import FeaturesMatcher
from rh_logger.api import logger
import logging
import rh_logger
from mb_aligner.common.thread_local_storage_lru import ThreadLocalStorageLRU
import tinyr... |
@staticmethod
def match_mfovs_features(matcher_params, sec1_cache, sec2_cache, mfovs1, mfovs2):
"""
Matches the features in mfovs1 (of sec1) to the features in mfovs2 (of sec2).
This method is run by a process that loads the matcher from its local thread storage.
"""
... | mfov1_center = np.array([
(mfov1.bbox[0] + mfov1.bbox[1]) / 2,
(mfov1.bbox[2] + mfov1.bbox[3]) / 2
])
# Add the triangle points
sec1_points = PreMatch3DFullSectionThenMfovsThumbsBlobs.OVERLAP_DELTAS + mfo... | identifier_body |
full_section_then_mfovs_thumbs_blobs.py | import cv2
import os
import numpy as np
from mb_aligner.common.detectors.blob_detector_2d import BlobDetector2D
from mb_aligner.common.matcher import FeaturesMatcher
from rh_logger.api import logger
import logging
import rh_logger
from mb_aligner.common.thread_local_storage_lru import ThreadLocalStorageLRU
import tinyr... | (matcher_params, sec1_cache, sec2_cache, mfovs1, mfovs2):
"""
Matches the features in mfovs1 (of sec1) to the features in mfovs2 (of sec2).
This method is run by a process that loads the matcher from its local thread storage.
"""
thread_local_store = ThreadLocalStorageLR... | match_mfovs_features | identifier_name |
full_section_then_mfovs_thumbs_blobs.py | import cv2
import os
import numpy as np
from mb_aligner.common.detectors.blob_detector_2d import BlobDetector2D
from mb_aligner.common.matcher import FeaturesMatcher
from rh_logger.api import logger
import logging
import rh_logger
from mb_aligner.common.thread_local_storage_lru import ThreadLocalStorageLRU
import tinyr... | # Note - the match_mfovs_features only reads from secX_cache, so we can send secX_cache._dict (the manager's part of that)
res = pool.apply_async(PreMatch3DFullSectionThenMfovsThumbsBlobs.match_mfovs_features, (self._kwargs.get("matcher_params", {}), sec1_cache._dict, sec2_cache._dict, [mfov1.mf... | async_results = []
for mfov1 in sec1.mfovs():
# find overlapping mfovs in sec2
mfovs2 = PreMatch3DFullSectionThenMfovsThumbsBlobs.get_overlapping_mfovs(mfov1, sec2, global_model, sec2_rtree)
logger.report_event("Finding local model between section {} (mfov {}) and sec... | random_line_split |
full_section_then_mfovs_thumbs_blobs.py | import cv2
import os
import numpy as np
from mb_aligner.common.detectors.blob_detector_2d import BlobDetector2D
from mb_aligner.common.matcher import FeaturesMatcher
from rh_logger.api import logger
import logging
import rh_logger
from mb_aligner.common.thread_local_storage_lru import ThreadLocalStorageLRU
import tinyr... |
# refine the global transform to a local one
async_results = []
for mfov1 in sec1.mfovs():
# find overlapping mfovs in sec2
mfovs2 = PreMatch3DFullSectionThenMfovsThumbsBlobs.get_overlapping_mfovs(mfov1, sec2, global_model, sec2_rtree)
logger.report_event("F... | sec2_rtree.insert(t, t.bbox) | conditional_block |
main.rs | use anyhow::{Context, Result};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::rc::{Rc, Weak};
use structopt::StructOpt;
use xml::{
attribute::OwnedAttribute,
name::OwnedName,
reader::{EventReader, XmlEvent},
};
#[derive(Debug, StructOpt)]
#[structopt(name ... | self.cur.replace(element);
}
}
/// 当前元素解析完成
fn fish_feed_element(&mut self) {
self.depth -= 1;
// 当前父节点指向上一层的节点
let mut parent = None;
if let Some(cur) = &self.cur {
if let Some(p) = &cur.borrow().parent {
parent = p.upgrade();... | // cur parent 变更为 最新节点
self.cur.replace(element);
} else {
// 第一个节点
self.root.replace(Rc::clone(&element)); | random_line_split |
main.rs | use anyhow::{Context, Result};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::rc::{Rc, Weak};
use structopt::StructOpt;
use xml::{
attribute::OwnedAttribute,
name::OwnedName,
reader::{EventReader, XmlEvent},
};
#[derive(Debug, StructOpt)]
#[structopt(name ... | element_type.is_text() {
let run_property = Element::find_run_property(&root);
let color_val = Element::get_color(&run_property);
let text = root_rc
.borrow()
.literal_text
.as_ref()
.cloned()
.unwrap_or_... | pth -= 1;
// 当前父节点指向上一层的节点
let mut parent = None;
if let Some(cur) = &self.cur {
if let Some(p) = &cur.borrow().parent {
parent = p.upgrade();
}
}
self.cur = parent;
}
/// 向当前的 element 中添加text, 目前只有 w:t 类型会有
fn feed_character... | identifier_body |
main.rs | use anyhow::{Context, Result};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::rc::{Rc, Weak};
use structopt::StructOpt;
use xml::{
attribute::OwnedAttribute,
name::OwnedName,
reader::{EventReader, XmlEvent},
};
#[derive(Debug, StructOpt)]
#[structopt(name ... | l的 OwnedName 中构建 ElementType
fn from_name(name: &OwnedName) -> Self {
let raw = format!(
"{}:{}",
name.prefix.as_ref().unwrap_or(&String::new()),
name.local_name
);
// 目前 只识别 `w:xxx` 格式, 且只是部分标签
if name.prefix.is_none() || name.prefix.as_ref().unw... | /// 从 xm | identifier_name |
main.rs | use anyhow::{Context, Result};
use std::cell::RefCell;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use std::rc::{Rc, Weak};
use structopt::StructOpt;
use xml::{
attribute::OwnedAttribute,
name::OwnedName,
reader::{EventReader, XmlEvent},
};
#[derive(Debug, StructOpt)]
#[structopt(name ... | // 调试信息
if opt.verbose {
println!(r#"{}Characters("{}")"#, " ".repeat(depth), data,);
}
// 当前元素添加 text data
doc_parsing.feed_characters(data);
}
XmlEvent::Whitespace(_) => {}
_ => {
... | nt_xml_owned_name(&name, depth, false);
}
// 当前元素解析完成
doc_parsing.fish_feed_element();
}
XmlEvent::Comment(_) => {}
XmlEvent::CData(_) => {}
XmlEvent::Characters(data) => {
| conditional_block |
utils.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
}
}
func replaceNullWithOtherType(vals ...arrow.DataType) {
debug.Assert(len(vals) == 2, "should be length 2")
if vals[0].ID() == arrow.NULL {
vals[0] = vals[1]
return
}
if vals[1].ID() == arrow.NULL {
vals[1] = vals[0]
return
}
}
func commonTemporalResolution(vals ...arrow.DataType) (arrow.TimeUnit,... | {
vals[i] = v.(*arrow.DictionaryType).ValueType
} | conditional_block |
utils.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | {
var (
allUTF8, allOffset32, allFixedWidth = true, true, true
)
for _, ty := range vals {
switch ty.ID() {
case arrow.STRING:
allFixedWidth = false
case arrow.BINARY:
allFixedWidth, allUTF8 = false, false
case arrow.FIXED_SIZE_BINARY:
allUTF8 = false
case arrow.LARGE_BINARY:
allOffset32, al... | identifier_body | |
utils.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
// decimal promotion rules compatible with amazon redshift
// https://docs.aws.amazon.com/redshift/latest/dg/r_numeric_computations201.html
var leftScaleup, rightScaleup int32
switch promote {
case decPromoteAdd:
leftScaleup = exec.Max(scale1, scale2) - scale1
rightScaleup = exec.Max(scale1, scale2) - scale2... | castedID = arrow.DECIMAL256
} | random_line_split |
utils.go | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (vals ...arrow.DataType) bool {
for _, v := range vals {
if arrow.IsDecimal(v.ID()) {
return true
}
}
return false
}
type decimalPromotion uint8
const (
decPromoteNone decimalPromotion = iota
decPromoteAdd
decPromoteMultiply
decPromoteDivide
)
func castBinaryDecimalArgs(promote decimalPromotion, vals ... | hasDecimal | identifier_name |
evaluator.py | import onnx
from typing import List, Tuple, Dict, Optional
import onnxruntime
import numpy as np
from .types import numpy_to_ort, ort_to_numpy
from .shapes import weak_shape_comparisson, as_shape
from .graph import Graph, ExecutableGraph, compile_graph
from .config import Config, get_ort_graph_optimization_level
from .... | except Exception: # pragma: no cover
# dump failed model for debugging purposes
onnx.save_model(m, "failed_model.onnx")
raise
io_binding = session.io_binding()
session_input_names = [i.name for i in session.get_inputs()]
graph_node_mapping = executab... | buffer, providers=Config().get_providers(),
sess_options=session_options) | random_line_split |
evaluator.py | import onnx
from typing import List, Tuple, Dict, Optional
import onnxruntime
import numpy as np
from .types import numpy_to_ort, ort_to_numpy
from .shapes import weak_shape_comparisson, as_shape
from .graph import Graph, ExecutableGraph, compile_graph
from .config import Config, get_ort_graph_optimization_level
from .... | (self):
return self._cache
class ArrayNodeLookupTable:
def __init__(self):
self._input_table: Dict[str, Tuple["array.Array"]] = {}
self._output_table: Dict[str, Tuple["array.Array"]] = {}
def add_input(self, node_name: str, arrays: Tuple["array.Array"]):
self._input_table[node... | to_dict | identifier_name |
evaluator.py | import onnx
from typing import List, Tuple, Dict, Optional
import onnxruntime
import numpy as np
from .types import numpy_to_ort, ort_to_numpy
from .shapes import weak_shape_comparisson, as_shape
from .graph import Graph, ExecutableGraph, compile_graph
from .config import Config, get_ort_graph_optimization_level
from .... |
if ort_value_dtype == np.uint64:
ort_value_dtype = np.ulonglong
shape = ortvalue.shape()
io_binding.bind_input(
name=input_name, device_type=ortvalue.device_name(),
device_id=0, element_type=ort_value_dtype, shape=shape,
... | ort_value_dtype = np.longlong | conditional_block |
evaluator.py | import onnx
from typing import List, Tuple, Dict, Optional
import onnxruntime
import numpy as np
from .types import numpy_to_ort, ort_to_numpy
from .shapes import weak_shape_comparisson, as_shape
from .graph import Graph, ExecutableGraph, compile_graph
from .config import Config, get_ort_graph_optimization_level
from .... |
def add_entry(self, node_name: str, index: int, array: "array.Array"):
if node_name in self._cache:
entry = self._cache[node_name]
if index >= len(entry):
# grow cache in order to fit the new entry
entry += [None] * (index - len(entry) + 1)
e... | self._cache = {**self._cache, **other._cache} | identifier_body |
main.js | $('body').click(function (event) {
if ($(event.target).hasClass('edui-default')) return;
var uis = solution.ui.getUiByType('ueditor comboTree select textarea');
for (var i = 0, len = uis.length; i < len; i++) {
if (uis[i].type === 'ueditor' && !uis[i]._isHide) uis[i].hide();
else uis[i].hide();
}
... | if (i == str.length - 1) {
canvas.fillText(str.substring(lastSubStrIndex, i + 1), initX, initY);
}
}
}
var getCanvasContext = function(width, height) {
var html = '<canvas id="MergeImageId" width="' + width + '" height="' + height + '" style="display:none"></canv... | random_line_split | |
main.js | $('body').click(function (event) {
if ($(event.target).hasClass('edui-default')) return;
var uis = solution.ui.getUiByType('ueditor comboTree select textarea');
for (var i = 0, len = uis.length; i < len; i++) {
if (uis[i].type === 'ueditor' && !uis[i]._isHide) uis[i].hide();
else uis[i].hide();
}
... | p="three-level-menu"><a href="#" data-chivox-event="click:subMenuClick&xsxx&' + jd.id + '&' + jd.stage + '">' + jd.stageName + '</a></li>');
var $sj = $('<li data-chivox-group="three-level-menu"><a href="#" data-chivox-event="click:subMenuClick&fzsj&' + jd.id + '">' + jd.stageName + '<img src="/css/images... | identifier_body | |
main.js | $('body').click(function (event) {
if ($(event.target).hasClass('edui-default')) return;
var uis = solution.ui.getUiByType('ueditor comboTree select textarea');
for (var i = 0, len = uis.length; i < len; i++) {
if (uis[i].type === 'ueditor' && !uis[i]._isHide) uis[i].hide();
else uis[i].hide();
}
... | [canvas对象]
* @param {[type]} initX [左间距]
* @param {[type]} initY [上间距]
* @param {[type]} lineHeight [行高]
*/
var canvasTextAutoLine = function (str, canvas, initX, initY, lineHeight) {
var lineWidth = 0;
// var canvasWidth = parseInt(canvas.width.replace("px",""));
var... | anvas | identifier_name |
dictionary.py | # -*- coding: utf-8 -*-
# Copyright 2019 Julian Betz
#
# 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 l... | tr__(self):
return (circled_number(self.sense_id) + ' '
+ (' ' + GLOSS_SEPARATOR + ' ').join(
[gloss for gloss_type, gloss in self.glosses]))
| r, %d, %d)>'
% (self.__class__.__name__, self.language_code, self.entry_id, self.sense_id))
def __s | identifier_body |
dictionary.py | # -*- coding: utf-8 -*-
# Copyright 2019 Julian Betz
#
# 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 l... | umber, bold_circle=True):
"""Provide a Unicode representation of the specified number.
:param int number: The positive number to convert to a string.
:param bool bold_circle: If ``True``, return a white number on a black
circle; return a black number on a white circle otherwise.
:return: A st... | rcled_number(n | identifier_name |
dictionary.py | # -*- coding: utf-8 -*-
# Copyright 2019 Julian Betz
#
# 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 l... | :param conn: The database connection for the dictionary.
:param str language_code: ISO 639-3 language code of the language of
interest.
:param int entry_id: The ID of the dictionary entry to which this
connotation belongs.
:param int sense_id: The ID of this connotation w.r.t. the ent... | A connotation may be described by multiple glosses, each of which can be a
direct translation, a description or similar.
On construction, all relevant data is loaded from the database.
| random_line_split |
dictionary.py | # -*- coding: utf-8 -*-
# Copyright 2019 Julian Betz
#
# 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 l... | elif bold_circle:
return '[%s]' % (number,) # raise ValueError()
elif number < 30:
return chr(0x323c + number)
elif number == 30:
return chr(0x325a)
elif number < 36:
return chr(0x323c + number)
elif number < 51:
return chr(0x328d + number)
else:
re... | turn chr(0x24e0 + number)
| conditional_block |
lib.rs | //! # mio-serial - A mio-compatable serial port implementation for *nix
//!
//! This crate provides a SerialPort implementation compatable with mio.
//!
//! ** This crate ONLY provides a unix implementation **
//!
//! Some basic helper methods are provided for setting a few serial port
//! parameters such as the baud ... |
/// Enable or disable raw mode
///
/// In raw mode, input is available character by character, echoing is disabled, and all
/// special processing of terminal input and output characters is disabled.
pub fn set_raw(&mut self, raw: bool) -> io::Result<()> {
if raw == self.is_raw() {
... | {
use termios::{B0, B50, B75, B110, B134, B150, B200, B300, B600,
B1200, B1800, B2400, B4800, B9600, B19200, B38400};
let s = self.termios()?;
// And the original rate
let baud = termios::cfgetospeed(&s);
let b = match baud {
B4800 => 4800,
... | identifier_body |
lib.rs | //! # mio-serial - A mio-compatable serial port implementation for *nix
//!
//! This crate provides a SerialPort implementation compatable with mio.
//!
//! ** This crate ONLY provides a unix implementation **
//!
//! Some basic helper methods are provided for setting a few serial port
//! parameters such as the baud ... | {
fd: RawFd,
orig_settings: termios::Termios,
is_raw: bool,
}
impl SerialPort {
/// Construct a new SerialPort
///
/// Opens the a serial port at the location provided by `path` with the following
/// default settings:
///
/// - 9600,8N1 (9600 Baud, 8-bit data, no parity, 1 st... | SerialPort | identifier_name |
lib.rs | //! # mio-serial - A mio-compatable serial port implementation for *nix
//!
//! This crate provides a SerialPort implementation compatable with mio.
//!
//! ** This crate ONLY provides a unix implementation **
//!
//! Some basic helper methods are provided for setting a few serial port
//! parameters such as the baud ... | /// - `Err(e)` for all other IO errors
pub fn maybe_read(&mut self, buf: &mut [u8]) -> io::Result<Option<usize>> {
match self.read(buf) {
Ok(s) => Ok(Some(s)),
Err(e) => {
if let io::ErrorKind::WouldBlock = e.kind() {
Ok(None)
... | /// # Returns
///
/// - `Ok(Some(size))` on successful reads
/// - `Ok(None)` if calling read would block. | random_line_split |
GradientBoostingClassifier.py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 16:06:10 2018
@author: vwzheng
"""
import pandas as pd
import numpy as np
import os
os.chdir('D:/Downloads/vivienne/ML/Classification_UW')
#Load dataset
loans = pd.read_csv('lending-club-data.csv')
#Explore some features
loans.columns
#Modify the ... | (dim, title, xlabel, ylabel, legend):
plt.rcParams['figure.figsize'] = dim
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if legend is not None:
plt.legend(loc=legend, prop={'size':15})
plt.rcParams.update({'font.size': 16})
plt.tight_layout()
#Make p... | make_figure | identifier_name |
GradientBoostingClassifier.py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 16:06:10 2018
@author: vwzheng
"""
import pandas as pd
import numpy as np
import os
os.chdir('D:/Downloads/vivienne/ML/Classification_UW')
#Load dataset
loans = pd.read_csv('lending-club-data.csv')
#Explore some features
loans.columns
#Modify the ... |
#Make plot
plt.plot(x, train_errors, linewidth=4.0, label='Training error')
plt.plot(x, valid_errors, linewidth=4.0, label='Validation error')
make_figure(dim=(10,5), title='Error vs number of trees',
xlabel='Number of trees',
ylabel='Classification error',
... | plt.rcParams['figure.figsize'] = dim
plt.title(title)
plt.xlabel(xlabel)
plt.ylabel(ylabel)
if legend is not None:
plt.legend(loc=legend, prop={'size':15})
plt.rcParams.update({'font.size': 16})
plt.tight_layout() | identifier_body |
GradientBoostingClassifier.py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 16:06:10 2018
@author: vwzheng
"""
import pandas as pd
import numpy as np
import os
os.chdir('D:/Downloads/vivienne/ML/Classification_UW')
#Load dataset
loans = pd.read_csv('lending-club-data.csv')
#Explore some features
loans.columns
#Modify the ... |
for feature in categorical_variables:
loans_one_hot_encoded = pd.get_dummies(loans[feature],prefix=feature)
loans = pd.concat([loans, loans_one_hot_encoded],axis=1)
loans = loans.drop(feature, axis=1)
#Import indices of train valid
train_idx = pd.read_json('module-8-assignment-1-train-idx.json')
... | if feat_type == object:
categorical_variables.append(feat_name) | conditional_block |
GradientBoostingClassifier.py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 3 16:06:10 2018
@author: vwzheng
"""
import pandas as pd
import numpy as np
import os
os.chdir('D:/Downloads/vivienne/ML/Classification_UW')
#Load dataset
loans = pd.read_csv('lending-club-data.csv')
#Explore some features
loans.columns
#Modify the ... | #classification error = 1 - accuracy
from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
def make_figure(dim, title, xlabel, ylabel, legend):
plt.rcParams['figure.figsize'] = dim
plt.title(title)
plt.xlabel(xlabel)
... | #model_100 has the best accuracy on the validation_data?
#it is not always true that the model with the most trees will perform best
#on test data?
#Plot the training and validation error vs. number of trees
| random_line_split |
filterset.py | import copy
from collections import OrderedDict
from django.db.models import Subquery
from django.db.models.constants import LOOKUP_SEP
from django_filters import filterset, rest_framework
from django_filters.utils import get_model_field
from . import filters, utils
def related(filterset, filter_name):
"""
... |
@classmethod
def get_fields(cls):
fields = super(FilterSet, cls).get_fields()
for name, lookups in fields.items():
if lookups == filters.ALL_LOOKUPS:
field = get_model_field(cls._meta.model, name)
fields[name] = utils.lookups_for_field(field)
... | self.base_filters = self.get_filter_subset(data or {}, relationship)
super().__init__(data, queryset, **kwargs)
self.relationship = relationship
self.related_filtersets = self.get_related_filtersets()
self.filters = self.get_request_filters() | identifier_body |
filterset.py | import copy
from collections import OrderedDict
from django.db.models import Subquery
from django.db.models.constants import LOOKUP_SEP
from django_filters import filterset, rest_framework
from django_filters.utils import get_model_field
from . import filters, utils
def related(filterset, filter_name):
"""
... |
return cleaned_data
return Form
| for key, error in related_filterset.form.errors.items():
self.form.errors[related(related_filterset, key)] = error | conditional_block |
filterset.py | import copy
from collections import OrderedDict
from django.db.models import Subquery
from django.db.models.constants import LOOKUP_SEP
from django_filters import filterset, rest_framework
from django_filters.utils import get_model_field
from . import filters, utils
def related(filterset, filter_name):
"""
... | (cls, params, rel=None):
"""
Returns the subset of filters that should be initialized by the
FilterSet, dependent on the requested `params`. This helps minimize
the cost of initialization by reducing the number of deepcopy ops.
The `rel` argument is used for related filtersets t... | get_filter_subset | identifier_name |
filterset.py | import copy
from collections import OrderedDict
from django.db.models import Subquery
from django.db.models.constants import LOOKUP_SEP
from django_filters import filterset, rest_framework
from django_filters.utils import get_model_field
from . import filters, utils
def related(filterset, filter_name):
"""
... | new_class._meta = copy.deepcopy(new_class._meta)
new_class.declared_filters = new_class.declared_filters.copy()
for name in new_class.auto_filters:
f = new_class.declared_filters[name]
# Remove auto filters from declared_filters so that they *are* overwritten
... | orig_meta, orig_declared = new_class._meta, new_class.declared_filters
# override opts/declared filters w/ copies | random_line_split |
file.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.23.0
// protoc v3.14.0
// source: protobuf/file.proto
// protoc --go_out=plugins=grpc:services/ protobuf/*
package services
import (
context "context"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
... | oadReq) GetBody() []byte {
if x != nil {
return x.Body
}
return nil
}
func (x *UploadReq) GetReplace() bool {
if x != nil {
return x.Replace
}
return false
}
type Response struct {
state protoimpl.MessageState
sizeCache protoimpl.SizeCache
unknownFields protoimpl.UnknownFields
Success bool ... | != nil {
return x.End
}
return false
}
func (x *Upl | identifier_body |
file.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.23.0
// protoc v3.14.0
// source: protobuf/file.proto
// protoc --go_out=plugins=grpc:services/ protobuf/*
package services
import (
context "context"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
... | 6, 0x69, 0x6c, 0x65, 0x2e,
0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x04, 0x66, 0x69, 0x6c, 0x65, 0x22, 0xd5, 0x01, 0x0a, 0x09,
0x55, 0x70, 0x6c, 0x6f, 0x61, 0x64, 0x52, 0x65, 0x71, 0x12, 0x1e, 0x0a, 0x0a, 0x46, 0x69, 0x6c,
0x65, 0x4d, 0x64, 0x35, 0x73, 0x75, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0a, 0x46,
0... | 75, 0x66, 0x2f, 0x6 | conditional_block |
file.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.23.0
// protoc v3.14.0
// source: protobuf/file.proto
// protoc --go_out=plugins=grpc:services/ protobuf/*
package services
import (
context "context"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
... | [0]
if protoimpl.UnsafeEnabled && x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UploadReq.ProtoReflect.Descriptor instead.
func (*UploadReq) Descriptor() ([]byte, []int) ... | gTypes | identifier_name |
file.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.23.0
// protoc v3.14.0
// source: protobuf/file.proto
// protoc --go_out=plugins=grpc:services/ protobuf/*
package services
import (
context "context"
proto "github.com/golang/protobuf/proto"
grpc "google.golang.org/grpc"
... | }
func (c *distributeClient) Upload(ctx context.Context, in *UploadReq, opts ...grpc.CallOption) (*Response, error) {
out := new(Response)
err := c.cc.Invoke(ctx, "/file.Distribute/Upload", in, out, opts...)
if err != nil {
return nil, err
}
return out, nil
}
// DistributeServer is the server API for Distribut... |
func NewDistributeClient(cc grpc.ClientConnInterface) DistributeClient {
return &distributeClient{cc} | random_line_split |
psd_channel.rs | use crate::sections::image_data_section::ChannelBytes;
use crate::sections::PsdCursor;
use thiserror::Error;
pub trait IntoRgba {
/// Given an index of a pixel in the current rectangle
/// (top left is 0.. to the right of that is 1.. etc) return the index of that pixel in the
/// RGBA image that will be ge... | (
&self,
rgba: &mut Vec<u8>,
channel_kind: PsdChannelKind,
channel_bytes: &[u8],
) {
let mut cursor = PsdCursor::new(&channel_bytes[..]);
let mut idx = 0;
let offset = channel_kind.rgba_offset().unwrap();
let len = cursor.get_ref().len() as u64;
... | insert_rle_channel | identifier_name |
psd_channel.rs | use crate::sections::image_data_section::ChannelBytes;
use crate::sections::PsdCursor;
use thiserror::Error;
pub trait IntoRgba {
/// Given an index of a pixel in the current rectangle
/// (top left is 0.. to the right of that is 1.. etc) return the index of that pixel in the
/// RGBA image that will be ge... | sixteen_to_eight_rgba(red, green)
}
},
ChannelBytes::RleCompressed(red) => {
let red = &rle_decompress(red);
match self.green().unwrap() {
ChannelBytes::RawData(green) => sixteen_to_eight_rgba(red, green),
... | ChannelBytes::RawData(red) => match self.green().unwrap() {
ChannelBytes::RawData(green) => sixteen_to_eight_rgba(red, green),
ChannelBytes::RleCompressed(green) => {
let green = &rle_decompress(green);
| random_line_split |
psd_channel.rs | use crate::sections::image_data_section::ChannelBytes;
use crate::sections::PsdCursor;
use thiserror::Error;
pub trait IntoRgba {
/// Given an index of a pixel in the current rectangle
/// (top left is 0.. to the right of that is 1.. etc) return the index of that pixel in the
/// RGBA image that will be ge... |
let byte = cursor.read_1()[0];
for _ in 0..repeat as usize {
let rgba_idx = self.rgba_idx(idx);
rgba[rgba_idx * 4 + offset] = byte;
idx += 1;
}
};
}
}
}
/// Rle decompress a channel
fn ... | {
break;
} | conditional_block |
train_nn.py | from __future__ import absolute_import
import os
import json
import torch
import argparse
import torchvision
import numpy as np
import torch.nn as nn
from DataLoader import CDATA
from main_model_nn import MemN2NDialog
from torch.autograd import Variable as Var
from data_utils import load_candidates, load_dialog_task, v... |
elif self.optim == 'rms':
optimizer = torch.optim.RMSprop(self.model.parameters(), lr=self.learning_rate, momentum=self.momentum)
print("RMSprop optimizer")
else:
optimizer = torch.optim.Adam(self.model.parameters(), lr=self.learning_rate)
print("Adam opt... | optimizer = torch.optim.SGD(self.model.parameters(), lr=self.learning_rate, momentum=self.momentum)
print("SGD optimizer") | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.