file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
Transformer_prac.py | import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import matplotlib as plt
dtype = torch.FloatTensor
sentence =['ich mochte ein bier P', 'S i want a beer','i want a beer E']
# S : Symbol that shows starting point of decoding input
# E : Symb... | optimizer.step() | enc_input, dec_input, target_batch = make_batch(sentence)
outputs, enc_self_attns, dec_self_attns, dec_enc_attns = model(enc_input, dec_input)
loss = criterion(outputs, target_batch.contiguous().view(-1))
print('Epoch:','%04d'%(epoch+1), 'cost = '.format(loss))
loss.backward()
| random_line_split |
importer.go | // Copyright 2022 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
// loadTarball unzips tarball with groups and deserializes them.
func loadTarball(ctx context.Context, content io.Reader, domain string, systems, groups []string) (map[string]GroupBundle, error) {
// map looks like: K: system, V: { K: groupName, V: []identities }
bundles := make(map[string]GroupBundle)
entries, er... | {
g, err := GetGroupImporterConfig(ctx)
if err != nil {
return nil, 0, err
}
gConfigProto, err := g.ToProto()
if err != nil {
return nil, 0, errors.Annotate(err, "issue getting proto from config entity").Err()
}
caller := auth.CurrentIdentity(ctx)
var entry *configspb.GroupImporterConfig_TarballUploadEntry
... | identifier_body |
importer.go | // Copyright 2022 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | // including removal of groups that are on the server, but no longer present in
// the tarball.
// Plain list format should have one userid per line and can only describe a single
// group in a single system. Such groups will be added to 'external/*' groups
// namespace. Removing such group from importer config will r... |
// Each tarball may have groups from multiple external systems, but groups from
// some external system must not be split between multiple tarballs. When importer
// sees <external group system name>/* in a tarball, it modifies group list from
// that system on the server to match group list in the tarball _exactly_, | random_line_split |
importer.go | // Copyright 2022 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... |
}
for groupName := range iGroups {
iGroupsSet.Add(groupName)
}
sysGroupsSet := stringset.NewFromSlice(systemGroups...)
toCreate := iGroupsSet.Difference(sysGroupsSet).ToSlice()
for _, g := range toCreate {
group := makeAuthGroup(ctx, g)
group.Members = identitiesToStrings(iGroups[g])
toPut = append(to... | {
systemGroups = append(systemGroups, gID)
} | conditional_block |
importer.go | // Copyright 2022 The LUCI Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed... | (ctx context.Context) (*GroupImporterConfig, error) {
groupsCfg := &GroupImporterConfig{
Kind: "GroupImporterConfig",
ID: "config",
}
switch err := datastore.Get(ctx, groupsCfg); {
case err == nil:
return groupsCfg, nil
case err == datastore.ErrNoSuchEntity:
return nil, err
default:
return nil, error... | GetGroupImporterConfig | identifier_name |
storeserv.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright 2017-2020 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://ww... | def post(self, url, body):
"""
Perform HTTP POST request to HPE 3PAR array. Method used to create new
objects.
:param str url: URL address. Base part of url address is generated
automatically and you should not care about it. Example of valid
url: 'system' or... | "
Perform HTTP GET request to HPE 3PAR array. Method used to get
information about objects.
:param str url: URL address. Base part of url address is generated
automatically and you should not care about it. Example of valid
url: 'system' or 'volumes'. All available url's... | identifier_body |
storeserv.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright 2017-2020 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://ww... | elf, exc_type, exc_val, exc_tb):
if self._key is not None:
self.close()
class AuthError(Exception):
""" Authentification error """
| exit__(s | identifier_name |
storeserv.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright 2017-2020 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://ww... | elif status == 403:
# 403 (forbidden) => Wrong user or password
raise AuthError('Cannot connect to StoreServ. '
'Authentification error: %s', data['desc'])
def close(self):
"""
Close Rest API session.
:return: None
"""
... | lf._headers.update({'X-HP3PAR-WSAPI-SessionKey': data['key']})
self._key = data['key']
| conditional_block |
storeserv.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (C) Copyright 2017-2020 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://ww... | LOG = logging.getLogger('hpestorapi.storeserv')
class StoreServ:
"""
HPE 3PAR array implementation class.
"""
def __init__(self, address, username, password, port=None, ssl=True, verify=True):
"""
HPE 3PAR constructor.
:param str address: Hostname or IP address of HPE 3PA... | if __name__ == "__main__":
pass
| random_line_split |
repository_repository.py | # -*- coding: utf-8 -*-
import re
import os
from os.path import isfile
from os import environ, path
from odoo import api, exceptions, fields, models, _, service, tools
import subprocess
import logging
from os.path import isdir as is_dir
import shutil
from datetime import datetime
from odoo import release
from odoo.too... |
else:
return False
def info(self):
branch = self._repo.active_branch.name
curr_rev = self._repo.rev_parse(branch)
git = self.info_base()
source = self._repo.remotes.origin.url.split('@')
if len(source) > 1:
source = "https://" + sourc... | self._repo = Repo(self._path)
return True | conditional_block |
repository_repository.py | # -*- coding: utf-8 -*-
import re
import os
from os.path import isfile
from os import environ, path
from odoo import api, exceptions, fields, models, _, service, tools
import subprocess
import logging
from os.path import isdir as is_dir
import shutil
from datetime import datetime
from odoo import release
from odoo.too... | 'target': 'current',
'domain': [('id', 'in', self.module_ids.ids)]
}
def install_requirements(self):
try:
requirement_file = self.path + '/requirements.txt'
if os.path.exists(requirement_file):
subprocess.check_call(["pip3", "install",... | 'res_model': 'ir.module.module',
'view_type': 'form',
'view_mode': 'kanban,tree,form', | random_line_split |
repository_repository.py | # -*- coding: utf-8 -*-
import re
import os
from os.path import isfile
from os import environ, path
from odoo import api, exceptions, fields, models, _, service, tools
import subprocess
import logging
from os.path import isdir as is_dir
import shutil
from datetime import datetime
from odoo import release
from odoo.too... | (path):
return [module for module in os.listdir(path) if any(map(
lambda f: isfile(path_join(path, module, f)), (
'__manifest__.py', '__openerp__.py')))]
class Git():
_source_http = None
_source_git = None
_repo = None
_user = None
_pass = None
_path = None
_output_... | find_modules | identifier_name |
repository_repository.py | # -*- coding: utf-8 -*-
import re
import os
from os.path import isfile
from os import environ, path
from odoo import api, exceptions, fields, models, _, service, tools
import subprocess
import logging
from os.path import isdir as is_dir
import shutil
from datetime import datetime
from odoo import release
from odoo.too... |
class Git():
_source_http = None
_source_git = None
_repo = None
_user = None
_pass = None
_path = None
_output_list = []
def __init__(self, path=None, user=None, password=None):
self._path = path
self._user = user
self._pass = password
def remove(self):
... | return [module for module in os.listdir(path) if any(map(
lambda f: isfile(path_join(path, module, f)), (
'__manifest__.py', '__openerp__.py')))] | identifier_body |
mod.rs | use std::{
alloc::Layout,
array::TryFromSliceError,
borrow::BorrowMut,
cell::{Cell, UnsafeCell},
collections::HashMap,
ffi::OsStr,
fs,
io::{self, Read, Write},
mem,
ops::{Deref, DerefMut},
path::Path,
sync::{Arc, Mutex, MutexGuard}, | use anyhow::{anyhow, Result};
use bevy_ecs::{
ComponentId, DynamicFetch, DynamicFetchResult, DynamicQuery, DynamicSystem, EntityBuilder,
QueryAccess, StatefulQuery, TypeAccess, TypeInfo, World,
};
use bincode::DefaultOptions;
use fs::OpenOptions;
use io::IoSlice;
use mem::ManuallyDrop;
use quill::ecs::TypeLayou... | todo, u32, vec,
};
| random_line_split |
mod.rs | use std::{
alloc::Layout,
array::TryFromSliceError,
borrow::BorrowMut,
cell::{Cell, UnsafeCell},
collections::HashMap,
ffi::OsStr,
fs,
io::{self, Read, Write},
mem,
ops::{Deref, DerefMut},
path::Path,
sync::{Arc, Mutex, MutexGuard},
todo, u32, vec,
};
use anyhow::{an... | (&mut self, buf: &[u8]) -> io::Result<usize> {
self.extend_from_slice(buf);
Ok(buf.len())
}
#[inline]
fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
let len = bufs.iter().map(|b| b.len() as u32).sum();
self.reserve(len);
for buf in bufs {
... | write | identifier_name |
mod.rs | use std::{
alloc::Layout,
array::TryFromSliceError,
borrow::BorrowMut,
cell::{Cell, UnsafeCell},
collections::HashMap,
ffi::OsStr,
fs,
io::{self, Read, Write},
mem,
ops::{Deref, DerefMut},
path::Path,
sync::{Arc, Mutex, MutexGuard},
todo, u32, vec,
};
use anyhow::{an... |
}
struct Buffer<'a> {
memory: &'a Memory,
// fn reserve(ptr: WasmPtr<u8, Array>, cap: u32, len: u32, additional: u32)
reserve: &'a NativeFunc<(WasmPtr<RawBuffer>, u32)>,
raw: WasmPtr<RawBuffer>,
}
#[repr(C)]
#[derive(Debug, Clone, Copy)]
struct RawBuffer {
ptr: WasmPtr<u8, Array>,
cap: u32,
... | {
let mut query = DynamicQuery::default();
query.access = self.access(layouts)?;
// TODO: TypeInfo
Ok(query)
} | identifier_body |
scheduler.rs | extern crate clap;
extern crate esvm;
extern crate fern;
extern crate ethereum_newtypes;
extern crate rayon;
extern crate regex;
extern crate reqwest;
extern crate hexdecode;
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
use std::fs::{self, File};
... |
fn add_worker(&self, worker: Worker) {
self.queue.lock().unwrap().push(worker);
}
fn get_worker(&self) -> WorkerHandle {
let worker;
loop {
if let Some(w) = self.queue.lock().unwrap().pop() {
worker = Some(w);
break;
}
... | {
let s = Scheduler::new();
for url in &urls {
s.queue.lock().unwrap().push(Worker::new(url, timeout).unwrap()); // if the workers can not connect initially fail
}
s
} | identifier_body |
scheduler.rs | extern crate clap;
extern crate esvm;
extern crate fern;
extern crate ethereum_newtypes;
extern crate rayon;
extern crate regex;
extern crate reqwest;
extern crate hexdecode;
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
use std::fs::{self, File};
... | (path: &str) -> (Arc<Mutex<Vec<(usize, String)>>>, usize) {
let mut acc_list = String::new();
File::open(path)
.expect("Could not open account list")
.read_to_string(&mut acc_list)
.expect("Could not read account list");
let acc_vec: Vec<(usize, String)> = acc_list
.lines()
... | parse_account_list | identifier_name |
scheduler.rs | extern crate clap;
extern crate esvm;
extern crate fern;
extern crate ethereum_newtypes;
extern crate rayon;
extern crate regex;
extern crate reqwest;
extern crate hexdecode;
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
use std::fs::{self, File};
... | }
res
}
}
impl<'a> Drop for WorkerHandle<'a> {
fn drop(&mut self) {
if !self.kill {
let worker = self
.worker
.take()
.expect("Worker replaced before adding back");
self.scheduler.add_worker(worker)
} else {... | } | random_line_split |
scheduler.rs | extern crate clap;
extern crate esvm;
extern crate fern;
extern crate ethereum_newtypes;
extern crate rayon;
extern crate regex;
extern crate reqwest;
extern crate hexdecode;
extern crate serde_json;
#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;
extern crate chrono;
use std::fs::{self, File};
... |
if attack.attack_type == AttackType::DeleteContract {
res.1 = true;
}
if attack.attack_type == AttackType::HijackControlFlow {
res.... | {
res.0 = true;
} | conditional_block |
lib.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![deny(missing_docs)]
//! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for
//! connecting components to whe... | <'a>(
listener: &'a mut fuchsia_async::net::TcpListener,
) -> impl Stream<Item = std::io::Result<fuchsia_async::net::TcpStream>> + 'a {
use std::task::{Context, Poll};
#[pin_project::pin_project]
struct AcceptStream<'a> {
#[pin]
listener: &'a mut fuchsia_async::net::TcpListener,
}
... | accept_stream | identifier_name |
lib.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![deny(missing_docs)]
//! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for
//! connecting components to whe... | else {
(None, false)
};
let task = fasync::Task::spawn(async move {
let listener = accept_stream(&mut listener);
let listener = listener
.map_err(Error::from)
.map_ok(|conn| fuchsia_hyper::TcpStream { stream: conn });
le... | {
// build a server configuration using a test CA and cert chain
let mut tls_config = rustls::ServerConfig::new(rustls::NoClientAuth::new());
tls_config.set_single_cert(cert_chain, private_key).unwrap();
let tls_acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(tls_conf... | conditional_block |
lib.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![deny(missing_docs)]
//! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for
//! connecting components to whe... |
}
AcceptStream { listener }
}
#[cfg(not(target_os = "fuchsia"))]
fn accept_stream<'a>(
listener: &'a mut async_net::TcpListener,
) -> impl Stream<Item = std::io::Result<async_net::TcpStream>> + 'a {
listener.incoming()
}
fn parse_cert_chain(mut bytes: &[u8]) -> Vec<rustls::Certificate> {
rustls:... | {
let mut this = self.project();
match this.listener.async_accept(cx) {
Poll::Ready(Ok((conn, _addr))) => Poll::Ready(Some(Ok(conn))),
Poll::Ready(Err(err)) => Poll::Ready(Some(Err(err))),
Poll::Pending => Poll::Pending,
}
} | identifier_body |
lib.rs | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![deny(missing_docs)]
//! This module provides a test HTTP(S) server that can be instantiated simply by a unit test, for
//! connecting components to whe... |
/// A builder to construct a `TestServer`.
#[derive(Default)]
pub struct TestServerBuilder {
handlers: Vec<Arc<dyn Handler>>,
https_certs: Option<(Vec<rustls::Certificate>, rustls::PrivateKey)>,
}
impl TestServerBuilder {
/// Create a new TestServerBuilder
pub fn new() -> Self {
Self::default(... | /// Create a Builder
pub fn builder() -> TestServerBuilder {
TestServerBuilder::new()
}
} | random_line_split |
concurrent_ntlm_auth_requests.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#allisnone 20200403
#https://github.com/urllib3/urllib3/issues/1434
#https://github.com/dopstar/requests-ntlm2
#https://github.com/requests/requests-ntlm
#base on python3
#if you request https website, you need to add ASWG CA to following file:
#/root/.pyenv/versio... | if num> len(sequences):
num = len(sequences)
choices = random.sample(sequences,num)
return choices
def popen_curl_request(url,user,eth,proxy='172.17.33.23:8080',cert='rootCA.cer'):
curl_cmd = 'curl --cacert {0} --interface {1} --proxy-user {2}:Firewall1 --proxy-ntlm -x {3} {4} &'.fo... | quences.append(prefix+str(i))
| conditional_block |
concurrent_ntlm_auth_requests.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#allisnone 20200403
#https://github.com/urllib3/urllib3/issues/1434
#https://github.com/dopstar/requests-ntlm2
#https://github.com/requests/requests-ntlm
#base on python3
#if you request https website, you need to add ASWG CA to following file:
#/root/.pyenv/versio... | subp = subprocess.Popen(curl_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,close_fds=True)#,encoding="utf-8")
try:
subp.wait(2) #็ญๅพ
่ถ
ๆถ
except Exception as e:
print('curl_request_timeout, error: ',e)
return
if subp.poll() == 0:
print(subp.communicate(... | def popen_curl_request(url,user,eth,proxy='172.17.33.23:8080',cert='rootCA.cer'):
curl_cmd = 'curl --cacert {0} --interface {1} --proxy-user {2}:Firewall1 --proxy-ntlm -x {3} {4} &'.format(
cert,eth,user,proxy,url)
| random_line_split |
concurrent_ntlm_auth_requests.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#allisnone 20200403
#https://github.com/urllib3/urllib3/issues/1434
#https://github.com/dopstar/requests-ntlm2
#https://github.com/requests/requests-ntlm
#base on python3
#if you request https website, you need to add ASWG CA to following file:
#/root/.pyenv/versio... | 172.18.1.', cert='rootCA.cer',is_same_url=False, is_http=False,debug=False):
"""
one ip/eth<--> one user
"""
i = 0
#count = max(len(urls),user_num,eth_num)
#for url in urls:
for i in range(max(user_num,eth_num)):
url = ''
if is_same_url:
if is_http:
... | ip_prefix = ' | identifier_name |
concurrent_ntlm_auth_requests.py | #!/usr/bin/env python
# -*- coding:utf-8 -*-
#allisnone 20200403
#https://github.com/urllib3/urllib3/issues/1434
#https://github.com/dopstar/requests-ntlm2
#https://github.com/requests/requests-ntlm
#base on python3
#if you request https website, you need to add ASWG CA to following file:
#/root/.pyenv/versio... | th_num=254):
"""
inet 172.18.1.1/16 brd 172.18.255.255 scope global secondary eth0:0
inet 172.18.1.254/16 brd 172.18.255.255 scope global secondary eth0:253
sequence: start with 0
eth_num: eth sequence start with 0
"""
user_index = sequence % user_num + user_start
eth_index = seq... | ๅ็ฑปๆต่ฏ๏ผๆต่ฏๆไปถไธญๅญๆพๅคง้็urlๅฐๅ
:param from_file: str
:return: list๏ผ URL_list๏ผGenerator๏ผ
"""
txtfile = open(from_file, 'r',encoding='utf-8')
url_list = txtfile.readlines()
for i in range(0,len(url_list)):
url_list[i] = url_list[i].replace('\n','')
# print(url_list[i])
if ur... | identifier_body |
spline.rs | use ordered_float::NotNan;
use crate::hitobject::SliderSplineKind;
use crate::math::{Math, Point};
/// Represents a spline, a set of points that represents the actual shape of a slider, generated
/// from the control points.
#[derive(Clone, Debug)]
pub struct Spline {
/// The actual points
pub spline_points: ... | self.cumulative_lengths[idx].into_inner(),
);
let proportion = (length - len1) / (len2 - len1);
let (p1, p2) = (self.spline_points[idx - 1], self.spline_points[idx]);
(p2 - p1) * P::new(proportion, proportion) + p1
}
... |
let (len1, len2) = (
self.cumulative_lengths[idx - 1].into_inner(), | random_line_split |
spline.rs | use ordered_float::NotNan;
use crate::hitobject::SliderSplineKind;
use crate::math::{Math, Point};
/// Represents a spline, a set of points that represents the actual shape of a slider, generated
/// from the control points.
#[derive(Clone, Debug)]
pub struct Spline {
/// The actual points
pub spline_points: ... | (control_points: &[P], l: &mut [P], r: &mut [P], midpoints_buf: &mut [P]) {
let count = control_points.len();
midpoints_buf.copy_from_slice(control_points);
for i in 0..count {
l[i] = midpoints_buf[0];
r[count - i - 1] = midpoints_buf[count - i - 1];
for j in 0..count - i - 1 {
... | subdivide | identifier_name |
spline.rs | use ordered_float::NotNan;
use crate::hitobject::SliderSplineKind;
use crate::math::{Math, Point};
/// Represents a spline, a set of points that represents the actual shape of a slider, generated
/// from the control points.
#[derive(Clone, Debug)]
pub struct Spline {
/// The actual points
pub spline_points: ... |
/// Calculate the angle at the given length on the slider
fn angle_at_length(&self, length: f64) -> P {
let _length_notnan = NotNan::new(length).unwrap();
// match self.cumulative_lengths.binary_search(&length_notnan) {
// Ok(_) => {}
// Err(_) => {}
// }
... | {
self.spline_points.last().cloned().unwrap()
} | identifier_body |
spline.rs | use ordered_float::NotNan;
use crate::hitobject::SliderSplineKind;
use crate::math::{Math, Point};
/// Represents a spline, a set of points that represents the actual shape of a slider, generated
/// from the control points.
#[derive(Clone, Debug)]
pub struct Spline {
/// The actual points
pub spline_points: ... |
SliderSplineKind::Bezier => {
let mut output = Vec::new();
let mut last_index = 0;
let mut i = 0;
while i < points.len() {
let multipart_segment = i < points.len() - 2 && (points[i] == points[i + 1]);
if... | {
let (p1, p2, p3) = (points[0], points[1], points[2]);
let (center, radius) = Math::circumcircle(p1, p2, p3);
// find the t-values of the start and end of the slider
let t0 = (center.y - p1.y).atan2(p1.x - center.x);
let mut mid = (center... | conditional_block |
pattern.rs | use fmt::Formatter;
use log::*;
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::{convert::TryFrom, str::FromStr};
use thiserror::Error;
use crate::*;
/// A pattern that can function as either a [`Searcher`] or [`Applier`].
///
/// A [`Pattern`] is essentially a for-all quantified expression with
/// [`... | lf) -> Vec<Var> {
Pattern::vars(self)
}
}
impl<L, A> Applier<L, A> for Pattern<L>
where
L: Language,
A: Analysis<L>,
{
fn get_pattern_ast(&self) -> Option<&PatternAst<L>> {
Some(&self.ast)
}
fn apply_matches(
&self,
egraph: &mut EGraph<L, A>,
matches: &[... | (&se | identifier_name |
pattern.rs | use fmt::Formatter;
use log::*;
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::{convert::TryFrom, str::FromStr};
use thiserror::Error;
use crate::*;
/// A pattern that can function as either a [`Searcher`] or [`Applier`].
///
/// A [`Pattern`] is essentially a for-all quantified expression with
/// [`... | }
*ids.last().unwrap()
}
#[cfg(test)]
mod tests {
use crate::{SymbolLang as S, *};
type EGraph = crate::EGraph<S, ()>;
#[test]
fn simple_match() {
crate::init_logger();
let mut egraph = EGraph::default();
let (plus_id, _) = egraph.union_instantiations(
&... | };
ids[i] = id; | random_line_split |
pattern.rs | use fmt::Formatter;
use log::*;
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::{convert::TryFrom, str::FromStr};
use thiserror::Error;
use crate::*;
/// A pattern that can function as either a [`Searcher`] or [`Applier`].
///
/// A [`Pattern`] is essentially a for-all quantified expression with
/// [`... | fn vars(&self) -> Vec<Var> {
Pattern::vars(self)
}
}
impl<L, A> Applier<L, A> for Pattern<L>
where
L: Language,
A: Analysis<L>,
{
fn get_pattern_ast(&self) -> Option<&PatternAst<L>> {
Some(&self.ast)
}
fn apply_matches(
&self,
egraph: &mut EGraph<L, A>,
... | let substs = self.program.run(egraph, eclass);
if substs.is_empty() {
None
} else {
let ast = Some(Cow::Borrowed(&self.ast));
Some(SearchMatches {
eclass,
substs,
ast,
})
}
}
| identifier_body |
pattern.rs | use fmt::Formatter;
use log::*;
use std::borrow::Cow;
use std::fmt::{self, Display};
use std::{convert::TryFrom, str::FromStr};
use thiserror::Error;
use crate::*;
/// A pattern that can function as either a [`Searcher`] or [`Applier`].
///
/// A [`Pattern`] is essentially a for-all quantified expression with
/// [`... | };
ids[i] = id;
}
*ids.last().unwrap()
}
#[cfg(test)]
mod tests {
use crate::{SymbolLang as S, *};
type EGraph = crate::EGraph<S, ()>;
#[test]
fn simple_match() {
crate::init_logger();
let mut egraph = EGraph::default();
let (plus_id, _) = egraph.union_... | let n = e.clone().map_children(|child| ids[usize::from(child)]);
trace!("adding: {:?}", n);
egraph.add(n)
}
| conditional_block |
main.rs | #![allow(clippy::single_match)]
use ::std::collections::HashMap;
use ::std::sync::Mutex;
use anyhow::Error;
use chrono::naive::NaiveDate as Date;
use derive_more::Display;
use log::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
mod citation;
mod filters;
mod github;
mod md;
lazy_static::lazy_static!... | (&self) -> String {
match self {
Self::BS => "Bachelor of Science".into(),
Self::MS => "Master of Science".into(),
Self::PhD => "PhD".into(),
}
}
}
#[derive(Serialize, Deserialize)]
struct Education {
institution: String,
degree: Degree,
major: String,
duration: DateRange,
#[serde(skip_serializing_i... | to_resume_string | identifier_name |
main.rs | #![allow(clippy::single_match)]
use ::std::collections::HashMap;
use ::std::sync::Mutex;
use anyhow::Error;
use chrono::naive::NaiveDate as Date;
use derive_more::Display;
use log::*;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
mod citation;
mod filters;
mod github;
mod md;
lazy_static::lazy_static!... | fn deserialize<D: Deserializer<'a>>(d: D) -> Result<Self, D::Error> {
let s = String::deserialize(d)?;
s.parse().map_err(serde::de::Error::custom)
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
enum Citation {
Raw(String),
RawWithYear { text: String, year: Option<u32> },
Url(citation::UrlCita... | }
impl<'a> Deserialize<'a> for DateRange { | random_line_split |
readbuf.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | /// A borrowed byte buffer which is incrementally filled and initialized.
///
/// This type is a sort of "double cursor". It tracks three regions in the buffer: a region at the beginning of the
/// buffer that has been logically filled with data, a region that has been initialized at some point but not yet
/// logicall... | random_line_split | |
readbuf.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... |
/// Returns a mutable reference to the initialized portion of the cursor.
#[inline]
pub fn init_mut(&mut self) -> &mut [u8] {
// SAFETY: We only slice the initialized part of the buffer, which is always valid
unsafe {
MaybeUninit::slice_assume_init_mut(&mut self.buf.buf[self.bu... | {
// SAFETY: We only slice the initialized part of the buffer, which is always valid
unsafe { MaybeUninit::slice_assume_init_ref(&self.buf.buf[self.buf.filled..self.buf.init]) }
} | identifier_body |
readbuf.rs | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may... | (&mut self, buf: &[u8]) -> Result<usize> {
self.append(buf);
Ok(buf.len())
}
fn flush(&mut self) -> Result<()> {
Ok(())
}
}
| write | identifier_name |
replicated_session.go | // Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... |
}
return err
}
// Origin returns the host that initiated the session.
func (s replicatedSession) Origin() topology.Host {
return s.session.Origin()
}
// Replicas returns the replication factor.
func (s replicatedSession) Replicas() int {
return s.session.Replicas()
}
// TopologyMap returns the current topology ... | {
s.log.Error("could not close async session: %v", zap.Error(err))
} | conditional_block |
replicated_session.go | // Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... |
// WriteTagged value to the database for an ID and given tags.
func (s replicatedSession) WriteTagged(
namespace, id ident.ID, tags ident.TagIterator, t xtime.UnixNano,
value float64, unit xtime.Unit, annotation []byte,
) error {
return s.replicate(replicatedParams{
namespace: namespace,
id: id,
t: ... | {
return s.replicate(replicatedParams{
namespace: namespace,
id: id,
t: t.Add(-s.writeTimestampOffset),
value: value,
unit: unit,
annotation: annotation,
})
} | identifier_body |
replicated_session.go | // Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | annotation: annotation,
tags: tags,
useTags: true,
})
}
// Fetch values from the database for an ID.
func (s replicatedSession) Fetch(
namespace, id ident.ID, startInclusive, endExclusive xtime.UnixNano,
) (encoding.SeriesIterator, error) {
return s.session.Fetch(namespace, id, startInclusive, endExc... | id: id,
t: t.Add(-s.writeTimestampOffset),
value: value,
unit: unit, | random_line_split |
replicated_session.go | // Copyright (c) 2019 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge... | (opts Options) error {
if opts.TopologyInitializer() == nil {
return nil
}
session, err := s.newSessionFn(opts)
if err != nil {
return err
}
s.session = session
return nil
}
func (s *replicatedSession) setAsyncSessions(opts []Options) error {
sessions := make([]clientSession, 0, len(opts))
for i, oo := r... | setSession | identifier_name |
shadow_logger.rs | use std::cell::RefCell;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::Arc;
use std::sync::{Mutex, RwLock};
use std::time::Duration;
use crossbeam::queue::ArrayQueue;
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use logger as c_log;
use once_cell::sync::{Lazy, OnceCell};
use shadow_sh... |
}
| {
set_buffering_enabled(buffering_enabled != 0)
} | identifier_body |
shadow_logger.rs | use std::cell::RefCell;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::Arc;
use std::sync::{Mutex, RwLock};
use std::time::Duration;
use crossbeam::queue::ArrayQueue;
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use logger as c_log;
use once_cell::sync::{Lazy, OnceCell};
use shadow_sh... | (&self, metadata: &Metadata) -> bool {
let filter = match Worker::with_active_host(|host| host.info().log_level) {
Some(Some(level)) => level,
_ => self.max_level(),
};
metadata.level() <= filter
}
fn log(&self, record: &Record) {
if !self.enabled(record.... | enabled | identifier_name |
shadow_logger.rs | use std::cell::RefCell;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::Arc;
use std::sync::{Mutex, RwLock};
use std::time::Duration;
use crossbeam::queue::ArrayQueue;
use log::{Level, LevelFilter, Log, Metadata, Record, SetLoggerError};
use logger as c_log;
use once_cell::sync::{Lazy, OnceCell};
use shadow_sh... | fn log(&self, record: &Record) {
if !self.enabled(record.metadata()) {
return;
}
let message = std::fmt::format(*record.args());
let host_info = Worker::with_active_host(|host| host.info().clone());
let mut shadowrecord = ShadowLogRecord {
level: re... | }
| random_line_split |
raw_data_process.py | import logging
import os
import random
import re
from collections import defaultdict, OrderedDict
import jieba
from utils.json_io import write_json, read_json
from utils.logger import setup_logging
import subprocess
ZH_SYMBOLS = set('๏ผใ๏ผ๏ผใใ๏ผ๏ผใใโโโโใ๏ผ๏ผ')
def preprocess(sentence: str) -> str:
"""
ๅฏนๅฅๅญ่ฟ่ก้ขๅค็๏ผๅปๆ... | trip('ไบ')
# ้ฟๅบฆไธ็ฌฆๅๆๅชๅ
ๅซๆฐๅญๅๅญๆฏ
if len(word.text) < self.least_word_len or word.text.isnumeric():
_words.remove(word)
return _words
@staticmethod
def generate_tags(sequence_len: int, words: [Word]):
"""
ๆ นๆฎ้ฟๅบฆๅไฝ็ฝฎ็ดขๅผไบง็BIOๆ ็ญพ
:param sequence_len: ้ฟๅบฆ
... | word.s | identifier_name |
raw_data_process.py | import logging
import os
import random
import re
from collections import defaultdict, OrderedDict
import jieba
from utils.json_io import write_json, read_json
from utils.logger import setup_logging
import subprocess
ZH_SYMBOLS = set('๏ผใ๏ผ๏ผใใ๏ผ๏ผใใโโโโใ๏ผ๏ผ')
def preprocess(sentence: str) -> str:
"""
ๅฏนๅฅๅญ่ฟ่ก้ขๅค็๏ผๅปๆ... | question = total_question['question']
# ่ทณ่ฟๆฒกๆ่ๆฏไฟกๆฏๆ่งฃๆ็้ข็ฎ
if not background or not explain or len(explain) < 50:
continue
# ้ขๅค็
background = preprocess(background)
explain = preprocess(explain)
... | # ๅค็raw_data
for idx, total_question in enumerate(raw_data):
# ๆๅ่ๆฏๅ่งฃๆ
background = total_question[background_key]
explain = total_question['explanation'] | random_line_split |
raw_data_process.py | import logging
import os
import random
import re
from collections import defaultdict, OrderedDict
import jieba
from utils.json_io import write_json, read_json
from utils.logger import setup_logging
import subprocess
ZH_SYMBOLS = set('๏ผใ๏ผ๏ผใใ๏ผ๏ผใใโโโโใ๏ผ๏ผ')
def preprocess(sentence: str) -> str:
"""
ๅฏนๅฅๅญ่ฟ่ก้ขๅค็๏ผๅปๆ... | redundant=use_redundant)
# ๅค็ๆฐๆฎ
processor.process_raw_data()
# ๅๅ
ฅๆฐๆฎ
processor.prepare_data(data_split_dict={'train': 0.7, 'dev': 0.2, 'test': 0.1})
# ๅๅ
ฅ็ป่ฎก่ฏ้ข
write_counter(processor.wor... | if not os.path.exists(store_data_path):
os.makedirs(store_data_path)
processor = RawProcessor(file_paths=file_paths, store_path=store_data_path, use_cut=use_cut,
| identifier_body |
raw_data_process.py | import logging
import os
import random
import re
from collections import defaultdict, OrderedDict
import jieba
from utils.json_io import write_json, read_json
from utils.logger import setup_logging
import subprocess
ZH_SYMBOLS = set('๏ผใ๏ผ๏ผใใ๏ผ๏ผใใโโโโใ๏ผ๏ผ')
def preprocess(sentence: str) -> str:
"""
ๅฏนๅฅๅญ่ฟ่ก้ขๅค็๏ผๅปๆ... | word) for word in jieba.tokenize(source)]
target_cut = [Word(*word) for word in jieba.tokenize(target)]
for word in source_cut:
if word in target_cut and word.text not in STOPWORDS and len(word.text) >= self.least_word_len:
res_words.append(word)
return res_words
... | ut(self, source: str, target: str):
"""
ไฝฟ็จ็ปๅทดๅ่ฏๆฅๆฝๅ็ธๅ่ฏ
"""
res_words: [Word] = []
source_cut = [Word(* | conditional_block |
exchange_endpoint0.py | from flask import Flask, request, g
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask import jsonify
import json
import eth_account
import algosdk
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import load_only
from datetime im... | print a dictionary nicely
def print_dict(d):
for key, value in d.items():
print(key, ' : ', value)
""" End of helper methods """
@app.route('/trade', methods=['POST'])
def trade():
print("In trade endpoint")
if request.method == "POST":
print("--------... | rn {
c.name: getattr(row, c.name)
for c in row.__table__.columns
}
# | identifier_body |
exchange_endpoint0.py | from flask import Flask, request, g
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask import jsonify
import json
import eth_account
import algosdk
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import load_only
from datetime im... | # print(len(order_list))
# pick the first one in the list
match_order = order_list[0]
# Set the filled field to be the current timestamp on both orders
# Set counterparty_id to be the id of the other order
match_order.filled = datetime.now()
current_order.filled ... |
# If a match is found between order and existing_order
if (len(order_list) > 0):
# print(" order_list_length") | random_line_split |
exchange_endpoint0.py | from flask import Flask, request, g
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask import jsonify
import json
import eth_account
import algosdk
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import load_only
from datetime im... |
# check whether the input contains all 7 fields of payload
for column in columns:
if not column in content['payload'].keys():
print( f"{column} not received by Trade" )
print( json.dumps(content) )
log_message(content)
ret... | t( f"{field} not received by Trade" )
print( json.dumps(content) )
log_message(content)
return jsonify( False )
| conditional_block |
exchange_endpoint0.py | from flask import Flask, request, g
from flask_restful import Resource, Api
from sqlalchemy import create_engine
from flask import jsonify
import json
import eth_account
import algosdk
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm import load_only
from datetime im... |
create_session()
order_obj = Log(message=d)
g.session.add(order_obj)
shutdown_session()
# convert a row in DB into a dict
def row2dict(row):
return {
c.name: getattr(row, c.name)
for c in row.__table__.columns
}
# print a dictionary nicely
def print_dict(d):
for key, valu... | message(d): | identifier_name |
wxpayv3.go | package mcommon
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"time"
"github.com/gin-gonic/gin" | // StWxPayRawResp ๅๅค
type StWxPayRawResp struct {
ID string `json:"id"`
CreateTime time.Time `json:"create_time"`
ResourceType string `json:"resource_type"`
EventType string `json:"event_type"`
Summary string `json:"summary"`
Resource struct {
OriginalType string `json:"ori... | jsoniter "github.com/json-iterator/go"
"github.com/parnurzeal/gorequest"
)
| random_line_split |
wxpayv3.go | package mcommon
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"time"
"github.com/gin-gonic/gin"
jsoniter "github.com/json-iterator/go"... | ]string) (string, error) {
var buf bytes.Buffer
for _, col := range cols {
buf.WriteString(col)
buf.WriteString("\n")
}
sign, err := RsaSign(buf.String(), key, crypto.SHA256)
if err != nil {
return "", err
}
return sign, nil
}
// WxPayV3Sign v3็ญพๅ
func WxPayV3Sign(mchid, keySerial string, key *rsa.PrivateK... | ateKey, cols [ | identifier_name |
wxpayv3.go | package mcommon
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"time"
"github.com/gin-gonic/gin"
jsoniter "github.com/json-iterator/go"... | if rawResp.EventType != "REFUND.SUCCESS" {
return nil, fmt.Errorf("error event_type: %s", rawResp.EventType)
}
if rawResp.ResourceType != "encrypt-resource" {
return nil, fmt.Errorf("error resource_type: %s", rawResp.ResourceType)
}
originalType := rawResp.Resource.OriginalType
if originalType != "refund" {
... | identifier_body | |
wxpayv3.go | package mcommon
import (
"bytes"
"crypto"
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"encoding/xml"
"fmt"
"io/ioutil"
"net/url"
"strconv"
"time"
"github.com/gin-gonic/gin"
jsoniter "github.com/json-iterator/go"... | " {
return nil, fmt.Errorf("error original_type: %s", originalType)
}
algorithm := rawResp.Resource.Algorithm
if algorithm != "AEAD_AES_256_GCM" {
return nil, fmt.Errorf("error algorithm: %s", algorithm)
}
ciphertext := rawResp.Resource.Ciphertext
associatedData := rawResp.Resource.AssociatedData
nonce := r... | originalType := rawResp.Resource.OriginalType
if originalType != "transaction | conditional_block |
functions.py | import os
import sys
import pygame
from settings import *
import random
import sqlite3
sc = pygame.display.set_mode((WIDTH, HEIGHT))
# ัะตะบััะธะน ััะพะฒะตะฝั
all_logs = []
def load_image(name, colorkey=None):
fullname = os.path.join('data', name)
# ะตัะปะธ ัะฐะนะป ะฝะต ัััะตััะฒัะตั, ัะพ ะฒัั
ะพะดะธะผ
if not os.path.isfile(fulln... | 5), (x, y, 50, 50), width=1)
def print_log():
font = pygame.font.Font(None, 25)
text_coord = 25
for line in all_logs:
string_rendered = font.render(line, 1, pygame.Color('yellow'))
intro_rect = string_rendered.get_rect()
text_coord += 10
intro_rect.top = text_coord
... | s[0]
def draw_white_rect(x, y):
pygame.draw.rect(sc, (255, 255, 25 | identifier_body |
functions.py | import os
import sys
import pygame
from settings import *
import random
import sqlite3
sc = pygame.display.set_mode((WIDTH, HEIGHT))
# ัะตะบััะธะน ััะพะฒะตะฝั
all_logs = []
def load_image(name, colorkey=None):
fullname = os.path.join('data', name)
# ะตัะปะธ ัะฐะนะป ะฝะต ัััะตััะฒัะตั, ัะพ ะฒัั
ะพะดะธะผ
if not os.path.isfile(fulln... | name = ""
if event.type == pygame.MOUSEBUTTONDOWN:
if button_exit.push_button(event.pos):
gameover(name, killed_monsters)
text = font.render(name, True, (255, 255, 255))
rect = text.get_rect()
rect.center = (600, 400)
... | if event.unicode.isalpha():
name += event.unicode
elif event.key == K_BACKSPACE:
name = name[:-1]
elif event.key == K_RETURN: | random_line_split |
functions.py | import os
import sys
import pygame
from settings import *
import random
import sqlite3
sc = pygame.display.set_mode((WIDTH, HEIGHT))
# ัะตะบััะธะน ััะพะฒะตะฝั
all_logs = []
def load_image(name, colorkey=None):
fullname = os.path.join('data', name)
# ะตัะปะธ ัะฐะนะป ะฝะต ัััะตััะฒัะตั, ัะพ ะฒัั
ะพะดะธะผ
if not os.path.isfile(fulln... |
button_exit.draw()
sc.blit(text, rect)
sc.blit(title, (500, 250))
pygame.display.flip()
def exchange_equipment_inventory(inventory, hero):
obj = inventory.get_selected_cell()
if obj.get_type() == "weapon":
old_w = hero.replace_weapon(obj)
inventory.board[invent... | 0)
| conditional_block |
functions.py | import os
import sys
import pygame
from settings import *
import random
import sqlite3
sc = pygame.display.set_mode((WIDTH, HEIGHT))
# ัะตะบััะธะน ััะพะฒะตะฝั
all_logs = []
def load_image(name, colorkey=None):
fullname = os.path.join('data', name)
# ะตัะปะธ ัะฐะนะป ะฝะต ัััะตััะฒัะตั, ัะพ ะฒัั
ะพะดะธะผ
if not os.path.isfile(fulln... | ted_cell[0]][inventory.selected_cell[1]] = old_w
if obj.get_name() == "Leg_armor1" or obj.get_name() == 'Leg_armor2':
old_w = hero.replace_leg(obj)
inventory.board[inventory.selected_cell[0]][inventory.selected_cell[1]] = old_w
if obj.get_name() == "Arm_armor1" or obj.get_name() == 'Arm_armor2... | entory.board[inventory.selec | identifier_name |
machine.go | /*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | return 0, err
}
if retryDuration > 0 {
return retryDuration, nil
}
}
// now, when the node is drained (or vmiDeleteGraceTimeoutDurationSeconds has passed), we can delete the VMI
propagationPolicy := metav1.DeletePropagationForeground
err = m.client.Delete(m.machineContext, m.vmiInstance, &client.Delet... | retryDuration, err := m.drainNode(wrkldClstr)
if err != nil { | random_line_split |
machine.go | /*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... | () error {
m.machineContext.Logger.Info(fmt.Sprintf("setting the %s annotation", infrav1.VmiDeletionGraceTime))
graceTime := time.Now().Add(vmiDeleteGraceTimeoutDurationSeconds * time.Second).UTC().Format(time.RFC3339)
patch := fmt.Sprintf(`{"metadata":{"annotations":{"%s": "%s"}}}`, infrav1.VmiDeletionGraceTime, gr... | setVmiDeletionGraceTime | identifier_name |
machine.go | /*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
switch runStrategy {
case kubevirtv1.RunStrategyAlways:
// VM should recover if it is down.
return false, "", nil
case kubevirtv1.RunStrategyManual:
// If VM is manually controlled, we stay out of the loop
return false, "", nil
case kubevirtv1.RunStrategyHalted, kubevirtv1.RunStrategyOnce:
if m.vmiInsta... | {
return false, "", err
} | conditional_block |
machine.go | /*
Copyright 2021 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, ... |
// This functions drains a node from a tenant cluster.
// The function returns 3 values:
// * drain done - boolean
// * retry time, or 0 if not needed
// * error - to be returned if we want to retry
func (m *Machine) drainNode(wrkldClstr workloadcluster.WorkloadCluster) (time.Duration, error) {
kubeClient, err := wr... | {
m.machineContext.Logger.Info(fmt.Sprintf("setting the %s annotation", infrav1.VmiDeletionGraceTime))
graceTime := time.Now().Add(vmiDeleteGraceTimeoutDurationSeconds * time.Second).UTC().Format(time.RFC3339)
patch := fmt.Sprintf(`{"metadata":{"annotations":{"%s": "%s"}}}`, infrav1.VmiDeletionGraceTime, graceTime)
... | identifier_body |
header.go | package member_role
import (
"net/http"
"fmt"
"text/template"
config "../../config"
"strconv"
"encoding/json"
datatables "../../datatables"
login "../../login"
"strings"
)
type Profile struct {
Message string // error status output or validated data
Status bool //pass or fail
ID string
}... | tconf["test_js"] = `alert("from webserver")`
arr_sysrole := datatables.DataList(`sysrole_get 2`)
type Data struct {
Rights string
Conf map[string]string
Arr_Sysrole [][]string
}
tmpl := template.New("Hadd.html").Funcs(local_FuncMap)
var err error
if tmpl, err = tmpl.ParseFiles("admin/membe... | random_line_split | |
header.go | package member_role
import (
"net/http"
"fmt"
"text/template"
config "../../config"
"strconv"
"encoding/json"
datatables "../../datatables"
login "../../login"
"strings"
)
type Profile struct {
Message string // error status output or validated data
Status bool //pass or fail
ID string
}... | (w http.ResponseWriter, r *http.Request) {
login.Session_renew(w,r)
if r.Method =="GET" {
tconf := make(map[string]string)
tconf["h_id"] = r.URL.Query().Get("h_id")
tconf["delete_url"] = "/administrator/member_role/HDeleteHandler"
tmpl := template.New("modal_delete_loghdr.html")
var err error
... | HDeleteHandler | identifier_name |
header.go | package member_role
import (
"net/http"
"fmt"
"text/template"
config "../../config"
"strconv"
"encoding/json"
datatables "../../datatables"
login "../../login"
"strings"
)
type Profile struct {
Message string // error status output or validated data
Status bool //pass or fail
ID string
}... |
func HEditHandler(w http.ResponseWriter, r *http.Request) {
login.Session_renew(w,r)
rights :=r.URL.Query().Get("rights")
Org_id :=login.Get_session_org_id(r)
str_OrgID :=strconv.Itoa(Org_id)
//rights :="rights"
if r.Method =="GET" {
username, _ := login.Get_account_info(r)
tconf := make(map[string]s... | {
//db_raw ,err, _,_ := config.Ap_sql(`LBR_OTHdr_Get 1 ,`+Hdr_id,1)
db_raw ,err, _,_ := config.Ap_sql(`dailysumhdr_get 1,`+Hdr_id,1)
if err != nil {
panic(err.Error())
}
var r Dailysumhdr_get
for db_raw.Next() {
err = db_raw.Scan(&r.ID, &r.Branch,&r.Docdate,&r.Remarks)
if err != ... | identifier_body |
header.go | package member_role
import (
"net/http"
"fmt"
"text/template"
config "../../config"
"strconv"
"encoding/json"
datatables "../../datatables"
login "../../login"
"strings"
)
type Profile struct {
Message string // error status output or validated data
Status bool //pass or fail
ID string
}... |
}
//edit here
type LBR_OTHdr struct{
ID int
Status string
Trandate interface{}
Lbr_assign int
Remarks interface{}
}
type Dailysumhdr_get struct{
ID int
Branch interface{}
Docdate interface{}
Remarks interface{}
}
func LBR_OTHdr_Get_id( Hdr_id string ) Dailysumhdr_get {
//db_raw ,err, _,_ :... | {
r.ParseForm()
item_id := r.Form["item_id"][0]
username, _ := login.Get_account_info(r)
Org_id :=login.Get_session_org_id(r)
str_OrgID :=strconv.Itoa(Org_id)
var returnData[] string
for key ,_ := range r.Form["tag"] {
tag := r.Form["tag"][key]
value_input := r.Form["value_input"][key]
remarks ... | conditional_block |
main.rs | extern crate byteorder;
///Used to get screen resolution.
extern crate screenshot;
extern crate inputbot;
extern crate ron;
extern crate bincode;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use prelude::*;
use std::{
net::{TcpStream},
io::{self,BufRead,BufReader},
fs::{File},
cmp::{Ordering},
... | impl Default for Config {
fn default()->Config {
let screen_res=get_screen_resolution();
Config{
target: Rect{min: pair!(_=>0),max: screen_res},
source: Rect{min: pair!(_=>0.05),max: pair!(_=>0.95)},
clip: Rect{min: pair!(_=>0),max: screen_res},
correct_device_orientation: true,
... | ///Whether to attempt to do ADB port forwarding automatically.
///The android device needs to have `USB Debugging` enabled.
pub android_attempt_usb_connection: bool,
} | random_line_split |
main.rs | extern crate byteorder;
///Used to get screen resolution.
extern crate screenshot;
extern crate inputbot;
extern crate ron;
extern crate bincode;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use prelude::*;
use std::{
net::{TcpStream},
io::{self,BufRead,BufReader},
fs::{File},
cmp::{Ordering},
... | //Parse arguments
let exec_path;
let cfg_path;
{
let mut args=env::args();
exec_path=args.next().expect("first argument should always be executable path!");
cfg_path=args.next().unwrap_or_else(|| String::from("config.txt"));
}
//Load configuration
let config=Config::load_path(&cfg_path);
... | identifier_body | |
main.rs | extern crate byteorder;
///Used to get screen resolution.
extern crate screenshot;
extern crate inputbot;
extern crate ron;
extern crate bincode;
#[macro_use]
extern crate serde_derive;
extern crate serde;
use prelude::*;
use std::{
net::{TcpStream},
io::{self,BufRead,BufReader},
fs::{File},
cmp::{Ordering},
... | AsRef<Path>>(path: P,config: &Config)->Result<()> {
use std::process::{Command};
let local_port=match config.remote {
Remote::Tcp(_,port)=>port,
_ => {
println!("not connecting through tcp, skipping adb port forwarding");
return Ok(())
},
};
println!("attempting to adb port forward u... | _adb_forward<P: | identifier_name |
offset-monitor.rs | extern crate kafka;
extern crate getopts;
extern crate env_logger;
extern crate time;
#[macro_use]
extern crate error_chain;
use std::ascii::AsciiExt;
use std::cmp;
use std::env;
use std::io::{self, stdout, stderr, BufWriter, Write};
use std::process;
use std::thread;
use std::time as stdtime;
use kafka::client::{Kaf... | let _ = write!(self.fmt_buf, "({})", curr_lag);
let _ = write!(self.out_buf, " {1:<0$}", self.lag_width, self.fmt_buf);
}
} else {
for p in partitions {
let _ = write!(self.out_buf, " {1:>0$}", self.offset_width, p.c... | self.fmt_buf.clear(); | random_line_split |
offset-monitor.rs | extern crate kafka;
extern crate getopts;
extern crate env_logger;
extern crate time;
#[macro_use]
extern crate error_chain;
use std::ascii::AsciiExt;
use std::cmp;
use std::env;
use std::io::{self, stdout, stderr, BufWriter, Write};
use std::process;
use std::thread;
use std::time as stdtime;
use kafka::client::{Kaf... | {
prev_latest: i64,
curr_latest: i64,
curr_lag: i64,
}
impl Default for Partition {
fn default() -> Self {
Partition {
prev_latest: -1,
curr_latest: -1,
curr_lag: -1,
}
}
}
struct State {
offsets: Vec<Partition>,
lag_decr: i64,
}
impl S... | Partition | identifier_name |
offset-monitor.rs | extern crate kafka;
extern crate getopts;
extern crate env_logger;
extern crate time;
#[macro_use]
extern crate error_chain;
use std::ascii::AsciiExt;
use std::cmp;
use std::env;
use std::io::{self, stdout, stderr, BufWriter, Write};
use std::process;
use std::thread;
use std::time as stdtime;
use kafka::client::{Kaf... |
fn print_head(&mut self, num_partitions: usize) -> Result<()> {
self.out_buf.clear();
{
// ~ format
use std::fmt::Write;
let _ = write!(self.out_buf, "{1:<0$}", self.time_width, "time");
if self.print_summary {
let _ = write!(self.out... | {
Printer {
out: out,
timefmt: "%H:%M:%S".into(),
fmt_buf: String::with_capacity(30),
out_buf: String::with_capacity(160),
time_width: 10,
offset_width: 11,
diff_width: 8,
lag_width: 6,
print_diff: cfg.di... | identifier_body |
export_animation.py | import argparse
import glob
import importlib
import inspect
import math
import os
import re
import subprocess
import sys
import moviepy.audio.fx.all as afx
import moviepy.video.fx.all as vfx
import numpy as np
from _appmanager import get_executable
from _shutil import format_time, get_time_str, getch, print2
from movi... |
if clip_info.start is not None:
clip = clip.set_start(clip_info.start)
# Adjust volume by keypoints
if len(clip_info.vol_keypoints) > 0:
clip = _adjust_mpy_audio_clip_volume(clip, clip_info.vol_keypoints)
clips.append(clip)
if ... | if clip_info.loop:
# pylint: disable=maybe-no-member
clip = clip.fx(afx.audio_loop, duration=duration)
else:
duration = min(duration, clip.duration)
if clip_info.subclip:
duration = min(
... | conditional_block |
export_animation.py | import argparse
import glob
import importlib
import inspect
import math
import os
import re
import subprocess
import sys
import moviepy.audio.fx.all as afx
import moviepy.video.fx.all as vfx
import numpy as np
from _appmanager import get_executable
from _shutil import format_time, get_time_str, getch, print2
from movi... | os.chdir(os.path.dirname(os.path.abspath(file)))
_parse_text(s)
os.chdir(cwd)
def _remove_unused_recordings(s):
used_recordings = set()
unused_recordings = []
apis = {"record": (lambda f, **kargs: used_recordings.add(f))}
_parse_text(s, apis=apis)
files = [f for f in glob.glob("recor... | s = f.read()
cwd = os.getcwd() | random_line_split |
export_animation.py | import argparse
import glob
import importlib
import inspect
import math
import os
import re
import subprocess
import sys
import moviepy.audio.fx.all as afx
import moviepy.video.fx.all as vfx
import numpy as np
from _appmanager import get_executable
from _shutil import format_time, get_time_str, getch, print2
from movi... |
def _parse_text(text, apis=core.apis, **kwargs):
def find_next(text, needle, p):
pos = text.find(needle, p)
if pos < 0:
pos = len(text)
return pos
# Remove all comments
text = re.sub(r"<!--[\d\D]*?-->", "", text)
p = 0 # Current position
while p < len(text):... | used_recordings = set()
unused_recordings = []
apis = {"record": (lambda f, **kargs: used_recordings.add(f))}
_parse_text(s, apis=apis)
files = [f for f in glob.glob("record/*") if os.path.isfile(f)]
files = [f.replace("\\", "/") for f in files]
for f in files:
if f not in used_record... | identifier_body |
export_animation.py | import argparse
import glob
import importlib
import inspect
import math
import os
import re
import subprocess
import sys
import moviepy.audio.fx.all as afx
import moviepy.video.fx.all as vfx
import numpy as np
from _appmanager import get_executable
from _shutil import format_time, get_time_str, getch, print2
from movi... | (text, apis=core.apis, **kwargs):
def find_next(text, needle, p):
pos = text.find(needle, p)
if pos < 0:
pos = len(text)
return pos
# Remove all comments
text = re.sub(r"<!--[\d\D]*?-->", "", text)
p = 0 # Current position
while p < len(text):
if text[p... | _parse_text | identifier_name |
mock.rs | // Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... |
pub(crate) fn events() -> Vec<pallet::Event<Test>> {
System::events()
.into_iter()
.map(|r| r.event)
.filter_map(|e| if let Event::Stake(inner) = e { Some(inner) } else { None })
.collect::<Vec<_>>()
}
// Same storage changes as EventHandler::note_author impl
pub(crate) fn set_author(round: u32, acc: u64, p... | {
System::events().pop().expect("Event expected").event
} | identifier_body |
mock.rs | // Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | type Block = frame_system::mocking::MockBlock<Test>;
// Configure a mock runtime to test the pallet.
construct_runtime!(
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage, Event<T>},
Timestamp: pallet_timest... | pub type Balance = u128;
pub type BlockNumber = u64;
type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>; | random_line_split |
mock.rs | // Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | <Ks: OpaqueKeys>(_: bool, keys: &[(u64, Ks)], _: &[(u64, Ks)]) {
SessionChangeBlock::set(System::block_number());
dbg!(keys.len());
SessionHandlerCollators::set(keys.iter().map(|(a, _)| *a).collect::<Vec<_>>())
}
fn on_before_session_ending() {}
fn on_disabled(_: u32) {}
}
impl pallet_session::Config for Te... | on_new_session | identifier_name |
mock.rs | // Copyright 2019-2021 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.... | )
.collect::<Vec<_>>()
}
// Same storage changes as EventHandler::note_author impl
pub(crate) fn set_author(round: u32, acc: u64, pts: u32) {
<Points<Test>>::mutate(round, |p| *p += pts);
<AwardedPts<Test>>::mutate(round, acc, |p| *p += pts);
}
#[test]
fn geneses() {
ExtBuilder::default()
.with_balances(vec![
... | { None } | conditional_block |
test_agent.py | """Run this file to train the User Agent"""
from __future__ import absolute_import, division, print_function
import argparse
import os
from functools import reduce
from math import log
from tqdm import tqdm
from kg_env import BatchKGEnvironment
from train_agent import ActorCritic
from utils import *
def evaluate(... |
new_path = path + [(relation, next_node_type, next_node_id)]
new_path_pool.append(new_path)
new_probs_pool.append(probs + [p])
path_pool = new_path_pool
probs_pool = new_probs_pool
if hop < 2:
state_pool = env._batch_get_state(path_poo... | next_node_type = KG_RELATION[path[-1][1]][relation] | conditional_block |
test_agent.py | """Run this file to train the User Agent"""
from __future__ import absolute_import, division, print_function
import argparse
import os
from functools import reduce
from math import log
from tqdm import tqdm
from kg_env import BatchKGEnvironment
from train_agent import ActorCritic
from utils import *
def evaluate(... | uid = path[0][2]
if uid not in pred_paths:
continue
pid = path[-1][2]
if pid not in pred_paths[uid]:
pred_paths[uid][pid] = []
path_score = scores[uid][pid]
path_prob = reduce(lambda x, y: x * y, probs)
pred_paths[uid][pid].append((path_sco... | random_line_split | |
test_agent.py | """Run this file to train the User Agent"""
from __future__ import absolute_import, division, print_function
import argparse
import os
from functools import reduce
from math import log
from tqdm import tqdm
from kg_env import BatchKGEnvironment
from train_agent import ActorCritic
from utils import *
def evaluate(... |
def batch_beam_search(env, model, uids, device, topk=[25, 5, 1]):
def _batch_acts_to_masks(batch_acts):
batch_masks = []
for acts in batch_acts:
num_acts = len(acts)
act_mask = np.zeros(model.act_dim, dtype=np.uint8)
act_mask[:num_acts] = 1
batch_ma... | """Compute metrics for predicted recommendations.
Args:
topk_matches: a list or dict of product ids in ascending order.
"""
invalid_users = []
# Compute metrics
precisions, recalls, ndcgs, hits, fairness = [], [], [], [], []
test_user_idxs = list(test_user_products.keys())
for uid in... | identifier_body |
test_agent.py | """Run this file to train the User Agent"""
from __future__ import absolute_import, division, print_function
import argparse
import os
from functools import reduce
from math import log
from tqdm import tqdm
from kg_env import BatchKGEnvironment
from train_agent import ActorCritic
from utils import *
def evaluate(... | (batch_acts):
batch_masks = []
for acts in batch_acts:
num_acts = len(acts)
act_mask = np.zeros(model.act_dim, dtype=np.uint8)
act_mask[:num_acts] = 1
batch_masks.append(act_mask)
return np.vstack(batch_masks)
state_pool = env.reset(uids) # n... | _batch_acts_to_masks | identifier_name |
non_blocking.rs | //! A non-blocking, off-thread writer.
//!
//! This spawns a dedicated worker thread which is responsible for writing log
//! lines to the provided writer. When a line is written using the returned
//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
//! written by the worker thread.
//!
//! The q... | (&mut self, buf: &[u8]) -> std::io::Result<usize> {
let buf_len = buf.len();
let _ = self.tx.send(String::from_utf8_lossy(buf).to_string());
Ok(buf_len)
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[test]
fn backpressure... | write | identifier_name |
non_blocking.rs | //! A non-blocking, off-thread writer.
//!
//! This spawns a dedicated worker thread which is responsible for writing log
//! lines to the provided writer. When a line is written using the returned
//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
//! written by the worker thread.
//!
//! The q... |
Ok(buf_size)
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
#[inline]
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
self.write(buf).map(|_| ())
}
}
impl<'a> MakeWriter<'a> for NonBlocking {
type Writer = NonBlocking;
fn make_writer(&'a self) -> ... | {
return match self.channel.send(Msg::Line(buf.to_vec())) {
Ok(_) => Ok(buf_size),
Err(_) => Err(io::Error::from(io::ErrorKind::Other)),
};
} | conditional_block |
non_blocking.rs | //! A non-blocking, off-thread writer.
//!
//! This spawns a dedicated worker thread which is responsible for writing log
//! lines to the provided writer. When a line is written using the returned
//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
//! written by the worker thread.
//!
//! The q... | ///
/// By default, the built `NonBlocking` will be lossy.
pub fn lossy(mut self, is_lossy: bool) -> NonBlockingBuilder {
self.is_lossy = is_lossy;
self
}
/// Override the worker thread's name.
///
/// The default worker thread name is "tracing-appender".
pub fn thread_n... | random_line_split | |
non_blocking.rs | //! A non-blocking, off-thread writer.
//!
//! This spawns a dedicated worker thread which is responsible for writing log
//! lines to the provided writer. When a line is written using the returned
//! `NonBlocking` struct's `make_writer` method, it will be enqueued to be
//! written by the worker thread.
//!
//! The q... |
/// Override the worker thread's name.
///
/// The default worker thread name is "tracing-appender".
pub fn thread_name(mut self, name: &str) -> NonBlockingBuilder {
self.thread_name = name.to_string();
self
}
/// Completes the builder, returning the configured `NonBlocking`.
... | {
self.is_lossy = is_lossy;
self
} | identifier_body |
key.rs | //! Protected key
//!
use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState};
use std::fmt::{self, Debug};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator};
use buf::ProtBuf;
/// Key of bytes
pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>;... |
}
/// An RAII protected key with write access
///
/// This instance is the result of a `write` request on a `ProtKey`. Its
/// raw memory may only be written during the lifetime of this object.
pub struct ProtKeyWrite<'a, T: Copy + 'a, A: KeyAllocator + 'a> {
ref_key: RefMut<'a, ProtBuf<T, A>>,
}
impl<'a, T: Co... | {
self.ref_key.fmt(f)
} | identifier_body |
key.rs | //! Protected key
//!
use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState};
use std::fmt::{self, Debug};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator};
use buf::ProtBuf;
/// Key of bytes
pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>;... | }
impl<'a, T: Copy, A: KeyAllocator> Drop for ProtKeyRead<'a, T, A> {
fn drop(&mut self) {
self.read_ctr.set(self.read_ctr.get().checked_sub(1).unwrap());
if self.read_ctr.get() == NOREAD {
unsafe {
<A as KeyAllocator>::protect_none(
self.ref_key.as_p... | pub fn clone_it(&self) -> ProtKeyRead<T, A> {
ProtKeyRead::new(Ref::clone(&self.ref_key), self.read_ctr.clone())
} | random_line_split |
key.rs | //! Protected key
//!
use std::cell::{Cell, Ref, RefCell, RefMut, BorrowState};
use std::fmt::{self, Debug};
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use allocator::{Allocator, KeyAllocator, DefaultKeyAllocator};
use buf::ProtBuf;
/// Key of bytes
pub type ProtKey8<A = DefaultKeyAllocator> = ProtKey<u8, A>;... | (&self) -> ProtKey<T, A> {
ProtKey::new(self.read().clone())
}
}
impl<T: Copy, A: KeyAllocator> PartialEq for ProtKey<T, A> {
fn eq(&self, other: &ProtKey<T, A>) -> bool {
match (self.try_read(), other.try_read()) {
(Some(ref s), Some(ref o)) => *s == *o,
(_, _) => false... | clone | identifier_name |
laptop.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: laptop.proto
package pc
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/... |
return ""
}
func init() {
proto.RegisterType((*Laptop)(nil), "pc.Laptop")
proto.RegisterType((*CreateLaptopRequest)(nil), "pc.CreateLaptopRequest")
proto.RegisterType((*CreateLaptopResponse)(nil), "pc.CreateLaptopResponse")
}
func init() {
proto.RegisterFile("laptop.proto", fileDescriptor_28a7e4886f546705)
}
v... | {
return m.ID
} | conditional_block |
laptop.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: laptop.proto
package pc
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/... | func (m *CreateLaptopResponse) Reset() { *m = CreateLaptopResponse{} }
func (m *CreateLaptopResponse) String() string { return proto.CompactTextString(m) }
func (*CreateLaptopResponse) ProtoMessage() {}
func (*CreateLaptopResponse) Descriptor() ([]byte, []int) {
return fileDescriptor_28a7e4886f546705, []int... | random_line_split | |
laptop.pb.go | // Code generated by protoc-gen-go. DO NOT EDIT.
// source: laptop.proto
package pc
import (
context "context"
fmt "fmt"
proto "github.com/golang/protobuf/proto"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/... | () *Screen {
if m != nil {
return m.Screen
}
return nil
}
func (m *Laptop) GetKeyboard() *Keyboard {
if m != nil {
return m.Keyboard
}
return nil
}
type isLaptop_Weight interface {
isLaptop_Weight()
}
type Laptop_WeightKg struct {
WeightKg float64 `protobuf:"fixed64,10,opt,name=weight_kg,json=weightKg,pr... | GetScreen | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.