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 |
|---|---|---|---|---|
views.py | SetNewPasswordSerializer, PhoneNumberSerializer, OtpSerializer)
from rest_framework.response import Response
from .models import User, Customer, Admin
from django.db import transaction
from django.contrib.auth import logout
from rest_framework_simplejwt.tokens import RefreshToken
from .utils i... | (self, request):
user = request.data
serializer = self.serializer_class(data=user)
serializer.is_valid(raise_exception=True)
return Response(serializer.data, status.HTTP_200_OK)
class LogoutView(generics.GenericAPIView):
serializer_class = LogoutSerializer
def post(self, requ... | post | identifier_name |
entryfile.go | }
//!! return nil
//!! }
func ExtractKeyFromRawBytes(b []byte) []byte {
bb := b[4:]
if (bb[0]&bb[1]&bb[2]&bb[3]) == 0xFF { // No MagicBytes to recover
length := int(binary.LittleEndian.Uint32(bb[4:8]))
return append([]byte{}, bb[8:8+length]...)
}
bb = append([]byte{}, b[4:]...)
n := recoverMagicBytes(bb)
bb... |
func ExtractSerialNum(entryBz []byte) int64 {
return int64(binary.LittleEndian.Uint64(entryBz[len(entryBz)-8:]))
}
func UpdateSerialNum(entryBz []byte, sn int64) {
binary.LittleEndian.PutUint64(entryBz[len(entryBz)-8:], uint64(sn))
}
func SNListToBytes(deactivedSerialNumList []int64) []byte {
res := make([]byte,... | {
bb := b[4:]
if (bb[0]&bb[1]&bb[2]&bb[3]) == 0xFF { // No MagicBytes to recover
e, _ := EntryFromBytes(bb[4:], 0)
return e
}
bb = append([]byte{}, b[4:]...)
n := recoverMagicBytes(bb)
e, _ := EntryFromBytes(bb[n+4:], 0)
return e
} | identifier_body |
entryfile.go | }
//!! return nil
//!! }
func ExtractKeyFromRawBytes(b []byte) []byte {
bb := b[4:]
if (bb[0]&bb[1]&bb[2]&bb[3]) == 0xFF { // No MagicBytes to recover
length := int(binary.LittleEndian.Uint32(bb[4:8]))
return append([]byte{}, bb[8:8+length]...)
}
bb = append([]byte{}, b[4:]...)
n := recoverMagicBytes(bb)
bb... |
allpos = append(allpos, pos+start)
}
return
}
func EntryFromBytes(b []byte, numberOfSN int) (*Entry, []int64) {
entry := &Entry{}
i := 0
length := int(binary.LittleEndian.Uint32(b[i : i+4]))
i += 4
entry.Key = b[i:i+length]
i += length
length = int(binary.LittleEndian.Uint32(b[i : i+4]))
i += 4
entry.V... | {
return
} | conditional_block |
entryfile.go | FromRawBytes(b []byte) *Entry {
bb := b[4:]
if (bb[0]&bb[1]&bb[2]&bb[3]) == 0xFF { // No MagicBytes to recover
e, _ := EntryFromBytes(bb[4:], 0)
return e
}
bb = append([]byte{}, b[4:]...)
n := recoverMagicBytes(bb)
e, _ := EntryFromBytes(bb[n+4:], 0)
return e
}
func ExtractSerialNum(entryBz []byte) int64 {
... | recoverMagicBytes | identifier_name | |
entryfile.go | activedSerialNumList)*8)
//!! }
PutUint24(b[1:4], uint32(length-4-len(deactivedSerialNumList)*8))
binary.LittleEndian.PutUint32(b[4:8], ^uint32(0))
return b
}
// if magicBytesPosList is not empty:
var zeroBuf [8]byte
for _, pos := range magicBytesPosList {
copy(b[start+pos:start+pos+8], zeroBuf[:]) // ov... | }
func (ef *EntryFile) Close() {
err := ef.HPFile.Close() | random_line_split | |
app_treasure_huanliang.py | pid'), 'productName': e.get('pname'), 'sd': sd, 'ed': ed
}
url = 'https://e.qq.com/atlas/%s/report/order?ptype=20&pid=%s&pname=%s' % (self.uid, e.get('pid'), quote(e.get('pname')))
self.d.get(url)
time.sleep(0.5)
if page_version == 'new': # 版本判断
... | ms=ms, ye=ye | identifier_name | |
app_treasure_huanliang.py | origin': "https://e.qq.com",
'referer': None,
'Cache-Control': "no-cache",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
class AppTreasureHL(TaskProcess):
def __init__(self, user_info, **kwargs):
... | ght, picname))
# 恢复
# u.pag.hotkey('ctrl', '0', interval=0.3)
else:
return {'succ': True}
def get_data_process(self, dates):
# 获取上个月到现在每天的数据
err_list, res, data_list, has_data_in_two_mth = [], None, [], []
for sd, ed in dates:
... | ], e['pname'], cut_res['msg']))
logger.info('height: %s ---picname: %s' % (hei | conditional_block |
app_treasure_huanliang.py | 'Content-Type': "application/x-www-form-urlencoded",
'cookie': None,
'origin': "https://e.qq.com",
'referer': None,
'Cache-Control': "no-cache",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36"
}
class A... | logger = None
page_version = 'old'
base_header = {
'Accept': "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
| random_line_split | |
app_treasure_huanliang.py | ("document.querySelector('.button-more').click()")
else:
self.wait_element(By.LINK_TEXT, '查看报表', ec=EC.presence_of_element_located).click()
time.sleep(2)
# if page_version != 'new':
# u.pag.hotkey('ctrl', '-', interval=0.3)
# 调整分页数量... | get_data_res:
self.result_kwargs['has_data'] = 0
return {'succ': True}
| identifier_body | |
meta.py | __(self):
# Hold codewords for threads as we store them.
self.asmwords = {}
self.codewords = {}
self.datawords = {}
# Initialize the space.
self.space = EvenStringIO()
self.bootloader()
self.lib()
def bootloader(self):
"""
Set up th... | raise Exception("Can't reference unknown word %r" % word)
self.space.write(pack(">H", self.asmwords["exit"]))
ma = MetaAssembler()
# Deep primitives.
ma.prim("read", read(A))
ma.prim("write", write(A))
# Top of the line: Go back to the beginning of the string.
ucode = assemble(SET, B, 0x0)... | """
Assemble a thread of words into the core.
Here's what a thread looks like:
|prev|len |name|ENTER|word|EXIT|
"""
print "Adding Forth thread %s" % name
self.create(name, flags)
# ENTER/DOCOL bytecode.
ucode = assemble(SET, PC, self.asmwords["enter"])... | identifier_body |
meta.py | __(self):
# Hold codewords for threads as we store them.
self.asmwords = {}
self.codewords = {}
self.datawords = {}
# Initialize the space.
self.space = EvenStringIO()
self.bootloader()
self.lib()
def bootloader(self):
"""
Set up th... | (loop):
return loop + ["0nbranch", len(loop)]
# Main stack manipulation.
ucode = assemble(SET, PUSH, Z)
ma.asm("dup", ucode)
# Return stack manipulation.
ucode = _push(0xd000)
ma.asm("r0", ucode)
ucode = _push(Y)
ma.asm("rsp@", | UNTIL | identifier_name |
meta.py | words, flags=None):
"""
Assemble a thread of words into the core.
Here's what a thread looks like:
|prev|len |name|ENTER|word|EXIT|
"""
print "Adding Forth thread %s" % name
self.create(name, flags)
# ENTER/DOCOL bytecode.
ucode = assemble(SET... | preamble = assemble(SET, A, [ma.HERE]) | random_line_split | |
meta.py | __(self):
# Hold codewords for threads as we store them.
self.asmwords = {}
self.codewords = {}
self.datawords = {}
# Initialize the space.
self.space = EvenStringIO()
self.bootloader()
self.lib()
def bootloader(self):
"""
Set up th... |
def finalize(self):
# Write HERE and LATEST.
location = self.space.tell()
here = pack(">H", location)
latest = pack(">H", self.previous)
self.space.seek(self.HERE)
self.space.write(here)
self.space.seek(self.LATEST)
self.space.write(latest)
... | print "Adding library function", name
self.library[name] = self.space.tell()
self.space.write(library[name]()) | conditional_block |
template.go | .Rendering.ChartsDir) == 0 {
return path.Join(common.Config.Rendering.ResourceDir, "helm", v.String())
}
return path.Join(common.Config.Rendering.ChartsDir, v.String())
}
// GetTemplatesDir returns the location of the Operator templates files
func (v Ver) GetUserTemplatesDir() string {
if len(common.Config.Render... | profile, profiles, err := v.getSMCPProfile(profileName, targetNamespace)
if err != nil {
return *smcp, err
}
if log.V(5).Enabled() {
rawValues, _ := yaml.Marshal(profile)
log.V(5).Info(fmt.Sprintf("profile values:\n%s\n", string(rawValues)))
rawValues, _ = yaml.Marshal(smcp)
log.V(5).Info(fmt.Sp... | }
log.Info(fmt.Sprintf("processing smcp profile %s", profileName))
| random_line_split |
template.go | ] = mergeValues(baseKeyAsMap, inputAsMap)
}
}
}
return base
}
func (v Ver) getSMCPProfile(name string, targetNamespace string) (*v1.ControlPlaneSpec, []string, error) {
if strings.Contains(name, "/") {
return nil, nil, fmt.Errorf("profile name contains invalid character '/'")
}
profileContent, err := iout... | {
return enabled
} | conditional_block | |
template.go | .ChartsDir) == 0 {
return path.Join(common.Config.Rendering.ResourceDir, "helm", v.String())
}
return path.Join(common.Config.Rendering.ChartsDir, v.String())
}
// GetTemplatesDir returns the location of the Operator templates files
func (v Ver) GetUserTemplatesDir() string {
if len(common.Config.Rendering.UserTe... |
func updateOauthProxyConfig(ctx context.Context, cr *common.ControllerResources, smcpSpec *v1.ControlPlaneSpec) error {
if !common.Config.OAuthProxy.Query || len(common.Config.OAuthProxy.Name) == 0 || len(common.Config.OAuthProxy.Namespace) == 0 {
return nil
}
log := common.LogFromContext(ctx)
is := &imagev1.Im... | {
log := common.LogFromContext(ctx)
log.Info("updating image names for disconnected install")
var err error
if err = v.Strategy().SetImageValues(ctx, cr, &smcpSpec); err != nil {
return smcpSpec, err
}
err = updateOauthProxyConfig(ctx, cr, &smcpSpec)
return smcpSpec, err
} | identifier_body |
template.go | 't want to overrwrite base.
// If both are values, again, ignore it since we don't want to overrwrite base.
if baseKeyAsMap, baseOK := base[key].(map[string]interface{}); baseOK {
if inputAsMap, inputOK := value.(map[string]interface{}); inputOK {
base[key] = mergeValues(baseKeyAsMap, inputAsMap)
}
}
}... | isEnabled | identifier_name | |
auto.go | Req)
scanReq.SetHostList(hostList)
scanResp, err := NetworkScan(ctx, client, scanReq)
if err != nil {
return nil, err
}
if len(scanResp.GetHostErrors()) > 0 {
return nil, &ConfigGenerateError{HostErrorsResp: scanResp.HostErrorsResp}
}
// verify homogeneous network
switch len(scanResp.HostFabrics) {
case... | return nil, errors.New("storage hardware not consistent across hosts")
}
storageSet := scanResp.HostStorage[scanResp.HostStorage.Keys()[0]]
log.Debugf("Storage hardware is consistent for hosts %s:\n\t%s\n\t%s",
storageSet.HostSet.String(), storageSet.HostStorage.ScmNamespaces.Summary(),
storageSet.HostStorag... | log.Info(hss.HostSet.String())
}
| random_line_split |
auto.go | return nil, err
}
nd.numaIfaces = numaIfaces
return nd, nil
}
// getStorageSet retrieves the result of storage scan over host list and
// verifies that there is only a single storage set in response which indicates
// that storage hardware setup is homogeneous across all hosts.
//
// Filter NVMe storage scan so o... | {
return nil, err
} | conditional_block | |
auto.go | (err error) bool {
_, ok := errors.Cause(err).(*ConfigGenerateError)
return ok
}
// ConfigGenerate attempts to automatically detect hardware and generate a DAOS
// server config file for a set of hosts with homogeneous hardware setup.
//
// Returns API response or error.
func ConfigGenerate(ctx context.Context, req ... | IsConfigGenerateError | identifier_name | |
auto.go |
// GetHostErrors returns the wrapped HostErrorsMap.
func (cge *ConfigGenerateError) GetHostErrors() HostErrorsMap {
return cge.HostErrors
}
// IsConfigGenerateError returns true if the provided error is a *ConfigGenerateError.
func IsConfigGenerateError(err error) bool {
_, ok := errors.Cause(err).(*ConfigGenerate... | {
return cge.Errors().Error()
} | identifier_body | |
core-tracing.d.ts | to created Span names.
*/
packagePrefix: string;
/**
* Service namespace
*
* NOTE: if this is empty no `az.namespace` attribute will be added to created Spans.
*/
namespace: string;
}
/**
* An Exception for a Span.
*/
export declare type Exception = ExceptionWithCo... | * if type is TimeInput and 3rd param is undefined
* @param startTime - start time of the event.
*/
addEvent(name: string, attributesOrStartTime?: SpanAttributes | TimeInput, startTime?: TimeInput): this;
/**
* Sets a status to the span. If used, this will override the default Span
... | * associated with this event. Can be also a start time
| random_line_split |
lex.go | )
}
if isalpha(c) {
for isalpha(in[i]) {
i++
}
lx.sym(i)
switch lx.tok {
case "union":
lx.tok = "struct"
case "NULL":
lx.tok = "nil"
}
yy.str = lx.tok
if t := tokId[lx.tok]; t != 0 {
return int(t)
}
yy.decl = lx.lookupDecl(lx.tok)
if yy.decl != nil && yy.decl.Storage&Typedef != 0 ... | Swap | identifier_name | |
lex.go | Lsh,
'>': tokRsh,
'=': tokEqEq,
'+': tokInc,
'-': tokDec,
'&': tokAndAnd,
'|': tokOrOr,
}
var tokTokEq = [256]int32{
'<': tokLshEq,
'>': tokRshEq,
}
var tokId = map[string]int32{
"auto": tokAuto,
"break": tokBreak,
"case": tokCase,
"char": tokChar,
"const": tokConst,
"continue": tokCon... | // tags = [ "a",
// "b" ], # comment
// | random_line_split | |
lex.go |
type lexInput struct {
wholeInput string
input string
tok string
lastsym string
file string
lineno int
column int
systemHeader bool // inside a system header file
}
func (lx *lexer) pos() Pos {
if lx.forcePos.Line != 0 {
return lx.forcePos
}
return Pos{lx.file,... | {
if lx.wholeInput == "" {
lx.wholeInput = lx.input
}
if lx.comments == nil {
lx.comments = make(map[Pos]Comment)
}
yyParse(lx)
} | identifier_body | |
lex.go | || in[i] == '.' || 'A' <= in[i] && in[i] <= 'Z' || 'a' <= in[i] && in[i] <= 'z' || (in[i] == '+' || in[i] == '-') && (in[i-1] == 'e' || in[i-1] == 'E') {
i++
}
lx.sym(i)
yy.str = lx.tok
return tokNumber
case '/':
switch in[1] {
case '*':
if strings.HasPrefix(in, "/*c2go") {
lx.skip(6)
lx.c2... | {
lx.enum(y)
} | conditional_block | |
stream.rs | , duration: Duration) -> Self {
self.interval = Box::new(interval(duration));
self
}
/// Alias for Box::pin, must be called in order to pin the stream and be able
/// to call `next` on it.
pub fn stream(self) -> Pin<Box<Self>> {
Box::pin(self)
}
}
// Pattern for flattening ... | if watch_received.len() == num_txs && sub_received.len() == num_txs { | random_line_split | |
stream.rs | 0);
enum FilterWatcherState<'a, R> {
WaitForInterval,
GetFilterChanges(PinBoxFut<'a, Vec<R>>),
NextItem(IntoIter<R>),
}
#[must_use = "filters do nothing unless you stream them"]
#[pin_project]
/// Streams data from an installed filter via `eth_getFilterChanges`
pub struct | <'a, P, R> {
/// The filter's installed id on the ethereum node
pub id: U256,
provider: &'a Provider<P>,
// The polling interval
interval: Box<dyn Stream<Item = ()> + Send + Unpin>,
state: FilterWatcherState<'a, R>,
}
impl<'a, P, R> FilterWatcher<'a, P, R>
where
P: JsonRpcClient,
R: ... | FilterWatcher | identifier_name |
HttpHelper.ts | GET', URL + url, true);
// if (cc.sys.isNative) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS');
xhr.setRequestHeader('... | readyState === 3 && xhr.status != 200) {
let data = this.doDecode(xhr.responseText);
callback(data);
}
//console.log('respone '+xhr.status);
}.bind(this);
console.log("[HTTP>POST]:URL>>>>>>>>>>>>>>>>>",URL+url," params "+JSON.stringify(params) )... | let data = this.doDecode(xhr.responseText);
callback(data);
}else if(xhr. | conditional_block |
HttpHelper.ts | .getConfig().isCD(path)
if(isCD)
{
return;
}
let url = G_RequestControl.getConfig().getURL(path)
let xhr = cc.loader.getXMLHttpRequest();
xhr.onreadystatechange = function () {
console.log("xhr.readyState "+xhr.readyState + " xhr.status == 200 ... | if (cryptData != undefined) {
var cryptDataArr = cryptData.split("hDdoAPaXI3S");
if (cryptDataArr.length == 3) {
var cryptDataStr = cryptDataArr[0];
var privateKey = "-----BEGIN PRIVATE KEY-----MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAPTYUA2oNnnEwCM+firQE... | identifier_body | |
HttpHelper.ts | GET', URL + url, true);
// if (cc.sys.isNative) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.setRequestHeader('Access-Control-Allow-Methods', 'GET,POST,PUT,OPTIONS');
xhr.setRequestHeader('... | }
/**
* AES加密数组 传入参数为需要传递的数组JSON
*/
AES_encrypt(data,KEY,IV,pkcs8_public) {
console.log("typeof data ",typeof(data));
var key_utf8 = CryptoJS.enc.Utf8.parse(KEY);// 秘钥
var iv_utf8= CryptoJS.enc.Utf8.parse(IV);//向量iv
let srcs = ''
... | }
return pwd; | random_line_split |
HttpHelper.ts | (path){
if(this.lastTime == null)
{
this.lastTime = new Date().getTime();
console.log("Time--------------------------->",path," ",0);
}else
{
let tt = new Date().getTime() - this.lastTime;
//this.lastTime = new Date().getTime();
... | cd | identifier_name | |
run_squad.py | _ in range(2):
f, g = lcs_match(max_dist, example.paragraph_text, tok_cat_text)
if f[n - 1, m - 1] > 0.8 * n:
break
max_dist *= 2
# Get the mapping from orgin text/tokenized text to tokenized text/origin text
orig_to_chartok_index = [None] * n
chartok_to_orig_index = [N... | ain() | identifier_name | |
run_squad.py | start_position', 'end_position', 'paragraph_text', 'paragraph_len', 'is_impossible'
])
def convert_examples_to_features(example, tokenizer=None, cls_token=None, sep_token=None,
vocab=None, max_seq_length=384, doc_stride=128,
max_query_length=64, is_tra... | "split an array into equal pieces"""
# TODO Replace this function with gluon.utils.split_data() once targeting MXNet 1.7
size = arr.shape[0]
if size < num_of_splits:
return [arr[i:i + 1] for i in range(size)]
slice_len, rest = divmod(size, num_of_splits)
div_points = [0] + [(slice_len * inde... | identifier_body | |
run_squad.py | .wd}
try:
trainer = mx.gluon.Trainer(net.collect_params(), args.optimizer, optimizer_params,
update_on_kvstore=False)
except ValueError as _:
warnings.warn('AdamW optimizer is not found. Please consider upgrading to '
'mxnet>=1.5.0. Now th... | scores_diff_json = collections.OrderedDict() | random_line_split | |
run_squad.py |
if pretrained_xlnet_parameters and args.model_parameters:
raise ValueError('Cannot provide both pre-trained BERT parameters and '
'BertForQA model parameters.')
ctx = [mx.cpu(0)] if not args.gpu else [mx.gpu(i) for i in range(args.gpu)]
log_interval = args.log_interval * args.accumulate if a... | sitions = [(len(seq_feature[0]) - 1, len(seq_feature[0]) - 1)
for seq_feature in seq_features]
| conditional_block | |
fix-md-dialect.py | } ]
def push_indent(self, n, new_type) :
#Increment the logical depth only if under a bullet type. This fixes problem #3.
level = self.logical_indent_level() + (self.current_type() == "bullet") # plus 1 if true
self.my_stack.append( {'physical':n, 'logical':level, 'type':new_type} )
... | # Now swap out the bad href for the fixed one in inputline. | random_line_split | |
fix-md-dialect.py | in auto-generated anchor text for Headings.
EXCLUDED_CHARS_REGEX_GHM = r'[^\w\-]' # all non-alphanumerics except "-" and "_". Whitespace are previously converted.
EXCLUDED_CHARS_REGEX_DOX = r'[^\w\.\-]' # all non-alphanumerics except "-", "_", and ".". Whitespace are previously converted.
def report_error(s) :
... | (s) :
# Courtesy of Python, this does a real column-aware tab expansion.
# If this doesn't work, we'll need to go back to erroring on " \t", that is, spaces followed by tabs.
trace("orig length {0}".format(len(s)) )
ct = s.count("\t")
s = s.expandtabs(4)
trace("after {0} tab substitutions, end l... | convert_tabs | identifier_name |
fix-md-dialect.py | in auto-generated anchor text for Headings.
EXCLUDED_CHARS_REGEX_GHM = r'[^\w\-]' # all non-alphanumerics except "-" and "_". Whitespace are previously converted.
EXCLUDED_CHARS_REGEX_DOX = r'[^\w\.\-]' # all non-alphanumerics except "-", "_", and ".". Whitespace are previously converted.
def report_error(s) :
... | return self.my_stack.pop()['physical']
else :
return 0
def current_indent(self) :
# top of stack, physical
return self.my_stack[-1]['physical']
def logical_indent_level(self) :
# top of stack, logical
return self.my_stack[-1]['logical']
def ... | 'This class maintains the indent stack during doc parsing.'
def __init__(self) :
self.my_stack = [ {'physical' : 0, 'logical' : 0, 'type' : 'none' } ]
def init_indent(self) :
del self.my_stack
self.my_stack = [ {'physical' : 0, 'logical' : 0, 'type' : 'none' } ]
def push_indent(se... | identifier_body |
fix-md-dialect.py | in auto-generated anchor text for Headings.
EXCLUDED_CHARS_REGEX_GHM = r'[^\w\-]' # all non-alphanumerics except "-" and "_". Whitespace are previously converted.
EXCLUDED_CHARS_REGEX_DOX = r'[^\w\.\-]' # all non-alphanumerics except "-", "_", and ".". Whitespace are previously converted.
def report_error(s) :
... |
for linkitem in links :
pieces = re.search(r'(\[[\s`]*)([^\]]*[^\s`\]])([\s`]*\]\([\s]*)([^\s]+)([\s]*\))', linkitem).groups()
trace("Link: " + linkitem)
trace("Pieces: " + " ".join( (pieces[0],pieces[1],pieces[2],pieces[3],pieces[4]) ))
labeltext = pieces[1]
href = pieces[... | report_error("Found link split across multiple lines. We can't process this.") | conditional_block |
utils.js | /**
* Wait until google map loader disappear
* @param {Puppeteer.Page} page
* @return {Promise<void>}
*/
const waitForGoogleMapLoader = async (page) => {
if (await page.$('#searchbox')) {
// @ts-ignore
await page.waitForFunction(() => !document.querySelector('#searchbox')
.classList.... | const { DEFAULT_TIMEOUT } = require('./consts');
const { log } = Apify.utils;
| random_line_split | |
utils.js | = (float) => Number(float.toFixed(7));
/**
* @param {any} result
* @param {boolean} isAdvertisement
*/
const parsePaginationResult = (result, isAdvertisement) => {
// index 14 has detailed data about each place
const detailInfoIndex = isAdvertisement ? 15 : 14;
const place = result[detailInfoIndex];
... |
return;
}
const waitingFor = Date.now() - start;
if (waitingFor > timeout) {
throw new Error(timeoutErrorMeesage || `Timeout reached when waiting for predicate for ${waitingFor} ms`);
}
await new Promise((resolve) => setTimeout(resolve, pollInterval));
... | {
log.info(successMessage);
} | conditional_block |
Flask_Server.py | .request
import cv2
import requests
from PIL import Image
from io import BytesIO
modelFullPath = '/tmp/output_graph.pb' # 읽어들일 graph 파일 경로
labelsFullPath = '/tmp/output_labels.txt' # 읽어들일 labels 파일 경로
# imagePath = /tmp/test.jpg # 추론을 진행할 이미지 경로
app = Fla... | d == 'POST':
# 파라미터를 전달 받습니다.
tagImg = []
backImg = []
# imageSrc = request.form['avg_img']
imageSrc = request.json['imgs']
print(imageSrc)
create_graph()
imageType = ['tagImg', 'backImg']
for imgType in imageType:
p... | metho | identifier_name |
Flask_Server.py | .request
import cv2
import requests
from PIL import Image
from io import BytesIO
modelFullPath = '/tmp/output_graph.pb' # 읽어들일 graph 파일 경로
labelsFullPath = '/tmp/output_labels.txt' # 읽어들일 labels 파일 경로
# imagePath = /tmp/test.jpg # 추론을 진행할 이미지 경로
app = Fla... |
# print(image)
elif info.get_content_subtype() == 'gif':
# print("gif file임")
img = BytesIO(resp.read())
img = Image.open(img)
mypalette = img.getpalett... | Img.append(run_inference_on_image(image))
| conditional_block |
Flask_Server.py | .request
import cv2
import requests
from PIL import Image
from io import BytesIO
modelFullPath = '/tmp/output_graph.pb' # 읽어들일 graph 파일 경로
labelsFullPath = '/tmp/output_labels.txt' # 읽어들일 labels 파일 경로
# imagePath = /tmp/test.jpg # 추론을 진행할 이미지 경로
app = Fla... | return answer
###############################################################################
# image_data = tf.gfile.FastGFile(imagePath, 'rb').read()
# url = "https://ssl.pstatic.net/tveta/libs/1240/1240155/1b47a8d4e3229d9531cf_20190510121017466.png"
###################... | 'rb') as f:
print("create_grpah()")
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
# print('finish create_graph()')
with tf.device('/gpu:0'):
def run_inference_on_image(image):
# if not tf.gfile... | identifier_body |
Flask_Server.py | .request
import cv2
import requests
from PIL import Image
from io import BytesIO
modelFullPath = '/tmp/output_graph.pb' # 읽어들일 graph 파일 경로
labelsFullPath = '/tmp/output_labels.txt' # 읽어들일 labels 파일 경로
# imagePath = /tmp/test.jpg # 추론을 진행할 이미지 경로
app = Fla... |
# Api.add_resource(T)
@app.route("/", methods=['GET', 'POST'])
def index():
if request.method == 'GET':
return render_template('index.html')
if request.method == 'POST':
# 파라미터를 전달 받습니다.
tagImg = []
backImg = []
# imageSrc = request.form['avg_img']
... | # r"*": {"origin" : "*"},
# })
# api = Api(app)
| random_line_split |
mallSwitcherDao.go | status = 0 WHERE id = ? and userid = ?`
_, err := db.Exec(updateSQL, userid, collectionid)
if nil != err {
log.Println(err)
return err
}
return nil
}
// 获取机器状态
func getMachineDao(machineid int, db *sql.DB) (Machine, error) {
var m Machine
selectSQL := `select id,machineid,shopid,slotnum,runstate,netstate,ma... | log.Println(err)
return m, err
}
return m, err
}
// 实体机器商品展示
func insertMachineTaskDao(machineid, userid, shopid, goodsid, slotid int, tx *sql.Tx) error {
// 增加机器任务sql
insertSQL := `insert into machinetask (machineid,shopid,userid,goodsid,slotid) values (?, ?, ?, ?, ?)`
_, err := tx.Exec(insertSQL, machineid,... | random_line_split | |
mallSwitcherDao.go | c.GoodsName = goodsName
c.Style = style
c.Unit = unit
c.Price = price
c.Width = width
c.Height = height
c.CompressPic = compressPic
c.ScenesURL = scenesURL
collection = append(collection, c)
}
return collection, err
}
// 用户增加收藏
func insertCollectionD
ao(userid, shopid, goodsid int, collectionType,... | ws, err := db.Query(selectSQL)
if err != nil {
log.Println(err)
return collection, err
}
defer rows.Close()
for rows.Next() {
var c Collection
var id, goodsID int
var collectionType, goodsName, style, unit, price, width, height, compressPic, scenesURL string
err := rows.Scan(&id, &goodsID, &collection... | identifier_body | |
mallSwitcherDao.go | status = 0 WHERE id = ? and userid = ?`
_, err := db.Exec(updateSQL, userid, collectionid)
if nil != err {
log.Println(err)
return err
}
return nil
}
// 获取机器状态
func getMachineDao(machineid int, db *sql.DB) (Machine, error) {
var m Machine
selectSQL := `select id,machineid,shopid,slotnum,runstate,netstate,ma... | nil {
log.Println(err)
return ACOS, err
}
defer rows.Close()
for rows.Next() {
var ACO AllClassOne
err := rows.Scan(&ACO.ID, &ACO.MenuName, &ACO.SuperID)
if err != nil {
log.Println(err)
return ACOS, err
}
ACOS = append(ACOS, ACO)
}
return ACOS, err
}
// 全部分类查询(二级分类查询 带图片数量)
func getAllClassi... | ery(selectSQL, shopid)
if err != | conditional_block |
mallSwitcherDao.go | status = 0 WHERE id = ? and userid = ?`
_, err := db.Exec(updateSQL, userid, collectionid)
if nil != err {
log.Println(err)
return err
}
return nil
}
// 获取机器状态
func getMachineDao(machineid int, db *sql.DB) (Machine, error) {
var m Machine
selectSQL := `select id,machineid,shopid,slotnum,runstate,netstate,ma... | Location, &SCI.Lng, &SCI.Lat)
if err != nil {
return "查询失败", err
}
return SCI, err
}
// 全部分类查询(一级分类查询)
func getAllClassifyOne(shopid string, db *sql.DB) ([]AllClassOne, error) {
var ACOS []AllClassOne
selectSQL := "select id, menuname, superid from menu where state = 1 and superid = 0 and shopid = ?"
rows, err... | I.Wechaturl, &SCI. | identifier_name |
nb_10_DogcatcherFlatten.py | on="name")
df["LA_length"] = df["LA_end"] - df["LA_start"]
df = df.drop_duplicates(subset=['name'],keep="first")
return df
def getAreas(df):
"""
This function will get the first and last exons for plu and min strand.
Call it area because not necessarily exon.
"""
df_plu = df[df["stran... | (df):
"""This function will take a gtf and return strand specific dictionary of different chrm"""
chr_names=df['chr'].unique().tolist()
d_chr = d_gtf_chr = {chrom : df[df["chr"]==chrom] for chrom in chr_names}
return d_chr
def countInside(df, start, end):
rows_df = df[ (start < df["start"]) & (df["... | chrDIC | identifier_name |
nb_10_DogcatcherFlatten.py | on="name")
df["LA_length"] = df["LA_end"] - df["LA_start"]
df = df.drop_duplicates(subset=['name'],keep="first")
return df
def getAreas(df):
"""
This function will get the first and last exons for plu and min strand.
Call it area because not necessarily exon.
"""
df_plu = df[df["stran... | ("chr11","NC_000011.10"),
("chr12","NC_000012.12"),
("chr13","NC_000013.11"),
("chr14","NC_000014.9"),
("chr15","NC_000015.10"),
("chr16","NC_000016.10"),
("chr17","NC_000017.11"),
("chr18","NC_000018.10"),
("chr19","NC_000019.10"),
("chr20... | print(f"Flattening REFSEQGFF like genome")
# https://ftp.ncbi.nlm.nih.gov/genomes/refseq/vertebrate_mammalian/Homo_sapiens/reference/
#download this GCF_000001405.39_GRCh38.p13_genomic.gtf.gz
# sort and index in IGV
# NC_000001.11 BestRefSeq gene 11874 14409 . + . gene_id "DDX11L1"; transcript_... | conditional_block |
nb_10_DogcatcherFlatten.py | ="name")
df["LA_length"] = df["LA_end"] - df["LA_start"]
df = df.drop_duplicates(subset=['name'],keep="first")
return df
def getAreas(df):
"""
This function will get the first and last exons for plu and min strand.
Call it area because not necessarily exon.
"""
df_plu = df[df["strand"... | df_gene = df_gene[["name","gene_start","gene_end"]].copy()
df = pd.merge(df,df_gene,how="left",on="name")
df = getAreas(df)
df["start"] = df["gene_start"]
df["end"] = df["gene_end"]
# df = df[["chr","start","end","strand | random_line_split | |
nb_10_DogcatcherFlatten.py | on="name")
df["LA_length"] = df["LA_end"] - df["LA_start"]
df = df.drop_duplicates(subset=['name'],keep="first")
return df
def getAreas(df):
"""
This function will get the first and last exons for plu and min strand.
Call it area because not necessarily exon.
"""
df_plu = df[df["stran... |
def removeInside(df):
d_chr = chrDIC(df)
df['genes_inside'] = df.apply(lambda row: countInside(d_chr[row['chr']], row["start"], row["end"]), axis=1)
df2 = df.dropna(subset=['genes_inside'])
all_names = []
for i in range(len(df2)):
names = df2["genes_inside"].iloc[i]
names = names.... | rows_df = df[ (start < df["start"]) & (df["end"] < end) ]
names = rows_df['name'].unique().tolist()
names = ",".join(names)
if len(names) >0:
return names
else:
return np.nan | identifier_body |
lib.rs | | None, required |
//! | `table` | Table your model belongs to | `crate::schema::cities` | None, required |
//! | `connection` | The connection type your app uses | `MysqlConnection` | `diesel::pg::PgConnection` |
//! | `id` | The type of your table's primary key | `i64` | `i32` |
//! | `id_name` | The name of your ta... | type Model;
| random_line_split | |
lib.rs | countries
//! .filter(identity.eq(&input))
//! .first::<Country>(con)
//! .unwrap()
//! }
//! ```
//!
//! ## `#[derive(Factory)]`
//!
//! ### Attributes
//!
//! These attributes are available on the struct itself inside `#[factory(...)]`.
//!
//! | Name | Description | Example | Default |
/... | {
let model = factory.clone().insert(con);
F::id_for_model(&model).clone()
} | conditional_block | |
lib.rs | (con: &PgConnection) -> i64 {
//! use crate::schema::cities;
//! use diesel::dsl::count_star;
//! cities::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn count_countries(con: &PgConnection) -> i64 {
//! use crate::schema::countries;
//! use diesel::dsl::count_star;
//! countries:... | {
Association::Model(inner)
} | identifier_body | |
lib.rs | use crate::schema::countries;
//! use diesel::dsl::count_star;
//! countries::table.select(count_star()).first(con).unwrap()
//! }
//!
//! fn find_country_by_id(input: i32, con: &PgConnection) -> Country {
//! use crate::schema::countries::dsl::*;
//! countries
//! .filter(identity.eq(&input))
... | insert_returning_id | identifier_name | |
msi.py | Type(self.attributes & 0xF00)
except Exception:
return MsiType.Unknown
@property
def is_integer(self) -> bool:
return self.attributes & 0x0F00 < 0x800
@property
def is_key(self) -> bool:
return self.attributes & 0x2000 == 0x2000
@property
def i... |
processed_table_data: Dict[str, List[Dict[str, str]]] = {}
tbl_properties: Dict[str, str] = {}
tbl_files: Dict[str, str] = {}
tbl_components: Dict[str, str] = {}
postprocessing: List[ScriptItem] = []
def format_string(string: str):
# https://learn.... | row_index: int
extension: Optional[str] | identifier_body |
msi.py | Type(self.attributes & 0xF00)
except Exception:
return MsiType.Unknown
@property
def is_integer(self) -> bool:
return self.attributes & 0x0F00 < 0x800
@property
def is_key(self) -> bool:
return self.attributes & 0x2000 == 0x2000
@property
def i... |
table_names_given = {strings.ref(k) for k in chunks.unpack(stream('!_Tables'), 2, False)}
table_names_known = set(tables)
for name in table_names_known - table_names_given:
self.log_warn(F'table name known but not given: {name}')
for name in table_names_given - tabl... | tbl_name = strings.ref(tbl_name_id)
col_name = strings.ref(col_name_id)
tables[tbl_name][col_name] = MSITableColumnInfo(col_number, col_attributes) | conditional_block |
msi.py | Type(self.attributes & 0xF00)
except Exception:
return MsiType.Unknown
@property
def is_integer(self) -> bool:
return self.attributes & 0x0F00 < 0x800
@property
def is_key(self) -> bool:
return self.attributes & 0x2000 == 0x2000
@property
def i... | table_names_given = {strings.ref(k) for k in chunks.unpack(stream('!_Tables'), 2, False)}
table_names_known = set(tables)
for name in table_names_known - table_names_given:
self.log_warn(F'table name known but not given: {name}')
for name in table_names_given - table_na... | tables[tbl_name][col_name] = MSITableColumnInfo(col_number, col_attributes)
| random_line_split |
msi.py | Type(self.attributes & 0xF00)
except Exception:
return MsiType.Unknown
@property
def is_integer(self) -> bool:
return self.attributes & 0x0F00 < 0x800
@property
def is_key(self) -> bool:
return self.attributes & 0x2000 == 0x2000
@property
def | (self) -> bool:
return self.attributes & 0x1000 == 0x1000
@property
def length(self) -> int:
vt = self.type
if vt is MsiType.Long:
return 4
if vt is MsiType.Short:
return 2
return self.attributes & 0xFF
@property
def struct_f... | is_nullable | identifier_name |
readpanel.py | (filename,samples,triggers,display,plot):
global dcvoltages
fout = open(os.path.join(rundir,filename),"r")
allts = []
deltats = []
data = fout.read()
if len(data) < 12:
print "No data found"
return
data = data.split('\n')
data = filter(lambda x: len(x)>0, data)
data = [(int(i,16... | plotfile | identifier_name | |
readpanel.py | gtimeold = -1
htimeold = -1
ctimeold = -1
latestold = 0
for itrig in range(triggers):
if (itrig+1)*(samples+12) > len(data):
break
tdata = data[itrig*(samples+12):(itrig+1)*(samples+12)]
channel = (tdata[3] >> 6) & 0x3F
gtime = ((tdata[0]<<24) + (tdata[1]... | global dcvoltages
fout = open(os.path.join(rundir,filename),"r")
allts = []
deltats = []
data = fout.read()
if len(data) < 12:
print "No data found"
return
data = data.split('\n')
data = filter(lambda x: len(x)>0, data)
data = [(int(i,16) & 0xFFF) for i in data]
print len(data),... | identifier_body | |
readpanel.py | 3FFFFF00) + (0xFF - (htime&0xFF));
ctime = (ctime & 0x3FFFFF00) + (0xFF - (ctime&0xFF));
hvfired = 0
calfired = 0
if htime > 0 and htime != htimeold:
hvfired = 1
if ctime > 0 and ctime != ctimeold:
calfired = 1
adc1 = tdata[12:]
T1.append(htime)
... |
if outline.startswith("HV")>0:
hvenvdata = outline.split()[-3:]
if outline.startswith("FAILED") or outline.startswith("SUCCESS") or outline.startswith("Channel 15") or outline.startswith("HV"):
return 0
# data taking mode
eli... | calenvdata = outline.split()[-3:] | conditional_block |
readpanel.py |
def showdata(y):
SampleRate = 20
nplot = 200
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_title("Data")
ax1.set_xlabel('ns')
ax1.set_ylabel('ADC counts')
x=range(0,SampleRate*len(y),SampleRate)
# y2 = y[:]
# for i in range(len(y)):
# y[i] = ... | import matplotlib
import matplotlib.pyplot as plt
import math
import rlcompleter
import datetime
| random_line_split | |
light_character.py | ) > 1:
save_options = {
"format": "GIF",
"save_all": True,
"append_images": frames[1:],
"duration": durations,
"loop": 0
}
if base_img is None:
# If this is just a block light, these settings allow "Off"
# to be ... | (pattern):
"""
Crack a pattern definition into its type and any grouping.
A pattern consists of the pattern type (e.g. flashing, occulting)
and optionally a group designation in parentheses.
The pattern definition could just be the type
>>> parse_pattern('Fl')
('fl', [1])
It could ha... | parse_pattern | identifier_name |
light_character.py | # If this is just a block light, these settings allow "Off"
# to be fully transparent
# Leaving them in place for images with lighthouses
# can cause odd effects, due to combining palettes.
save_options.update(
{
"transparency": 0,
... | if period <= 2000:
raise ValueError(
"The cycle period for a flash must be longer than 2 seconds"
)
return [
(colour, 1000),
('Off', period-1000)
] | conditional_block | |
light_character.py | ) > 1:
save_options = {
"format": "GIF",
"save_all": True,
"append_images": frames[1:],
"duration": durations,
"loop": 0
}
if base_img is None:
# If this is just a block light, these settings allow "Off"
# to be ... | Composite groups are separated by an even period of darkness
>>> flash([3, 1], 'R', 10000)
[('R', 500), ('Off', 1000), ('R', 500), ('Off', 1000), ('R', 500),\
('Off', 1000), ('Off', 2000), ('R', 500), ('Off', 1000), ('Off', 2000)]
The total duration of all states matches the requested period
>>>... | [('R', 500), ('Off', 1000), ('R', 500), ('Off', 1000), ('R', 500),\
('Off', 1000), ('Off', 5500)]
| random_line_split |
light_character.py | ) > 1:
save_options = {
"format": "GIF",
"save_all": True,
"append_images": frames[1:],
"duration": durations,
"loop": 0
}
if base_img is None:
# If this is just a block light, these settings allow "Off"
# to be ... | >>> parse_period(['3s'])
3000
"""
period_spec = fragments[-1]
# The last term is the cycle period,
# it may or may not have 's' for seconds
# The 's' may or may not be attached to the number
if period_spec == 's':
period_spec = fragments[-2]
if period_spec[-1] == 's':
... | """
Given the split up characteristic, return the period in milliseconds
The period is specified in seconds
>>> parse_period(['2'])
2000
The letter 's' to mark the units may be present
>>> parse_period(['3s'])
3000
It may be separated from the number by a space
>>> parse_period... | identifier_body |
adapter_test.go | ID.")
}
var item2Chk optionType2
res := optionTypes.Find(db.Cond{"id": id})
err = res.One(&item2Chk)
assert.NoError(t, err)
assert.Equal(t, id.(int64), item2Chk.ID)
assert.Equal(t, item2Chk.Name, item2.Name)
assert.Equal(t, item2Chk.Tags[0], item2.Tags[0])
assert.Equal(t, len(item2Chk.Tags), len(item2.Tag... | cleanUpCheck | identifier_name | |
adapter_test.go | 5)
)`,
}
for _, s := range batch {
driver := sess.Driver().(*sql.DB)
if _, err := driver.Exec(s); err != nil {
return err
}
}
return nil
}
type customJSONB struct {
N string `json:"name"`
V float64 `json:"value"`
}
func (c customJSONB) Value() (driver.Value, error) {
return EncodeJSONB(c)
}
func... | PGType{},
PGType{
IntegerArray: []int64{1},
StringArray: []string{"a"},
},
PGType{
IntegerArray: []int64{0, 0, 0, 0},
StringValue: &testValue,
CustomJSONB: customJSONB{
N: "Hello",
},
StringArray: []string{"", "", "", ``, `""`},
},
PGType{
StringValue: &testValue,
},
PGType... | },
PGType{
IntegerArray: []int64{},
StringArray: []string{},
}, | random_line_split |
adapter_test.go | [0], item2.Tags[0])
assert.Equal(t, len(item2Chk.Tags), len(item2.Tags))
// Update the value
m := JSONBMap{}
m["lang"] = "javascript"
m["num"] = 31337
item2.Settings = &m
err = res.Update(item2)
assert.NoError(t, err)
err = res.One(&item2Chk)
assert.NoError(t, err)
assert.Equal(t, float64(31337), (*item2C... | {
return fmt.Errorf("Expecting active statements to be at most 128, got %d", activeStatements)
} | conditional_block | |
adapter_test.go | .Update(item2)
assert.NoError(t, err)
err = res.One(&item2Chk)
assert.NoError(t, err)
assert.Equal(t, float64(31337), (*item2Chk.Settings)["num"].(float64))
assert.Equal(t, "javascript", (*item2Chk.Settings)["lang"])
// An option type to pointer string array field
type optionType3 struct {
ID int64 ... | {
var stats map[string]int
stats, err = getStats(sess)
if err != nil {
return err
}
if activeStatements := sqladapter.NumActiveStatements(); activeStatements > 128 {
return fmt.Errorf("Expecting active statements to be at most 128, got %d", activeStatements)
}
sess.ClearCache()
stats, err = getStats(sess... | identifier_body | |
test_util.rs | (())
}
pub fn temp_file() -> PathBuf {
let path = std::env::temp_dir();
let file_name = random_string(16);
path.join(file_name + ".log")
}
pub fn temp_dir() -> PathBuf {
let path = std::env::temp_dir();
let dir_name = random_string(16);
path.join(dir_name)
}
pub fn random_lines_with_stream(
... | {
CountReceiver::new(|count, tripwire| async move {
let mut listener = tokio::net::UnixListener::bind(path).unwrap();
CountReceiver::receive_lines_stream(listener.incoming(), count, tripwire).await
})
} | identifier_body | |
test_util.rs | _| "off".to_string());
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_env_filter(env)
.finish();
let _ = tracing_log::LogTracer::init();
let _ = tracing::dispatcher::set_global_default(tracing::Dispatch::new(subscriber));
}
pub async fn send_lines(
addr: SocketAdd... | pub fn wait_for_tcp(addr: SocketAddr) {
wait_for(|| std::net::TcpStream::connect(addr).is_ok())
}
pub fn wait_for_atomic_usize<T, F>(val: T, unblock: F)
where
T: AsRef<AtomicUsize>,
F: Fn(usize) -> bool,
{
let val = val.as_ref();
wait_for(|| unblock(val.load(Ordering::SeqCst)))
}
pub fn shutdown_o... |
pub fn runtime() -> Runtime {
Runtime::single_threaded().unwrap()
}
| random_line_split |
test_util.rs | _| "off".to_string());
let subscriber = tracing_subscriber::FmtSubscriber::builder()
.with_env_filter(env)
.finish();
let _ = tracing_log::LogTracer::init();
let _ = tracing::dispatcher::set_global_default(tracing::Dispatch::new(subscriber));
}
pub async fn send_lines(
addr: SocketAdd... | (
len: usize,
breadth: usize,
depth: usize,
count: usize,
) -> (Vec<Event>, impl Stream01<Item = Event, Error = ()>) {
random_events_with_stream_generic(count, move || {
let mut log = LogEvent::default();
let tree = random_pseudonested_map(len, breadth, depth);
for (k, v) in... | random_nested_events_with_stream | identifier_name |
test_util.rs | FmtSubscriber::builder()
.with_env_filter(env)
.finish();
let _ = tracing_log::LogTracer::init();
let _ = tracing::dispatcher::set_global_default(tracing::Dispatch::new(subscriber));
}
pub async fn send_lines(
addr: SocketAddr,
lines: impl IntoIterator<Item = String>,
) -> Result<(), I... | {
panic!("Future already completed");
} | conditional_block | |
tree_entries.go | *treeEntriesTable) WithFilters(filters []sql.Expression) sql.Table {
nt := *r
nt.filters = filters
return &nt
}
func (r *treeEntriesTable) WithIndexLookup(idx sql.IndexLookup) sql.Table {
nt := *r
nt.index = idx
return &nt
}
func (r *treeEntriesTable) IndexLookup() sql.IndexLookup { return r.index }
func (r *t... | {
if i.trees != nil {
i.trees.Close()
}
if i.idx != nil {
i.idx.Close()
}
if i.repo != nil {
i.repo.Close()
}
return nil
} | identifier_body | |
tree_entries.go | )
func (treeEntriesTable) isSquashable() {}
func (treeEntriesTable) isGitbaseTable() {}
func (treeEntriesTable) Name() string {
return TreeEntriesTableName
}
func (treeEntriesTable) Schema() sql.Schema {
return TreeEntriesSchema
}
func (r *treeEntriesTable) WithFilters(filters []sql.Expression) sql.Table {
nt ... |
} else {
k.Offset = -1
if k.Hash, err = readHash(buf); err != nil {
return err
}
}
pos, err := readInt64(buf)
if err != nil {
return err
}
k.Pos = int(pos)
return nil
}
type treeEntriesKeyValueIter struct {
pool *RepositoryPool
repo *Repository
idx *repositoryIndex
trees *object.Tr... | {
return err
} | conditional_block |
tree_entries.go | func (treeEntriesTable) isGitbaseTable() {}
func (treeEntriesTable) Name() string {
return TreeEntriesTableName
}
func (treeEntriesTable) Schema() sql.Schema {
return TreeEntriesSchema
}
func (r *treeEntriesTable) WithFilters(filters []sql.Expression) sql.Table {
nt := *r
nt.filters = filters
return &nt
}
func... | Close | identifier_name | |
tree_entries.go | nil)
func (treeEntriesTable) isSquashable() {}
func (treeEntriesTable) isGitbaseTable() {}
func (treeEntriesTable) Name() string {
return TreeEntriesTableName
}
func (treeEntriesTable) Schema() sql.Schema {
return TreeEntriesSchema
}
func (r *treeEntriesTable) WithFilters(filters []sql.Expression) sql.Table {
... | }
}
func (i *treeEntriesRowIter) Close() error {
if i.iter != nil {
i.iter.Close()
}
i.repo.Close()
return nil
}
// TreeEntry is a tree entry object.
type TreeEntry struct {
TreeHash plumbing.Hash
object.TreeEntry
}
func treeEntryToRow(repoID string, entry *TreeEntry) sql.Row {
return sql.NewRow(
repoI... | entry := &TreeEntry{i.tree.Hash, i.tree.Entries[i.cursor]}
i.cursor++
return treeEntryToRow(i.repo.ID, entry), nil | random_line_split |
api_op_CancelZonalShift.go | to be active, which
// Route 53 ARC converts to an expiry time (expiration time). You can cancel a
// zonal shift, for example, if you're ready to restore traffic to the Availability
// Zone. Or you can update the zonal shift to specify another length of time to
// expire in.
//
// This member is required.
Expi... | {
return stack.Serialize.Insert(&opCancelZonalShiftResolveEndpointMiddleware{
EndpointResolver: options.EndpointResolverV2,
BuiltInResolver: &builtInResolver{
Region: options.Region,
UseDualStack: options.EndpointOptions.UseDualStackEndpoint,
UseFIPS: options.EndpointOptions.UseFIPSEndpoint,
... | identifier_body | |
api_op_CancelZonalShift.go | of a zonal shift.
//
// This member is required.
ZonalShiftId *string
noSmithyDocumentSerde
}
type CancelZonalShiftOutput struct {
// The Availability Zone that traffic is moved away from for a resource when you
// start a zonal shift. Until the zonal shift expires or you cancel it, traffic for
// the resour... | {
v4aScheme.SigningName = aws.String("arc-zonal-shift")
} | conditional_block | |
api_op_CancelZonalShift.go | in your AWS account in an AWS Region.
func (c *Client) CancelZonalShift(ctx context.Context, params *CancelZonalShiftInput, optFns ...func(*Options)) (*CancelZonalShiftOutput, error) {
if params == nil {
params = &CancelZonalShiftInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CancelZonalShift", param... | if err = addResolveEndpointMiddleware(stack, options); err != nil {
return err
}
if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
return err
}
if err = addRetryMiddlewares(stack, options); err != nil {
return err
}
if err = addHTTPSignerV4Middleware(stack, options); err != nil {
return ... | if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
return err
} | random_line_split |
api_op_CancelZonalShift.go | your AWS account in an AWS Region.
func (c *Client) | (ctx context.Context, params *CancelZonalShiftInput, optFns ...func(*Options)) (*CancelZonalShiftOutput, error) {
if params == nil {
params = &CancelZonalShiftInput{}
}
result, metadata, err := c.invokeOperation(ctx, "CancelZonalShift", params, optFns, c.addOperationCancelZonalShiftMiddlewares)
if err != nil {
... | CancelZonalShift | identifier_name |
admin_commands.go | Usage: "Delete any local sessions",
Action: s.Logout,
},
{
Name: "profile",
Usage: "Collects profile metrics from the node.",
Action: s.Profile,
Flags: []cli.Flag{
cli.Uint64Flag{
Name: "seconds, s",
Usage: "duration of profile capture",
Value: 8,
},
cli.StringFlag{
... |
// RenderTable implements TableRenderer
func (p *AdminUsersPresenter) RenderTable(rt RendererTable) error {
rows := [][]string{p.ToRow()}
renderList(adminUsersTableHeaders, rows, rt.Writer)
return utils.JustError(rt.Write([]byte("\n")))
}
type AdminUsersPresenters []AdminUsersPresenter
// RenderTable implement... | {
row := []string{
p.ID,
string(p.Role),
p.HasActiveApiToken,
p.CreatedAt.String(),
p.UpdatedAt.String(),
}
return row
} | identifier_body |
admin_commands.go | Usage: "Delete any local sessions",
Action: s.Logout,
},
{
Name: "profile",
Usage: "Collects profile metrics from the node.",
Action: s.Profile,
Flags: []cli.Flag{
cli.Uint64Flag{
Name: "seconds, s",
Usage: "duration of profile capture",
Value: 8,
},
cli.StringFlag{
... | () []string {
row := []string{
p.ID,
string(p.Role),
p.HasActiveApiToken,
p.CreatedAt.String(),
p.UpdatedAt.String(),
}
return row
}
// RenderTable implements TableRenderer
func (p *AdminUsersPresenter) RenderTable(rt RendererTable) error {
rows := [][]string{p.ToRow()}
renderList(adminUsersTableHeader... | ToRow | identifier_name |
admin_commands.go | Usage: "Delete any local sessions",
Action: s.Logout,
},
{
Name: "profile",
Usage: "Collects profile metrics from the node.",
Action: s.Profile,
Flags: []cli.Flag{
cli.Uint64Flag{
Name: "seconds, s",
Usage: "duration of profile capture",
Value: 8,
},
cli.StringFlag{
... |
for _, user := range users {
if strings.EqualFold(user.Email, c.String("email")) {
return s.errorOut(fmt.Errorf("user with email %s already exists", user.Email))
}
}
fmt.Println("Password of new user:")
pwd := s.PasswordPrompter.Prompt()
request := struct {
Email string `json:"email"`
Role str... | {
return s.errorOut(err)
} | conditional_block |
admin_commands.go | Usage: "Delete any local sessions",
Action: s.Logout,
},
{
Name: "profile",
Usage: "Collects profile metrics from the node.",
Action: s.Profile,
Flags: []cli.Flag{
cli.Uint64Flag{
Name: "seconds, s",
Usage: "duration of profile capture",
Value: 8,
},
cli.StringFlag{
... | {
Name: "chrole",
Usage: "Changes an API user's role",
Action: s.ChangeRole,
Flags: []cli.Flag{
cli.StringFlag{
Name: "email",
Usage: "email of user to be edited",
Required: true,
},
cli.StringFlag{
Name: "new-role, newrole",
Usa... | Usage: "Permission level of new user. Options: 'admin', 'edit', 'run', 'view'.",
Required: true,
},
},
}, | random_line_split |
classes.py | .new)
def responce(self):
response = []
for mail in self.get_new_mails():
response.append(mail.response())
return {"mails": response}
class UserBackground:
boss = 'начальник'
bssid = 'TPLink 0707'
email = ''
ldap = 'office'
def __init__(self, boss, bssid, ... | .text = text
self.link = link
def response(self):
return {
"tag": self.tag,
"text": self.text,
"link": self.link,
}
class Buff:
name = ""
cost = 0
description = ""
id = 0
@classmethod
def action(cls, client):
pass
clas... | self | identifier_name |
classes.py | .new)
def responce(self):
response = []
for mail in self.get_new_mails():
response.append(mail.response())
return {"mails": response}
class UserBackground:
boss = 'начальник'
bssid = 'TPLink 0707'
email = ''
ldap = 'office'
def __init__(self, boss, bssid, ... | self.state = Environment.states[0]
self.scores = 50
self.av_checked()
def response(self):
return {
"state": self.state['state'],
"cpu": self.state['cpu'],
"ram": self.state['ram'],
"network": self.state['network'],
"lastAvC... | random_line_split | |
classes.py | return len(self.new)
def responce(self):
response = []
for mail in self.get_new_mails():
response.append(mail.response())
return {"mails": response}
class UserBackground:
boss = 'начальник'
bssid = 'TPLink 0707'
email = ''
ldap = 'office'
def __in... | mails = {}
new = []
archive = []
def __init__(self):
pass
def add_new(self, mail):
self.new.append(mail)
self.mails[mail.id] = mail
def mail_processed(self, mail_id):
mail = self.mails[mail_id]
self.new.remove(mail)
self.archive.append(mail)
de... | identifier_body | |
classes.py | .new)
def responce(self):
response = []
for mail in self.get_new_mails():
response.append(mail.response())
return {"mails": response}
class UserBackground:
boss = 'начальник'
bssid = 'TPLink 0707'
email = ''
ldap = 'office'
def __init__(self, boss, bssid, ... | "id": self.id,
"header": self.header,
"text": self.text,
"sent": self.sent,
"receiver": self.receiver,
"date": self.date,
"attachments": self.attachments,
"actions": actions,
}
class Action:
id = 0
feedback... | ion.response())
return {
| conditional_block |
model.rs | izing_if = "Option::is_none")]
pub ca: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum NarStatus {
Pending,
Available,
Trashed,
}
impl Default for NarStatus {
fn default() -> Self {
Self::Pending
}
}
impl Nar {
fn ref_paths(&self) -> impl Iterator<Item = Re... | (&self) -> StorePathHash {
StorePathHash(
<[u8; StorePathHash::LEN]>::try_from(
self.path[Self::STORE_PREFIX.len()..Self::SEP_POS].as_bytes(),
)
.unwrap(),
)
}
pub fn name(&self) -> &str {
&self.path[Self::SEP_POS + 1..]
}
}
impl ... | hash | identifier_name |
model.rs | _if = "Option::is_none")]
pub ca: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum NarStatus {
Pending,
Available,
Trashed,
}
impl Default for NarStatus {
fn default() -> Self {
Self::Pending
}
}
impl Nar {
fn ref_paths(&self) -> impl Iterator<Item = Result<... |
pub fn root(&self) -> &str {
&Self::STORE_PREFIX[..Self::STORE_PREFIX.len() - 1]
}
pub fn hash_str(&self) -> &str {
&self.path[Self::STORE_PREFIX.len()..Self::SEP_POS]
}
pub fn hash(&self) -> StorePathHash {
StorePathHash(
<[u8; StorePathHash::LEN]>::try_from(... | {
&self.path
} | identifier_body |
model.rs | izing_if = "Option::is_none")]
pub ca: Option<String>,
}
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum NarStatus {
Pending,
Available,
Trashed,
}
impl Default for NarStatus {
fn default() -> Self {
Self::Pending
}
}
impl Nar {
fn ref_paths(&self) -> impl Iterator<Item = Re... | }
}
impl TryFrom<String> for StorePath {
type Error = Error;
// https://github.com/NixOS/nix/blob/abb8ef619ba2fab3ae16fb5b5430215905bac723/src/libstore/store-api.cc#L85
fn try_from(path: String) -> Result<Self, Self::Error> {
use failure::ensure;
fn is_valid_hash(s: &[u8]) -> bool {
... | }
pub fn name(&self) -> &str {
&self.path[Self::SEP_POS + 1..] | random_line_split |
main.rs | if let Some(faulty_trap_manifest) = f.traps() {
let trap_ptr = faulty_trap_manifest.traps.as_ptr();
let traps_count = faulty_trap_manifest.traps.len();
let traps_byte_count = traps_count * std::mem::size_of::<TrapSite>();
if let Some(traps_byte_slice) =
summary.read_memor... | {
imported_symbols.remove(idx);
} | conditional_block | |
main.rs | }
}
}
}
self.serialized_module = self.symbols.lucet_module.as_ref().map(|module_sym| {
let buffer = self
.read_memory(
module_sym.address(),
mem::size_of::<SerializedModule>() as u64,
... | Some(name) => {
println!(" ELF header name: {}", name);
}
None => {
println!(" No corresponding ELF symbol.");
}
};
break;
}
let colorize_name = |x: Option<&str>| match ... | " Function {} {}",
i,
"is missing the module data part of its declaration".red()
);
match header_name { | random_line_split |
main.rs | <'a> {
lucet_module: Option<object::read::Symbol<'a, 'a>>,
}
#[derive(Debug)]
struct DataSegments {
segments: Vec<DataSegment>,
}
#[derive(Debug)]
struct DataSegment {
offset: u32,
len: u32,
data: Vec<u8>,
}
impl<'a> ArtifactSummary<'a> {
fn new(buffer: &'a Vec<u8>, obj: &'a object::File<'_>)... | StandardSymbols | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.