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 |
|---|---|---|---|---|
hh.js | 'use strict';
require('test');
var tpl = Set.Class({
constructor: function() {
},
isCompress: false,
bound:{left:'{', right:'}'},
boundChar: '%',
command: {cond:1, echo:1, getv:1, code:1, for:0, foreach:0, if:3, elseif:3, else:3, html:0, block:0, head:0, body:0, phpend:0},
isN... | return render;
},
render: function (id, data) {
var cache = template.get(id) || _debug({
id: id,
name: 'Render Error',
message: 'No Template'
});
return cache(data);
},
mapFn: function(func) {
var partialTpl = '';
... | }
| random_line_split |
hh.js | 'use strict';
require('test');
var tpl = Set.Class({
constructor: function() {
},
isCompress: false,
bound:{left:'{', right:'}'},
boundChar: '%',
command: {cond:1, echo:1, getv:1, code:1, for:0, foreach:0, if:3, elseif:3, else:3, html:0, block:0, head:0, body:0, phpend:0},
isN... |
try {
return new Render(data, id) + ''; //运行时错误捕捉
} catch (e) {
_debug(e)();
throw(e);
}
}
render.prototype = Render.prototype;
render.toString = function () {
return Render.toString();
... | ta) {
| identifier_name |
translate_baidu.js | console.info("start document")
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
// listen for messages sent from background.js
if (request.message === 'url') {
if(!request.cookie){
//用户未登录
show_sign_in()
} else {
... | s('selected');
});
$(".option-menu .tag-item").mouseout((ev)=>{
$(ev.target).removeClass("selected");
});
$('.option-menu .tag-item').click((ev)=>{
$(ev.target).parent().find('.tag-item').removeClass('clicked');
$(ev.target).addClass('clicked');
let word_item=null
var tar... | ckground-color: ${tag_item.color}"></div>`)
}
})
$(".option-menu .tag-item").mouseover((ev)=>{
$(ev.target).addClas | conditional_block |
translate_baidu.js | console.info("start document")
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
// listen for messages sent from background.js
if (request.message === 'url') {
if(!request.cookie){
//用户未登录
show_sign_in()
} else {
... | ag_item)=>{
if(select_tag==tag_item.tag){
option_menu.append(`<div id="${tag_item.tag}" class="tag-item clicked" style="background-color: ${tag_item.color}"></div>`)
} else {
option_menu.append(`<div id="${tag_item.tag}" class="tag-item" style="background-color: ${tag_item.color}... | ms.forEach((t | identifier_name |
translate_baidu.js | console.info("start document")
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
// listen for messages sent from background.js
if (request.message === 'url') {
if(!request.cookie){
//用户未登录
show_sign_in()
} else {
... | r-settting")
if(user_setting.length){
user_setting.fadeOut("normal")
}
$(this).off("click")
} | identifier_body | |
translate_baidu.js | console.info("start document")
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
// listen for messages sent from background.js
if (request.message === 'url') {
if(!request.cookie){
//用户未登录
show_sign_in()
} else {
... | let user_setting=$(".user-settting")
if(user_setting.length){
user_setting.fadeOut("normal")
}
$(this).off("click")
} |
//点击外围让阴影层消失
function dismiss_user_setting(){
if (event.target.closest(".user-settting")) return; | random_line_split |
dict.js | $(function() {
var t = {
"Home": {
pt: "Início",
es: "Inicio",
},
"Watch instructions": {
pt: "Assista as instruções",
es: "Ver las instrucciones",
},
"Contact": {
pt: "Contato",
es: "Contacto",
},
"Arrival time": {
pt: "Tempo de chegada",
... | pt: "B: Bloqueado",
es: "B: Obstruido",
},
"Ready Queue":{
pt: "Fila de Pronto",
es: "Cola Ready",
},
"Blocked Queue":{
pt: "Fila de Bloqueado",
es: "Cola Locked",
},
"Run Statistics":{
pt: "Estatística de execução",
es: "Estadísticas de Ejecuci... | "B: Blocked":{ | random_line_split |
functional.py | from __future__ import division
import torch
import math
import random
from PIL import Image, ImageOps
try:
import accimage
except ImportError:
accimage = None
import numpy as np
import numbers
import types
import collections
from skimage.external import tifffile
from skimage import transform, filters, util
imp... |
def normalize(tensor, mean, std):
"""Normalize a tensor image with mean and standard deviation.
See ``Normalize`` for more details.
Args:
tensor (Tensor): Tensor image of size (C, H, W) to be normalized.
mean (sequence): Sequence of means for each channel.
std (sequence): Sequen... | if not (_is_numpy_image(pic) or _is_tensor_image(pic)):
raise TypeError('pic should be Tensor or ndarray. Got {}.'.format(type(pic)))
npimg = pic
if isinstance(pic, torch.FloatTensor):
if dtype == 'uint8':
npimg = (pic.numpy() * np.iinfo(np.uint8).max).astype(np.uint8)
elif ... | identifier_body |
functional.py | from __future__ import division
import torch
import math
import random
from PIL import Image, ImageOps
try:
import accimage
except ImportError:
accimage = None
import numpy as np
import numbers
import types
import collections
from skimage.external import tifffile
from skimage import transform, filters, util
imp... | (img):
return isinstance(img, np.ndarray) and (img.ndim in {2, 3})
def to_tensor(pic):
if not (_is_pil_image(pic) or _is_numpy_image(pic)):
raise TypeError('pic should be PIL Image or ndarray. Got {}'.format(type(pic)))
if isinstance(pic, np.ndarray):
# get max value of dtype, if the dtyp... | _is_numpy_image | identifier_name |
functional.py | from __future__ import division
import torch
import math
import random
from PIL import Image, ImageOps
try:
import accimage
except ImportError:
accimage = None
import numpy as np
import numbers
import types
import collections
from skimage.external import tifffile
from skimage import transform, filters, util
imp... |
# backward compatibility
return img.float().div(denominator)
if accimage is not None and isinstance(pic, accimage.Image):
nppic = np.zeros([pic.channels, pic.height, pic.width], dtype=np.float32)
pic.copyto(nppic)
return torch.from_numpy(nppic)
# handle PIL Image
i... | img = torch.from_numpy(pic.transpose((2, 0, 1))) | conditional_block |
functional.py | from __future__ import division
import torch
import math
import random
from PIL import Image, ImageOps
try:
import accimage
except ImportError:
accimage = None
import numpy as np
import numbers
import types
import collections
from skimage.external import tifffile
from skimage import transform, filters, util
imp... | img_new = (img_new * np.iinfo(np.int32).max).astype(np.int32)
else:
raise ValueError('not support type')
return img_new
def piecewise_transform(image, numcols=5, numrows=5, warp_left_right=10, warp_up_down=10, order=1):
"""2D piecewise affine transformation.
Control points are use... | img_new = filters.gaussian(img, sigma, multichannel)
if dtype == 'uint8':
print(img_new.max(), img_new.min())
img_new = (img_new * np.iinfo(np.uint8).max).astype(np.uint8)
elif dtype == 'uint16': | random_line_split |
eip.go | // Copyright 2019 Yunion
//
// 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 writi... | self.region.GetInstance(self.InstanceId); err == nil {
switch instance.InternetAccessible.InternetChargeType {
case InternetChargeTypeTrafficPostpaidByHour:
return api.EIP_CHARGE_TYPE_BY_TRAFFIC
default:
return api.EIP_CHARGE_TYPE_BY_BANDWIDTH
}
}
}
}
return api.EIP_CHARGE_TYPE_BY_TRAF... | redAt() time.Time {
return time.Time{}
}
func (self *SEipAddress) GetInternetChargeType() string {
if len(self.InstanceId) > 0 {
if strings.HasPrefix(self.InstanceId, "ins-") {
if instance, err := | conditional_block |
eip.go | // Copyright 2019 Yunion
//
// 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 writi... | func (self *SEipAddress) Associate(conf *cloudprovider.AssociateConfig) error {
err := self.region.AssociateEip(self.AddressId, conf.InstanceId)
if err != nil {
return err
}
if conf.Bandwidth > 0 {
err = self.region.UpdateInstanceBandwidth(conf.InstanceId, conf.Bandwidth)
if err != nil {
log.Warningf("fail... | RGE_TYPE_BY_TRAFFIC
}
| identifier_body |
eip.go | // Copyright 2019 Yunion
//
// 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 writi... | }
return api.EIP_CHARGE_TYPE_BY_TRAFFIC
}
func (self *SEipAddress) Associate(conf *cloudprovider.AssociateConfig) error {
err := self.region.AssociateEip(self.AddressId, conf.InstanceId)
if err != nil {
return err
}
if conf.Bandwidth > 0 {
err = self.region.UpdateInstanceBandwidth(conf.InstanceId, conf.Bandw... | }
} | random_line_split |
eip.go | // Copyright 2019 Yunion
//
// 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 writi... | UNBINDING:
return api.EIP_STATUS_DISSOCIATE
case EIP_STATUS_UNBIND, EIP_STATUS_BIND, EIP_STATUS_OFFLINING, EIP_STATUS_BIND_ENI:
return api.EIP_STATUS_READY
case EIP_STATUS_CREATE_FAILED:
return api.EIP_STATUS_ALLOCATE_FAIL
default:
return api.EIP_STATUS_UNKNOWN
}
}
func (self *SEipAddress) Refresh() error ... | ATUS_ | identifier_name |
parser.py | from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Tuple, Optional, List
import jmespath
import logging
import re
import yaml
from yaml import YAMLError
from checkov.cloudformation.parser import cfn_yaml
from checkov.cloudformation.context_parser import ContextParse... |
return s
block_start_index = 0
search_start_index = block_start_index
tokens = []
index = string.find(",", search_start_index)
while index > 0:
is_quoted = False
for quoted_comma_range in quoted_comma_ranges:
if index in quoted_comma_range:
is_qu... | s = s[1:-1] | conditional_block |
parser.py | from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Tuple, Optional, List
import jmespath
import logging
import re
import yaml
from yaml import YAMLError
from checkov.cloudformation.parser import cfn_yaml
from checkov.cloudformation.context_parser import ContextParse... | (file_location, file_data_cache, service_file_directory):
file_location = file_location.replace("~", str(Path.home()))
file_location = file_location if os.path.isabs(file_location) else \
os.path.join(service_file_directory, file_location)
data = file_data_cache.get(file_location)
if data is No... | _load_file_data | identifier_name |
parser.py | from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Tuple, Optional, List
import jmespath
import logging
import re
import yaml
from yaml import YAMLError
from checkov.cloudformation.parser import cfn_yaml
from checkov.cloudformation.context_parser import ContextParse... |
def process_variables_loop(template, var_pattern, param_lookup_function):
"""
Generic processing loop for variables.
:param template: The dictionary currently being processed. This function will
be called recursively starting at dict provided.
:param var... | """
Modifies the template data in-place to resolve variables.
"""
file_data_cache = {}
service_file_directory = os.path.dirname(filename)
var_pattern = jmespath.search("provider.variableSyntax", template)
if var_pattern is not None:
# Remove to prevent self-matching during processing
... | identifier_body |
parser.py | from __future__ import annotations
import json
import os
from pathlib import Path
from typing import Tuple, Optional, List
import jmespath
import logging
import re
import yaml
from yaml import YAMLError
from checkov.cloudformation.parser import cfn_yaml
from checkov.cloudformation.context_parser import ContextParse... | tokens.append(clean(string[block_start_index:]))
return tokens |
if block_start_index < len(string): | random_line_split |
context_test.go | // Copyright 2014 The Cockroach 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 ag... | {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop()
clock := hlc.NewClock(time.Unix(0, 1).UnixNano)
serverCtx := newNodeTestContext(clock, stopper)
_, ln := newTestServer(t, serverCtx, true)
remoteAddr := ln.Addr().String()
clientCtx := newNodeTestContext(clock, stopper)
// The... | identifier_body | |
context_test.go | // Copyright 2014 The Cockroach 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 ag... |
heartbeat.ready <- struct{}{} // Allow one heartbeat for initialization.
util.SucceedsSoon(t, func() error {
clientCtx.RemoteClocks.mu.Lock()
defer clientCtx.RemoteClocks.mu.Unlock()
if _, ok := clientCtx.RemoteClocks.mu.offsets[remoteAddr]; !ok {
return errors.Errorf("expected offset of %s to be initiali... | {
t.Fatal(err)
} | conditional_block |
context_test.go | // Copyright 2014 The Cockroach 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 ag... | nodeCtxs[i].ctx.HeartbeatInterval = maxOffset
s, ln := newTestServer(t, nodeCtxs[i].ctx, true)
RegisterHeartbeatServer(s, &HeartbeatService{
clock: clock,
remoteClockMonitor: nodeCtxs[i].ctx.RemoteClocks,
})
nodeCtxs[i].ctx.Addr = ln.Addr().String()
}
// Fully connect the nodes.
for i,... | clock := offsetClock(nodeCtxs[i].offset)
nodeCtxs[i].errChan = make(chan error, 1)
clock.SetMaxOffset(maxOffset)
nodeCtxs[i].ctx = newNodeTestContext(clock, stopper) | random_line_split |
context_test.go | // Copyright 2014 The Cockroach 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 ag... | () time.Duration {
v := ac.advancementInterval.Load()
if v == nil {
return 0
}
return v.(time.Duration)
}
func (ac *AdvancingClock) UnixNano() int64 {
ac.Lock()
time := ac.time
ac.time = time.Add(ac.getAdvancementInterval())
ac.Unlock()
return time.UnixNano()
}
func TestRemoteOffsetUnhealthy(t *testing.T) ... | getAdvancementInterval | identifier_name |
my_optimisation.py | import numpy as np
def app_products2optimisation(products):
# вес P — x1, к --x2
# c = [-250,-210] #Функция цели 250x1+210x2 – уменьшение расходов на продуктовую корзину ;
# A_ub = [[15,4]] #'1' жиры последовательно для Р и К
# b_ub = [14] #'1' 15x1+4x2 <=14 – ограничение количества жира;
# A_eq ... | conditional_block | ||
my_optimisation.py | import numpy as np
def app_products2optimisation(products):
# вес P — x1, к --x2
# c = [-250,-210] #Функция цели 250x1+210x2 – уменьшение расходов на продуктовую корзину ;
# A_ub = [[15,4]] #'1' жиры последовательно для Р и К
# b_ub = [14] #'1' 15x1+4x2 <=14 – ограничение количества жира;
# A_eq ... | е осталось отрицательных
min_bi = min(filled_table[:-1,-1])
if min_bi >= 0:
return False # Достигнут оптимум, переход к выводу
else:
return True # Необходимо пересчитать строку
def check_cj0(filled_table):
#Проверка условия: все ли элементы последней строки отрицательны, cj<=0
amoun... | олбце свободных членов н | identifier_name |
my_optimisation.py | import numpy as np
def app_products2optimisation(products):
# вес P — x1, к --x2
# c = [-250,-210] #Функция цели 250x1+210x2 – уменьшение расходов на продуктовую корзину ;
# A_ub = [[15,4]] #'1' жиры последовательно для Р и К
# b_ub = [14] #'1' 15x1+4x2 <=14 – ограничение количества жира;
# A_eq ... | for i, b in zip(col, last_column):
if i != 0 and b / i > 0:
division.append(b / i)
else:
division.append(10000)
index = division.index(min(division)) #наименьшее позитивное частное
return [index,min_in_row_column_number]
def row_choice(fil... | last_column = filled_table[:-1,-1] | random_line_split |
my_optimisation.py | import numpy as np
def app_products2optimisation(products):
# вес P — x1, к --x2
# c = [-250,-210] #Функция цели 250x1+210x2 – уменьшение расходов на продуктовую корзину ;
# A_ub = [[15,4]] #'1' жиры последовательно для Р и К
# b_ub = [14] #'1' 15x1+4x2 <=14 – ограничение количества жира;
# A_eq ... | ditions, :-1]) #+ 1 Возвращает индекс наибольшего элемента в слайсе [последняя строка, вся таблица без последнего столбца], добавляем 1 чтобы номер столбца был человекочитаемым
return min_cj_column_number
def bi_to_positive(filled_table):
division = [] # Разрешение двойственной задачи линейного программир... | # return (max_cj <= 0) # идентично
if max_cj >= 0:
return False #Переход к следующему шагу метода
else:
return True #Переход к выводу результата
def neg_bi_index(filled_table):
# Поиск номера строки с отрицательным свободным членом
amount_conditions = np.size(filled_table,0)-1 # Подсч... | identifier_body |
soda.js | /*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS203: Remove `|| {}` from converted for-own loops
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* DS208... |
getDefaultHandler() {
// instance variable for easy chaining
let emitter, handler;
this.emitter = (emitter = new EventEmitter(this.emitterOpts));
// return the handler
return handler = function(error, response) {
// TODO: possibly more granular handling?
if (response.ok) {
i... | {
this.dataSite = dataSite;
if (sodaOpts == null) { sodaOpts = {}; }
this.sodaOpts = sodaOpts;
if (!/^[a-z0-9-_.]+(:[0-9]+)?$/i.test(this.dataSite)) { throw new Error('dataSite does not appear to be valid! Please supply a domain name, eg data.seattle.gov'); }
// options passed directly into EventEm... | identifier_body |
soda.js | /*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS203: Remove `|| {}` from converted for-own loops
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* DS208... | (id, data) {
const opts = {method: 'put'};
opts.path = `/resource/${this._datasetId}/${id}`;
return this._exec(opts, data);
}
// add objects, update if existing, delete if :delete=true
upsert(data) {
const opts = {method: 'post'};
opts.path = `/resource/${this._datasetId}`;
return this.... | replace | identifier_name |
soda.js | /*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS203: Remove `|| {}` from converted for-own loops
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* DS208... |
})();
const handleLiteral = function(literal) {
if (isString(literal)) {
return `'${literal}'`;
} else if (isNumber(literal)) {
// TODO: possibly ensure number cleanliness for sending to the api? sci not?
return literal;
} else {
return literal;
}
};
const handleOrder = function(order) {
if... | {
// adapted/modified from https://github.com/rwz/base64.coffee
const base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='.split('');
const rawToBase64 = typeof btoa !== 'undefined' && btoa !== null ? btoa : function(str) {
const result = [];
let i = 0;
while ... | conditional_block |
soda.js | /*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* DS203: Remove `|| {}` from converted for-own loops
* DS205: Consider reworking code to avoid use of IIFEs
* DS207: Consider shorter variations of null checks
* DS208... | const toQuerystring = function(obj) {
str = [];
for (let key of Object.keys(obj || {})) {
const val = obj[key];
str.push(encodeURIComponent(key) + '=' + encodeURIComponent(val));
}
return str.join('&');
};
class Connection {
constructor(dataSite, sodaOpts) {
this.dataSite = dataSite;
if (soda... | };
// serialize object to querystring | random_line_split |
main.rs | use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items.
/* This function will remove any newline characters or returns that are read in.
In this the string is passed by reference. I created this as an example and initially
used both remove, and removed, but for convienence I en... | (mut string: String) -> String {
if let Some('\n')=string.chars().next_back() {
string.pop();
}
if let Some('\r')=string.chars().next_back() {
string.pop();
}
string
}
/*This will set up to take input from the keyboard.
It will then remove any newline or return characters, by ca... | removed | identifier_name |
main.rs | use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items.
/* This function will remove any newline characters or returns that are read in.
In this the string is passed by reference. I created this as an example and initially
used both remove, and removed, but for convienence I en... | } else if tip == 4{
println!("Please enter a specific amount, including the change. Ex '10.00':");
total += rdin().parse::<f32>().unwrap(); //Will convert the string to a floating point number. Will break if letters are read in.
} else{
println!("I... | } else if tip == 3{
total += DOLLAR; | random_line_split |
main.rs | use std::collections::HashMap; // To allow me to use the hashmap I created with the menu items.
/* This function will remove any newline characters or returns that are read in.
In this the string is passed by reference. I created this as an example and initially
used both remove, and removed, but for convienence I en... | {
//Constants declared for the tax rate, default tip rates, and special tip cases.
const TAX: f32 = 0.06;
const FIVE: f32 = 0.05;
const TEN: f32 = 0.10;
const FTN: f32 = 0.15;
const TWN: f32 = 0.20;
const QRT: f32 = 0.25;
const HALF: f32 = 0.50;
const DOLLAR: f32 = 1.00;
//use mu... | identifier_body | |
lib.rs | extern crate image;
extern crate imageproc;
extern crate rustfft;
use image::{imageops, GrayImage, ImageBuffer, Luma};
use imageproc::geometric_transformations::Projection;
use imageproc::geometric_transformations::{rotate_about_center, warp, Interpolation};
use rustfft::num_complex::Complex;
use rustfft::num_traits::... |
// TODO: below tests are used as a scratch pad and for syntax experiments, not serious unit testing.
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sanity_test_max_by() {
let filtered: Vec<f32> = vec![1.0, 2.0, 3.0, 4.0, 5.0];
let maxel = filtered
.iter()
.enum... | {
ImageBuffer::from_vec(width, height, buf.iter().map(|c| *c as u8).collect()).unwrap()
} | identifier_body |
lib.rs | extern crate image;
extern crate imageproc;
extern crate rustfft;
use image::{imageops, GrayImage, ImageBuffer, Luma};
use imageproc::geometric_transformations::Projection;
use imageproc::geometric_transformations::{rotate_about_center, warp, Interpolation};
use rustfft::num_complex::Complex;
use rustfft::num_traits::... | (&self) -> usize {
self.trackers.len()
}
}
pub struct Prediction {
pub location: (u32, u32),
pub psr: f32,
}
pub struct MosseTracker {
filter: Vec<Complex<f32>>,
// constants frame height
frame_width: u32,
frame_height: u32,
// stores dimensions of tracking window and its cen... | size | identifier_name |
lib.rs | extern crate image;
extern crate imageproc;
extern crate rustfft;
use image::{imageops, GrayImage, ImageBuffer, Luma};
use imageproc::geometric_transformations::Projection;
use imageproc::geometric_transformations::{rotate_about_center, warp, Interpolation};
use rustfft::num_complex::Complex;
use rustfft::num_traits::... | // checked sub returns None if overflow occurred, which is also a panicable offense.
// checked_div returns None if rhs == 0, which would indicate an upstream error (width == 0).
let y = (index.checked_sub(x).unwrap()).checked_div(width).unwrap();
return (x, y);
}
pub fn to_imgbuf(buf: &Vec<f32>, width... | fn index_to_coords(width: u32, index: u32) -> (u32, u32) {
// modulo/remainder ops are theoretically O(1)
// checked_rem returns None if rhs == 0, which would indicate an upstream error (width == 0).
let x = index.checked_rem(width).unwrap();
| random_line_split |
main.rs | #![deny(unused_must_use)]
#![type_length_limit = "1340885"]
extern crate serenity;
extern crate ctrlc;
#[macro_use]
pub mod logger;
pub mod canary_update;
pub mod dogebotno;
pub mod permissions;
pub mod servers;
pub mod voice;
use canary_update::*;
use futures::{Stream, StreamExt};
use lazy_static::*;
use logger::get_... |
async fn ready(&self, ctx: Context, _data: Ready) {
log_timestamp!("INFO", format!("Shard {} ready", ctx.shard_id));
}
async fn cache_ready(&self, ctx: Context, guilds: Vec<GuildId>) {
let shard = ctx.shard_id;
let rctx = &ctx;
// Get all the guilds that this shard is connected to
// Not that this bot wil... | {
log_timestamp!("INFO", "Reconnected to discord");
} | identifier_body |
main.rs | #![deny(unused_must_use)]
#![type_length_limit = "1340885"]
extern crate serenity;
extern crate ctrlc;
#[macro_use]
pub mod logger;
pub mod canary_update;
pub mod dogebotno;
pub mod permissions;
pub mod servers;
pub mod voice;
use canary_update::*;
use futures::{Stream, StreamExt};
use lazy_static::*;
use logger::get_... | })
.log_err();
// Hah you think this bot is big enough to be sharded? Nice joke
// But if yours is use .start_autosharded()
client.start().await?;
Ok(())
}
/// Handles the @someone ping. Yes im evil.
async fn someone_ping(ctx: &Context, msg: &Message) {
let guild_id: Option<GuildId> = msg.guild_id;
let channel... | std::process::exit(0); | random_line_split |
main.rs | #![deny(unused_must_use)]
#![type_length_limit = "1340885"]
extern crate serenity;
extern crate ctrlc;
#[macro_use]
pub mod logger;
pub mod canary_update;
pub mod dogebotno;
pub mod permissions;
pub mod servers;
pub mod voice;
use canary_update::*;
use futures::{Stream, StreamExt};
use lazy_static::*;
use logger::get_... | (ctx: &Context, msg: &Message) -> CommandResult {
if msg.author.id != 453344368913547265 {
msg.channel_id.say(&ctx, "No").await.log_err();
return Ok(());
}
//let canary = ctx.data.read().get::<CanaryUpdateHandler>().cloned().unwrap();
//let lock = canary.lock()?;
//let res = lock.create_db();
//res.log_err();... | test | identifier_name |
index.ts | import { Match } from 'dimensions-ai/lib/main/Match';
import { MatchWarn } from 'dimensions-ai/lib/main/DimensionError';
import { MatchEngine } from 'dimensions-ai/lib/main/MatchEngine';
import { MoveAction, SpawnAction, Action } from '../Actions';
import { GameMap } from '../GameMap';
import { Replay } from '../Replay... |
moveUnit(team: Unit.TEAM, unitid: Unit.ID, direction: Game.DIRECTIONS): void {
const unit = this.getUnit(team, unitid);
// remove unit from old cell and move to new one and update unit pos
this.map.getTileByPos(unit.pos).units.delete(unit.id);
unit.pos = unit.pos.translate(direction, 1);
this.map... | {
return this.state.teamStates[team].units.get(unitid);
} | identifier_body |
index.ts | import { Match } from 'dimensions-ai/lib/main/Match';
import { MatchWarn } from 'dimensions-ai/lib/main/DimensionError';
import { MatchEngine } from 'dimensions-ai/lib/main/MatchEngine';
import { MoveAction, SpawnAction, Action } from '../Actions';
import { GameMap } from '../GameMap';
import { Replay } from '../Replay... | }
});
});
brokenDownUnits.forEach((unit) => {
match.log.warn(`Team ${unit.team}'s unit ${unit.id} broke down`);
this.destroyUnit(unit.team, unit.id);
});
}
}
export namespace Game {
export interface State {
turn: 0;
teamStates: {
[x in Unit.TEAM]: {
units... | if (b >= this.configs.parameters.BREAKDOWN_MAX) {
brokenDownUnits.push(unit); | random_line_split |
index.ts | import { Match } from 'dimensions-ai/lib/main/Match';
import { MatchWarn } from 'dimensions-ai/lib/main/DimensionError';
import { MatchEngine } from 'dimensions-ai/lib/main/MatchEngine';
import { MoveAction, SpawnAction, Action } from '../Actions';
import { GameMap } from '../GameMap';
import { Replay } from '../Replay... | (tilesToCheck: Set<Tile>, match: Match): void {
const unitsToRemove: Array<{ unit: Unit; tile: Tile }> = [];
tilesToCheck.forEach((tile) => {
if (tile.units.size > 1) {
// find lowest brokendown unit
// remove all units as they collided
let lowestBreakdown = 999999;
let low... | handleCollisions | identifier_name |
index.ts | import { Match } from 'dimensions-ai/lib/main/Match';
import { MatchWarn } from 'dimensions-ai/lib/main/DimensionError';
import { MatchEngine } from 'dimensions-ai/lib/main/MatchEngine';
import { MoveAction, SpawnAction, Action } from '../Actions';
import { GameMap } from '../GameMap';
import { Replay } from '../Replay... |
const unit = teamState.units.get(unitid);
switch (direction) {
case Game.DIRECTIONS.NORTH:
case Game.DIRECTIONS.EAST:
case Game.DIRECTIONS.SOUTH:
case Game.DIRECTIONS.WEST: {
const newpos = unit.pos.translate(direction, 1);... | {
valid = false;
errormsg = `Team ${cmd.agentID} tried to move unit ${unitid} that it does not own`;
break;
} | conditional_block |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import CheckBox from './CheckBox';
import './index.css';
class Square extends React.Component {
render() {
return (
<button className="square"
onClick={() => this.props.onClick()}>
{this.props.value}
</button>
);
}
}... | squares_print[result[1]] = squares[result[1]]
result[2] = true
score[p] = score[p] + 3
nbPairsFound += 1
} else {
result[2] = false
score[p] = score[p] - 1
}
if(prevstate.mode !== 1){
oneIsNext = !oneIsNext... | squares_print[result[0]] = squares[result[0]] | random_line_split |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import CheckBox from './CheckBox';
import './index.css';
class Square extends React.Component {
render() {
return (
<button className="square"
onClick={() => this.props.onClick()}>
{this.props.value}
</button>
);
}
}... | heckModes(modes){
//1 joueur
if (modes[0].isChecked){
return(modes[0].id)
}
//2 joueur
else if (modes[1].isChecked){
return(modes[1].id)
}
//random
else if (modes[2].isChecked){
return(modes[2].id)
}
}
handleSquareClick(i) {
this.setState((prevstate) => {... | {
this.setState((prevstate) => {
let col = 1
let cXr = 0
let nickname2 = "Titeuf"
let mode = this.checkModes(prevstate.modes)
console.log("mode: " + mode)
if(mode === 1){
nickname2 = "---"
}
console.log("cXr :" + cXr)
// On cherche à avoir un c... | identifier_body |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import CheckBox from './CheckBox';
import './index.css';
class Square extends React.Component {
render() {
return (
<button className="square"
onClick={() => this.props.onClick()}>
{this.props.value}
</button>
);
}
}... | ){
//1 joueur
if (modes[0].isChecked){
return(modes[0].id)
}
//2 joueur
else if (modes[1].isChecked){
return(modes[1].id)
}
//random
else if (modes[2].isChecked){
return(modes[2].id)
}
}
handleSquareClick(i) {
this.setState((prevstate) => {
let res... | odes(modes | identifier_name |
index.js | import React from 'react';
import ReactDOM from 'react-dom';
import CheckBox from './CheckBox';
import './index.css';
class Square extends React.Component {
render() {
return (
<button className="square"
onClick={() => this.props.onClick()}>
{this.props.value}
</button>
);
}
}... | maining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
} | conditional_block | |
backend.rs | use crate::intrinsics::Intrinsics;
use inkwell::{
memory_buffer::MemoryBuffer,
module::Module,
targets::{CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine},
OptimizationLevel,
};
use libc::{
c_char, mmap, mprotect, munmap, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_R... | {
NONE,
READ,
READ_WRITE,
READ_EXECUTE,
}
#[allow(non_camel_case_types, dead_code)]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(C)]
enum LLVMResult {
OK,
ALLOCATE_FAILURE,
PROTECT_FAILURE,
DEALLOC_FAILURE,
OBJECT_LOAD_FAILURE,
}
#[repr(C)]
struct Callbacks {
alloc_memo... | MemProtect | identifier_name |
backend.rs | use crate::intrinsics::Intrinsics;
use inkwell::{
memory_buffer::MemoryBuffer,
module::Module,
targets::{CodeModel, FileType, InitializationConfig, RelocMode, Target, TargetMachine},
OptimizationLevel,
};
use libc::{
c_char, mmap, mprotect, munmap, MAP_ANON, MAP_PRIVATE, PROT_EXEC, PROT_NONE, PROT_R... | let name_slice = unsafe { slice::from_raw_parts(name_ptr as *const u8, length) };
let name = str::from_utf8(name_slice).unwrap();
match name {
fn_name!("vm.memory.grow.dynamic.local") => vmcalls::local_dynamic_memory_grow as _,
fn_name!("vm.memory.size.dynamic.local") =>... | random_line_split | |
algorithm.py | import csv
import bisect
from explore.models import MovieObj
import requests
from time import sleep
import pprint
ratings = {"Passed": 0, "Approved": 0, "Unrated": 0, "Not Rated": 0, "": 0, "TV-Y": 0, "TV-G": 1,
"G": 1, "TV-Y7": 2, "GP": 2, "TV-PG": 2, "PG": 2, "TV-14": 3, "PG-13": 3, "TV-MA": 4,
... | :
def __init__(self):
self.title = ""
self.titleWords = []
self.year = 0
self.actor1 = ""
self.actor2 = ""
self.actor3 = ""
self.director = ""
self.keywords = []
self.genres = []
self.relevance = 0
self.country = ""
self... | Movie | identifier_name |
algorithm.py | import csv
import bisect
from explore.models import MovieObj
import requests
from time import sleep
import pprint
ratings = {"Passed": 0, "Approved": 0, "Unrated": 0, "Not Rated": 0, "": 0, "TV-Y": 0, "TV-G": 1,
"G": 1, "TV-Y7": 2, "GP": 2, "TV-PG": 2, "PG": 2, "TV-14": 3, "PG-13": 3, "TV-MA": 4,
... |
def getTitles():
count = 0
titles = []
with open("movieDBbackup.txt", 'r', encoding="utf8") as csvfile:
TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True)
for row in TSVreader:
temp = Movie()
if count > 0: # Makes sure the headers... | listIDs = ID_string.split(" ") # Splits inFilm string into list of IDs
movies = reader("movieDBbackup.txt")
# Populates
inputs = []
for i in movies:
for j in listIDs:
if i.ID == j:
inputs.append(i)
print(i.titleWords)
print(i.genr... | identifier_body |
algorithm.py | import csv
import bisect
from explore.models import MovieObj
import requests
from time import sleep
import pprint
ratings = {"Passed": 0, "Approved": 0, "Unrated": 0, "Not Rated": 0, "": 0, "TV-Y": 0, "TV-G": 1,
"G": 1, "TV-Y7": 2, "GP": 2, "TV-PG": 2, "PG": 2, "TV-14": 3, "PG-13": 3, "TV-MA": 4,
... | return topN
def getTitles():
count = 0
titles = []
with open("movieDBbackup.txt", 'r', encoding="utf8") as csvfile:
TSVreader = csv.reader(csvfile, delimiter='\t', quotechar='"', skipinitialspace=True)
for row in TSVreader:
temp = Movie()
if count > 0: # Makes s... | for i in range(0, num_results):
topN.append([top[i].ID, str(top[i].relevance), top[i].criteria, ", ".join(top[i].genres)]) | random_line_split |
algorithm.py | import csv
import bisect
from explore.models import MovieObj
import requests
from time import sleep
import pprint
ratings = {"Passed": 0, "Approved": 0, "Unrated": 0, "Not Rated": 0, "": 0, "TV-Y": 0, "TV-G": 1,
"G": 1, "TV-Y7": 2, "GP": 2, "TV-PG": 2, "PG": 2, "TV-14": 3, "PG-13": 3, "TV-MA": 4,
... |
top = []
for i in movies:
for inFilm in inputs:
# Actor Check
if i.actor1 == inFilm.actor1 or i.actor1 == inFilm.actor2 or i.actor1 == inFilm.actor3:
i.relevance += (35 * actorWeight)
i.criteria.append("Actor: "+i.actor1)
if i.actor2 ... | if i.ID == j:
inputs.append(i)
print(i.titleWords)
print(i.genres)
print(i.keywords)
print() | conditional_block |
kernel.rs | use crate::api::event::create_and_queue;
use crate::api::icd::*;
use crate::api::util::*;
use crate::core::device::*;
use crate::core::event::*;
use crate::core::kernel::*;
use crate::core::program::*;
use mesa_rust_util::ptr::*;
use mesa_rust_util::string::*;
use rusticl_opencl_gen::*;
use std::collections::HashSet;... | if arg_value.is_null() {
return Err(CL_INVALID_ARG_VALUE);
}
}
_ => {}
};
// let's create the arg now
let arg = unsafe {
if arg.dead {
KernelArgValue::None
} else {
... | }
// If the argument is of type sampler_t, the arg_value entry must be a pointer to the
// sampler object.
KernelArgType::Constant | KernelArgType::Sampler => { | random_line_split |
kernel.rs | use crate::api::event::create_and_queue;
use crate::api::icd::*;
use crate::api::util::*;
use crate::core::device::*;
use crate::core::event::*;
use crate::core::kernel::*;
use crate::core::program::*;
use mesa_rust_util::ptr::*;
use mesa_rust_util::string::*;
use rusticl_opencl_gen::*;
use std::collections::HashSet;... | (
kernel: cl_kernel,
arg_index: cl_uint,
arg_size: usize,
arg_value: *const ::std::os::raw::c_void,
) -> CLResult<()> {
let k = kernel.get_arc()?;
// CL_INVALID_ARG_INDEX if arg_index is not a valid argument index.
if let Some(arg) = k.args.get(arg_index as usize) {
// CL_INVALID_AR... | set_kernel_arg | identifier_name |
kernel.rs | use crate::api::event::create_and_queue;
use crate::api::icd::*;
use crate::api::util::*;
use crate::core::device::*;
use crate::core::event::*;
use crate::core::kernel::*;
use crate::core::program::*;
use mesa_rust_util::ptr::*;
use mesa_rust_util::string::*;
use rusticl_opencl_gen::*;
use std::collections::HashSet;... |
pub fn create_kernels_in_program(
program: cl_program,
num_kernels: cl_uint,
kernels: *mut cl_kernel,
num_kernels_ret: *mut cl_uint,
) -> CLResult<()> {
let p = program.get_arc()?;
let devs = get_devices_with_valid_build(&p)?;
// CL_INVALID_VALUE if kernels is not NULL and num_kernels is ... | {
let p = program.get_arc()?;
let name = c_string_to_string(kernel_name);
// CL_INVALID_VALUE if kernel_name is NULL.
if kernel_name.is_null() {
return Err(CL_INVALID_VALUE);
}
// CL_INVALID_PROGRAM_EXECUTABLE if there is no successfully built executable for program.
if p.kernels()... | identifier_body |
kernel.rs | use crate::api::event::create_and_queue;
use crate::api::icd::*;
use crate::api::util::*;
use crate::core::device::*;
use crate::core::event::*;
use crate::core::kernel::*;
use crate::core::program::*;
use mesa_rust_util::ptr::*;
use mesa_rust_util::string::*;
use rusticl_opencl_gen::*;
use std::collections::HashSet;... |
_ => {
if arg.size != arg_size {
return Err(CL_INVALID_ARG_SIZE);
}
}
}
// CL_INVALID_ARG_VALUE if arg_value specified is not a valid value.
match arg.kind {
// If the argument is declared with the local qu... | {
if arg_size != std::mem::size_of::<cl_mem>() {
return Err(CL_INVALID_ARG_SIZE);
}
} | conditional_block |
Faces.py | # -*- coding: utf-8 -*-
from math import atan, cos, degrees, radians, sin
import cv2
import dlib
import face_recognition_models
import numpy as np
from PIL import Image
# 当检测不到人脸时对人脸进行旋转的 按照如下列表的角度逐个尝试
ANGLE_LIST = [0, -45, 45]
# 加载Dlib库中的人脸检测算子、ResNet模型
face_detector = dlib.get_frontal_face_detector()
predictor_6... | return degrees(atan((point_x[1] - point_y[1]) / (point_y[0] - point_x[0])))
def get_stdface(image, detection_save_path=None, stdface_save_path=None):
"""
输入一张RGB三通道图片 返回经过摆正并裁剪的256*256的人脸图像
检测不到的时候返回空值None
:param image: 原图
:param detection_save_path: 如果需要将检测结果保存下来 请传入本值
:param stdface_save... | random_line_split | |
Faces.py | # -*- coding: utf-8 -*-
from math import atan, cos, degrees, radians, sin
import cv2
import dlib
import face_recognition_models
import numpy as np
from PIL import Image
# 当检测不到人脸时对人脸进行旋转的 按照如下列表的角度逐个尝试
ANGLE_LIST = [0, -45, 45]
# 加载Dlib库中的人脸检测算子、ResNet模型
face_detector = dlib.get_frontal_face_detector()
predictor_6... | 不进行旋转时
else:
# 得到所有人脸的位置
locations = face_locations(image, upsample)
# 统计人脸个数,并得到像素面积最大的人脸的位置
max_pixel_area = 0
number_of_faces = len(locations)
result_top, result_right, result_bottom, result_left = -1, -1, -1, -1
for location in locations:
top... | return image, 0, -1, -1, -1, -1
# | conditional_block |
Faces.py | # -*- coding: utf-8 -*-
from math import atan, cos, degrees, radians, sin
import cv2
import dlib
import face_recognition_models
import numpy as np
from PIL import Image
# 当检测不到人脸时对人脸进行旋转的 按照如下列表的角度逐个尝试
ANGLE_LIST = [0, -45, 45]
# 加载Dlib库中的人脸检测算子、ResNet模型
face_detector = dlib.get_frontal_face_detector()
predictor_6... | cation) for face_location in face_locations_]
pose_predictor = pose_predictor_68_point
if model == "small":
pose_predictor = pose_predictor_5_point
return [pose_predictor(face_image, face_location) for face_location in face_locations_]
def rgb2bgr(rgb_image):
"""
(ndarray)将rgb通道转换为bgr通道... |
else:
face_locations_ = [css2rect(face_lo | identifier_body |
Faces.py | # -*- coding: utf-8 -*-
from math import atan, cos, degrees, radians, sin
import cv2
import dlib
import face_recognition_models
import numpy as np
from PIL import Image
# 当检测不到人脸时对人脸进行旋转的 按照如下列表的角度逐个尝试
ANGLE_LIST = [0, -45, 45]
# 加载Dlib库中的人脸检测算子、ResNet模型
face_detector = dlib.get_frontal_face_detector()
predictor_6... | 向量初始化
:param x: X值
:param y: Y值
"""
self.x = x
self.y = y
def rotate(self, alpha):
"""
将向量旋转一定的角度 无返回值
:param alpha: 要旋转的角度
:return: 无返回值
"""
# print("cos:{:.2f} sin:{:.2f}".format(cos(alpha), sin(alpha)))
rad_al... | """
| identifier_name |
view.rs | use clap::Clap;
use io::Write;
use json::JsonValue;
use log::{info, warn};
use num_format::{Locale, ToFormattedString};
use rusqlite::types::ValueRef;
use rusqlite::{params, OpenFlags, OptionalExtension};
use std::{env, fs, io, path, process};
use crate::bad_command;
use crate::util;
use crate::util::Result;
#[derive... | refseq_name,
(refseq_begin + 1).to_formatted_string(&Locale::en),
refseq_end.to_formatted_string(&Locale::en)
))?;
}
}
info!("wrote CSV with guessed segment ranges to {}", csv_filename);
Ok(())
}
}
// He... | writer.write_fmt(format_args!(
"\"{}\",\"~{}:{}-{}\"\n",
name, | random_line_split |
view.rs | use clap::Clap;
use io::Write;
use json::JsonValue;
use log::{info, warn};
use num_format::{Locale, ToFormattedString};
use rusqlite::types::ValueRef;
use rusqlite::{params, OpenFlags, OptionalExtension};
use std::{env, fs, io, path, process};
use crate::bad_command;
use crate::util;
use crate::util::Result;
#[derive... | (db: &rusqlite::Connection, writer: &mut dyn io::Write) -> Result<()> {
let tags_json: String = db.query_row(
"SELECT tags_json FROM gfa1_header WHERE _rowid_ = 1",
[],
|row| row.get(0),
)?;
writer.write(b"H")?;
write_tags("gfa1_header", 1, &tags_json, writer)?;
writer.write(... | write_header | identifier_name |
view.rs | use clap::Clap;
use io::Write;
use json::JsonValue;
use log::{info, warn};
use num_format::{Locale, ToFormattedString};
use rusqlite::types::ValueRef;
use rusqlite::{params, OpenFlags, OptionalExtension};
use std::{env, fs, io, path, process};
use crate::bad_command;
use crate::util;
use crate::util::Result;
#[derive... |
if !gfa_filename.ends_with(".gfa") {
warn!("output filename should end with .gfa")
}
Ok(Box::new(io::BufWriter::new(fs::File::create(
gfa_filename,
)?)))
}
/// Start `less -S` and call `write` with its standard input pipe.
/// Tolerate BrokenPipe errors (user exited before viewing all ... | {
return Ok(Box::new(io::BufWriter::new(io::stdout())));
} | conditional_block |
do.go | /**
* (Probably) the world's first one file RPA tool impremented by Golang!
*
* @author yasutakatou
* @copyright 2020 yasutakatou
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 , 3-clause BSD License
*/
package main
import (
"bufio"
"crypto/md5"
"encoding/hex"
"flag"
"f... | else {
return true
}
breakCounter = breakCounter - 1
if breakCounter < 0 {
return false
}
time.Sleep(time.Duration(waitSeconds) * time.Millisecond)
}
}
func recordingMode(exportFile string) {
fmt.Printf(" - - recording start! you want to end this mode, key press ascii code (%d) - - \n", ... | {
SetActiveWindow(HWND(setHwnd), Debug)
} | conditional_block |
do.go | /**
* (Probably) the world's first one file RPA tool impremented by Golang!
*
* @author yasutakatou
* @copyright 2020 yasutakatou
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 , 3-clause BSD License
*/
package main
import (
"bufio"
"crypto/md5"
"encoding/hex"
"flag"
"f... | }
func GetWindow(funcName string, Debug bool) uintptr {
hwnd, _, _ := syscall.Syscall(procGetForegroundWindow.Addr(), 6, 0, 0, 0)
if Debug == true {
fmt.Printf("currentWindow: handle=0x%x.\n", hwnd)
}
return hwnd
}
func SetActiveWindow(hwnd HWND, Debug bool) {
if Debug == true {
fmt.Printf("SetAc... | return 1
})
EnumWindows(cb, 0)
return uintptr(hwnd)
| random_line_split |
do.go | /**
* (Probably) the world's first one file RPA tool impremented by Golang!
*
* @author yasutakatou
* @copyright 2020 yasutakatou
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 , 3-clause BSD License
*/
package main
import (
"bufio"
"crypto/md5"
"encoding/hex"
"flag"
"f... | (Rawcode, Kind int, bufStrs uint16, exportFile string) int {
altFlag := 0
switch Rawcode {
case 162, 164: //Ctrl,Alt
if Kind == 4 {
altFlag = Rawcode
} else {
altFlag = 0
}
case LiveExitAsciiCode: //Default Escape
ExportHistory(exportFile)
return 256
case 160:
default:
if Kind ==... | keyHoldUp | identifier_name |
do.go | /**
* (Probably) the world's first one file RPA tool impremented by Golang!
*
* @author yasutakatou
* @copyright 2020 yasutakatou
* @license https://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 , 3-clause BSD License
*/
package main
import (
"bufio"
"crypto/md5"
"encoding/hex"
"flag"
"f... |
func GetWindowText(hwnd syscall.Handle, str *uint16, maxCount int32) (len int32, err error) {
r0, _, e1 := syscall.Syscall(procGetWindowTextW.Addr(), 3, uintptr(hwnd), uintptr(unsafe.Pointer(str)), uintptr(maxCount))
if len = int32(r0); len == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscal... | {
r1, _, e1 := syscall.Syscall(procGetWindowRect.Addr(), 7, uintptr(hwnd), uintptr(unsafe.Pointer(rect)), 0)
if r1 == 0 {
if e1 != 0 {
err = error(e1)
} else {
err = syscall.EINVAL
}
}
return
} | identifier_body |
server.go | package server
import (
"bufio"
"fmt"
"io"
"net"
"os"
"time"
// "github.com/pkg/profile" //uncomment to enable
"sync/atomic"
)
/*
Constants for server connection.
*/
const (
ConnHost = "localhost"
ConnPort = "3333"
ConnType = "tcp"
)
// RequestHeader is for representing a request header structure in Binar... | () {
// defer profile.Start().Stop() // uncomment to enable profiler
// Listen for incoming connections.
l, err := net.Listen(ConnType, ConnHost+":"+ConnPort)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
// Close the listener when the application closes.
defer l.Close()
fmt.Prin... | Start | identifier_name |
server.go | package server
import (
"bufio"
"fmt"
"io"
"net"
"os"
"time"
// "github.com/pkg/profile" //uncomment to enable
"sync/atomic"
)
/*
Constants for server connection.
*/
const (
ConnHost = "localhost"
ConnPort = "3333"
ConnType = "tcp"
)
// RequestHeader is for representing a request header structure in Binar... |
func handleCommand(context *ConnectionContext) error {
// Make a buffer to hold incoming data.
bufHeader := context.ReadBuf[:24]
readLen := 0
for readLen < len(bufHeader) {
reqLen, err := context.RW.Read(bufHeader[readLen:])
if err != nil {
return err
}
readLen += reqLen
}
context.CommandSeq++
conte... | {
err := rw.WriteByte(header.Magic)
if err != nil {
return err
}
err = rw.WriteByte(header.Opcode)
if err != nil {
return err
}
err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 0))
if err != nil {
return err
}
err = rw.WriteByte(GetNthByteFromUint16(header.KeyLength, 1))
if err != nil {
re... | identifier_body |
server.go | package server
import (
"bufio"
"fmt"
"io"
"net"
"os"
"time"
// "github.com/pkg/profile" //uncomment to enable
"sync/atomic"
)
/*
Constants for server connection.
*/
const (
ConnHost = "localhost"
ConnPort = "3333"
ConnType = "tcp"
)
// RequestHeader is for representing a request header structure in Binar... |
for pos := 0; pos < 4; pos++ {
err = rw.WriteByte(GetNthByteFromUint32(header.TotalBodyLength, pos))
if err != nil {
return err
}
}
for pos := 0; pos < 4; pos++ {
err = rw.WriteByte(GetNthByteFromUint32(header.Opaque, pos))
if err != nil {
return err
}
}
l := uint32(header.CAS >> 32)
r := ui... | {
return err
} | conditional_block |
server.go | package server
import (
"bufio"
"fmt"
"io"
"net"
"os"
"time"
// "github.com/pkg/profile" //uncomment to enable
"sync/atomic"
)
/*
Constants for server connection.
*/
const (
ConnHost = "localhost"
ConnPort = "3333"
ConnType = "tcp"
)
// RequestHeader is for representing a request header structure in Binar... | return ret, nil
}
/*
Byte/ 0 | 1 | 2 | 3 |
/ | | | |
|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|0 1 2 3 4 5 6 7|
+---------------+---------------+---------------+---------------+
0| Magic ... |
ret.CAS = GetUint64(buf)
| random_line_split |
gitiles.go | // Copyright 2016 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... | else {
ctl.DebugLog("%d refs changed", refsChanged)
// Force save to ensure triggers are actually emitted.
if err := ctl.Save(c); err != nil {
// At this point, triggers have not been sent, so bail now and don't save
// the refs' heads newest values.
return err
}
if err := saveState(c, ctl.JobID(), ... | {
ctl.DebugLog("No changes detected")
} | conditional_block |
gitiles.go | // Copyright 2016 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... | (c context.Context, ctl task.Controller) error {
return nil
}
// HandleNotification is part of Manager interface.
func (m TaskManager) HandleNotification(c context.Context, ctl task.Controller, msg *pubsub.PubsubMessage) error {
return errors.New("not implemented")
}
// HandleTimer is part of Manager interface.
fun... | AbortTask | identifier_name |
gitiles.go | // Copyright 2016 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... | mockGitilesClient gitilespb.GitilesClient // Used for testing only.
maxTriggersPerInvocation int // Avoid choking on DS or runtime limits.
}
// Name is part of Manager interface.
func (m TaskManager) Name() string {
return "gitiles"
}
// ProtoMessageType is part of Manager interface.
fun... | const defaultMaxTriggersPerInvocation = 100
// TaskManager implements task.Manager interface for tasks defined with
// GitilesTask proto message.
type TaskManager struct { | random_line_split |
gitiles.go | // Copyright 2016 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... |
// HandleTimer is part of Manager interface.
func (m TaskManager) HandleTimer(c context.Context, ctl task.Controller, name string, payload []byte) error {
return errors.New("not implemented")
}
// getRefsTips returns tip for each ref being watched.
func (m TaskManager) getRefsTips(c context.Context, ctl task.Contro... | {
return errors.New("not implemented")
} | identifier_body |
settings.go | // Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | {
wireSettings := wire.ReceiveSettings{
MaxOutstandingMessages: DefaultReceiveSettings.MaxOutstandingMessages,
MaxOutstandingBytes: DefaultReceiveSettings.MaxOutstandingBytes,
Timeout: DefaultReceiveSettings.Timeout,
Partitions: s.Partitions,
Framework: wire.Framewo... | identifier_body | |
settings.go | // Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | if s.Timeout != 0 {
if s.Timeout >= wire.MinTimeout {
wireSettings.Timeout = s.Timeout
} else {
log.Println("WARNING: PublishSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.")
wireSettings.Timeout = wire.MinTimeout
}
}
if s.Buffere... | random_line_split | |
settings.go | // Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... |
if s.Timeout != 0 {
if s.Timeout >= wire.MinTimeout {
wireSettings.Timeout = s.Timeout
} else {
log.Println("WARNING: ReceiveSettings.Timeout has been overridden to 2 minutes (the minimum value). A lower value will cause an error in the future.")
wireSettings.Timeout = wire.MinTimeout
}
}
return wire... | {
wireSettings.MaxOutstandingBytes = s.MaxOutstandingBytes
} | conditional_block |
settings.go | // Copyright 2020 Google LLC
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in ... | () wire.PublishSettings {
wireSettings := wire.PublishSettings{
DelayThreshold: DefaultPublishSettings.DelayThreshold,
CountThreshold: DefaultPublishSettings.CountThreshold,
ByteThreshold: DefaultPublishSettings.ByteThreshold,
Timeout: DefaultPublishSettings.Timeout,
BufferedByteLimit: De... | toWireSettings | identifier_name |
honeyproxyserver.py | from wsgiref.simple_server import make_server
import bottle, json, threading, time, subprocess, collections, sys, os, datetime, IPy, re, time, urllib
from bottle import Bottle, static_file, request, redirect, PasteServer as wsgiserver, response
from bottle.ext import sqlalchemy as bottlealchemy
from jinja2 import Envi... | (analysis_id,session):
analysis = session.query(Analysis).get(analysis_id)
if not analysis:
return {"error":"not found"}
else:
return analysis.as_htmlsafe_dict()
@app.post('/api/analyze')
def api_analyze(session):
response = captcha.submit(
request.forms.get(r'recaptcha_challeng... | api_analysis | identifier_name |
honeyproxyserver.py | from wsgiref.simple_server import make_server
import bottle, json, threading, time, subprocess, collections, sys, os, datetime, IPy, re, time, urllib
from bottle import Bottle, static_file, request, redirect, PasteServer as wsgiserver, response
from bottle.ext import sqlalchemy as bottlealchemy
from jinja2 import Envi... |
def spawnInstance(self, analysis, instance_type, apiport=None, guiport=None):
apiport, guiport = self._getPorts(apiport, guiport)
print "Spawn %s instance(%d, %d)..." % (instance_type, apiport, guiport)
args = (config["HoneyProxy"] +
[
"--api-auth",... | if apiport:
self.ports.remove(apiport)
else:
apiport = self.ports.pop()
if guiport:
self.ports.remove(guiport)
else:
guiport = self.ports.pop()
return apiport, guiport | identifier_body |
honeyproxyserver.py | from wsgiref.simple_server import make_server
import bottle, json, threading, time, subprocess, collections, sys, os, datetime, IPy, re, time, urllib
from bottle import Bottle, static_file, request, redirect, PasteServer as wsgiserver, response
from bottle.ext import sqlalchemy as bottlealchemy
from jinja2 import Envi... | "-Z","5m"])
else:
args.extend(
[
"-r", analysis.getDumpfileLocation(),
"-n",
"--readonly"])
p = subprocess.Popen(args,
stdout=PIPE,
stderr... | "-s","./resources/suppresswinupdate.py", | random_line_split |
honeyproxyserver.py | from wsgiref.simple_server import make_server
import bottle, json, threading, time, subprocess, collections, sys, os, datetime, IPy, re, time, urllib
from bottle import Bottle, static_file, request, redirect, PasteServer as wsgiserver, response
from bottle.ext import sqlalchemy as bottlealchemy
from jinja2 import Envi... |
@app.post('/api/analyze')
def api_analyze(session):
response = captcha.submit(
request.forms.get(r'recaptcha_challenge_field'),
request.forms.get('recaptcha_response_field'),
config["recaptcha"]["privatekey"],
request.environ.get('REMOTE_ADDR')
)
if not response.is_vali... | return analysis.as_htmlsafe_dict() | conditional_block |
file_test.go | // Copyright 2016 The Prometheus 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 agree... | (file string) []*targetgroup.Group {
return []*targetgroup.Group{
{
Targets: []model.LabelSet{
{
model.AddressLabel: model.LabelValue("my.domain"),
},
},
Labels: model.LabelSet{
fileSDFilepathLabel: model.LabelValue(file),
},
Source: fileSource(file, 0),
},
{
Targets: []model.L... | valid2Tg | identifier_name |
file_test.go | // Copyright 2016 The Prometheus 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 agree... | }
}
func TestNoopFileUpdate(t *testing.T) {
t.Parallel()
runner := newTestRunner(t)
sdFile := runner.copyFile("fixtures/valid.yml")
runner.run("*.yml")
defer runner.stop()
// Verify that we receive the initial target groups.
runner.requireUpdate(time.Time{}, validTg(sdFile))
// Verify that we receive an u... | t.Fatalf("unexpected targets received: %v", runner.targets())
}
}) | random_line_split |
file_test.go | // Copyright 2016 The Prometheus 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 agree... |
}()
for i := range files {
files[i] = filepath.Join(t.dir, files[i])
}
ctx, cancel := context.WithCancel(context.Background())
t.cancelSD = cancel
go func() {
NewDiscovery(
&SDConfig{
Files: files,
// Setting a high refresh interval to make sure that the tests only
// rely on file watches.
... | {
select {
case <-t.done:
os.RemoveAll(t.dir)
return
case tgs := <-t.ch:
t.mtx.Lock()
t.receivedAt = time.Now()
for _, tg := range tgs {
t.tgs[tg.Source] = tg
}
t.mtx.Unlock()
}
} | conditional_block |
file_test.go | // Copyright 2016 The Prometheus 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 agree... |
func TestInvalidFile(t *testing.T) {
for _, tc := range []string{
"fixtures/invalid_nil.yml",
"fixtures/invalid_nil.json",
} {
tc := tc
t.Run(tc, func(t *testing.T) {
t.Parallel()
now := time.Now()
runner := newTestRunner(t)
runner.copyFile(tc)
runner.run("*" + filepath.Ext(tc))
defer ru... | {
for _, tc := range []string{
"fixtures/valid.yml",
"fixtures/valid.json",
} {
tc := tc
t.Run(tc, func(t *testing.T) {
t.Parallel()
runner := newTestRunner(t)
sdFile := runner.copyFile(tc)
runner.run("*" + filepath.Ext(tc))
defer runner.stop()
// Verify that we receive the initial target... | identifier_body |
main.rs | use std::fs::File;
use std::io::Write;
use std::str;
use std::collections::HashMap;
use std::mem;
use std::fmt;
use std::thread;
use std::sync::mpsc;
use std::sync::{Mutex, Arc};
use std::time::Duration;
use std::io::Read;
use std::collections::HashSet;
extern crate bio;
extern crate clap;
extern crate flate2;
extern... | (seq: &[u8]) -> Result<u64, &str> {
let mut res: u64 = 0;
let mut res_rc: u64 = 0;
let end = seq.len() - 1;
for i in 0..seq.len() {
if i >= 32 {
return Err("Seq can't longer than 32.")
}
let m = SEQ_NT4_TABLE[seq[i] as usize];
res |= m << i*2;
res_rc |... | compress_seq | identifier_name |
main.rs | use std::fs::File;
use std::io::Write;
use std::str;
use std::collections::HashMap;
use std::mem;
use std::fmt;
use std::thread;
use std::sync::mpsc;
use std::sync::{Mutex, Arc};
use std::time::Duration;
use std::io::Read;
use std::collections::HashSet;
extern crate bio;
extern crate clap;
extern crate flate2;
extern... | for (k0, k1, v) in kv_vec {
let _ = writeln!(cnt_file, "{}\t{}\t{}", k0, k1, v);
}
info!("Write sequences to fastq file: {}", fq_out_path);
let mut key_vec = key_set.into_iter().collect::<Vec<u64>>();
key_vec.sort();
for k in key_vec {
let seq = recover_seq(k, flanking);
... | random_line_split | |
qcloud.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from api.QcloudApi.qcloudapi import QcloudApi
import json
import sys
import datetime
import traceback
import logging
import re
from utils import send_alarm
from models import ServersModel, RdsModel, ServerConf
from Free.settings import QCLOUD_KEY, QCLOUD_VALUE
r... | ("change_region_cvm")
params = {"wanlp": "1", "needSecurityAgent": "1", "needMonitorAgent": "1", "storageType": '2'}
passwd = data['passwd1']
match = re.match(ur'^([a-z,A-z,0-9]{8,16}|[0-9,\W]{8,16}|[a-z,A-Z,\W]{8,16}|[a-z,A-Z,0-9,\W]{8,16})$', passwd)
if not match:
return "密码格式有误,请按要求输入"
... | data.pop | identifier_name |
qcloud.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from api.QcloudApi.qcloudapi import QcloudApi
import json
import sys
import datetime
import traceback
import logging
import re
from utils import send_alarm
from models import ServersModel, RdsModel, ServerConf
from Free.settings import QCLOUD_KEY, QCLOUD_VALUE
r... | passwd = data['passwd1']
match = re.match(ur'^([a-z,A-z,0-9]{8,16}|[0-9,\W]{8,16}|[a-z,A-Z,\W]{8,16}|[a-z,A-Z,0-9,\W]{8,16})$', passwd)
if not match:
return "密码格式有误,请按要求输入"
else:
params.update({"password": passwd})
for key, value in {"100002": "region_g2", "100003": "region_g... | {"wanlp": "1", "needSecurityAgent": "1", "needMonitorAgent": "1", "storageType": '2'}
| identifier_body |
qcloud.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from api.QcloudApi.qcloudapi import QcloudApi
import json
import sys
import datetime
import traceback
import logging
import re
from utils import send_alarm
from models import ServersModel, RdsModel, ServerConf
from Free.settings import QCLOUD_KEY, QCLOUD_VALUE
r... | break
region_change = {"100002": "gz", "100003": "gz", "200001": "sh", "800001": "bj", "300001": 'xg'}
for key, value in data.items():
if key in ("region_g2", 'region_g3', "region_s1", "region_b1", "region_x1", "passwd1", "passwd2", "csrfmiddlewaretoken"):
continue
par... | params.update({"zoneId": region})
| conditional_block |
qcloud.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
from api.QcloudApi.qcloudapi import QcloudApi
import json
import sys
import datetime
import traceback
import logging
import re
from utils import send_alarm
from models import ServersModel, RdsModel, ServerConf
from Free.settings import QCLOUD_KEY, QCLOUD_VALUE
r... | one['status'] ='运行中'
else:
one['status'] = '创建中'
for key,value in one.items():
one[key] = str(value)
atime = one["cdbInstanceDeadlineTime"].split(' ')
atime = atime[0].split('-')
d3 = datetime.datetime(i... | one['zoneId'] = zone.value
if one['status'] == 1:
| random_line_split |
views.py | from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from logging import getLogger
from django_redis import get_redis_connection
from decimal import Decimal
import json
from django import http
f... | # 构造购物车中被勾选商品的数据 new_cart_dict,{sku_id: 2, sku_id: 1}
new_cart_dict = {}
for sku_id in redis_selected:
new_cart_dict[int(sku_id)] = int(redis_cart[sku_id])
# 获取被勾选商品的sku_id
sku_ids = new_cart_dict.keys()
# 获取被勾选商品的sku信息
skus = SKU.objects.filter(id__in... | redis_cart = redis_conn.hgetall('carts_%s' % user.id)
# 被勾选的商品sku_id
redis_selected = redis_conn.smembers('selected_{}'.format(user.id)) | random_line_split |
views.py | from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from logging import getLogger
from django_redis import get_redis_connection
from decimal import Decimal
import json
from django import http
f... | lse:
# 返回响应
return http.JsonResponse({'code': RETCODE.OK, 'errmsg': err_msg[RETCODE.OK], 'order_id': order_id})
class OrderSettlementView(LoginRequiredMixin, View):
"""结算订单"""
def get(self, request):
"""查询并展示要结算的订单数据"""
# 获取登录用户
user = request.user
# 查询用... | e | conditional_block |
views.py | from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from logging import getLogger
from django_redis import get_redis_connection
from decimal import Decimal
import json
from django import http
f... | iew):
"""提交订单"""
def post(self, request):
"""保存订单基本信息和订单商品信息"""
# 接收参数
json_dict = json.loads(request.body.decode())
address_id = json_dict.get('address_id')
pay_method = json_dict.get('pay_method')
# 校验参数
if not all([address_id, pay_method]):
... | iredJsonMixin, V | identifier_name |
views.py | from django.core.paginator import Paginator, EmptyPage
from django.shortcuts import render
from django.views import View
from django.contrib.auth.mixins import LoginRequiredMixin
from logging import getLogger
from django_redis import get_redis_connection
from decimal import Decimal
import json
from django import http
f... | hod_name = OrderInfo.PAY_METHOD_CHOICES[order.pay_method-1][1]
order.sku_list = []
# 查询订单商品
order_goods = order.skus.all()
# 遍历订单商品
for order_good in order_goods:
sku = order_good.sku
sku.count = order_good.count
... | score = json_dict.get('score')
comment = json_dict.get('comment')
is_anonymous = json_dict.get('is_anonymous')
# 校验参数
if not all([order_id, sku_id, score, comment]):
return http.HttpResponseForbidden('缺少必传参数')
try:
OrderInfo.objects.filter(order_id=o... | identifier_body |
test1.go | // Copyright 2018 Alexander S.Kresin <alex@kresin.ru>, http://www.kresin.ru
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"fmt"
egui "github.com/alkresin/external"
"io/ioutil"
"strconv"
"time"
)
const (
CLR_LBLUE = 16759929
CLR_L... |
func ftab([]string) string {
egui.BeginPacket()
pFont := egui.CreateFont(&egui.Font{Name: "f1", Family: "Georgia", Height: 16})
pDlg := &egui.Widget{Name: "dlg2", X: 300, Y: 200, W: 200, H: 340, Title: "Tab", Font: pFont,
AProps: map[string]string{"NoExitOnEsc": "t","NoCloseAble": "t"}}
egui.InitDialog(pDlg)
... | {
arr := egui.GetValues(egui.Wnd("dlg"), []string{"edi1", "edi2", "comb", "chk1", "chk2", "rg", "upd1"})
egui.PLastWindow.Close()
egui.MsgInfo("Id: "+arr[0]+"\r\n"+"Date: "+arr[1]+"\r\n"+"Combo: "+arr[2]+"\r\n"+
"Married: "+arr[3]+"\r\n"+"Has children: "+arr[4]+"\r\n"+"Sex: "+arr[5]+"\r\n"+
"Age: "+arr[6], "Res... | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.