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 |
|---|---|---|---|---|
common.js | type}&page={page}&uid={uid}",//)获取下面指定层数人员(如 一 级好友 二级好友)
changpwd: "/game/g_user.ashx?action=changpwd&pwd0={pwd0}&pwd1={pwd1}&pwd2={pwd2}&pwd3={pwd3}&pwd4={pwd4}&pwd5={pwd5}&usercode={usercode}",//修改密码
backpwd: "/game/g_user.ashx?action=backpwd&pwd={pwd}&usercode={usercode}",//找回密码
changname: "/game/g_user... | -----------注册短信(电话,回调函数(返回 json 值))--------------------------------------------
sen | conditional_block | |
common.js | .ashx?action=regcheck&tel={tel}&yzm={yzm}",
backcode: "/game/g_sendsms.ashx?action=backcheck&tel={tel}&yzm={yzm}",
ruser: "/game/g_user.ashx?action=ruser&uid={uid}",//获取会员余额信息
geturl: '/game/g_user.ashx?action=getuser&uid={uid}', //获得会员信息
hzhuan: "/game/g_user.ashx?action=hzhuan&usercode={usercode}&pwd... | // console.log(response);
response = JSON.parse(response);
if (response.msg2 == '非法操作') {
window.url = response.msg3;
cc.director.loadScene('update');
} else {
fun(resp... |
var response = xhr.responseText; | random_line_split |
read_archive.rs | ::recover::{accounts_into_recovery, LegacyRecovery};
fn get_runtime() -> (Runtime, u16) {
let port = get_available_port();
let path = TempPath::new();
let rt = start_backup_service(
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
Arc::new(LibraDB::new_for_test(&path)),
);
(r... |
/// Without modifying the data convert an AccountState struct, into a WriteSet Item which can be included in a genesis transaction. This should take all of the resources in the account.
fn get_unmodified_writeset(account_state: &AccountState) -> Result<WriteSetMut, Error> {
let mut ws = WriteSetMut::new(vec![]);
... | {
let mut write_set_mut = WriteSetMut::new(vec![]);
for blob in account_state_blobs {
let account_state = AccountState::try_from(blob)?;
// TODO: borrow
let clean = get_unmodified_writeset(&account_state)?;
let auth = authkey_rotate_change_item(&account_state, get_alice_authkey_f... | identifier_body |
read_archive.rs | ::recover::{accounts_into_recovery, LegacyRecovery};
fn get_runtime() -> (Runtime, u16) {
let port = get_available_port();
let path = TempPath::new();
let rt = start_backup_service(
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
Arc::new(LibraDB::new_for_test(&path)),
);
(r... |
fn read_from_file(path: &str) -> Result<Vec<u8>> {
let mut data = Vec::<u8>::new();
let mut f = File::open(path).expect("Unable to open file");
f.read_to_end(&mut data).expect("Unable to read data");
Ok(data)
}
fn read_from_json(path: &PathBuf) -> Result<StateSnapshotBackup> {
let config = std::fs... | } | random_line_split |
read_archive.rs | ) -> Result<WriteSetMut, Error> {
let mut write_set_mut = WriteSetMut::new(vec![]);
for blob in account_state_blobs {
let account_state = AccountState::try_from(blob)?;
// TODO: borrow
let clean = get_unmodified_writeset(&account_state)?;
let auth = authkey_rotate_change_item(&ac... | {
panic!("MinerStateResource not found");
} | conditional_block | |
read_archive.rs | ::recover::{accounts_into_recovery, LegacyRecovery};
fn get_runtime() -> (Runtime, u16) {
let port = get_available_port();
let path = TempPath::new();
let rt = start_backup_service(
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port),
Arc::new(LibraDB::new_for_test(&path)),
);
(r... | (
archive_path: PathBuf,
) -> Result<WriteSetMut, Error> {
let backup = read_from_json(&archive_path)?;
let account_blobs = accounts_from_snapshot_backup(backup, &archive_path).await?;
accounts_into_writeset_swarm(&account_blobs)
}
/// take an archive file path and parse into a writeset
pub async fn ar... | archive_into_swarm_writeset | identifier_name |
manager.go | {
log.Printf("[Error] Unable to connect to Docker: %v", err)
}
context := fs.Context{DockerRoot: docker.RootDir(), DockerInfo: dockerInfo}
fsInfo, err := fs.NewFsInfo(context)
if err != nil {
return nil, err
}
// If started with host's rootfs mounted, assume that its running
// in its own namespaces.
inH... |
func (m *manager) DockerInfo() (DockerStatus, error) {
info, err := docker.DockerInfo()
if err != nil {
return Docker | {
self.eventHandler.StopWatch(watch_id)
} | identifier_body |
manager.go | {
log.Printf("[Error] Unable to connect to Docker: %v", err)
}
context := fs.Context{DockerRoot: docker.RootDir(), DockerInfo: dockerInfo}
fsInfo, err := fs.NewFsInfo(context)
if err != nil {
return nil, err
}
// If started with host's rootfs mounted, assume that its running
// in its own namespaces.
inH... |
return false
}
func (m *manager) GetMachineInfo() (*info.MachineInfo, error) {
// Copy and return the MachineInfo.
return &m.machineInfo, nil
}
func (m *manager) GetVersionInfo() (*info.VersionInfo, error) {
return &m.versionInfo, nil
}
// can be called by the api which will take events returned on the channel
... | {
return true
} | conditional_block |
manager.go | {
log.Printf("[Error] Unable to connect to Docker: %v", err)
}
context := fs.Context{DockerRoot: docker.RootDir(), DockerInfo: dockerInfo}
fsInfo, err := fs.NewFsInfo(context)
if err != nil {
return nil, err
}
// If started with host's rootfs mounted, assume that its running
// in its own namespaces.
inH... | () map[string]*containerData {
self.containersLock.RLock()
defer self.containersLock.RUnlock()
containers := make(map[string]*containerData, len(self.containers))
// Get containers in the Docker namespace.
for name, cont := range self.containers {
if name.Namespace == docker.DockerNamespace {
containers[cont... | getAllDockerContainers | identifier_name |
manager.go | Reader.Stop()
self.loadReader = nil
}
return nil
}
// Get a container by name.
func (self *manager) GetContainerInfo(containerName string) (*info.ContainerInfo, error) {
cont, err := self.getContainerData(containerName)
if err != nil {
return nil, err
}
return self.containerDataToContainerInfo(cont)
}
func ... | }()
return nil | random_line_split | |
main.go | /primitive"
)
//error class
type Error struct{
StatusCode int `json:"status_code"`
ErrorMessage string `json:"error_message"`
}
//new meeting
type new_meet struct{
Meet_ID string `json:"Id"`
}
//participant shema
type participant struct{
Name string `json:"Name" bson:"name"`
Email string `json... | (w http.ResponseWriter, r *http.Request){
switch r.Method{
//if method is POST
case "POST":
//disallow query strings with POST method
if keys := r.URL.Query(); len(keys)!=0{
invalid_request(w, 400, "Queries not allowed at this endpoint with this method")
}else{
//... | meets_handler | identifier_name |
main.go | }
//meeting schema
type meeting struct{
Id primitive.ObjectID `bson:"_id"`
Title string `json:"Title" bson:"title"`
Part []participant `json:"Participants" bson:"participants" `
Start time.Time `json:"Start Time" bson:"start" `
End time.Time `json:"End Time" bson:"end"`
Stamp time.Time `bson:"... | {
switch r.Method{
case "GET":
//extract meeting id from url
if meet_id := r.URL.Path[len("/meeting/"):]; len(meet_id)==0{
invalid_request(w, 400, "Not a valid Meeting ID")
}else{
//check forvalid id
id, err := primitive.ObjectIDFromHex(meet_id)
... | identifier_body | |
main.go | /primitive"
)
//error class
type Error struct{
StatusCode int `json:"status_code"`
ErrorMessage string `json:"error_message"`
}
//new meeting
type new_meet struct{
Meet_ID string `json:"Id"`
}
//participant shema
type participant struct{
Name string `json:"Name" bson:"name"`
Email string `json... |
if check1 || check2 || check3 {
final_check =true
}
}
if final_check{
invalid_request(w, 400, "Meeting clashes with other meeting/s with some common participant/s")
}else{
insertRes... | {
check3 = false
} | conditional_block |
main.go | /primitive"
)
//error class
type Error struct{
StatusCode int `json:"status_code"`
ErrorMessage string `json:"error_message"`
}
//new meeting
type new_meet struct{
Meet_ID string `json:"Id"`
}
//participant shema
type participant struct{
Name string `json:"Name" bson:"name"`
Email string `json... | case 2:
start, okStart := keys["start"]
end, okEnd := keys["end"]
//check both start and end time are provided, else error
if !okStart || !okEnd {invalid_request(w, 400, "Not a valid query at this end point")
}else{
start_time := start[... | json.NewEncoder(w).Encode(my_meets)
} | random_line_split |
column_chunk.go | information and metadata for a given column chunk
// and it's associated Column
type ColumnChunkMetaData struct {
column *format.ColumnChunk
columnMeta *format.ColumnMetaData
decryptedMeta format.ColumnMetaData
descr *schema.Column
writerVersion *AppVersion
encodings []parquet.Encoding
enc... | else {
return nil, xerrors.New("cannot decrypt column metadata. file decryption not setup correctly")
}
}
}
for _, enc := range c.columnMeta.Encodings {
c.encodings = append(c.encodings, parquet.Encoding(enc))
}
for _, enc := range c.columnMeta.EncodingStats {
c.encodingStats = append(c.encodingStats,... | {
// should decrypt metadata
path := parquet.ColumnPath(ccmd.ENCRYPTION_WITH_COLUMN_KEY.GetPathInSchema())
keyMetadata := ccmd.ENCRYPTION_WITH_COLUMN_KEY.GetKeyMetadata()
aadColumnMetadata := encryption.CreateModuleAad(fileDecryptor.FileAad(), encryption.ColumnMetaModule, rowGroupOrdinal, columnOrdinal,... | conditional_block |
column_chunk.go | information and metadata for a given column chunk
// and it's associated Column
type ColumnChunkMetaData struct {
column *format.ColumnChunk
columnMeta *format.ColumnMetaData
decryptedMeta format.ColumnMetaData
descr *schema.Column
writerVersion *AppVersion
encodings []parquet.Encoding
enc... | () parquet.ColumnPath {
return c.columnMeta.GetPathInSchema()
}
// Compression provides the type of compression used for this particular chunk.
func (c *ColumnChunkMetaData) Compression() compress.Compression {
return compress.Compression(c.columnMeta.Codec)
}
// Encodings returns the list of different encodings us... | PathInSchema | identifier_name |
column_chunk.go | information and metadata for a given column chunk
// and it's associated Column
type ColumnChunkMetaData struct {
column *format.ColumnChunk
columnMeta *format.ColumnMetaData
decryptedMeta format.ColumnMetaData
descr *schema.Column
writerVersion *AppVersion
encodings []parquet.Encoding
enc... | // encrypted and how to decrypt it.
func (c *ColumnChunkMetaData) CryptoMetadata() *format.ColumnCryptoMetaData {
return c.column.GetCryptoMetadata()
}
// FileOffset is the location in the file where the column data begins
func (c *ColumnChunkMetaData) FileOffset() int64 { return c.column.FileOffset }
// FilePath gi... |
// CryptoMetadata returns the cryptographic metadata for how this column was | random_line_split |
column_chunk.go | information and metadata for a given column chunk
// and it's associated Column
type ColumnChunkMetaData struct {
column *format.ColumnChunk
columnMeta *format.ColumnMetaData
decryptedMeta format.ColumnMetaData
descr *schema.Column
writerVersion *AppVersion
encodings []parquet.Encoding
enc... | } else {
return nil, xerrors.New("cannot decrypt column metadata. file decryption not setup correctly")
}
}
}
for _, enc := range c.columnMeta.Encodings {
c.encodings = append(c.encodings, parquet.Encoding(enc))
}
for _, enc := range c.columnMeta.EncodingStats {
c.encodingStats = append(c.encodingSt... | {
c := &ColumnChunkMetaData{
column: column,
columnMeta: column.GetMetaData(),
descr: descr,
writerVersion: writerVersion,
mem: memory.DefaultAllocator,
}
if column.IsSetCryptoMetadata() {
ccmd := column.CryptoMetadata
if ccmd.IsSetENCRYPTION_WITH_COLUMN_KEY() {
if fileD... | identifier_body |
store.go | {
name: "free IP no subnet",
fn: testFreeIPNoSubnet,
},
{
name: "free IP OK",
fn: testFreeIPOK,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := ms(t)
defer s.Close()
tt.fn(t, s)
})
}
}
func testLeasesEmpty(t *testing.T, s wgipam.Store) {
t.Helper()
le... | testAllocateIPMismatchedSubnet | identifier_name | |
store.go | string
fn func(t *testing.T, s wgipam.Store)
}{
{
name: "leases empty",
fn: testLeasesEmpty,
},
{
name: "leases OK",
fn: testLeasesOK,
},
{
name: "lease not exist",
fn: testLeaseNotExist,
},
{
name: "save lease OK",
fn: testSaveLeaseOK,
},
{
name: "delete lease... |
if diff := cmp.Diff([]*net.IPNet{want.IPs[0]}, ip4s); diff != "" {
t.Fatalf("unexpected remaining IPv4 allocation (-want +got):\n%s", diff)
}
ip6s, err := s.AllocatedIPs(okSubnet6)
if err != nil {
t.Fatalf("failed to get allocated IPv6s: %v", err)
}
if diff := cmp.Diff([]*net.IPNet{want.IPs[1]}, ip6s); di... | {
t.Fatalf("failed to get allocated IPv4s: %v", err)
} | conditional_block |
store.go | string
fn func(t *testing.T, s wgipam.Store)
}{
{
name: "leases empty",
fn: testLeasesEmpty,
},
{
name: "leases OK",
fn: testLeasesOK,
},
{
name: "lease not exist",
fn: testLeaseNotExist,
},
{
name: "save lease OK",
fn: testSaveLeaseOK,
},
{
name: "delete lease... |
var want *wgipam.Lease
for i := 0; i < 3; i++ {
ips, ok, err := ipa.Allocate(wgipam.DualStack)
if err != nil {
t.Fatalf("failed to allocate IPs: %v", err)
}
if !ok {
t.Fatal("ran out of IP addresses")
}
// Create leases which start at regular intervals.
l := &wgipam.Lease{
IPs: ips,
Sta... | {
t.Helper()
if err := s.SaveSubnet(okSubnet4); err != nil {
t.Fatalf("failed to save subnet: %v", err)
}
ipa, err := wgipam.DualStackIPAllocator(s, []wgipam.Subnet{
{Subnet: *okSubnet4},
{Subnet: *okSubnet6},
})
if err != nil {
t.Fatalf("failed to create IP allocator: %v", err)
}
// Leases start eve... | identifier_body |
store.go | string
fn func(t *testing.T, s wgipam.Store)
}{
{
name: "leases empty",
fn: testLeasesEmpty,
},
{
name: "leases OK",
fn: testLeasesOK,
},
{
name: "lease not exist",
fn: testLeaseNotExist,
},
{
name: "save lease OK",
fn: testSaveLeaseOK,
},
{
name: "delete lease... | },
{
name: "subnets OK",
fn: testSubnetsOK,
},
{
name: "allocated IPs no subnet",
fn: testAllocatedIPsNoSubnet,
},
{
name: "allocate IP mismatched subnet",
fn: testAllocateIPMismatchedSubnet,
},
{
name: "allocate IP no subnet",
fn: testAllocateIPNoSubnet,
},
{
name... | fn: testPurgeOK,
},
{
name: "subnets empty",
fn: testSubnetsEmpty, | random_line_split |
chat_template.js | $/g;
// can't do a username.tmi.twitch.tv since the latter part of the host could change at any point
// course this is just a relately standard IRC parser anyway.
// but this will trip a ReDoS scanner since >= 10
// A Twitch username is up to 25 letters, we'll leave some wiggle room
const hostRegex = /([a-z_0-9]{1,30}... |
case 'NOTICE':
// General notices about Twitch/rooms you are in
// https://dev.twitch.tv/docs/irc/commands#notice-twitch-commands
// moderationy stuff
case 'CLEARCHAT':
// A users message is to be removed
... | {
if (payload.tags.hasOwnProperty('msg-id')) {
this.emit(
`usernotice_${payload.tags['msg-id']}`,
payload
);
}
} | conditional_block |
chat_template.js | anyway.
// but this will trip a ReDoS scanner since >= 10
// A Twitch username is up to 25 letters, we'll leave some wiggle room
const hostRegex = /([a-z_0-9]{1,30})!([a-z_0-9]{1,30})@([a-z._0-9]{1,60})/;
class ChatBot extends EventEmitter {
constructor(opts) {
super();
this.reconnect = true;
... | // close the socket and let the close handler grab it
this.ws.close();
break; | random_line_split | |
chat_template.js | 1$/g;
// can't do a username.tmi.twitch.tv since the latter part of the host could change at any point
// course this is just a relately standard IRC parser anyway.
// but this will trip a ReDoS scanner since >= 10
// A Twitch username is up to 25 letters, we'll leave some wiggle room
const hostRegex = /([a-z_0-9]{1,30... | () {
console.log('Got Error');
// reconnect
this.emit('close');
if (this.reconnect) {
console.log('Reconnecting');
this._reconnect();
}
}
_onClose() {
console.log('Got Close');
// reconnect
this.emit('close');
if (... | _onError | identifier_name |
chat_template.js | $/g;
// can't do a username.tmi.twitch.tv since the latter part of the host could change at any point
// course this is just a relately standard IRC parser anyway.
// but this will trip a ReDoS scanner since >= 10
// A Twitch username is up to 25 letters, we'll leave some wiggle room
const hostRegex = /([a-z_0-9]{1,30}... |
_onMessage(event) {
let message = event.data.toString().trim().split(/\r?\n/);
// uncomment this line to log all inbounc messages
//console.log(message);
for (var x=0;x<message.length;x++) {
// the last line is empty
if (message[x].length == 0) {
... | {
// pinger
this.pinger.start();
this.ws.send('CAP REQ :twitch.tv/commands');
this.ws.send('CAP REQ :twitch.tv/tags');
this.emit('open');
} | identifier_body |
download-ganglia-metrics.py | =Bytes%20Sent',
'unit': 'bytes per second',
'name': 'send data',
},
'bytes_in': {
'uri': 'm=bytes_in&vl=bytes%2Fsec&ti=Bytes%20Received',
'unit': 'bytes per second',
'name': 'received data',
},
'mem_free': {
'uri': 'm=mem_free&vl=KB&ti=Free%20Memory',
... |
return formatted_data
def save_formatted_metrics(data, directory):
for step in WORKFLOW_STEPS:
for metric in FORMATTED_METRICS:
subdirectory = os.path.join(directory, step)
if not os.path.exists(subdirectory):
os.makedirs(subdirectory)
filepath = os... | formatted_data[step] = pd.DataFrame(
index=HOST_GROUPS.keys(), columns=FORMATTED_METRICS.keys()
)
for group in HOST_GROUPS:
aggregates = dict()
for metric in RAW_METRICS:
values = data[step][group][metric]
# TODO: cutoff?
... | conditional_block |
download-ganglia-metrics.py | =Bytes%20Sent',
'unit': 'bytes per second',
'name': 'send data',
},
'bytes_in': {
'uri': 'm=bytes_in&vl=bytes%2Fsec&ti=Bytes%20Received',
'unit': 'bytes per second',
'name': 'received data',
},
'mem_free': {
'uri': 'm=mem_free&vl=KB&ti=Free%20Memory',
... |
def _get_compute_nodes(cluster):
n = _get_number_of_processors(cluster)
return tuple([
'{0}-slurm-worker-{1:03d}'.format(cluster, i+1) for i in range(n)
])
def _get_fs_nodes(cluster):
n = _get_number_of_processors(cluster)
# Ratio of compute to storage nodes is 1:4
return tuple([
... | match = re.search(r'^cluster-([0-9]+)$', cluster)
n = match.group(1)
# All cluster architectuers use nodes with 4 processors
return int(n)/4 | identifier_body |
download-ganglia-metrics.py | =Bytes%20Sent',
'unit': 'bytes per second',
'name': 'send data',
},
'bytes_in': {
'uri': 'm=bytes_in&vl=bytes%2Fsec&ti=Bytes%20Received',
'unit': 'bytes per second',
'name': 'received data',
},
'mem_free': {
'uri': 'm=mem_free&vl=KB&ti=Free%20Memory',
... | 'output': {
'func': lambda m: m['bytes_out'],
'unit': 'bytes per second',
'name': 'data output'
}
}
def _get_number_of_processors(cluster):
match = re.search(r'^cluster-([0-9]+)$', cluster)
n = match.group(1)
# All cluster architectuers use nodes with 4 processors
retur... | 'input': {
'func': lambda m: m['bytes_in'],
'unit': 'bytes per second',
'name': 'data input'
}, | random_line_split |
download-ganglia-metrics.py | =Bytes%20Sent',
'unit': 'bytes per second',
'name': 'send data',
},
'bytes_in': {
'uri': 'm=bytes_in&vl=bytes%2Fsec&ti=Bytes%20Received',
'unit': 'bytes per second',
'name': 'received data',
},
'mem_free': {
'uri': 'm=mem_free&vl=KB&ti=Free%20Memory',
... | (cluster):
return tuple(['{0}-postgresql-master-001'.format(cluster)])
def _get_db_worker_nodes(cluster):
n = _get_number_of_processors(cluster)
# Ratio of compute to storage nodes is 1:4
return tuple([
'{0}-postgresql-worker-{1:03d}'.format(cluster, i+1)
for i in range(n/4)
])
H... | _get_db_coordinator_nodes | identifier_name |
mfg_event_converter.py | fgEvent proto."""
# TODO(openhtf-team):
# * Missing in proto: set run name from metadata.
# * `part_tags` field on proto is unused
# * `timings` field on proto is unused.
# * Handle arbitrary units as uom_code/uom_suffix.
# Populate non-repeated fields.
mfg_event.dut_serial = record.dut_id
mfg_... | __init__ | identifier_name | |
mfg_event_converter.py | attachment.type = test_runs_pb2.TEXT_UTF8
def _attach_argv(mfg_event):
attachment = mfg_event.attachment.add()
attachment.name = 'argv'
argv = [os.path.realpath(sys.argv[0])] + sys.argv[1:]
attachment.value_binary = _convert_object_to_json(argv)
attachment.type = test_runs_pb2.TEXT_UTF8
class UniqueNameM... | sum(value_copied_attachment_sizes) + size >
MAX_TOTAL_ATTACHMENT_BYTES):
skipped_attachment_names.append(name)
else:
value_copied_attachment_sizes.append(size) | random_line_split | |
mfg_event_converter.py |
for unit in units.UNITS_BY_NAME.values():
UNITS_BY_CODE[unit.code] = unit
def mfg_event_from_test_record(
record: htf_test_record.TestRecord,
attachment_cache: Optional[AttachmentCacheT] = None,
) -> mfg_event_pb2.MfgEvent:
"""Convert an OpenHTF TestRecord to an MfgEvent proto.
Most fields are co... | return | conditional_block | |
mfg_event_converter.py | the mutated record.
Metadata fields:
test_name: The name field from the test's TestOptions.
config: The OpenHTF config, as a dictionary.
assembly_events: List of AssemblyEvent protos.
(see proto/assembly_event.proto).
operator_name: Name of the test operator.
Args:
record: An OpenHTF ... |
json_encoder = json.JSONEncoder(
sort_keys=True,
indent=2,
ensure_ascii=False,
default=unsupported_type_handler)
return json_encoder.encode(obj).encode('utf-8', errors='replace')
def _attach_config(mfg_event, record):
"""Attaches the OpenHTF config file as JSON."""
if 'config' not in... | if isinstance(o, bytes):
return o.decode(encoding='utf-8', errors='replace')
elif isinstance(o, (datetime.date, datetime.datetime)):
return o.isoformat()
else:
raise TypeError(repr(o) + ' is not JSON serializable') | identifier_body |
fit_nixing.py | (w-1, int(float(box[2])))
y2 = min(h-1, int(float(box[3])))
B, G, R = color
img[y1:y2, x1:x2, 0] = img[y1:y2, x1:x2, 0] * alphaReserve + B * (1 - alphaReserve)
img[y1:y2, x1:x2, 1] = img[y1:y2, x1:x2, 1] * alphaReserve + G * (1 - alphaReserve)
img[y1:y2, x1:x2, 2] = img[y1:y2, x1:x2, 2] * alphaReser... | = [_ for i, _ in enumerate(history_record) if history_cnt[i]>0]
history_platenum = [_ for i, _ in enumerate(history_platenum) if history_cnt[i]>0]
history_cnt = [_-1 for i, _ in enumerate(history_cnt) if history_cnt[i]>0]
for i, plate in enumerate(history):
ph, pw = plate.shape[:2]
if 70+50... | th, textSize, encoding="utf-8")
draw.text((left, top), unicode(text.decode('utf-8')) , textColor, font=fontText)
return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
def draw_history(blend_img, history, history_cnt, history_record, history_platenum):
history = [_ for i, _ in enumerate(history) if histor... | identifier_body |
fit_nixing.py |
def draw_box_v2(img, box, alphaReserve=0.8, color=None):
color = (rand() * 255, rand() * 255, rand() * 255) if color is None else color
h,w,_ = img.shape
x1 = max(0, int(float(box[0])))
y1 = max(0, int(float(box[1])))
x2 = min(w-1, int(float(box[2])))
y2 = min(h-1, int(float(box[3])))
B, G,... | type_map = {'BigTruck': '货车', 'Bus': '公交车', 'Lorry': '货车', 'MPV': '轿车', 'MiniVan': '轿车', 'MiniBus': '公交车',
'SUV': '轿车', 'Scooter': '轿车', 'Sedan_Car': '轿车', 'Special_vehicle': '其他', 'Three_Wheeled_Truck':'其他', 'other': '其他', 'Minibus': '公交车'}
| random_line_split | |
fit_nixing.py | (w-1, int(float(box[2])))
y2 = min(h-1, int(float(box[3])))
B, G, R = color
img[y1:y2, x1:x2, 0] = img[y1:y2, x1:x2, 0] * alphaReserve + B * (1 - alphaReserve)
img[y1:y2, x1:x2, 1] = img[y1:y2, x1:x2, 1] * alphaReserve + G * (1 - alphaReserve)
img[y1:y2, x1:x2, 2] = img[y1:y2, x1:x2, 2] * alphaReser... | (box1[2] - box1[0] + 1) * (box1[3] - box1[1] + 1)
box2_area = (box2[2] - box2[0] + 1) * (box2[3] - box2[1] + 1)
all_area = float(box1_area + box2_area - iw * ih)
return iw * ih / all_area
return 0
# judge whether line segment (xc,yc)->(xr,yr) is crossed with infinite line (x1,y1... | area = | identifier_name |
fit_nixing.py | 0, 0),\
textSize=20, font_path="./LiHeiPro.ttf")
return blend_img, history, history_cnt, history_record, history_platenum
def cal_iou(box1, box2):
iw = min(box1[2], box2[2]) - max(box1[0], box2[0]) + 1
if iw > 0:
ih = min(box1[3], box2[3]) - max(box1[1], box2[1]) + 1
... | # cv2.line(blend_ | conditional_block | |
main.rs | : usize, limit: &mut usize) -> TlsResult<()> {
*limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?;
Ok(())
}
impl<R: AsyncReadExt> TlsHandshakeReader<R> {
fn new(source: R) -> Self {
TlsHandshakeReader {
source: source,
buffer: Vec::with_capacity(4096),
... | // section 5.1: "The record layer fragments information blocks into TLSPlaintext
// records carrying data in chunks of 2^14 bytes or less."
if length > (1 << 14) {
return Err(TlsError::RecordOverflow);
}
self.offset += 5;
self.limi... | {
while self.offset >= self.limit {
self.fill_to(self.limit + 5).await?;
// section 5.1: "Handshake messages MUST NOT be interleaved with other record types.
// That is, if a handshake message is split over two or more records, there MUST NOT be
// any other reco... | identifier_body |
main.rs | self.buffer[self.limit + 3] as usize) << 8
| (self.buffer[self.limit + 4] as usize);
// section 5.1: "Implementations MUST NOT send zero-length fragments of Handshake
// types, even if those fragments contain padding."
if length == 0 {
return Err(TlsE... | {
TlsError::UnrecognizedName
} | conditional_block | |
main.rs | : usize, limit: &mut usize) -> TlsResult<()> {
*limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?;
Ok(())
}
impl<R: AsyncReadExt> TlsHandshakeReader<R> {
fn new(source: R) -> Self {
TlsHandshakeReader {
source: source,
buffer: Vec::with_capacity(4096),
... | Ok(v)
}
async fn read_length(&mut self, length: u8) -> TlsResult<usize> {
debug_assert!(length > 0 && length <= 4);
let mut result = 0;
for _ in 0..length {
result <<= 8;
result |= self.read().await? as usize;
}
Ok(result)
}
async... | }
self.fill_to(self.offset + 1).await?;
let v = self.buffer[self.offset];
self.offset += 1; | random_line_split |
main.rs | (length: usize, limit: &mut usize) -> TlsResult<()> {
*limit = limit.checked_sub(length).ok_or(TlsError::DecodeError)?;
Ok(())
}
impl<R: AsyncReadExt> TlsHandshakeReader<R> {
fn new(source: R) -> Self {
TlsHandshakeReader {
source: source,
buffer: Vec::with_capacity(4096),
... | check_length | identifier_name | |
app.rs | }
diffable!(Application);
generation!(Application => generation);
default_resource!(Application);
impl Resource for Application {
fn owner(&self) -> Option<&str> {
self.owner.as_deref()
}
fn members(&self) -> &IndexMap<String, MemberEntry> {
&self.members
}
}
#[derive(Clone, Copy, De... | let builder = SelectBuilder::new(select, Vec::new(), Vec::new())
.name(&name)
.labels(&labels.0)
.auth_read(&id)
.lock(lock)
.sort(sort)
.limit(limit)
.offset(offset);
let (select, params, types) = builder.build();
... | {
let select = r#"
SELECT
NAME,
UID,
LABELS,
ANNOTATIONS,
CREATION_TIMESTAMP,
GENERATION,
RESOURCE_VERSION,
DELETION_TIMESTAMP,
FINALIZERS,
OWNER,
TRANSFER_OWNER,
MEMBERS,
DATA
FROM APPLICATIONS
"#
.to_string();
| identifier_body |
app.rs | }
diffable!(Application);
generation!(Application => generation);
default_resource!(Application);
impl Resource for Application {
fn owner(&self) -> Option<&str> {
self.owner.as_deref()
}
fn members(&self) -> &IndexMap<String, MemberEntry> {
&self.members
}
}
#[derive(Clone, Copy, De... | {
let select = r#"
SELECT
NAME,
UID,
LABELS,
ANNOTATIONS,
CREATION_TIMESTAMP,
GENERATION,
RESOURCE_VERSION,
DELETION_TIMESTAMP,
FINALIZERS,
OWNER,
TRANSFER_OWNER,
MEMBERS,
DATA
FROM APPLICATIONS
"#
.to_string();
let builder = SelectBuilder... | offset: Option<usize>,
id: Option<&UserInformation>,
lock: Lock,
sort: &[&str],
) -> Result<Pin<Box<dyn Stream<Item = Result<Application, ServiceError>> + Send>>, ServiceError> | random_line_split |
app.rs | diffable!(Application);
generation!(Application => generation);
default_resource!(Application);
impl Resource for Application {
fn owner(&self) -> Option<&str> {
self.owner.as_deref()
}
fn members(&self) -> &IndexMap<String, MemberEntry> {
&self.members
}
}
#[derive(Clone, Copy, Debug... | (&self, id: &str) -> Result<(), ServiceError> {
let sql = "DELETE FROM APPLICATIONS WHERE NAME = $1";
let stmt = self.client.prepare_typed(sql, &[Type::VARCHAR]).await?;
let count = self.client.execute(&stmt, &[&id]).await?;
if count > 0 {
Ok(())
} else {
... | delete | identifier_name |
app.rs | diffable!(Application);
generation!(Application => generation);
default_resource!(Application);
impl Resource for Application {
fn owner(&self) -> Option<&str> {
self.owner.as_deref()
}
fn members(&self) -> &IndexMap<String, MemberEntry> {
&self.members
}
}
#[derive(Clone, Copy, Debug... |
let stmt = self
.client
.prepare_typed(
"INSERT INTO APPLICATION_ALIASES (APP, TYPE, ALIAS) VALUES ($1, $2, $3)",
&[Type::VARCHAR, Type::VARCHAR, Type::VARCHAR],
)
.await?;
for alias in aliases {
self.client
... | {
return Ok(());
} | conditional_block |
main.rs | isa_attribute,
core_intrinsics,
maybe_uninit_ref,
bindings_after_at,
stmt_expr_attributes,
default_alloc_error_handler,
const_fn_floating_point_arithmetic,
)]
extern crate alloc;
mod gfx;
mod heap;
mod mem;
use core::fmt::Write;
use alloc::{vec::Vec, vec};
use vek::*;
use num_traits::floa... | random_line_split | ||
main.rs | 32> {
(m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0)
}
fn apply4(m: Mat4<F32>, n: Mat4<F32>) -> Mat4<F32> {
(m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0)
}
#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> ! {
gba::error!("Panic: {:?}", info);
Mode3::clear_to(Color::from_rgb(0xFF, 0, 0));
... | {
timer0_handler();
} | conditional_block | |
main.rs | (x: f32) -> f32 {
let y = f32::from_bits(0x5f375a86 - (x.to_bits() >> 1));
y * (1.5 - ( x * 0.5 * y * y ))
}
fn fsqrt(x: f32) -> f32 {
f32::from_bits((x.to_bits() + (127 << 23)) >> 1)
}
let v = q.into_vec4();
(v * F32::from_num(finvsqrt(v.magnitude_squared().to_num::<f32>()))... | (m: Mat4<F32>, n: Mat4<F32>) -> Mat4<F32> {
(m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0)
}
#[panic_handler]
fn panic(info: &core::panic::PanicInfo) -> ! {
gba::error!("Panic: {:?}", info);
Mode3::clear_to(Color::from_rgb(0xFF, 0, 0));
loop {}
}
#[start]
fn main(_argc: isize, _argv: *const *const u8)... | apply4 | identifier_name |
main.rs | (x: f32) -> f32 {
let y = f32::from_bits(0x5f375a86 - (x.to_bits() >> 1));
y * (1.5 - ( x * 0.5 * y * y ))
}
fn fsqrt(x: f32) -> f32 {
f32::from_bits((x.to_bits() + (127 << 23)) >> 1)
}
let v = q.into_vec4();
(v * F32::from_num(finvsqrt(v.magnitude_squared().to_num::<f32>()))... |
}
impl vek::ops::MulAdd<NumWrap, NumWrap> for NumWrap {
type Output = NumWrap;
fn mul_add(self, mul: NumWrap, add: NumWrap) -> NumWrap {
NumWrap(self.0 * mul.0 + add.0)
}
}
fn apply(m: Mat3<F32>, n: Mat3<F32>) -> Mat3<F32> {
(m.map(NumWrap) * n.map(NumWrap)).map(|e| e.0)
}
fn apply4(m: Mat4... | { NumWrap(self.0 * rhs.0) } | identifier_body |
Assign_LLID_Toxics_DO_unverified_LASAR_Stations.py | /WQ_2010_IntegratedReport_V3/WQ_2010_IntegratedReport_V3/Assessment.gdb/DEQ_Streams_25APR2013"
station_river_name_field = "LOCATION_D"
streams_river_name_field = "NAME"
rid = "LLID"
search_radius = 12000
output_table = "E:/GitHub/ToxicsRedo/StationsToLocate/FinalList/assign_llid_temp.gdb/out1"
output_success = "out_suc... |
arcpy.DeleteField_management(output_success, fields_to_drop)
#Merge with output table
arcpy.JoinField_management(output_success, 'Unique_ID', output_table, 'Unique_ID')
#Now split success fc into one fc with successful qc and one with stations needing review
arcpy.MakeFeatureLayer_management(output_success, qc_... | if field.name not in ['Unique_ID', 'Shape','OBJECTID']:
fields_to_drop.append(field.name) | conditional_block |
Assign_LLID_Toxics_DO_unverified_LASAR_Stations.py | /WQ_2010_IntegratedReport_V3/WQ_2010_IntegratedReport_V3/Assessment.gdb/DEQ_Streams_25APR2013"
station_river_name_field = "LOCATION_D"
streams_river_name_field = "NAME"
rid = "LLID"
search_radius = 12000
output_table = "E:/GitHub/ToxicsRedo/StationsToLocate/FinalList/assign_llid_temp.gdb/out1"
output_success = "out_suc... | else:
arcpy.CreateFileGDB_management(temp_location, final_gdb)
arcpy.env.workspace = workspace
arcpy.CopyFeatures_management(original_sampling_stations, sampling_stations)
arcpy.AddField_management(sampling_stations, "Unique_ID", "DOUBLE")
arcpy.CalculateField_management(sampling_stations, "Unique_ID", "!OBJECTID... | print "It exist!" | random_line_split |
main.rs | bool,
#[structopt(long = "manifest-path", value_name = "PATH", parse(from_os_str))]
/// Path to Cargo.toml
manifest_path: Option<PathBuf>,
#[structopt(long = "invert", short = "i")]
/// Invert the tree direction
invert: bool,
#[structopt(long = "no-indent")]
/// Display the dependencies... | graph: petgraph::Graph<Node<'a>, Kind>,
nodes: HashMap<PackageId, NodeIndex>,
}
fn build_graph<'a>(
resolve: &'a Resolve,
packages: &'a PackageSet<'_>,
root: PackageId,
target: Option<&str>,
cfgs: Option<&[Cfg]>,
) -> CargoResult<Graph<'a>> {
let mut graph = Graph {
graph: petgra... | > {
| identifier_name |
main.rs | ,
#[structopt(long = "manifest-path", value_name = "PATH", parse(from_os_str))]
/// Path to Cargo.toml
manifest_path: Option<PathBuf>,
#[structopt(long = "invert", short = "i")]
/// Invert the tree direction
invert: bool,
#[structopt(long = "no-indent")]
/// Display the dependencies as a... | l_main(args: Args, config: &mut Config) -> CliResult {
config.configure(
args.verbose,
args.quiet,
&args.color,
args.frozen,
args.locked,
&args.target_dir,
&args.unstable_flags,
)?;
let workspace = workspace(config, args.manifest_path)?;
let packa... | v_logger::init();
let mut config = match Config::default() {
Ok(cfg) => cfg,
Err(e) => {
let mut shell = Shell::new();
cargo::exit_with_error(e.into(), &mut shell)
}
};
let Opts::Tree(args) = Opts::from_args();
if let Err(e) = real_main(args, &mut confi... | identifier_body |
main.rs | value_name = "CHARSET", default_value = "utf8")]
/// Character set to use in output: utf8, ascii
charset: Charset,
#[structopt(
long = "format",
short = "f",
value_name = "FORMAT",
default_value = "{p}"
)]
/// Format string used for printing dependencies
format: ... | random_line_split | ||
main.rs | let graph = build_graph(
&resolve,
&packages,
package.package_id(),
target,
cfgs.as_ref().map(|r| &**r),
)?;
let direction = if args.invert || args.duplicates {
EdgeDirection::Incoming
} else {
EdgeDirection::Outgoing
};
let symbols = match ... | return;
}
// | conditional_block | |
Liquid.go | pressed bool
x, y float32
}
type Liquid struct {
width float32
height float32
pressed bool
pressedprev bool
mouse MouseState
grid *Nodemap
particles []*Particle
}
type Nodemap struct {
width, height int
nodes []*Node
}
func NewNodemap(width int, height int) *Nodema... | () {
var mu, mv float32
for _, p := range l.particles {
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
n := l.grid.Get(int(p.cx)+i, int(p.cy)+j)
| _step3 | identifier_name |
Liquid.go | {
pressed bool
x, y float32
}
type Liquid struct {
width float32
height float32
pressed bool
pressedprev bool
mouse MouseState
grid *Nodemap
particles []*Particle
}
type Nodemap struct {
width, height int
nodes []*Node
}
func NewNodemap(width int, height int) *Nod... | n.gx += particle.gx[i] * particle.py[j]
n.gy += particle.px[i] * particle.gy[j]
}
}
}
}
func (l *Liquid) _density_summary(drag bool, mdx, mdy float32) {
var n01, n02, n11, n12 *Node
var cx, cy, cxi, cyi int
var pdx, pdy, C20, C02, C30, C03, csum1, csum2, C21, C31,
C12, C13, C11, density, pressure, f... | random_line_split | |
Liquid.go | pressed bool
x, y float32
}
type Liquid struct {
width float32
height float32
pressed bool
pressedprev bool
mouse MouseState
grid *Nodemap
particles []*Particle
}
type Nodemap struct {
width, height int
nodes []*Node
}
func NewNodemap(width int, height int) *Nodema... |
for i := 0; i < 3; i++ {
for j := 0; j < 3; j++ {
n := l.grid.Get(int(p.cx)+i, int(p.cy)+j)
phi := p.px[i] * p.py[j]
n.ax += -(p.gx[i] * p.py[j] * pressure) + fx*phi
n.ay += -(p.px[i] * p.gy[j] * pressure) + fy*phi
}
}
}
}
func (l *Liquid) _step3() {
var mu, mv float32
for _, p := range l... | {
vx := Abs(p.x - l.mouse.x)
vy := Abs(p.y - l.mouse.y)
if vx < 10.0 && 10.0 > vy {
weight := p.material.m * (1.0 - vx*0.10) *
(1.0 - vy*0.10)
fx += weight * (mdx - p.u)
fy += weight * (mdy - p.v)
}
} | conditional_block |
Liquid.go | pressed bool
x, y float32
}
type Liquid struct {
width float32
height float32
pressed bool
pressedprev bool
mouse MouseState
grid *Nodemap
particles []*Particle
}
type Nodemap struct {
width, height int
nodes []*Node
}
func NewNodemap(width int, height int) *Nodema... |
func (l *Liquid) _step1() {
for _, particle := range l.particles {
particle.cx = float32(int(particle.x - 0.5))
particle.cy = float32(int(particle.y - 0.5))
_equation1(&particle.px, &particle.gx, particle.cx-particle.x)
_equation1(&particle.py, &particle.gy, particle.cy-particle.y)
for i := 0; i < 3; i+... | {
pressure[0] = 0.5*x*x + 1.5*x + 1.125
gravity[0] = x + 1.5
x += 1.0
pressure[1] = -x*x + 0.75
gravity[1] = -2.0 * x
x += 1.0
pressure[2] = 0.5*x*x - 1.5*x + 1.125
gravity[2] = x - 1.5
} | identifier_body |
arena.rs | pub(super) mem: Vec<u8>,
}
impl AggressiveArena {
/// Create an AggressiveArena with given cap.
/// This function will allocate a cap size memory block directly for further usage
pub fn new(cap: usize) -> AggressiveArena {
AggressiveArena {
offset: AtomicUsize::new(0),
m... | arena.alloc_node(MAX_HEIGHT); // 152
arena.alloc_node(1); // 64
arena.alloc_bytes(&Slice::from(vec![1u8, 2u8, 3u8, 4u8].as_slice())); // 4
assert_eq!(152 + 64 + 4, arena.memory_used())
} | random_line_split | |
arena.rs | skiplist::{Node, MAX_HEIGHT, MAX_NODE_SIZE};
pub trait Arena {
/// Allocate memory for a node by given height.
/// This method allocates a Node size + height * ptr ( u64 ) memory area.
// TODO: define the potential errors and return Result<Error, *mut Node> instead of raw pointer
fn alloc_node(&self, h... | () {
let arena = Arc::new(AggressiveArena::new(500));
let results = Arc::new(Mutex::new(vec![]));
let mut tests = vec![vec![1u8, 2, 3, 4, 5], vec![6u8, 7, 8, 9], vec![10u8, 11]];
for t in tests
.drain(..)
.map(|test| {
let cloned_arena = arena.clon... | test_alloc_bytes_concurrency | identifier_name |
arena.rs | skiplist::{Node, MAX_HEIGHT, MAX_NODE_SIZE};
pub trait Arena {
/// Allocate memory for a node by given height.
/// This method allocates a Node size + height * ptr ( u64 ) memory area.
// TODO: define the potential errors and return Result<Error, *mut Node> instead of raw pointer
fn alloc_node(&self, h... | (*node).height = height;
(*node).next_nodes = next_nodes;
node
}
}
fn alloc_bytes(&self, data: &Slice) -> u32 {
let start = self.offset.fetch_add(data.size(), Ordering::SeqCst);
unsafe {
let ptr = self.mem.as_ptr().add(start) as *mut u8;
... | {
let ptr_size = mem::size_of::<*mut u8>();
// truncate node size to reduce waste
let used_node_size = MAX_NODE_SIZE - (MAX_HEIGHT - height) * ptr_size;
let n = self.offset.fetch_add(used_node_size, Ordering::SeqCst);
unsafe {
let node_ptr = self.mem.as_ptr().add(n) a... | identifier_body |
goes.py | 18"),
9: TimeRange("1997-01-01", "1998-09-08"),
10: TimeRange("1998-07-10", "2009-12-01"),
11: TimeRange("2006-06-20", "2008-02-15"),
12: TimeRange("2002-12-13", "2007-05-08"),
13: TimeRange("2006-08-01", "2006-08-01"),
14: TimeRange("2009-12-02", ... |
def _get_time_for_url(self, urls):
times = []
for uri in urls:
uripath = urlsplit(uri).path
# Extract the yymmdd or yyyymmdd timestamp
datestamp = os.path.splitext(os.path.split(uripath)[1])[0][4:]
# 1999-01-15 as an integer.
if int(dat... | raise ValueError(
"No operational GOES satellites on {}".format(
date.strftime(TIME_FORMAT)
)
) | conditional_block |
goes.py | 8: TimeRange("1996-03-21", "2003-06-18"),
9: TimeRange("1997-01-01", "1998-09-08"),
10: TimeRange("1998-07-10", "2009-12-01"),
11: TimeRange("2006-06-20", "2008-02-15"),
12: TimeRange("2002-12-13", "2007-05-08"),
13: TimeRange("2006-08-01", "2006-0... | 6: TimeRange("1983-06-01", "1994-08-18"),
7: TimeRange("1994-01-01", "1996-08-13"), | random_line_split | |
goes.py | -18"),
9: TimeRange("1997-01-01", "1998-09-08"),
10: TimeRange("1998-07-10", "2009-12-01"),
11: TimeRange("2006-06-20", "2008-02-15"),
12: TimeRange("2002-12-13", "2007-05-08"),
13: TimeRange("2006-08-01", "2006-08-01"),
14: TimeRange("2009-12-02",... | (self, urls):
these_timeranges = []
for this_url in urls:
if this_url.count('/l2/') > 0: # this is a level 2 data file
start_time = parse_time(os.path.basename(this_url).split('_s')[2].split('Z')[0])
end_time = parse_time(os.path.basename(this_url).split('_e... | _get_time_for_url | identifier_name |
goes.py | 6-06-20", "2008-02-15"),
12: TimeRange("2002-12-13", "2007-05-08"),
13: TimeRange("2006-08-01", "2006-08-01"),
14: TimeRange("2009-12-02", "2010-10-04"),
15: TimeRange("2010-09-01", parse_time("now")),
}
results = []
for sat_num in goes_operationa... | these_timeranges = []
for this_url in urls:
if this_url.count('/l2/') > 0: # this is a level 2 data file
start_time = parse_time(os.path.basename(this_url).split('_s')[2].split('Z')[0])
end_time = parse_time(os.path.basename(this_url).split('_e')[1].split('Z')[0])
... | identifier_body | |
writeToStore.ts | , incoming) as T;
},
variables,
varString: JSON.stringify(variables),
fragmentMap: createFragmentMap(getFragmentDefinitions(query)),
},
});
if (!isReference(ref)) {
throw new InvariantError(`Could not identify object ${JSON.stringify(result)}`);
}
// Any IDs... | fieldsWithSelectionSets.has(fieldNameFromStoreName(storeFieldName));
const fieldsWithSelectionSets = new Set<string>();
workSet.forEach(selection => {
if (isField(selection) && selection.selectionSet) {
fieldsWithSelectionSets.add(selection.name.value);
}
... | random_line_split | |
writeToStore.ts | storeFieldName]: incomingValue,
});
} else if (
policies.usingPossibleTypes &&
!hasDirectives(["defer", "client"], selection)
) {
throw new InvariantError(
`Missing field '${resultFieldKey}' in ${JSON.stringify(
result,
nul... | {
const getChild = (objOrRef: StoreObject | Reference): StoreObject | false => {
const child = store.getFieldValue<StoreObject>(objOrRef, storeFieldName);
return typeof child === "object" && child;
};
const existing = getChild(existingRef);
if (!existing) return;
const incoming = getChild(incomingOb... | identifier_body | |
writeToStore.ts | ,
field: selection,
variables: context.variables,
});
const childTree = getChildMergeTree(mergeTree, storeFieldName);
let incomingValue =
this.processFieldValue(value, selection, context, childTree);
const childTypename = selection.selection... | warnAboutDataLoss | identifier_name | |
service.go | -height:1.5em;font-family:Helvetica Neue, Helvetica, Arial, sans-serif;font-size:14px;color:#000;"> Hello %recipient.firstname% %recipient.lastname%, <br/> <br/> Forgot your password? No problem! <br/> <br/> To reset your password, click the following link: <br/> <a href="https://www.example.com/auth/password-reset/%re... | getUserByEmail | identifier_name | |
service.go | AddProvider(id uuid.UUID, user goth.User) (User, error)
// GetUser gets a user account by their ID
GetUser(id uuid.UUID) (User, error)
// UpdateUser update the user's details
UpdateUser(u User) (User, error)
// DeleteUser flag a user as deleted
DeleteUser(id uuid.UUID) (User, error)
// AuthenticateUser logs ... |
// Check Password
p := strings.TrimSpace(password)
if len(p) == 0 {
return User{}, ErrInvalidPassword
}
// Get user from database
u, err := s.getUserByEmail(e.Address)
if err != nil {
return User{}, err
}
// check password
hashed, err := base64.StdEncoding.DecodeString(u.Password)
if err != nil {
r... | {
return User{}, err
} | conditional_block |
service.go | you can safely ignore this email. Rest assured your customer account is safe. <br/> <br/> </p>{{end}}`))
template.Must(s.tpl.AddTemplate("auth.PasswordResetConfirmEmail", "auth.baseHTMLEmailTemplate", `{{define "title"}}Password Reset Complete{{end}}{{define "content"}}<p style="margin:0;padding:1em 0 0 0;line-height... | random_line_split | ||
service.go | AddProvider(id uuid.UUID, user goth.User) (User, error)
// GetUser gets a user account by their ID
GetUser(id uuid.UUID) (User, error)
// UpdateUser update the user's details
UpdateUser(u User) (User, error)
// DeleteUser flag a user as deleted
DeleteUser(id uuid.UUID) (User, error)
// AuthenticateUser logs ... |
func (s *authService) UpdateUser(u User) (User, error) {
eUser := User{}
err := s.db.Get(&eUser, "SELECT * FROM user WHERE email=$1", u.Email)
if err == sql.ErrNoRows {
return User{}, ErrUserNotFound
} else if err != nil {
return User{}, err
}
if !uuid.Equal(eUser.ID, u.ID) {
return User{}, ErrInconsiste... | {
if id == uuid.Nil {
return User{}, ErrInvalidID
}
u := User{}
err := s.db.Get(&u, "SELECT * FROM user WHERE id=$1", id)
if err != nil && err != sql.ErrNoRows {
return User{}, err
} else if err == sql.ErrNoRows {
return User{}, ErrUserNotFound
}
return u, nil
} | identifier_body |
pkg_util.go | 无法更新")
return e;
}
for i := range tempArr {
var tomcatInfo = tempArr[i];
if !tomcatInfo.Update {
continue;
}
tomcatInfo.ConfigFileBackupDir = tomcatInfo.ProcessHome+ "pkg_cfg\\"
_, stat_err := os.Stat(tomcatInfo.ProcessHome+ "pkg_cfg\\");
if stat_err != nil && os.IsNotExist(stat_err) {
var mk... |
if err != nil {
fmt.Printf("filepath.Walk() returned %v\n", err);
return err; | random_line_split | |
pkg_util.go | 6\webapps\agent
PackageFileName string // 更新包名称 agent_1114
PackageBackFileName string // 备份包名称 201712081536更新前备份.zip
ConfigFileBackupDir string // 配置文件临时目录d:\xx\tomcat6\temp_config
NewPackageDir string // 新包地址
Update bool // 是否需要更新
Complete bool // 更新完成
}
/**
备份tomcat目录下项目
... |
} else {
fmt.Println(err2)
}
//fmt.Println("------------------------------------------------------")
}
}
}
return tomcatArr;
//fmt.Println(TOMCAT_PROCESS_MAP)
}
/**
确认tomcat
*/
func ConfirmTomcat(tomcatArr []* TomcatInfo) {
var tempArr []*TomcatInfo;
tempArr = tomcatArr;
for i := rang... | x(processName, tomcatSuffix) {
out2, err2 := exec.Command("cmd", "/C", "wmic process where name='" + processName + "' get ExecutablePath").Output()
if err2 == nil {
// TODO
var fileDirectoryArr[] string = strings.Split(strings.Split(string(out2), "\r\n", )[1], "\\");
if(len(fileDirectoryArr) < ... | identifier_body |
pkg_util.go | cat6\webapps\agent
PackageFileName string // 更新包名称 agent_1114
PackageBackFileName string // 备份包名称 201712081536更新前备份.zip
ConfigFileBackupDir string // 配置文件临时目录d:\xx\tomcat6\temp_config
NewPackageDir string // 新包地址
Update bool // 是否需要更新
Complete bool // 更新完成
}
/**
备份tomcat目录下项... | il;
}
/**
获取tomcat信息
*/
func GetTomcatArray(
tomcatPrefix string,
tomcatSuffix string) [] TomcatInfo {
//out, err := exec.Command("cmd", "/C", "tasklist ").Output()
out, err := exec.Command("cmd", "/C", "tasklist").Output()
if err != nil {
log.Fatal(err)
}
//fmt.Printf(string(out))
var processStrList[] st... | fmt.Println("复制" + tomcatInfo.ProcessName+ "配置文件成功,文件:" + cfgFileName + ",大小:", written, "byte");
}
}
//fmt.Println(tomcatArr);
return n | conditional_block |
pkg_util.go | var cfgFilePath = tomcatInfo.ProcessHome + PKG_CFGFILE_PATH_ARR[i];
var cfgFileName = strings.Split(PKG_CFGFILE_PATH_ARR[i], "\\")[len(strings.Split(PKG_CFGFILE_PATH_ARR[i], "\\")) - 1]; //配置文件名
// 备份目录不存在则创建备份目录
_, stateErr := os.Stat(tomcatInfo.ProcessHome + "pkg_cfg\\");
if stateErr != nil {
direrr... | identifier_name | ||
aweMBPicker.py | ButtonState.kFBButtonState0, FBColor(0.4,0.2,0.5))
removeBtn.SetStateColor(FBButtonState.kFBButtonState1, FBColor(0.35,0.15,0.45))
removeBtn.OnClick.Add(_removeObjects)
removeBtn.picker = parentBox.picker
optionLayout.AddRelative(removeBtn,0.25,height=25, space=2)
renameBtn = FBButton()
renameBtn.Caption = "ab*"... | removeSceneCB( | identifier_name | |
aweMBPicker.py | m.Selected = False
for o in self.objects:
o.Selected = True
FBEndChangeAllModels()
return True
else:
return False
def delete(self):
'''Deletes this Picker's associated pickerObject'''
if self.pickerObject:
self.pickerObject.FBDelete()
def add(self,objectList):
'''Adds a list of objects ... | optionLayout.AddRelative(removeBtn,0.25,height=25, space=2)
renameBtn = FBButton()
renameBtn.Caption = "ab*"
renameBtn.Look = FBButtonLook.kFBLookColorChange
renameBtn.SetStateColor(FBButtonState.kFBButtonState0, FBColor(0.3,0.4,0.5))
renameBtn.SetStateColor(FBButtonState.kFBButtonState1, FBColor(0.25,0.35,0.45)... | ''Creates a layout that holds a Picker's option UI'''
optionLayout = pyui.FBHBoxLayout()
addBtn = FBButton()
addBtn.Caption = "+"
addBtn.OnClick.Add(_addObjects)
addBtn.picker = parentBox.picker
addBtn.Look = FBButtonLook.kFBLookColorChange
addBtn.SetStateColor(FBButtonState.kFBButtonState0, FBColor(0.4,0.5,0.... | identifier_body |
aweMBPicker.py | .2,0.3))
deleteBtn.SetStateColor(FBButtonState.kFBButtonState1, FBColor(0.65,0.15,0.25))
deleteBtn.OnClick.Add(_deletePicker)
deleteBtn.picker = parentBox.picker
deleteBtn.box = parentBox
optionLayout.AddRelative(deleteBtn,0.25,height=25, space=2)
return optionLayout
def _addObjects(control,event):
'''Callback... | tool.StartSizeX = startX
tool.StartSizeY = startY
tool.OnResize.Add(_toolResize)
| random_line_split | |
aweMBPicker.py |
def createPickerObject(self, name, tab, pickerObject, objectList=[]):
'''Creates the Set object used to store the Picker in the Scene
When used during initPickers(), it doesn't create a new set and
returns the existing set instead.
'''
po = pickerObject
if not po:
po = aweCreateSet(name)
# sear... | self.pickerObject.PropertyList.Find('Objects').append(o) | conditional_block | |
types.go | be spent
// atomically; that is, they must all be spent in the same transaction. The
// UnlockHash is the hash of a set of UnlockConditions that must be fulfilled
// in order to spend the output.
//
// When the SiafundOutput is spent, a SiacoinOutput is created, where:
//
// SiacoinOutput.Value := (SiafundPool - C... | // FileContractID returns the ID of a file contract at the given index, which
// is calculated by hashing the concatenation of the FileContract Specifier,
// all of the fields in the transaction (except the signatures), and the | random_line_split | |
types.go | for spending the output. The UnlockConditions must match the UnlockHash of
// the output.
type SiacoinInput struct {
ParentID SiacoinOutputID
UnlockConditions UnlockConditions
}
// A SiacoinOutput holds a volume of siacoins. Outputs must be spent
// atomically; that is, they must all be spent in the same tr... | {
return new(big.Int).SetBytes(t[:])
} | identifier_body | |
types.go |
SiafundOutputs []uint64
MinerFees []uint64
ArbitraryData []uint64
Signatures []uint64
}
// CurrentTimestamp returns the current time as a Timestamp.
func CurrentTimestamp() Timestamp {
return Timestamp(time.Now().Unix())
}
// CalculateCoinbase calculates the coi... | {
signedData = append(signedData, encoding.Marshal(t.FileContracts[contract])...)
} | conditional_block | |
types.go | SiacoinOutput
TerminationHash UnlockHash
}
// A FileContractTermination terminates a file contract. The ParentID
// specifies the contract being terminated, and the TerminationConditions are
// the conditions under which termination will be treated as valid. The hash
// of the TerminationConditions must match the ... | ID | identifier_name | |
SurveySimulator.py |
self._a = value
#----------- e
@property
def e(self):
"""I'm the e property."""
return self._e
@e.setter
def e(self, value):
if not 0.0 <= value <= 1.0:
raise ValueError('Bad e value. e must be between 0 and 1')
self._e = float(value)
#-----------... | raise ValueError('Bad a value. Ensure 0.0 < a < 10E6') | conditional_block | |
SurveySimulator.py | raise ValueError('Bad a value. Ensure 0.0 < a < 10E6')
self._a = value
#----------- e
@property
def e(self):
"""I'm the e property."""
return self._e
@e.setter
def e(self, value):
if not 0.0 <= value <= 1.0:
raise ValueError('Bad e value. e must... | if not 0.0 <= value <= 10E6: | random_line_split | |
SurveySimulator.py | a = value
#----------- e
@property
def e(self):
"""I'm the e property."""
return self._e
@e.setter
def e(self, value):
if not 0.0 <= value <= 1.0:
raise ValueError('Bad e value. e must be between 0 and 1')
self._e = float(value)
#----------- inc
@prop... | (self, value):
if not 0.0 <= value <= 180.0:
raise ValueError('Bad inclination value. Ensure 0.0 < inclination < 90 degrees')
self._inc = value
#----------- Om
@property
def Om(self):
"""I'm the Om property."""
return self._Om
@Om.setter
def Om(self, value)... | inc | identifier_name |
SurveySimulator.py | a = value
#----------- e
@property
def e(self):
|
@e.setter
def e(self, value):
if not 0.0 <= value <= 1.0:
raise ValueError('Bad e value. e must be between 0 and 1')
self._e = float(value)
#----------- inc
@property
def inc(self):
"""I'm the inc property."""
return self._inc
@inc.setter
def inc(... | """I'm the e property."""
return self._e | identifier_body |
simanalysis.py | /np.sum(p)
def contacts_with (sim,polymer_text,tracers_text,bindingsites_text,teq,tsample,threshold) :
"""
Calculate the relative proportion of contacts of the tracers with binding
sites compared with non-binding sites. As usual user should supply
equilibration time, sampling time, and contact threshol... | (sim,polymer_text,tracer_text,teq,tsample,t_threshold,p_threshold) :
# define DKL(t) vector
| DKL_t | identifier_name |
simanalysis.py | /np.sum(p)
def contacts_with (sim,polymer_text,tracers_text,bindingsites_text,teq,tsample,threshold) :
"""
Calculate the relative proportion of contacts of the tracers with binding
sites compared with non-binding sites. As usual user should supply
equilibration time, sampling time, and contact threshol... |
return np.mean(np.array(c))
def fit_msd (msd,cutoff,delta_t,scale_l) :
"""
Perform a simple fit of the supplied time-dependent MSD, using a linear
regression of the logarithms of the values. User must supply the conversion
factor from time to real time and from length to real length. Also, user
... | c.append ((cB/cA) / (float(bs_n)/nbs_n)) | conditional_block |
simanalysis.py |
def ps (H) :
"""
Calculate the normalized probability of contact between a monomer and all
others as a function of the linear distance s.
"""
p = np.array ([np.mean (np.diagonal (H, offset=k))
for k in range (H.shape[0])])
return p/np.sum(p)
def contacts_with (sim,polymer_t... | """
Calculate the Pearson correlation coefficient between the row sum of the
given Hi-C matrix and the given ChIP-seq profile.
"""
hic_rowsum = np.sum(hic,axis=1)/float(np.sum(hic))
return np.corrcoef(hic_rowsum,chipseq)[0,1]**2 | identifier_body | |
simanalysis.py | import mybiotools as mbt
def traj_nslice (u,teq,tsample) :
"""
Returns the number of frames in the trajectory in universe u, using teq as
equilibration time and tsample as sampling time
"""
# get the number of frames in the slice (http://stackoverflow.com/a/7223557)
traj_slice = u.trajectory[te... | from MDAnalysis.analysis.distances import distance_array | random_line_split | |
wikibrief.go | \")")
return
}
func (bs *bStarted) AddRevision(ctx context.Context, t xml.StartElement) (be builder, err error) { //no obligatory element "title"
err = bs.Wrapf(errInvalidXML, "Error invalid xml (not found obligatory element \"title\")")
return
}
func (bs *bStarted) ClosePage() (be builder, err error) { //no obligat... | {
wg.Add(1)
go func() {
defer wg.Done()
for range revisions {
//skip
}
}()
} | identifier_body | |
wikibrief.go | err := run(ctx, bBase{xml.NewDecoder(r), article2TopicID, ID2Bot, simplePages, &errorContext{"", filename(r)}})
if err != nil {
fail(err)
}
}(r)
}
if err != io.EOF {
fail(err)
}
wg.Wait()
}()
return completeInfo(ctx, fail, lang, simplePages)
}
//EvolvingPage represents a wikipedia pag... |
//There are 4 buffers in various forms: 4*pageBufferSize is the maximum number of wikipedia pages in memory.
//Each page has a buffer of revisionBufferSize revisions: this means that at each moment there is
//a maximum of 4*pageBufferSize*revisionBufferSize page texts in memory.
const (
pageBufferSize = 40
revis... | Text, SHA1 string
IsRevert uint32
Timestamp time.Time
} | random_line_split |
wikibrief.go | err := run(ctx, bBase{xml.NewDecoder(r), article2TopicID, ID2Bot, simplePages, &errorContext{"", filename(r)}})
if err != nil {
fail(err)
}
}(r)
}
if err != io.EOF {
fail(err)
}
wg.Wait()
}()
return completeInfo(ctx, fail, lang, simplePages)
}
//EvolvingPage represents a wikipedia page t... |
bs.ErrorContext.LastTitle = title //used for error reporting purposes
be = &bTitled{
bStarted: *bs,
Title: title,
}
return
}
func (bs *bStarted) SetPageID(ctx context.Context, t xml.StartElement) (be builder, err error) { //no obligatory element "title"
err = bs.Wrapf(errInvalidXML, "Error invalid xml (... | {
err = bs.Wrapf(err, "Error while decoding the title of a page")
return
} | conditional_block |
wikibrief.go | (ctx context.Context, fail func(err error) error, tmpDir, lang string, restrict bool) <-chan EvolvingPage {
//Default value to a closed channel
dummyPagesChan := make(chan EvolvingPage)
close(dummyPagesChan)
ID2Bot, err := wikibots.New(ctx, lang)
if err != nil {
fail(err)
return dummyPagesChan
}
latestDump... | New | identifier_name | |
keys.rs | => F(11); ALT);
insert!(b"\x1B[23;6~" => F(11); LOGO);
insert!(b"\x1B[23;2~" => F(11); SHIFT);
insert!(b"\x1B[23~" => F(11));
insert!(b"\x1B[24;5~" => F(12); CTRL);
insert!(b"\x1B[24;3~" => F(12); ALT);
insert!(b"\x1B[24;6~" => F(12); LOGO);
insert!(b"\x1B[24;2~" => F(12); SHIFT);
insert!(b"... | return (&input[length..], Some(Key {
modifier: mods,
value: Char(string.chars().next().unwrap())
}));
}
| conditional_block | |
keys.rs |
#[derive(Eq, PartialEq, Copy, Clone, Debug)]
pub enum Value {
Escape,
Enter,
Down,
Up,
Left,
Right,
PageUp,
PageDown,
BackSpace,
BackTab,
Tab,
Delete,
Insert,
Home,
End,
Begin,
F(u8),
Char(char),
}
pub use self::Value::*;
impl Keys {
pub fn new(info: &info::Database) -> Self {
let mut map =... | Modifier::empty()
}
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.