file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
main.js | _LC_SR_W_DR',
'TILED': true
}
})
})
var highways = new ImageLayer({
source: new ImageArcGISRest({
ratio: 1,
params: {},
url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer'
})
})
var none = new ImageLayer({
source: new Sta... | ){
var extent = map.getView().calculateExtent();
var resolution = map.getView().getResolution();
var radius = 40*resolution;
for (var i in Speaker.eightChannelSpeakerCoordinateRatios){
var x = speakerCoordinateRatios[i][0];
var y = speakerCoordinateRatios[i][1];
var coord = [(extent[2]-extent[0])*x+... | ositionSpeakers( | identifier_name |
main.js | _LC_SR_W_DR',
'TILED': true
}
})
})
var highways = new ImageLayer({
source: new ImageArcGISRest({
ratio: 1,
params: {},
url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer'
})
})
var none = new ImageLayer({
source: new Sta... |
function positionSpeakers(){
var extent = map.getView().calculateExtent();
var resolution = map.getView().getResolution();
var radius = 40*resolution;
for (var i in Speaker.eightChannelSpeakerCoordinateRatios){
var x = speakerCoordinateRatios[i][0];
var y = speakerCoordinateRatios[i][1];
var coord ... |
var resolution = map.getView().getResolution();
var radius = 15*resolution;
for (var i in Remote.remotes){
//TODO some error here, seems like remotes gets out of sync somehow...
Remote.remotes[i].getGeometry().setRadius(radius);
}
}
| identifier_body |
main.js | ,2/3],[1,1/3],[2/3,0],[1/3,0],[0,1/3],[0,2/3]];
for (var i in speakerCoordinateRatios){
new Speaker([0,0],audienceSource)
}
positionSpeakers()
Connection.connections.on(['add','remove'],function(){
var dag = Connection.getConnectionsDAG(); // [{from:..., to:...}] where from and to are from 'getGraphData'
var ms... | random_line_split | ||
main.js | _LC_SR_W_DR',
'TILED': true
}
})
})
var highways = new ImageLayer({
source: new ImageArcGISRest({
ratio: 1,
params: {},
url: 'https://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Specialty/ESRI_StateCityHighway_USA/MapServer'
})
})
var none = new ImageLayer({
source: new Sta... | else {
cmdBox.hidden = true;
cmdBox.innerHTML = ""
}
});
map.addInteraction(dragBox);
map.addInteraction(select);
// Connection Interaction
function onConnectable(coordinate){
var features = audienceSource.getFeatures().map(function(f){return f.type})
var a = audienceSource.getFeaturesAtCoordinate(co... |
cmdBox.hidden = false;
cmdBox.innerHTML = "";
for(var i in innerHTML){
cmdBox.appendChild(innerHTML[i])
}
} | conditional_block |
iptool.py | 1m ERROR: {host} resolve error: {e.__class__.__name__}\033[0m")
socket_record=[]
# print(google_record,socket_record)
socket_record.extend([x for x in google_record if x not in socket_record])
# print(google_record,socket_record)
if len(socket_record) == 0:
print(f"\033[1;31m ERROR: {hos... |
if __name__ == '__main__': | random_line_split | |
iptool.py | 88&p_ip=180.101.49.12&callback=sogouCallback1620961932681")
# except Exception as e:
# pass
# else:
# try:
# requests.get("https://open.onebox.so.com/dataApi?callback=jQuery18301409029392462775_1620962038263&type=ip&src=onebox&tpl=0&num=1&query=ip&ip=180.101.49.12&url=ip&_=1620962046570")
... | if ip in sigleIP.keys():
sigleIP[ip].append(info[0])
| conditional_block | |
iptool.py | ,}', replZero, s1) # 去掉 123.0.02.1 中 0 开头的多位数
s1 = re.split(r'[\n\s,,、;;]+', s1) # 以这些符号分隔成列表并去重
s1 = list({x for x in s1 if x !=''})
s1.sort()
logging.info(s1)
logging.info("-" * 80)
for x in ipParse(s1):
print(x)
def dns_record(domain):
green = "\x1b[1;32m"
cyan = "\x1b[1;... | # gevent.s | identifier_name | |
iptool.py | &url=ip&_=1620962046570")
# except Exception as e:
# pass
# try:
# requests.get("https://apiquark.sm.cn/rest?method=sc.number_ip_new&request_sc=shortcut_searcher::number_ip_new&callback=sc_ip_search_callback&q=103.235.46.39&callback=jsonp2")
# except Exception as e:
# pass
# tr... | # print(info[1])
for info in info_pool:
for ip in info[1]:
if ip in sigleIP.keys():
sigleIP[ip].append(info[0])
break
else:
print(info[0],info[1])
# print(sigleIP)
for i,v in sigleIP.items():
print(f"### {i}\t"+ip_... | identifier_body | |
electron.js | />
</BreadProvider>
);
}
}`;
const html = `<!DOCTYPE html>
<html>
<head>
<title>Material Bread Electron</title>
<meta charset="utf-8" />
</head>
<body>
<div id="app"></div>
<script
type="text/javascript"
src="http://localhost:7000/bundle.js"
></script>
</body>
</htm... |
render() {
return (
<div style={styles.container}>
<Helmet title={'React Native Electron'} />
<PageTitle>Electron</PageTitle>
<ComponentSubtitle
description={
'Build cross platform desktop apps with JavaScript, HTML, and CSS'
}
/>
<Si... | {
Prism.highlightAll();
} | identifier_body |
electron.js | />
</BreadProvider>
);
}
}`;
const html = `<!DOCTYPE html>
<html>
<head>
<title>Material Bread Electron</title>
<meta charset="utf-8" />
</head>
<body>
<div id="app"></div>
<script
type="text/javascript"
src="http://localhost:7000/bundle.js"
></script>
</body>
</htm... | () {
Prism.highlightAll();
}
render() {
return (
<div style={styles.container}>
<Helmet title={'React Native Electron'} />
<PageTitle>Electron</PageTitle>
<ComponentSubtitle
description={
'Build cross platform desktop apps with JavaScript, HTML, and CSS'
... | componentDidMount | identifier_name |
electron.js | Root /> | </BreadProvider>
);
}
}`;
const html = `<!DOCTYPE html>
<html>
<head>
<title>Material Bread Electron</title>
<meta charset="utf-8" />
</head>
<body>
<div id="app"></div>
<script
type="text/javascript"
src="http://localhost:7000/bundle.js"
></script>
</body>
</html>
`... | random_line_split | |
nfa.rs | transition between states _without_ reading any new symbol
/// through use of
/// [epsilon links](https://en.wikipedia.org/wiki/Nondeterministic_finite_automaton#NFA_with_%CE%B5-moves).
///
/// ```text
/// ┌───┐ 'N' ┌───┐ ┌───┐ 'F' ┌───┐ ┌───┐ 'A' ┌───┐
/// │ 0 │ ----> │ 1 │ -> │ 2 │ ----> │ 3 │ -> │ 3 │... | for (state_ix, source) in self.states.iter().enumerate() {
let targets = source.targets(&self.alphabet_segmentation);
for (voc_ix, &target) in targets.iter().enumerate() {
matrix[(state_ix,voc_ix)] = target;
}
}
matrix
}
}
// === Trait Impls ===... | ;
| identifier_name |
nfa.rs | pub fn connect_via
( &mut self
, source : state::Identifier
, target_state : state::Identifier
, symbols : &RangeInclusive<Symbol>
) {
self.alphabet_segmentation.insert(symbols.clone());
self.states[source.id].links.push(Transition{symbols:symbols.clone(),target_state}... | tate::from(vec![11]).named("group_0_rule_0"),
State::from(vec![4]),
State::from(vec![(32..=32,5)]),
State::from(vec![6]),
State::from(vec![7,10]),
State::from(vec![8]),
State::from(vec![(32..=32,9)]),
State::... | identifier_body | |
nfa.rs | transition between states _without_ reading any new symbol
/// through use of
/// [epsilon links](https://en.wikipedia.org/wiki/Nondeterministic_finite_automaton#NFA_with_%CE%B5-moves).
///
/// ```text
/// ┌───┐ 'N' ┌───┐ ┌───┐ 'F' ┌───┐ ┌───┐ 'A' ┌───┐
/// │ 0 │ ----> │ 1 │ -> │ 2 │ ----> │ 3 │ -> │ 3 │... |
DFA{alphabet_segmentation,links,callbacks}
}
}
// ===========
// == Tests ==
// ===========
#[cfg(test)]
pub mod tests {
extern crate test;
use crate::automata::dfa;
use super::*;
use test::Bencher;
/// NFA that accepts a newline '\n'.
pub fn newline() -> NFA {
NFA {
... | }
}
let alphabet_segmentation = nfa.alphabet_segmentation.clone();
let links = dfa_mat; | random_line_split |
compressed_arith.go | Ind[k], j)
}
if v != 0 {
c.matrix.Ind = append(c.matrix.Ind, j)
c.matrix.Data = append(c.matrix.Data, v)
}
}
c.matrix.Indptr[i+1] = len(c.matrix.Ind)
}
}
// mulDIACSR handles CSR = DIA * CSR (or CSR = CSR * DIA if trans == true)
func (c *CSR) mulDIACSR(dia *DIA, other *CSR, trans bool) {
diagona... | NewSPA | identifier_name | |
compressed_arith.go | , bc := b.Dims()
if ac != br {
panic(mat.ErrShape)
}
if m, temp, restore := c.spalloc(a, b); temp |
lhs, isLCsr := a.(*CSR)
rhs, isRCsr := b.(*CSR)
if isLCsr && isRCsr {
// handle CSR * CSR
c.mulCSRCSR(lhs, rhs)
return
}
if dia, ok := a.(*DIA); ok {
if isRCsr {
// handle DIA * CSR
c.mulDIACSR(dia, rhs, false)
return
}
// handle DIA * mat.Matrix
c.mulDIAMat(dia, b, false)
return
}
if... | {
defer restore()
c = m
} | conditional_block |
compressed_arith.go |
// spalloc ensures appropriate storage is allocated for the receiver sparse matrix
// ensuring it is row * col dimensions and checking for any overlap or aliasing
// between operands a or b with c in which case a temporary isolated workspace is
// allocated and the returned value isTemp is true with restore represent... | {
w = getWorkspace(row, col, nnz, clear)
return w, func() {
c.cloneCSR(w)
putWorkspace(w)
}
} | identifier_body | |
compressed_arith.go | br, bc := b.Dims()
if ac != br {
panic(mat.ErrShape)
}
if m, temp, restore := c.spalloc(a, b); temp {
defer restore()
c = m
}
lhs, isLCsr := a.(*CSR)
rhs, isRCsr := b.(*CSR)
if isLCsr && isRCsr {
// handle CSR * CSR
c.mulCSRCSR(lhs, rhs)
return
}
if dia, ok := a.(*DIA); ok {
if isRCsr {
/... | for i := 0; i < ar; i++ {
// each element t in row i of A
for t := lhs.matrix.Indptr[i]; t < lhs.matrix.Indptr[i+1]; t++ {
begin := rhs.matrix.Indptr[lhs.matrix.Ind[t]]
end := rhs.matrix.Indptr[lhs.matrix.Ind[t]+1]
spa.Scatter(rhs.matrix.Data[begin:end], rhs.matrix.Ind[begin:end], lhs.matrix.Data[t], &c.m... | spa := NewSPA(bc)
// rows in C | random_line_split |
IP6_Address.go | // of the Apache Software License. See the accompanying LICENSE file
// for more information.
//
import array
from six import string_types
type IP6_Address: struct {
ADDRESS_BYTE_SIZE = 16
//A Hex Group is a 16-bit unit of the address
TOTAL_HEX_GROUPS = 8
HEX_GROUP_SIZE = 4 //Size in characters
T... | if group == "0" {
start_index = index
end_index = index
//Find the end of this chain of zeroes
while end_index < 7 and groups[end_index + 1] == "0":
end_index += 1
... | random_line_split | |
BasePersonFactory.ts | ]: actionSaveData };
//绑定一个progressBar
travelProgressNotice: ProgressNotice;
//上一个城市
lastCityId: number;
constructor() {
}
/**
* 改变人物大地图上的位置
*/
changeMapPos(person: BasePerson, addMinutes: number) {
if (!person.goalCityMapPos) {
return;
}
... | }.bind(this));
}
/**
* 判断是否在自己家所在的城市
*/ | random_line_split | |
BasePersonFactory.ts | Pos = person.goalCityMapPos;
person.goalCityMapPos = undefined;
person.goalCityId = undefined;
if (this.mapMoveFinishCb) {
this.mapMoveFinishCb();
if (this.isUserRole) {
MyGame.GameManager.gameSpeedResetting(... | identifier_body | ||
BasePersonFactory.ts | .nowMapPos.y + addY;
if (person.nowMapPos.y >= person.goalCityMapPos.y) {
person.nowMapPos.y = person.goalCityMapPos.y;
}
} else {
person.nowMapPos.y = person.nowMapPos.y - addY;
if (person.nowMapPos.... | this.power = | identifier_name | |
BasePersonFactory.ts | : number;
//是否在战斗中
//暂定是不记录战斗信息
inInBattle: boolean;
//自宅
home: SelfHome;
//是否是主角
isUserRole: boolean;
//正在执行的行动id
nowActionIds: number[];
//正在执行的行动
nowActions: Action[];
//正在执行的动作的进度保存
nowActionData: { [actionId: number]: actionSaveData };
//绑定一个progressBar
t... | alCityMapPos: this.goalCityMapPos,
nowMapPos: this.nowMapPos,
goalCityId: this.goalCityId,
itemObj: this.itemObj,
money: this.money,
power: this.power,
inInBattle: this.inInBattle,
nowActionIds: this.nowActionIds,
nowActionD... | is.presonSkillIdArr,
equipAttack: this.equipAttack,
equipDef: this.equipDef,
equipJewelry: this.equipJewelry,
equipHorse: this.equipHorse,
personId: this.personId,
personPos: this.personPos,
homePos: this.homePos,
go | conditional_block |
py2_whole_image_desc_server_ts.py | buffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width, -1)
return X
if msg.encoding == "8UC1" or msg.encoding=='mono8':
X = np.frombuffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width)
return X
class ProtoBufferModelImageDescriptor:
"""
This class loads the net ... |
dt_last = self.queue[-1].header.stamp.to_sec() - stamp.to_sec()
rospy.logwarn("Finding failed, dt is {:3.2f}ms; If this number > 0 means swarm_loop is too slow".format(dt_last)*1000)
if dt_last < 0:
return None, 1
return None, 0
def handle_req( self, req ):
... | cv_image = imgmsg_to_cv2( self.queue[index] )
del self.queue[0:index+1]
if cv_image.shape[0] != 240 or cv_image.shape[1] != 320:
cv_image = cv2.resize(cv_image, (320, 240))
return cv_image, 0 | conditional_block |
py2_whole_image_desc_server_ts.py | buffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width, -1)
return X
if msg.encoding == "8UC1" or msg.encoding=='mono8':
X = np.frombuffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width)
return X
class ProtoBufferModelImageDescriptor:
"""
This class loads the net ... | (self, stamp):
print("Find...", stamp, "queue_size", len(self.queue), "lag is", (self.queue[-1].header.stamp.to_sec() - stamp.to_sec())*1000, "ms")
index = -1
for i in range(len(self.queue)):
if math.fabs(self.queue[i].header.stamp.to_sec() - stamp.to_sec()) < 0.001:
... | pop_image_by_timestamp | identifier_name |
py2_whole_image_desc_server_ts.py | buffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width, -1)
return X
| return X
class ProtoBufferModelImageDescriptor:
"""
This class loads the net structure from the .h5 file. This file contains
the model weights as well as architecture details.
In the argument `frozen_protobuf_file`
you need to specify the full path (keras model file).
"""
def __in... | if msg.encoding == "8UC1" or msg.encoding=='mono8':
X = np.frombuffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width) | random_line_split |
py2_whole_image_desc_server_ts.py | buffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width, -1)
return X
if msg.encoding == "8UC1" or msg.encoding=='mono8':
X = np.frombuffer(msg.data, dtype=np.uint8).reshape(msg.height, msg.width)
return X
class ProtoBufferModelImageDescriptor:
"""
This class loads the net ... | return None, 0
def handle_req( self, req ):
""" The received image from CV bridge has to be [0,255]. In function makes it to
intensity range [-1 to 1]
"""
start_time_handle = time.time()
stamp = req.stamp.data
cv_image = None
for i in range(3):
... | print("Find...", stamp, "queue_size", len(self.queue), "lag is", (self.queue[-1].header.stamp.to_sec() - stamp.to_sec())*1000, "ms")
index = -1
for i in range(len(self.queue)):
if math.fabs(self.queue[i].header.stamp.to_sec() - stamp.to_sec()) < 0.001:
index = i
... | identifier_body |
vaultdb_test.go | to configure DB engine in Vault: %v", err)
}
// Create a role in Vault that is configured to create a Postgres role
// with all privileges.
createSQL := `
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
VALID UNTIL '{{expiration}}';
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{... |
go func() {
for {
renewAt, err := secret.TokenTTL()
assert.NoError(err)
renewAt = renewAt * 3 / 4
select {
case <-time.After(renewAt):
secret, err := tokenAuth.Create(tcr)
assert.NoError(err)
token, err := secret.TokenID()
assert.NoError(err)
vc.SetToken(token)
notifier.noti... | {
assert := require.New(t)
notifier := newfanout(make(chan struct{}))
stopChan := make(chan struct{})
// We have to get the TokenAuth from a clone of passed-in client, or
// we'll end up trying to get new tokens using a token that's about to
// expire. Note that a Clone() doesn't clone the token, so we set that... | identifier_body |
vaultdb_test.go | db",
"default_ttl": ttl,
"max_ttl": maxTTL,
"creation_statements": createSQL,
"revocation_statements": revokeSQL,
})
if err != nil {
t.Fatalf("Failed to create DB role '%s' in Vault: %v", role, err)
}
}
// setupVault creates a database and a secrets engine in Vault for it.
func ... | testMultiVDBC | identifier_name | |
vaultdb_test.go | to configure DB engine in Vault: %v", err)
}
// Create a role in Vault that is configured to create a Postgres role
// with all privileges.
createSQL := `
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
VALID UNTIL '{{expiration}}';
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{... |
return vaultConfig{
dbURI: cleanDBURI,
path: path,
vcl: vcl,
}
}
// fakeVaultAuth mimics vaultgcpauth, except that we log in with the root token,
// and rotate the passed-in client's token with a time-limited sub-token.
func fakeVaultAuth(t *testing.T, vc *vaultapi.Client) (*fanout, chan struct{}) {
asse... | {
t.Fatalf("Failed to configure DB engine in Vault: %v", err)
} | conditional_block |
vaultdb_test.go | to configure DB engine in Vault: %v", err)
}
// Create a role in Vault that is configured to create a Postgres role
// with all privileges.
createSQL := `
CREATE ROLE "{{name}}" WITH
LOGIN
PASSWORD '{{password}}'
VALID UNTIL '{{expiration}}';
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO "{{... | "creation_statements": createSQL,
"revocation_statements": revokeSQL,
})
if err != nil {
t.Fatalf("Failed to create DB role '%s' in Vault: %v", role, err)
}
}
// setupVault creates a database and a secrets engine in Vault for it.
func setupVault(t *testing.T, vc *vaultapi.Client, bpg *briefpg.BriefPG) vaul... | "db_name": "db",
"default_ttl": ttl,
"max_ttl": maxTTL, | random_line_split |
helpers.py | .path.join(dirpath, x))
return wav_files
def get_features(x, fs):
# f0 calculate
_f0, t = pw.dio(x, fs)
f0 = pw.stonemask(x, _f0, t, fs)
# mcep calculate
sp = trim_zeros_frames(pw.cheaptrick(x, f0, t, fs))
mcep = pysptk.sp2mc(sp, order=24, alpha=pysptk.util.mcepalpha(fs))
# bap calculat... |
def sort_dict(dict):
return sorted(dict.items(), key=lambda x: x[1])
def sort_dict_reverse(dict):
return sorted(dict.items(), key=lambda x: x[1], reverse=True)
def sort_dict_by_len(dict):
return sorted(dict.items(), key=lambda x: len(x[1]))
class Experiment:
def __init__(self, encoder, sdr_length,... | tensor_minus_mean = tensor - tensor.mean()
return tensor_minus_mean / tensor_minus_mean.abs().max() | identifier_body |
helpers.py | .path.join(dirpath, x))
return wav_files
def get_features(x, fs):
# f0 calculate
_f0, t = pw.dio(x, fs)
f0 = pw.stonemask(x, _f0, t, fs)
# mcep calculate
sp = trim_zeros_frames(pw.cheaptrick(x, f0, t, fs))
mcep = pysptk.sp2mc(sp, order=24, alpha=pysptk.util.mcepalpha(fs))
# bap calculat... | (data):
data = data.astype(np.float64)
amp = max(np.abs(np.max(data)), np.abs(np.min(data)))
data = data / amp
data.clip(-1, 1)
return data
def normalize(tensor):
tensor_minus_mean = tensor - tensor.mean()
return tensor_minus_mean / tensor_minus_mean.abs().max()
def sort_dict(dict):
re... | peak_normalize | identifier_name |
helpers.py | def get_wavfile_list(path):
wav_files = []
for dirpath, subdirs, files in os.walk(path):
for x in files:
if x.endswith(".wav"):
wav_files.append(os.path.join(dirpath, x))
return wav_files
def get_features(x, fs):
# f0 calculate
_f0, t = pw.dio(x, fs)
f0 = pw.... | import param
| random_line_split | |
helpers.py | .path.join(dirpath, x))
return wav_files
def get_features(x, fs):
# f0 calculate
_f0, t = pw.dio(x, fs)
f0 = pw.stonemask(x, _f0, t, fs)
# mcep calculate
sp = trim_zeros_frames(pw.cheaptrick(x, f0, t, fs))
mcep = pysptk.sp2mc(sp, order=24, alpha=pysptk.util.mcepalpha(fs))
# bap calculat... |
else:
self.setting = setting
self.split_ratio = self.setting.ratio
self.input_path = input_path
self.unknown = unknown
self.sp2idx = self.speakers_to_idx()
self.idx2sp = self.idx_to_speakers()
self.encoder = self.create_encoder()
self.experim... | with open(os.path.join(model_path, 'setting.json'), 'r') as f:
self.setting = AttrDict(json.load(f)) | conditional_block |
kmip.go | kms.writeTimeout = uint8(timeout)
}
caCert := GetParam(config, KmipCACert)
if caCert == "" {
return nil, ErrKMIPCACertNotSet
}
clientCert := GetParam(config, KmipClientCert)
if clientCert == "" {
return nil, ErrKMIPClientCertNotSet
}
clientKey := GetParam(config, KmipClientKey)
if clientKey == "" {
r... | {
return nil, nil, nil,
fmt.Errorf("failed to ttlv marshal message: %w", err)
} | conditional_block | |
kmip.go | MIPEndpointNotSet = errors.Errorf("%s not set.", kmipEndpoint)
ErrKMIPCACertNotSet = errors.Errorf("%s not set.", KmipCACert)
ErrKMIPClientCertNotSet = errors.Errorf("%s not set.", KmipClientCert)
ErrKMIPClientKeyNotSet = errors.Errorf("%s not set.", KmipClientKey)
)
t... | if len(respDiscoverVersionsPayload.ProtocolVersion) != 1 {
return fmt.Errorf("invalid len of discovered protocol versions %v expected 1",
len(respDiscoverVersionsPayload.ProtocolVersion))
}
pv := respDiscoverVersionsPayload.ProtocolVersion[0] | random_line_split | |
kmip.go | = "WRITE_TIMEOUT"
KmipCACert = "CA_CERT"
KmipClientCert = "CLIENT_CERT"
KmipClientKey = "CLIENT_KEY"
KmipUniqueIdentifier = "UNIQUE_IDENTIFIER"
// EtcKmipDir is kmip config dir.
EtcKmipDir = "/etc/kmip"
)
var (
kmsKMIPMandatoryTokenDetails = []string{KmipCACert, KmipClientCert,... | return err
| {
respMsg, decoder, uniqueBatchItemID, err := kms.send(conn,
kmip14.OperationDiscoverVersions,
kmip.DiscoverVersionsRequestPayload{
ProtocolVersion: []kmip.ProtocolVersion{
{
ProtocolVersionMajor: protocolMajor,
ProtocolVersionMinor: protocolMinor,
},
},
})
if err != nil {
return err
... | identifier_body |
kmip.go | = "WRITE_TIMEOUT"
KmipCACert = "CA_CERT"
KmipClientCert = "CLIENT_CERT"
KmipClientKey = "CLIENT_KEY"
KmipUniqueIdentifier = "UNIQUE_IDENTIFIER"
// EtcKmipDir is kmip config dir.
EtcKmipDir = "/etc/kmip"
)
var (
kmsKMIPMandatoryTokenDetails = []string{KmipCACert, KmipClientCert,... | (conn io.ReadWriter) error {
respMsg, decoder, uniqueBatchItemID, err := kms.send(conn,
kmip14.OperationDiscoverVersions,
kmip.DiscoverVersionsRequestPayload{
ProtocolVersion: []kmip.ProtocolVersion{
{
ProtocolVersionMajor: protocolMajor,
ProtocolVersionMinor: protocolMinor,
},
},
})
if ... | discover | identifier_name |
views.py | ","Щ","Э","Ю","Я",)
@login_required(login_url='/login/')
def guest_visit(request, id=0, ):
try:
guest = Guest.objects.get(pk=id)
except Guest.DoesNotExist:
o_name = 'Гость'
context_dict = dict(request=request, o_name=o_name, b_url=b_url)
return render_to_response("err404.html", context_dict)
b_url = reverse... | tle, b_url=b_url, )
context_dict.update(csrf(request))
return render_to_response("guest_add.html", context_dict)
if 'query' in request.GET.keys():
query = request.GET.get('query')
lst = Guest.objects.filter(lastname__icontains=query).order_by("lastname")
elif id > -1:
lst = Guest.objects.filter(lastname__i... | f.pk
post_values['date'] = datetime.now()
post_values['is_free'] = True
fi = FormInvitation(post_values)
if fi.is_valid():
fi.save()
else:
fi = fi.errors
url = reverse('r_guest', args=(0, ))
return HttpResponseRedirect(url)
context_dict = dict(request=request, p_title=p_ti | conditional_block |
views.py | (request))
return render_to_response('guest_visit.html', context_dict)
@login_required(login_url='/login/')
def cashier(request, ):
p_title='Работа с кассой'
cashhost = settings.CASHIER_HOST
context_dict = dict(request=request, p_title=p_title, cashhost=cashhost,)
return render_to_response("cashier.html", context... | equest.POST.get('lastname')
if isinstance(find, long):
res = Contract.objects.filter(card=find, is_current=1)
# if not find in the current try find in the prospect
if res.count() < 1:
res = Contract.objects.filter(card=find, is_current=2)
employees = Employee.objects.filter(card=find,)
else:
ac ... | identifier_body | |
views.py | ","Щ","Э","Ю","Я",)
@login_required(login_url='/login/')
def guest_visit(request, id=0, ):
try:
guest = Guest.objects.get(pk=id)
except Guest.DoesNotExist:
o_name = 'Гость'
context_dict = dict(request=request, o_name=o_name, b_url=b_url)
return render_to_response("err404.html", context_dict)
b_url = reverse... | ery = request.GET.get('query')
if len(query) > 0:
clnts = Client.objects.filter(last_name__icontains=query).order_by("last_name")
for c in Contract.objects.filter(contract_type__in=ct,
is_current=1, client__in=clnts):
invites = Invitation.objects.filter(contract=c)
lst.append((c, invites))
... | keys():
qu | identifier_name |
views.py | ","Щ","Э","Ю","Я",)
@login_required(login_url='/login/')
def guest_visit(request, id=0, ):
try:
guest = Guest.objects.get(pk=id)
except Guest.DoesNotExist:
o_name = 'Гость'
context_dict = dict(request=request, o_name=o_name, b_url=b_url)
return render_to_response("err404.html", context_dict)
b_url = reverse... | if len(query) > 0:
clnts = Client.objects.filter(last_name__icontains=query).order_by("last_name")
for c in Contract.objects.filter(contract_type__in=ct,
is_current=1, client__in=clnts):
invites = Invitation.objects.filter(contract=c)
lst.append((c, invites))
else:
for c in Contract.obj... | query = request.GET.get('query') | random_line_split |
warming.rs | arming-related state with interior mutability.
#[derive(Clone)]
pub(crate) struct WarmingState(Arc<Mutex<WarmingStateInner>>);
impl WarmingState {
pub fn new(
num_warming_threads: usize,
warmers: Vec<Weak<dyn Warmer>>,
searcher_generation_inventory: Inventory<SearcherGeneration>,
) -> c... |
/// Start tracking a new generation of [Searcher], and [Warmer::warm] it if there are active
/// warmers.
///
/// A background GC thread for [Warmer::garbage_collect] calls is uniquely created if there are
/// active warmers.
pub fn warm_new_searcher_generation(&self, searcher: &Searcher) -> cr... | }))))
} | random_line_split |
warming.rs | arming-related state with interior mutability.
#[derive(Clone)]
pub(crate) struct WarmingState(Arc<Mutex<WarmingStateInner>>);
impl WarmingState {
pub fn new(
num_warming_threads: usize,
warmers: Vec<Weak<dyn Warmer>>,
searcher_generation_inventory: Inventory<SearcherGeneration>,
) -> c... | (
&mut self,
searcher: &Searcher,
this: &Arc<Mutex<Self>>,
) -> crate::Result<()> {
let warmers = self.pruned_warmers();
// Avoid threads (warming as well as background GC) if there are no warmers
if warmers.is_empty() {
return Ok(());
}
se... | warm_new_searcher_generation | identifier_name |
warming.rs | arming-related state with interior mutability.
#[derive(Clone)]
pub(crate) struct WarmingState(Arc<Mutex<WarmingStateInner>>);
impl WarmingState {
pub fn new(
num_warming_threads: usize,
warmers: Vec<Weak<dyn Warmer>>,
searcher_generation_inventory: Inventory<SearcherGeneration>,
) -> c... | else {
Executor::multi_thread(num_threads, "tantivy-warm-")
}
}
#[cfg(test)]
mod tests {
use std::collections::HashSet;
use std::sync::atomic::{self, AtomicUsize};
use std::sync::{Arc, RwLock, Weak};
use super::Warmer;
use crate::core::searcher::SearcherGeneration;
use crate::dire... | {
Ok(Executor::single_thread())
} | conditional_block |
main.py | .option('--debug/--no-debug', default=False, help="Whether to run some more expensive checks (default no debug)")
@click.option('-r', '--repetitions', default=1, help="How many times to run the model (default 1)")
@click.option('-l', '--lockdown-file', default="google_mobility_lockdown_daily.csv",
help="O... | if initialise:
print("Have finished initialising model. -init flag is set so not running it. Exitting")
return
run_python_model(individuals, activity_locations, time_activity_multiplier, msim_args, iterations,
repetitions, parameters_file) | conditional_block | |
main.py | not output any data (output=False) but also write the data at every "
"iteration (output_every_iteration=True)")
print(f"Running model with the following parameters:\n"
f"\tParameters file: {parameters_file}\n"
f"\tScenario directory: {scenario}\n"
f"\tInitia... | create_params | identifier_name | |
main.py | (not reading parameters file)' if no_parameters_file else str(disease_params)}\n")
# To fix file path issues, use absolute/full path at all times
# Pick either: get working directory (if user starts this script in place, or set working directory
# Option A: copy current working directory:
base_dir = o... | current_risk_beta = disease_params["current_risk_beta"]
# NB: OpenCL model incorporates the current risk beta by pre-multiplying the hazard multipliers with it
location_hazard_multipliers = LocationHazardMultipliers(
retail=calibration_params["hazard_location_multipliers"]["Retail"] * current_risk_beta... | identifier_body | |
main.py | caches and snapshots. Dont' run it.")
@click.option('-i', '--iterations', default=10, help='Number of model iterations. 0 means just run the initialisation')
@click.option('-s', '--scenario', default="default", help="Name this scenario; output results will be put into a "
... | # Option A: copy current working directory:
base_dir = os.getcwd() # get current directory
data_dir = os.path.join(base_dir, data_dir)
r_script_dir = os.path.join(base_dir, "R", "py_int")
### section for fetching data
if not os.path.isdir(data_dir):
print(f"No data directory detected.... | # To fix file path issues, use absolute/full path at all times
# Pick either: get working directory (if user starts this script in place, or set working directory | random_line_split |
main.rs | CollCircle>();
world.register::<AISlime>();
world.register::<Hurt>();
world.register::<Health>();
world.register::<Lifetime>();
world.register::<Knockback>();
world.register::<HurtKnockbackDir>();
world.register::<Tint>();
world.register::<Rot>();
world.register::<Alliance>();
wo... | {
println!("Resizing window viewport");
renderer.update_window_size(&window);
} | conditional_block | |
main.rs | VertexBuffer(renderer::VertexBuffer);
/// Vertex buffer for terrain (tilesets). This is so we don't have to re-buffer
/// tilesets all the tiem, and means we don't have to implement perspective
/// frustum culling
pub struct TerrainVertexBuffer(renderer::VertexBuffer);
/// If true, we should update the terrain vertex b... | .with(PlayerControlled::new())
.with(FollowCamera)
.with(Health::new(8, Hitmask(HITMASK_PLAYER)))
.with(Collector { magnet_radius: 64.0 })
.with(Equipment {
.. Default::default()
})
.with(CollCircle { r: 8.0, off: Vec32::zero(),
... | .with(Vel { vel: Vec32::zero() })
.with(Alliance::good()) | random_line_split |
main.rs | VertexBuffer(renderer::VertexBuffer);
/// Vertex buffer for terrain (tilesets). This is so we don't have to re-buffer
/// tilesets all the tiem, and means we don't have to implement perspective
/// frustum culling
pub struct TerrainVertexBuffer(renderer::VertexBuffer);
/// If true, we should update the terrain vertex b... | (renderer::VertexBuffer);
/// Entities that have been 'killed' and need to produce on-death effects. This
/// doesn't mean all deleted entities - it means alive characters have been
/// killed by combat or other effects.
pub struct KilledEntities(Vec<Entity>);
/// Empty specs::System to use in the dispatcher as a com... | UIVertexBuffer | identifier_name |
main.rs | (renderer::VertexBuffer);
/// Vertex buffer for terrain (tilesets). This is so we don't have to re-buffer
/// tilesets all the tiem, and means we don't have to implement perspective
/// frustum culling
pub struct TerrainVertexBuffer(renderer::VertexBuffer);
/// If true, we should update the terrain vertex buffer.
pub s... |
}
/// Create the world and register all the components
fn create_world() -> specs::World {
let mut world = specs::World::new();
world.register::<Pos>();
world.register::<Vel>();
world.register::<PlayerControlled>();
world.register::<Tilemap>();
world.register::<AnimSprite>();
world.registe... | {} | identifier_body |
mod.rs | str.trim().starts_with("-----BEGIN") {
// PEM format
Ok(parse_pem_pubkey(keystr.as_bytes())?)
} else {
// openssh format
Ok(parse_ossh_pubkey(keystr)?)
}
}
/// Indicate the key type being stored
pub fn keytype(&self) -> KeyType {
match... | {
stringify_pem_privkey(self, passphrase)
} | identifier_body | |
mod.rs | SHA512,
}
impl FingerprintHash {
fn hash(self, data: &[u8]) -> Vec<u8> {
fn digest_hash<D>(hasher: &mut D, data: &[u8]) -> Vec<u8>
where
D: Digest + FixedOutputReset,
{
// Fix error[E0034]: multiple applicable items in scope
Digest::update(hasher, dat... | SHA256, | random_line_split | |
mod.rs | from_keystr(keystr: &str) -> OsshResult<Self> {
if keystr.trim().starts_with("-----BEGIN") {
// PEM format
Ok(parse_pem_pubkey(keystr.as_bytes())?)
} else {
// openssh format
Ok(parse_ossh_pubkey(keystr)?)
}
}
/// Indicate the key type be... | (inner: rsa::RsaPublicKey) -> PublicKey {
PublicKey {
key: PublicKeyType::RSA(inner),
comment: String::new(),
}
}
}
impl From<dsa::DsaPublicKey> for PublicKey {
fn from(inner: dsa::DsaPublicKey) -> PublicKey {
PublicKey {
key: PublicKeyType::DSA(inner... | from | identifier_name |
mod.rs | example
/// #set text(size: 25pt)
/// Totally
///
/// #set text(kerning: false)
/// Totally
/// ```
#[default(true)]
pub kerning: bool,
/// Whether to apply stylistic alternates.
///
/// Sometimes fonts contain alternative glyphs for the same codepoint.
/// Setting this ... | ric) = metric.try_into() {
font.metrics().vertical(metric).resolve(styles)
} else {
bbox.map(|bbox| (font.to_em(bbox.y_max)).resolve(styles))
.unwrap_or_default()
}
}
TopEdge::Length(le | conditional_block | |
mod.rs | to `{auto}`, the
/// default numbers for the font are used.
///
/// ```example
/// #set text(font: "Noto Sans", 20pt)
/// #set text(number-type: "lining")
/// Number 9.
///
/// #set text(number-type: "old-style")
/// Number 9.
/// ```
pub number_type: Smart<NumberType>,
... | }
}
cast! {
BottomEdge, | random_line_split | |
mod.rs | (global: &mut Scope) {
global.define("text", TextElem::func());
global.define("linebreak", LinebreakElem::func());
global.define("smartquote", SmartQuoteElem::func());
global.define("strong", StrongElem::func());
global.define("emph", EmphElem::func());
global.define("lower", lower_func());
... | define | identifier_name | |
tetris.py | Display classes."""
def paint_square(self, pos, color, cr):
"""Paints a square on the grid at a particular (int, int) position.
Color is given as an RGB triple (of floats between 0 and 1); cr is the
Cairo context. Used only in the expose methods of Board and
NextPieceDisplay"""
... | (self):
"""Clear any full rows, modifying the variables locked_squares,
level, lines, and score as appropriate."""
### Previous version had a bug, in that it assumed the set of ###
### indices of full rows had to be a contiguous sequence! ###
full_rows = [j for j in range(ROWS) i... | clear_rows | identifier_name |
tetris.py | PieceDisplay classes."""
def paint_square(self, pos, color, cr):
"""Paints a square on the grid at a particular (int, int) position.
Color is given as an RGB triple (of floats between 0 and 1); cr is the
Cairo context. Used only in the expose methods of Board and
NextPieceDisplay"""... |
self.increment_score(delta[1])
self.move_curr_piece(delta)
self.lock_curr_piece()
self.queue_draw()
def rotate_curr_piece(self):
"""Check the validity of a rotation, and conditionally perform it."""
if self.over: return
hypothetical = self.curr_piece.test_ro... | break | conditional_block |
tetris.py | PieceDisplay classes."""
def paint_square(self, pos, color, cr):
"""Paints a square on the grid at a particular (int, int) position.
Color is given as an RGB triple (of floats between 0 and 1); cr is the
Cairo context. Used only in the expose methods of Board and
NextPieceDisplay"""... | self.game_over()
def game_over(self):
"""End the game. (Doesn't currently have to do much, because the
actual painting is done conditionally in expose.)"""
self.over = True
def clear_rows(self):
"""Clear any full rows, modifying the variables locked_squares,
... | self.clear_rows()
self.curr_piece = self.next_piece_display.get_piece()
if any(pos in self.locked_squares
for pos in self.curr_piece.occupying()): | random_line_split |
tetris.py | OLS*DOT_SIZE, ROWS*DOT_SIZE)
self.connect("expose-event", self.expose)
self.next_piece_display = next_piece_display
self.level_display = level_display
self.lines_display = lines_display
self.score_display = score_display
self.level = 0
self.lines = 0
sel... | super(Main, self).__init__()
self.set_title("Tetris")
self.set_resizable(False)
self.set_position(gtk.WIN_POS_CENTER)
self.connect("destroy", gtk.main_quit)
self.connect("key-press-event", self.on_key_down)
### Create and reformat labels ###
self.next_piece_word... | identifier_body | |
SPACE-BLASTER-FINAL.py |
# For-loop appending coordinates for the meteors
# on blue spaceship side
x_meteor_blue = random.randrange(15, 550)
meteor_list_blue.append([x_meteor_blue, 0])
# Blue meteor width & height values
blue_meteorw = 30
blue_meteorh = 30
# Function for displaying blue spaceship
def BLUE(x_change_blue, y_chang... | random_line_split | ||
SPACE-BLASTER-FINAL.py | 2w:
if obj1y + obj1h >= obj2y and obj1y <= obj2y + obj2h:
return True
return False
# Blue Player scoring function
score_blue = 0
def blue_player(score_blue):
font_blue_score = pygame.font.SysFont('monospace', 25, True, False)
score_blue_text = font_blue_score.render("SC... | startX_red += 3
startX_red += 3
startX_red += 3 | conditional_block | |
SPACE-BLASTER-FINAL.py | spaceship side
x_meteor_blue = random.randrange(15, 550)
meteor_list_blue.append([x_meteor_blue, 0])
# Blue meteor width & height values
blue_meteorw = 30
blue_meteorh = 30
# Function for displaying blue spaceship
def BLUE(x_change_blue, y_change_blue):
screen.blit(blue_spaceship, (x_change_blue, y_c... |
# Importing & loading music file
background_music = pygame.mixer.music.load("Instrumental Music.mp3")
# Music timer set at zero before loop
music_timer = 0
# Initializing game timer (set to zero)
game_timer = 90
# --- Main Game Title Screen ---
start = False
done = False
while not start and not done:... | font_red_score = pygame.font.SysFont('monospace', 25, True, False)
score_red_text = font_red_score.render("SCORE :" + str(int(score_red)), True, RED_FADE)
screen.blit(score_red_text, [865, 10])
return score_red | identifier_body |
SPACE-BLASTER-FINAL.py | spaceship side
x_meteor_blue = random.randrange(15, 550)
meteor_list_blue.append([x_meteor_blue, 0])
# Blue meteor width & height values
blue_meteorw = 30
blue_meteorh = 30
# Function for displaying blue spaceship
def BLUE(x_change_blue, y_change_blue):
screen.blit(blue_spaceship, (x_change_blue, y_c... | (obj1x, obj1y, obj1w, obj1h, obj2x, obj2y, obj2w, obj2h):
# check bounding box
if obj1x + obj1w >= obj2x and obj1x <= obj2x + obj2w:
if obj1y + obj1h >= obj2y and obj1y <= obj2y + obj2h:
return True
return False
# Blue Player scoring function
score_blue = 0
def blue_pla... | checkCollision | identifier_name |
rust_gtest_interop.rs | pub use crate::expect_ge;
pub use crate::expect_gt;
pub use crate::expect_le;
pub use crate::expect_lt;
pub use crate::expect_ne;
pub use crate::expect_true;
}
// The gtest_attribute proc-macro crate makes use of small_ctor, with a path
// through this crate here to ensure it's available.
#[doc... | random_line_split | ||
rust_gtest_interop.rs | a path
// through this crate here to ensure it's available.
#[doc(hidden)]
pub extern crate small_ctor;
/// A marker trait that promises the Rust type is an FFI wrapper around a C++
/// class which subclasses `testing::Test`. In particular, casting a
/// `testing::Test` pointer to the implementing class type is promi... | {
data: [u8; 0],
marker: std::marker::PhantomData<(*mut u8, std::marker::PhantomPinned)>,
}
#[doc(hidden)]
pub trait TestResult {
fn into_error_message(self) -> Option<String>;
}
impl TestResult for () {
fn into_error_message(self) -> Option<String> {
None
}
}
// This impl requires an `Err... | OpaqueTestingTest | identifier_name |
rust_gtest_interop.rs | a path
// through this crate here to ensure it's available.
#[doc(hidden)]
pub extern crate small_ctor;
/// A marker trait that promises the Rust type is an FFI wrapper around a C++
/// class which subclasses `testing::Test`. In particular, casting a
/// `testing::Test` pointer to the implementing class type is promi... |
}
// Internals used by code generated from the gtest-attriute proc-macro. Should
// not be used by human-written code.
#[doc(hidden)]
pub mod __private {
use super::{GtestFactoryFunction, OpaqueTestingTest, Pin};
/// Rust wrapper around the same C++ method.
///
/// We have a wrapper to convert the fi... | {
match self {
Ok(_) => None,
Err(e) => Some(format!("Test returned error: {}", e.into())),
}
} | identifier_body |
main.rs | );
let mut data_chars = data.chars();
let mut out = Vec::new(); //(Key, Value)
out.push(("Barcode type", "PDF217".to_string()));
//Version
let version = data_chars.next().unwrap();
match version {
'1' | 'N' => out.push(("Barcode version", version.to_string())),
_ => return format!("Unknown barc... | //Electronic Data Interchange Person Identifier (base 32)
let edipi = data_chars.by_ref().take(7).collect::<String>();
out.push(("Electronic Data Interchange Person Identifier", base32.decimal(edipi).to_string()));
//Personnel Category Code
out.push(("Personnel Category Code", lookup_ppc(data_chars.next().un... | random_line_split | |
main.rs | );
let mut data_chars = data.chars();
let mut out = Vec::new(); //(Key, Value)
out.push(("Barcode type", "PDF217".to_string()));
//Version
let version = data_chars.next().unwrap();
match version {
'1' | 'N' => out.push(("Barcode version", version.to_string())),
_ => return format!("Unknown barc... | (data: String) -> String {
let mut data_chars = data.chars();
let base32 = BaseCustom::<String>::new("0123456789ABCDEFGHIJKLMNOPQRSTUV", None);
let mut out = Vec::new(); //(Key, Value)
out.push(("Barcode type", "Code39".to_string()));
//Version
let version = data_chars.next().unwrap();
match version {... | decode_code39 | identifier_name |
main.rs |
fn decode_pdf217(data: String) -> String {
let base32 = BaseCustom::<String>::new("0123456789ABCDEFGHIJKLMNOPQRSTUV", None);
let base_time = Utc.ymd(1000, 1, 1);
let mut data_chars = data.chars();
let mut out = Vec::new(); //(Key, Value)
out.push(("Barcode type", "PDF217".to_string()));
//Version
l... | {
match data.len() {
18 => return decode_code39(data),
88 | 89 => return decode_pdf217(data),
_ => return format!("Incorrect barcode length: {}. Make sure to include all spaces.", data.len()),
}
} | identifier_body | |
source_manager.go | {
// Perform analysis of the filesystem tree rooted at path, with the
// root import path importRoot, to determine the project's constraints, as
// indicated by a Manifest and Lock.
DeriveManifestAndLock(path string, importRoot ProjectRoot) (Manifest, Lock, error)
// Report the name and version of this ProjectAn... | // gps's SourceManager is intended to be threadsafe (if it's not, please file a
// bug!). It should be safe to reuse across concurrent solving runs, even on
// unrelated projects.
func NewSourceManager(an ProjectAnalyzer, cachedir string) (*SourceMgr, error) {
if an == nil {
return nil, fmt.Errorf("a ProjectAnalyzer... | random_line_split | |
source_manager.go | // Perform analysis of the filesystem tree rooted at path, with the
// root import path importRoot, to determine the project's constraints, as
// indicated by a Manifest and Lock.
DeriveManifestAndLock(path string, importRoot ProjectRoot) (Manifest, Lock, error)
// Report the name and version of this ProjectAnaly... | (id ProjectIdentifier) ([]Version, error) {
src, err := sm.getSourceFor(id)
if err != nil {
// TODO(sdboyer) More-er proper-er errors
return nil, err
}
return src.listVersions()
}
// RevisionPresentIn indicates whether the provided Revision is present in the given
// repository.
func (sm *SourceMgr) RevisionP... | ListVersions | identifier_name |
source_manager.go | // Perform analysis of the filesystem tree rooted at path, with the
// root import path importRoot, to determine the project's constraints, as
// indicated by a Manifest and Lock.
DeriveManifestAndLock(path string, importRoot ProjectRoot) (Manifest, Lock, error)
// Report the name and version of this ProjectAnaly... |
return src.listVersions()
}
// RevisionPresentIn indicates whether the provided Revision is present in the given
// repository.
func (sm *SourceMgr) RevisionPresentIn(id ProjectIdentifier, r Revision) (bool, error) {
src, err := sm.getSourceFor(id)
if err != nil {
// TODO(sdboyer) More-er proper-er errors
ret... | {
// TODO(sdboyer) More-er proper-er errors
return nil, err
} | conditional_block |
source_manager.go | // Perform analysis of the filesystem tree rooted at path, with the
// root import path importRoot, to determine the project's constraints, as
// indicated by a Manifest and Lock.
DeriveManifestAndLock(path string, importRoot ProjectRoot) (Manifest, Lock, error)
// Report the name and version of this ProjectAnaly... |
// ListVersions retrieves a list of the available versions for a given
// repository name.
//
// The list is not sorted; while it may be returned in the order that the
// underlying VCS reports version information, no guarantee is made. It is
// expected that the caller either not care about order, or sort the result... | {
src, err := sm.getSourceFor(id)
if err != nil {
return PackageTree{}, err
}
return src.listPackages(id.ProjectRoot, v)
} | identifier_body |
detailed-titanic-analysis-and-solution.py | unknown age values to mean value of a corresponding title.
#
# We will do so by adding a column called 'Title' to the data and fill it out with a new funciton.
# In[ ]:
def get_title(pasngr_name):
|
# In[ ]:
train['Title'] = train['Name'].apply(get_title)
test['Title'] = test['Name'].apply(get_title)
# In[ ]:
plt.figure(figsize=(16, 10))
sns.boxplot('Title', 'Age', data=train)
# Now that we have all the titles, we can find out a mean value for each of them and use it to fill the gaps in the data.
# In[... | index_1 = pasngr_name.find(', ') + 2
index_2 = pasngr_name.find('. ') + 1
return pasngr_name[index_1:index_2] | identifier_body |
detailed-titanic-analysis-and-solution.py | far we've worked with features that came with the dataset, but we can also create our own custom features (so far we have FamilySize as a custom, or engineered feature).
# ### Cabin
# Now this is a tricky part. Cabin could be a really important feature, especially if we knew the distribution of cabins on the ship, bu... | class_scores.append(cross_val_score(classifier, X_train, y_train, scoring='accuracy', cv=cv_kfold)) | conditional_block | |
detailed-titanic-analysis-and-solution.py | unknown age values to mean value of a corresponding title.
#
# We will do so by adding a column called 'Title' to the data and fill it out with a new funciton.
# In[ ]:
def get_title(pasngr_name):
index_1 = pasngr_name.find(', ') + 2
index_2 = pasngr_name.find('. ') + 1
return pasngr_name[ind... | (cols):
age = cols[0]
titles = cols[1]
if pd.isnull(age):
return age_by_title[titles]
else:
return age
# In[ ]:
train['Age'] = train[['Age', 'Title']].apply(fill_missing_ages, axis=1)
test['Age'] = test[['Age', 'Title']].apply(fill_missing_ages, axis=1)
#and one Fare value in t... | fill_missing_ages | identifier_name |
detailed-titanic-analysis-and-solution.py | WithLargeFamily'
elif(family_size > 0 and family_size<= 3):
return 'WithFamily'
else:
return 'TraveledAlone'
train['FamilyCategory'] = train['FamilySize'].apply(get_family_category)
test['FamilyCategory'] = test['FamilySize'].apply(get_family_category)
# ** (needs a description depending ... | random_line_split | ||
getdata.py | 6.80859375%2C-109.96875%2C42.2578125
"""
import pymodis
# dictionary to designate a directory
datadir = {'ET': '/ET/', 'PET': '/PET/', 'LE': '/LE/', 'PLE': '/PLE/'}
# dictionary to select layer from hdf file that contains the datatype
matrdir = {'ET': [1, 0, 0, 0], 'LE': [0, 1, 0, 0], 'PET': [0,... |
arcpy.env.mask = area
arcpy.CheckOutExtension("spatial")
for rast in arcpy.ListRasters():
calc = SetNull(arcpy.Raster(rast) > 32700, arcpy.Raster(rast))
calc.save(outpath + data_type + rast[1:5] + rast[6:8] + 'h' + rast[10:11] + 'v' + rast[13:14])
print(outpath + data_type + rast[1... | area = 'H:/GIS/Calc.gdb/WBD_UT' | conditional_block |
getdata.py | (save_path, wld='*.105*.hdf'):
"""
Args:
save_path: path to folder where raw MODIS files are
wld: common wildcard in all of the raw MODIS files
Returns:
list of files to analyze in the raw folder
"""
return glob.glob(os.path.join(save_path, wld))
def reproject_modis(file... | get_file_list | identifier_name | |
getdata.py | y + 'h' + h + 'v' + v
pref = os.path.join(save_path + datadir[data_type] + fname)
else:
month = f.split('\\')[1].split('.')[1][-2:] # parse month from hdf filename
fname = 'A' + year + 'M' + month + 'h' + h + 'v' + v
pref = os.path.join(save_path + datadir[data_t... | def rename_polaris_snodas(path): | random_line_split | |
getdata.py | 6.80859375%2C-109.96875%2C42.2578125
"""
import pymodis
# dictionary to designate a directory
datadir = {'ET': '/ET/', 'PET': '/PET/', 'LE': '/LE/', 'PLE': '/PLE/'}
# dictionary to select layer from hdf file that contains the datatype
matrdir = {'ET': [1, 0, 0, 0], 'LE': [0, 1, 0, 0], 'PET': [0,... | for rast in arcpy.ListRasters():
calc = SetNull(arcpy.Raster(rast) > 32700, arcpy.Raster(rast))
calc.save(outpath + data_type + rast[1:5] + rast[6:8] + 'h' + rast[10:11] + 'v' + rast[13:14])
print(outpath + data_type + rast[1:5] + rast[6:8] + 'h' + rast[10:11] + 'v' + rast[13:14])
def mer... | """Clips raster to Utah's Watersheds and makes exception values null.
Args:
path: folder of the reprojected MODIS files
outpath: ESRI gdb to store the clipped files
data_type: type of MODIS16 data being reprojected; options are 'ET','PET','LE', and 'PLE'
area: path to polygon used t... | identifier_body |
nfa2regex.py | ]:
nfa.addDelta(new, input, nfa._deltas[old][input])
del nfa._deltas[old]
if DEBUG:
print('R_SwitchedSource(%s, %s) ---' % (old, new), nfa)
deltas_temp = copyDeltas(nfa._deltas)
for src in deltas_temp:
for input in deltas_temp[src]:
if old in deltas_temp[src]... |
# Sort pliable nodes by distance from terminal
pliableNodes.sort(key=lambda x: nodeFinalDist[x], reverse=True)
if DEBUG:
print('Pliables: ', pliableNodes)
for node in pliableNodes:
# Remove Node
network.remNode(node)
# Save delta
delta = copy(network.getDelta(... | for node in toProcess:
dests = network.getDelta(node).values()
if len(dests) == 0:
dests = set([])
else:
dests = reduce(set.union, network.getDelta(node).values())
if len(dests) == 0:
toProcess.remove(node)
else... | conditional_block |
nfa2regex.py | old]:
nfa.addDelta(new, input, nfa._deltas[old][input])
del nfa._deltas[old]
if DEBUG:
print('R_SwitchedSource(%s, %s) ---' % (old, new), nfa)
deltas_temp = copyDeltas(nfa._deltas)
for src in deltas_temp:
for input in deltas_temp[src]:
if old in deltas_temp[s... |
seq = [reverse(i) for i in seq]
return reverse(commonprefix(seq))
class NetworkNFA(NFA):
def __init__(self, nfa):
if type(nfa) is not NFA:
raise AutomataError('Can create a NetworkNFA only from an NFA.')
if all([len(i) == 1 for i in nfa.charset]):
self._charset =... | out = ''
for c in reversed(s):
out += c
return out | identifier_body |
nfa2regex.py | (src):
out = dict()
for k in src:
out[k] = dict()
for k2 in src[k]:
out[k][k2] = copy(src[k][k2])
return out
def replaceNode(nfa, old, new):
if DEBUG:
print('R_Start(%s, %s) ---' % (old, new), nfa)
if old in nfa._deltas:
for input in nfa._deltas[old]:
... | copyDeltas | identifier_name | |
nfa2regex.py | old]:
nfa.addDelta(new, input, nfa._deltas[old][input])
del nfa._deltas[old]
if DEBUG:
print('R_SwitchedSource(%s, %s) ---' % (old, new), nfa)
deltas_temp = copyDeltas(nfa._deltas)
for src in deltas_temp:
for input in deltas_temp[src]:
if old in deltas_temp[s... | if type(dest) is set and all([type(i) is Node for i in dest]):
if len(dest):
if node in self._deltas:
if input in self._deltas[node]:
self._deltas[node][input] = self._deltas[node][input].union(
... | raise AutomataError('%s contains symbols not in charset.' % input)
if type(node) is Node: | random_line_split |
metrics.py | = os.path.join(
os.path.dirname(os.path.abspath(__file__)), '..', '..')
self.test_responses = os.path.join(self.project_path,
config.test_responses)
if not os.path.exists(self.test_responses):
print('Can\' find test responses at ' + self.test_responses +
... | total_length = int(data_stream.headers.get('content-length'))
for chunk in progress.bar(data_stream.iter_content(chunk_size=1024),
expected_size=total_length / 1024 + 1):
if chunk:
file.write(chunk)
file.flush()
# Extract file.
zip_file = ... | 'vectors-english/wiki-news-300d-1M.vec.zip', stream=True)
zipped_path = os.path.join(self.input_dir, 'fasttext.zip')
with open(zipped_path, 'wb') as file: | random_line_split |
metrics.py | os.path.join(
os.path.dirname(os.path.abspath(__file__)), '..', '..')
self.test_responses = os.path.join(self.project_path,
config.test_responses)
if not os.path.exists(self.test_responses):
print('Can\' find test responses at ' + self.test_responses +
... |
if not os.path.exists(self.vector_vocab):
print('File containing word vectors not found in ' + self.vector_vocab)
print('If you would like to use FastText embeddings press \'y\'')
if input() == 'y':
self.get_fast_text_embeddings()
else:
print('Embedding metrics and \'coheren... | print('Can\' find test targets at ' + self.test_target +
', embedding, kl divergence, and bleu metrics won\'t be computed.')
self.delete_from_metrics(['kl-div', 'embedding', 'bleu']) | conditional_block |
metrics.py | os.path.join(
os.path.dirname(os.path.abspath(__file__)), '..', '..')
self.test_responses = os.path.join(self.project_path,
config.test_responses)
if not os.path.exists(self.test_responses):
print('Can\' find test responses at ' + self.test_responses +
... | self):
for filename in self.metrics:
responses = open(filename, encoding='utf-8')
# If we don't need these just open a dummy file.
sources = open(self.test_source, encoding='utf-8') \
if os.path.exists(self.test_source) else open(filename, encoding='utf-8')
gt_responses = open(self.t... | un( | identifier_name |
metrics.py | .project_path, config.test_target)
self.text_vocab = os.path.join(self.project_path, config.text_vocab)
self.vector_vocab = os.path.join(self.project_path, config.vector_vocab)
# Check which metrics we can compute.
if not os.path.exists(self.train_source):
print('Can\'t find train data at ' + sel... | ith open(self.output_path, 'w') as output:
output.write('filename ')
output.write(' '.join([k for k, v in self.which_metrics.items() if v]))
output.write('\n')
''' The first row contains the names of the metrics, then each row
contains the name of the file and its metrics separated by spa... | identifier_body | |
cmh_test.py | return lview,dview
def launch_engines(engines:int, profile:str):
"""Launch ipcluster with engines under profile."""
print(ColorText(f"\nLaunching ipcluster with {engines} engines...").bold())
def _launch(engines, profile):
subprocess.call([shutil.which('ipcluster'), 'start', '-n', str(engines... | controlcol = casecol.replace(case, control)
if not controlcol in controlcols:
badcols.append((casecol, controlcol))
continue
pairs[casecol] = controlcol | conditional_block | |
cmh_test.py |
def __str__(self):
return self.text
def bold(self):
self.text = '\033[1m' + self.text + self.ending
return self
def underline(self):
self.text = '\033[4m' + self.text + self.ending
return self
def green(self):
self.text = '\033[92m' + self.text + self... | self.text = text
self.ending = '\033[0m'
self.colors = [] | identifier_body | |
cmh_test.py | 0]).fail())
exit()
break
else:
print(ColorText("Please respond with 'yes' or 'no'").fail())
return inp
def | (engines:int, profile:str):
"""Reload engines until number matches input engines arg."""
lview = []
dview = []
count = 1
while any([len(lview) != engines, len(dview) != engines]):
if count % 30 == 0:
# if waiting too long..
# TODO: if found engines = 0, no reason to a... | wait_for_engines | identifier_name |
cmh_test.py | ...').bold())
logs = dict((locus,reason) for j in jobs for (locus,reason) in j.r[1].items())
output = pandas.concat([j.r[0] for j in jobs])
# output = pandas.concat([j for j in jobs]) # for testing
return output, logs
def get_cc_pairs(casecols, controlcols, case, control):
"""For a given popula... | # run cmh tests in parallel
output,logs = parallelize_cmh(casedata, controldata, lview)
| random_line_split | |
regexp.go | .ranges[n] = a;
n++;
cclass.ranges[n] = b;
n++;
}
func (cclass *_CharClass) matches(c int) bool {
for i := 0; i < len(cclass.ranges); i = i + 2 {
min := cclass.ranges[i];
max := cclass.ranges[i+1];
if min <= c && c <= max {
return !cclass.negate
}
}
return cclass.negate;
}
func newCharClass() *_CharC... | return
}
switch p.c() {
case '*':
// (start,end)*:
alt := new(_Alt);
p.re.add(alt);
end.setNext(alt); // after end, do alt
alt.left = start; // alternate brach: return to start
start = alt; // alt becomes new (start, end)
end = alt;
case '+':
// (start,end)+:
alt := new(_Alt);
p.re.add(alt);
... | start, end = p.term();
if start == nil || p.error != "" { | random_line_split |
regexp.go | );
re.add(start);
s, e := p.regexp();
if p.error != "" {
return p.error
}
start.setNext(s);
re.start = start;
e.setNext(re.add(new(_End)));
re.eliminateNops();
return p.error;
}
// CompileRegexp parses a regular expression and returns, if successful, a Regexp
// object that can be used to match against text... | {
if r[i] != -1 { // -1 means no match for this subexpression
a[i/2] = s[r[i]:r[i+1]]
}
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.