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 |
|---|---|---|---|---|
hh.js |
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("query-info")
var target = document.getElementById('zonedword-wrap');
let stringify=null
if($(target).is(':visible')){
let select_item = get_select_item()
stringify=JSON.stringify(select_item)
} 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("query-info")
var target = document.getElementById('zonedword-wrap');
let stringify=null
if($(target).is(':visible')){
let select_item = get_select_item()
stringify=JSON.stringify(select_item)
} 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 | .data
});
} else if("word-tag-complete"==request.message){
$.each($(".tag-item"),(index,ele)=>{ ele.remove() });
let tag_items = $.parseJSON(request.data);
init_word_tag(request.select_tag,tag_items)
}
});
function hide_ui_element(){
//隐藏界面无用元素
... | r-settting")
if(user_setting.length){
user_setting.fadeOut("normal")
}
$(this).off("click")
} | identifier_body | |
translate_baidu.js | session_list_selected(request.data)
} else if("user-query-complete"==request.message){
chrome.runtime.sendMessage({
message: 'get-word-tag',
data:request.data
});
} else if("word-tag-complete"==request.message){
$.each($(".tag-item")... |
//点击外围让阴影层消失
function dismiss_user_setting(){
if (event.target.closest(".user-settting")) return; | random_line_split | |
dict.js | ",
es: "Pasos de ejecución",
},
"Experiment Parameters": {
pt: "Parâmetros de execução",
es: "Parámetros de ejecución",
},
"New Experiment": {
pt: "Novo experimento",
es: "Nuevo experimento"
},
"Instructions (P: CPU | B: I/O)": {
pt: "Instruções (P: CPU | B: I... | 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 | 'I;16':
nchannel = 1
else:
nchannel = len(pic.mode)
img = img.view(pic.size[1], pic.size[0], nchannel)
# put it from HWC to CHW format
# yikes, this transpose takes 80% of the loading time/CPU
img = img.transpose(0, 1).transpose(0, 2).contiguous()
if isinstance(img, torch.ByteTe... |
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 | (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 |
# 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 | standard deviations for each channely.
Returns:
Tensor: Normalized Tensor image.
"""
if not _is_tensor_image(tensor):
raise TypeError('tensor is not a torch image.')
# TODO: make efficient
for t, m, s in zip(tensor, mean, std):
t.sub_(m).div_(s)
return tensor
def flip... | 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 | UNBIND"
EIP_STATUS_OFFLINING = "OFFLINING"
EIP_STATUS_BIND_ENI = "BIND_ENI"
EIP_STATUS_CREATE_FAILED = "CREATE_FAILED"
EIP_TYPE_CALCIP = "CalcIP" //表示设备ip
EIP_TYPE_WANIP = "WanIP" //普通公网ip
EIP_TYPE_EIP = "EIP" //弹性公网ip
EIP_TYPE_ANYCASTEIP = "AnycastEIP" //加速EIP
)
type S... | 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 | UNBIND"
EIP_STATUS_OFFLINING = "OFFLINING"
EIP_STATUS_BIND_ENI = "BIND_ENI"
EIP_STATUS_CREATE_FAILED = "CREATE_FAILED"
EIP_TYPE_CALCIP = "CalcIP" //表示设备ip
EIP_TYPE_WANIP = "WanIP" //普通公网ip
EIP_TYPE_EIP = "EIP" //弹性公网ip
EIP_TYPE_ANYCASTEIP = "AnycastEIP" //加速EIP
)
type S... | 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 | "UNBIND"
EIP_STATUS_OFFLINING = "OFFLINING"
EIP_STATUS_BIND_ENI = "BIND_ENI"
EIP_STATUS_CREATE_FAILED = "CREATE_FAILED"
EIP_TYPE_CALCIP = "CalcIP" //表示设备ip
EIP_TYPE_WANIP = "WanIP" //普通公网ip
EIP_TYPE_EIP = "EIP" //弹性公网ip
EIP_TYPE_ANYCASTEIP = "AnycastEIP" //加速EIP
)
type... | }
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 | UNBIND"
EIP_STATUS_OFFLINING = "OFFLINING"
EIP_STATUS_BIND_ENI = "BIND_ENI"
EIP_STATUS_CREATE_FAILED = "CREATE_FAILED"
EIP_TYPE_CALCIP = "CalcIP" //表示设备ip
EIP_TYPE_WANIP = "WanIP" //普通公网ip
EIP_TYPE_EIP = "EIP" //弹性公网ip
EIP_TYPE_ANYCASTEIP = "AnycastEIP" //加速EIP
)
type S... | 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 | dictionary
if isinstance(template['provider'], DictNode):
if template['provider'].get('name', '').lower() not in SUPPORTED_PROVIDERS:
return False
# Case provider is direct provider name
if isinstance(template['provider'], StrNode):
if template['provider'... | s = s[1:-1] | conditional_block | |
parser.py | _TOKEN = 'stackTags' # nosec
TAGS_TOKEN = 'tags' # nosec
SUPPORTED_PROVIDERS = ['aws']
QUOTED_WORD_SYNTAX = re.compile(r"(?:('|\").*?\1)")
FILE_LOCATION_PATTERN = re.compile(r'^file\(([^?%*:|"<>]+?)\)')
def parse(filename):
template = None
template_lines = None
try:
(template, template_lines) =... | (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 | _TOKEN = 'stackTags' # nosec
TAGS_TOKEN = 'tags' # nosec
SUPPORTED_PROVIDERS = ['aws']
QUOTED_WORD_SYNTAX = re.compile(r"(?:('|\").*?\1)")
FILE_LOCATION_PATTERN = re.compile(r'^file\(([^?%*:|"<>]+?)\)')
def parse(filename):
template = None
template_lines = None
try:
(template, template_lines) =... | loop_count = 0
for _ in range(0, 25):
loop_count += 1
made_change = False
if process_variables_loop(template, compiled_var_pattern,
# vt = var type
# vl = var location
# ft = fallback v... | """
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 | , template, []):
return True
return False
def process_variables(template, filename):
"""
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", temp... |
if block_start_index < len(string): | random_line_split | |
context_test.go | ")
}
}
func TestOffsetMeasurement(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop()
serverTime := time.Unix(0, 20)
serverClock := hlc.NewClock(serverTime.UnixNano)
serverCtx := newNodeTestContext(serverClock, stopper)
s, ln := newTestServer(t, serverCtx, true)
r... | {
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 | )
if err != nil {
t.Fatal(err)
}
return s, ln
}
func TestHeartbeatCB(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop()
serverClock := hlc.NewClock(time.Unix(0, 20).UnixNano)
serverCtx := newNodeTestContext(serverClock, stopper)
s, ln := newTestServer(t, serve... |
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 | TestServer(t, serverCtx, true)
remoteAddr := ln.Addr().String()
RegisterHeartbeatServer(s, &HeartbeatService{
clock: serverClock,
remoteClockMonitor: serverCtx.RemoteClocks,
})
// Clocks don't matter in this test.
clientCtx := newNodeTestContext(serverClock, stopper)
var once sync.Once
ch := ... | 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 | )
if err != nil {
t.Fatal(err)
}
return s, ln
}
func TestHeartbeatCB(t *testing.T) {
defer leaktest.AfterTest(t)()
stopper := stop.NewStopper()
defer stopper.Stop()
serverClock := hlc.NewClock(time.Unix(0, 20).UnixNano)
serverCtx := newNodeTestContext(serverClock, stopper)
s, ln := newTestServer(t, serve... | () 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 | цательным свободным членом, исключая последний столбец , добавляем 1 чтобы номер столбца был человекочитаемым
col = filled_table[:-1, min_in_row_column_number]
# все коэффициенты ограничений этого столбца
last_column = filled_table[:-1,-1]
for i, b in zip(col, last_column):
i... | conditional_block | ||
my_optimisation.py | = amount_columns(amount_variables,amount_constraints)
empty_table = np.zeros((r, c))
return empty_table
#Количество строк = кол-ву ограничений + целевая функция amount_constraints+1
#Количество столбцов = кол-ву переменных + кол-ву дополнительных переменных для приведения системы к каноническому виду +... | е осталось отрицательных
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 | c = amount_columns(amount_variables,amount_constraints)
empty_table = np.zeros((r, c))
return empty_table
#Количество строк = кол-ву ограничений + целевая функция amount_constraints+1
#Количество столбцов = кол-ву переменных + кол-ву дополнительных переменных для приведения системы к каноническому виду... | 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 | = amount_columns(amount_variables,amount_constraints)
empty_table = np.zeros((r, c))
return empty_table
#Количество строк = кол-ву ограничений + целевая функция amount_constraints+1
#Количество столбцов = кол-ву переменных + кол-ву дополнительных переменных для приведения системы к каноническому виду +... | 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 | have to solve this problem here
const toBase64 =
(() => {
if (typeof Buffer !== 'undefined' && Buffer !== null) {
return str => new Buffer(str).toString('base64');
} else {
// adapted/modified from https://github.com/rwz/base64.coffee
const base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqr... | if (this.sodaOpts.apiToken != null) { client.set('X-App-Token', this.sodaOpts.apiToken); }
if ((this.sodaOpts.username != null) && (this.sodaOpts.password != null)) { client.set('Authorization', "Basic " + toBase64(`${this.sodaOpts.username}:${this.sodaOpts.password}`)); }
if (this.sodaOpts.accessToke... | {
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 | i have to solve this problem here
const toBase64 =
(() => {
if (typeof Buffer !== 'undefined' && Buffer !== null) {
return str => new Buffer(str).toString('base64');
} else {
// adapted/modified from https://github.com/rwz/base64.coffee
const base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop... | (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 | have to solve this problem here
const toBase64 =
(() => {
if (typeof Buffer !== 'undefined' && Buffer !== null) {
return str => new Buffer(str).toString('base64');
} else | enc4 = 64;
}
result.push(base64Lookup[enc1]);
result.push(base64Lookup[enc2]);
result.push(base64Lookup[enc3]);
result.push(base64Lookup[enc4]);
}
return result.join('');
};
return str => rawToBase64(unescape(encodeURIComponent(str)));
}
})();
c... | {
// 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 | i have to solve this problem here
const toBase64 =
(() => {
if (typeof Buffer !== 'undefined' && Buffer !== null) {
return str => new Buffer(str).toString('base64');
} else {
// adapted/modified from https://github.com/rwz/base64.coffee
const base64Lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnop... | 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 | (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 | }
/*This function was created for checking for correct input when integers were to be used.
It is necessary before trying to convert the string to an integer.
This is implimented with the tips. */
fn strchecker(mut temp: String) -> String{
while !temp.contains(&"1") && !temp.contains(&"2") && !temp.contains(&"3")... | } else if tip == 3{
total += DOLLAR; | random_line_split | |
main.rs | return characters, by calling removed, and then return the string splice */
fn rdin() -> String{
let mut reader = String::new();
std::io::stdin().read_line(&mut reader).unwrap();
reader = removed(reader.to_lowercase()); // Changes everything to lowercase so it is not a case sensetive program.
println!(... | items.insert(String::from("pizza"), 2.95);
items.insert(String::from("fries"), 1.95);
items.insert(String::from("stake"), 9.95);
//Creates a vector. It is necessary to specify the data type that will be in the vector.
let mut itemPrice: Vec<f32> = Vec::new();
let mut total: f32;
let mut five... | {
//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 | let x_max = self.frame_width as i32 - window_half;
let y_max = self.frame_height as i32 - window_half;
#[cfg(debug_assertions)]
{
println!(
"distance of new in-window max from window center: x = {}, y = {}",
x_delta, y_delta,
);
}... | {
ImageBuffer::from_vec(width, height, buf.iter().map(|c| *c as u8).collect()).unwrap()
} | identifier_body | |
lib.rs | ));
// if the tracker made the PSR threshold, update it.
// if not, we increment its death ticker.
if tracker.last_psr > self.settings.psr_threshold {
tracker.update(frame);
*death_watch = 0u32;
} else {
*death_watch += 1;
... | (&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 | _cmp(&b.1.re).unwrap_or(Ordering::Equal)
})
.unwrap(); // we can unwrap the result of max_by(), as we are sure filtered.len() > 0
// convert the array index of the max to the coordinates in the window
let max_coord_in_window = index_to_coords(self.window_size, maxind as u32);
... | 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 | 53>").unwrap(),
}
}
}
#[async_trait]
impl EventHandler for Handler {
async fn presence_update(&self, ctx: Context, data: PresenceUpdateEvent) {
// oofbot only handles guild presence updates
if data.guild_id.is_none() {
return;
}
// Dogebot is oofbots greatest enemy. We got some checks in here just for h... |
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 | 53>").unwrap(),
}
}
}
#[async_trait]
impl EventHandler for Handler {
async fn presence_update(&self, ctx: Context, data: PresenceUpdateEvent) {
// oofbot only handles guild presence updates
if data.guild_id.is_none() {
return;
}
// Dogebot is oofbots greatest enemy. We got some checks in here just for h... | })
.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 | (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 { Unit } from '../Unit';
export class Game {
public replay: Replay;
public map: GameMap;
public rng: () => number = Math.random;
private globalUnitIDCount = 0;
public state: Game.State = {
turn: 0,
teamStates: {
[Unit.TEAM.A]: {
units: new Map(),
points: 0,
},
... |
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 | Unit.TEAM.A]: {
units: new Map(),
points: 0,
},
[Unit.TEAM.B]: {
units: new Map(),
points: 0,
},
},
};
constructor(public configs: AIMatchConfigs) {
Unit.ALL_TEAMS.forEach((team) => {
this.state.teamStates[team].points = configs.parameters.INITIAL_POIN... | if (b >= this.configs.parameters.BREAKDOWN_MAX) {
brokenDownUnits.push(unit); | random_line_split | |
index.ts | ';
import { Unit } from '../Unit';
export class Game {
public replay: Replay;
public map: GameMap;
public rng: () => number = Math.random;
private globalUnitIDCount = 0;
public state: Game.State = {
turn: 0,
teamStates: {
[Unit.TEAM.A]: {
units: new Map(),
points: 0,
},
... | (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 { Unit } from '../Unit';
export class Game {
public replay: Replay;
public map: GameMap;
public rng: () => number = Math.random;
private globalUnitIDCount = 0;
public state: Game.State = {
turn: 0,
teamStates: {
[Unit.TEAM.A]: {
units: new Map(),
points: 0,
},
... |
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 | PairsFound: 0,
score: [0,0],
nickname1: "Hopla",
nickname2: "Titeuf",
oneIsNext: false,
infos: " | Start pour jouer",
cXr: 0, //Nombre de cases (Columns * Rows)
col: 0, //Nombre de colones
};
this.handleFormPairs = this.handleFormPairs.bind(this)
this.handleFormNi... | 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 | Found: 0,
score: [0,0],
nickname1: "Hopla",
nickname2: "Titeuf",
oneIsNext: false,
infos: " | Start pour jouer",
cXr: 0, //Nombre de cases (Columns * Rows)
col: 0, //Nombre de colones
};
this.handleFormPairs = this.handleFormPairs.bind(this)
this.handleFormNick1 =... | }
console.log("col: " + col + " | cXr: "+ cXr + " | " + this.state.nbPairs*2)
// Création de l'array a affiché rempli de null
console.log("nbPairs: " + prevstate.nbPairs)
let squares_print = Array(parseInt(prevstate.nbPairs, 10) * 2).fill("?")
squares_print = squares_print.concat(Ar... | {
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 | PairsFound: 0,
score: [0,0],
nickname1: "Hopla",
nickname2: "Titeuf",
oneIsNext: false,
infos: " | Start pour jouer",
cXr: 0, //Nombre de cases (Columns * Rows)
col: 0, //Nombre de colones
};
this.handleFormPairs = this.handleFormPairs.bind(this)
this.handleFormNi... | ){
//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 | id)
}
//random
else if (modes[2].isChecked){
return(modes[2].id)
}
}
handleSquareClick(i) {
this.setState((prevstate) => {
let result = { ...prevstate.result }
let squares = { ...prevstate.squares }
let squares_print = { ...prevstate.squares_print }
let score = ... | 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 | {
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 | ,
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_memory: extern "C" fn(usi... | 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 | -17": 4, "X": 5}
common = ["the", "and", "of"] # List of common words to be filtered from titles
flag = True
class | :
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 | -17": 4, "X": 5}
common = ["the", "and", "of"] # List of common words to be filtered from titles
flag = True
class Movie:
def __init__(self):
self.title = ""
self.titleWords = []
self.year = 0
self.actor1 = ""
self.actor2 = ""
self.actor3 = ""
self.directo... | i.criteria.append("Actor: "+i.actor1)
if i.actor2 == inFilm.actor1 or i.actor2 == inFilm.actor2 or i.actor2 == inFilm.actor3:
i.relevance += (35 * actorWeight)
i.criteria.append("Actor: "+i.actor2)
if i.actor3 == inFilm.actor1 or i.actor3 == inFilm... | 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 | -17": 4, "X": 5}
common = ["the", "and", "of"] # List of common words to be filtered from titles
flag = True
class Movie:
def __init__(self):
self.title = ""
self.titleWords = []
self.year = 0
self.actor1 = ""
self.actor2 = ""
self.actor3 = ""
self.directo... | 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 | -17": 4, "X": 5}
common = ["the", "and", "of"] # List of common words to be filtered from titles
flag = True
class Movie:
def __init__(self):
self.title = ""
self.titleWords = []
self.year = 0
self.actor1 = ""
self.actor2 = ""
self.actor3 = ""
self.directo... |
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 | if !kernel.prog.devs.contains(&dev) {
return Err(CL_INVALID_DEVICE);
}
Ok(match *q {
CL_KERNEL_COMPILE_WORK_GROUP_SIZE => cl_prop::<[usize; 3]>(kernel.work_group_size),
CL_KERNEL_LOCAL_MEM_SIZE => cl_prop::<cl_ulong>(kernel.local_mem_size(&dev)),
CL_KERN... | 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 | if !kernel.prog.devs.contains(&dev) {
return Err(CL_INVALID_DEVICE);
}
Ok(match *q {
CL_KERNEL_COMPILE_WORK_GROUP_SIZE => cl_prop::<[usize; 3]>(kernel.work_group_size),
CL_KERNEL_LOCAL_MEM_SIZE => cl_prop::<cl_ulong>(kernel.local_mem_size(&dev)),
CL_KERN... | (
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 | if !kernel.prog.devs.contains(&dev) {
return Err(CL_INVALID_DEVICE);
}
Ok(match *q {
CL_KERNEL_COMPILE_WORK_GROUP_SIZE => cl_prop::<[usize; 3]>(kernel.work_group_size),
CL_KERNEL_LOCAL_MEM_SIZE => cl_prop::<cl_ulong>(kernel.local_mem_size(&dev)),
CL_KERN... | // kernel_name such as the number of arguments, the argument types are not the same for all
// devices for which the program executable has been built.
let devs = get_devices_with_valid_build(&p)?;
let kernel_args: HashSet<_> = devs.iter().map(|d| p.args(d, &name)).collect();
if kernel_args.len() !=... | {
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 | if !kernel.prog.devs.contains(&dev) {
return Err(CL_INVALID_DEVICE);
}
Ok(match *q {
CL_KERNEL_COMPILE_WORK_GROUP_SIZE => cl_prop::<[usize; 3]>(kernel.work_group_size),
CL_KERNEL_LOCAL_MEM_SIZE => cl_prop::<cl_ulong>(kernel.local_mem_size(&dev)),
CL_KERN... |
_ => {
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 | _times_to_upsample)
def raw_face_landmarks(face_image, face_locations_=None, model="large"):
if face_locations_ is None:
face_locations_ = raw_face_locations(face_image)
else:
face_locations_ = [css2rect(face_location) for face_location in face_locations_]
pose_predictor = pose_predictor_... | 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 | _to_upsample)
def raw_face_landmarks(face_image, face_locations_=None, model="large"):
if face_locations_ is None:
face_locations_ = raw_face_locations(face_image)
else:
face_locations_ = [css2rect(face_location) for face_location in face_locations_]
pose_predictor = pose_predictor_68_poi... | 不进行旋转时
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 | _to_upsample)
def raw_face_landmarks(face_image, face_locations_=None, model="large"):
if face_locations_ is None:
face_locations_ = raw_face_locations(face_image) | 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 | 向量初始化
: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 | _id, coalesce(name, cast(path_id AS TEXT)), coalesce(tags_json, '{{}}')
FROM gfa1_path {} ORDER BY path_id",
where_clause
);
let mut paths_query = db.prepare(&paths_query_sql)?;
let mut elements_query = db.prepare(
"SELECT
coalesce(name, cast(segment_id AS TEXT)) AS segm... | writer.write_fmt(format_args!(
"\"{}\",\"~{}:{}-{}\"\n",
name, | random_line_split | |
view.rs | }
/// Start `less -S` and call `write` with its standard input pipe.
/// Tolerate BrokenPipe errors (user exited before viewing all data)
pub fn less<F>(write: F) -> Result<()>
where
F: FnOnce(&mut dyn io::Write) -> Result<()>,
{
if which::which("less").is_err() {
return write(&mut io::stdout());
}... | (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 |
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 | 4 {
fmt.Println("Error: your tsv file broken")
History = nil
return false
}
History = append(History, historyData{Device: strs[0], Pre: strs[1], Aft: strs[2], Params: strs[3]})
}
fmt.Println("importFile: ", params)
return true
}
func replayMode(importFile string) {
if Exists(importFile) ==... | {
SetActiveWindow(HWND(setHwnd), Debug)
} | conditional_block | |
do.go | bufStrs, strs = keyDown(altFlag, int(ev.Rawcode), strs, string(ev.Keychar), bufStrs)
preWindow = aftWindow
aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false)
}
if ev.Kind == 4 || ev.Kind == 5 { //KeyHold = 4,KeyUp = 5
altFlag = keyHoldUp(int(ev.Rawcode), int(ev.Kind)... | return 1
})
EnumWindows(cb, 0)
return uintptr(hwnd)
| random_line_split | |
do.go | [i].Pre, Debug); ChangeTarget(targetHwnd) == false {
fmt.Println("not found title: ", History[i].Pre)
if len(History[i].Aft) > 0 {
if targetHwnd := FocusWindow(History[i].Aft, Debug); ChangeTarget(targetHwnd) == false {
fmt.Println("not found title: ", History[i].Aft)
return false
}
}
... | keyHoldUp | identifier_name | |
do.go | .Kind == 7 { //MouseHold
if actFlag == false {
actFlag = true
aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false)
}
addMouseAction(int(ev.Button), int(ev.X), int(ev.Y))
preWindow = aftWindow
aftWindow = getHwndToTitle(GetWindow("GetForegroundWindow", false), false)
... | {
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 | c RDecrQ
0x3d Set VBucket *
0x3e Get VBucket *
0x3f Del VBucket *
0x40 TAP Connect *
0x41 TAP Mutation *
0x42 TAP Delete *
0x43 TAP Flush *
0x44 TAP Opaque *
0x45 TAP VBucket Set *
0x46 TAP Checkpoint Start *
0x47 TAP Checkpoint End *
*/
const (
OpGet = 0x00
OpSet = 0x01
OpAdd = 0x02
OpReplace = 0x0... | Start | identifier_name | |
server.go | long a connection has been idle.
CommandSeq uint64 // Every connection starts counting command from 0
ReadBuf []byte // Local to the goroutine handling a connection. Better utilizing memory.
}
/*
0x0000 No error
0x0001 Key not found
0x0002 Key exists
0x0003 Value too large
0x0004 Invalid arguments
0x0005... | err = rw.WriteByte(header.ExtraLength)
if err != nil {
return err
}
err = rw.WriteByte(header.DataType)
if err != nil {
return err
}
err = rw.WriteByte(GetNthByteFromUint16(header.Status, 0))
if err != nil {
return err
}
err = rw.WriteByte(GetNthByteFromUint16(header.Status, 1))
if err != nil {
ret... | {
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 | long a connection has been idle.
CommandSeq uint64 // Every connection starts counting command from 0
ReadBuf []byte // Local to the goroutine handling a connection. Better utilizing memory.
}
/*
0x0000 No error
0x0001 Key not found
0x0002 Key exists
0x0003 Value too large
0x0004 Invalid arguments
0x0005... |
for pos := 0; pos < 4; pos++ {
err = rw.WriteByte(GetNthByteFromUint32(header.TotalBodyLength, pos))
if err != nil {
return err
}
}
for pos := 0; pos < | {
return err
} | conditional_block |
server.go | long a connection has been idle.
CommandSeq uint64 // Every connection starts counting command from 0
ReadBuf []byte // Local to the goroutine handling a connection. Better utilizing memory.
}
/*
0x0000 No error
0x0001 Key not found
0x0002 Key exists
0x0003 Value too large
0x0004 Invalid arguments
0x0005... | 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 | /luci/config/validation"
"go.chromium.org/luci/server/auth"
api "go.chromium.org/luci/scheduler/api/scheduler/v1"
"go.chromium.org/luci/scheduler/appengine/internal"
"go.chromium.org/luci/scheduler/appengine/messages"
"go.chromium.org/luci/scheduler/appengine/task"
)
// defaultMaxTriggersPerInvocation limits num... | 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 | /luci/config/validation"
"go.chromium.org/luci/server/auth"
api "go.chromium.org/luci/scheduler/api/scheduler/v1"
"go.chromium.org/luci/scheduler/appengine/internal"
"go.chromium.org/luci/scheduler/appengine/messages"
"go.chromium.org/luci/scheduler/appengine/task"
)
// defaultMaxTriggersPerInvocation limits num... | (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 | /luci/config/validation"
"go.chromium.org/luci/server/auth"
api "go.chromium.org/luci/scheduler/api/scheduler/v1"
"go.chromium.org/luci/scheduler/appengine/internal"
"go.chromium.org/luci/scheduler/appengine/messages"
"go.chromium.org/luci/scheduler/appengine/task"
)
// defaultMaxTriggersPerInvocation limits num... | 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 | /luci/config/validation"
"go.chromium.org/luci/server/auth"
api "go.chromium.org/luci/scheduler/api/scheduler/v1"
"go.chromium.org/luci/scheduler/appengine/internal"
"go.chromium.org/luci/scheduler/appengine/messages"
"go.chromium.org/luci/scheduler/appengine/task"
)
// defaultMaxTriggersPerInvocation limits num... |
// 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 | Otherwise must be > 0.
//
// Note that this setting applies per partition. If BufferedByteLimit is being
// used to bound memory usage, keep in mind the number of partitions in the
// topic.
//
// Note that Pub/Sub Lite topics are provisioned a publishing throughput
// capacity, per partition, shared by all pub... | {
wireSettings := wire.ReceiveSettings{
MaxOutstandingMessages: DefaultReceiveSettings.MaxOutstandingMessages,
MaxOutstandingBytes: DefaultReceiveSettings.MaxOutstandingBytes,
Timeout: DefaultReceiveSettings.Timeout,
Partitions: s.Partitions,
Framework: wire.Framewo... | identifier_body | |
settings.go | RequestBytes = wire.MaxPublishRequestBytes
)
// KeyExtractorFunc is a function that extracts an ordering key from a Message.
type KeyExtractorFunc func(*pubsub.Message) []byte
// PublishMessageTransformerFunc transforms a pubsub.Message to a Pub/Sub Lite
// PubSubMessage API proto. If this returns an error, the pubsu... | 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 | // PublisherClient terminating during short periods of backend unavailability.
Timeout time.Duration
// The maximum number of bytes that the publisher will keep in memory before
// returning ErrOverflow. If BufferedByteLimit is 0, it will be treated as
// DefaultPublishSettings.BufferedByteLimit. Otherwise must be... | {
wireSettings.MaxOutstandingBytes = s.MaxOutstandingBytes
} | conditional_block | |
settings.go | RequestBytes = wire.MaxPublishRequestBytes
)
// KeyExtractorFunc is a function that extracts an ordering key from a Message.
type KeyExtractorFunc func(*pubsub.Message) []byte
// PublishMessageTransformerFunc transforms a pubsub.Message to a Pub/Sub Lite
// PubSubMessage API proto. If this returns an error, the pubsu... | () wire.PublishSettings {
wireSettings := wire.PublishSettings{
DelayThreshold: DefaultPublishSettings.DelayThreshold,
CountThreshold: DefaultPublishSettings.CountThreshold,
ByteThreshold: DefaultPublishSettings.ByteThreshold,
Timeout: DefaultPublishSettings.Timeout,
BufferedByteLimit: De... | toWireSettings | identifier_name |
honeyproxyserver.py | config.json","r") as f:
config = json.loads(f.read())
if not os.path.isdir(config["logdir"]):
os.makedirs(config["logdir"])
engine = create_engine('sqlite:///honeyproxy.sqlite', echo=False)
Session = sessionmaker(bind=engine)
#session = Session()
Base = declarative_base()
class Analysis(Base):
__tablenam... | (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 | config.json","r") as f:
config = json.loads(f.read())
if not os.path.isdir(config["logdir"]):
os.makedirs(config["logdir"])
engine = create_engine('sqlite:///honeyproxy.sqlite', echo=False)
Session = sessionmaker(bind=engine)
#session = Session()
Base = declarative_base()
class Analysis(Base):
__tablenam... |
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 | config.json","r") as f:
config = json.loads(f.read())
if not os.path.isdir(config["logdir"]):
os.makedirs(config["logdir"])
engine = create_engine('sqlite:///honeyproxy.sqlite', echo=False)
Session = sessionmaker(bind=engine)
#session = Session()
Base = declarative_base()
class Analysis(Base):
__tablenam... | "-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 | config.json","r") as f:
config = json.loads(f.read())
if not os.path.isdir(config["logdir"]):
os.makedirs(config["logdir"])
engine = create_engine('sqlite:///honeyproxy.sqlite', echo=False)
Session = sessionmaker(bind=engine)
#session = Session()
Base = declarative_base()
class Analysis(Base):
__tablenam... |
@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 | time.Time
}
func newTestRunner(t *testing.T) *testRunner {
t.Helper()
return &testRunner{
T: t,
dir: t.TempDir(),
ch: make(chan []*targetgroup.Group),
done: make(chan struct{}),
stopped: make(chan struct{}),
tgs: make(map[string]*targetgroup.Group),
}
}
// copyFile atomically co... | (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 | At time.Time
}
func newTestRunner(t *testing.T) *testRunner {
t.Helper()
return &testRunner{
T: t,
dir: t.TempDir(),
ch: make(chan []*targetgroup.Group),
done: make(chan struct{}),
stopped: make(chan struct{}),
tgs: make(map[string]*targetgroup.Group),
}
}
// copyFile atomically ... | }
}
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 | time.Time
}
func newTestRunner(t *testing.T) *testRunner {
t.Helper()
return &testRunner{
T: t,
dir: t.TempDir(),
ch: make(chan []*targetgroup.Group),
done: make(chan struct{}),
stopped: make(chan struct{}),
tgs: make(map[string]*targetgroup.Group),
}
}
// copyFile atomically co... |
}()
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 | time.Time
}
func newTestRunner(t *testing.T) *testRunner {
t.Helper()
return &testRunner{
T: t,
dir: t.TempDir(),
ch: make(chan []*targetgroup.Group),
done: make(chan struct{}),
stopped: make(chan struct{}),
tgs: make(map[string]*targetgroup.Group),
}
}
// copyFile atomically co... |
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 | 4, 4,
4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, ... | (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 | : u64,
left_too_short: u64,
right_too_short: u64,
}
impl ResCounter {
fn new() -> Self {
Self {
linker_reads: 0,
score_too_low: 0,
left_too_short: 0,
right_too_short: 0,
}
}
fn count(&mut self, res: &ExtractRes) {
match res{
... | random_line_split | ||
qcloud.py | 中', '21': '维护中'}
PAY_TYPE = {'0': '按月结算的后付费', '1': "包年包月", "2": '按量计费'}
NET_PAY = {'0': '按月结算的后付费', '1': '包年包月', '2': '按流量', '3': "按带宽"}
#腾讯给的调用api的SDK
def qcloud(module, action, region, params):
config = {
'Region': region,
'secretId': QCLOUD_KEY,
'secretKey': QCLOUD_VALUE,
... | ("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 | 中', '21': '维护中'}
PAY_TYPE = {'0': '按月结算的后付费', '1': "包年包月", "2": '按量计费'}
NET_PAY = {'0': '按月结算的后付费', '1': '包年包月', '2': '按流量', '3': "按带宽"}
#腾讯给的调用api的SDK
def qcloud(module, action, region, params):
config = {
'Region': region,
'secretId': QCLOUD_KEY,
'secretKey': QCLOUD_VALUE,
... | 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 | ', '21': '维护中'}
PAY_TYPE = {'0': '按月结算的后付费', '1': "包年包月", "2": '按量计费'}
NET_PAY = {'0': '按月结算的后付费', '1': '包年包月', '2': '按流量', '3': "按带宽"}
#腾讯给的调用api的SDK
def qcloud(module, action, region, params):
config = {
'Region': region,
'secretId': QCLOUD_KEY,
'secretKey': QCLOUD_VALUE,
... | 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 | 中', '21': '维护中'}
PAY_TYPE = {'0': '按月结算的后付费', '1': "包年包月", "2": '按量计费'}
NET_PAY = {'0': '按月结算的后付费', '1': '包年包月', '2': '按流量', '3': "按带宽"}
#腾讯给的调用api的SDK
def qcloud(module, action, region, params):
config = {
'Region': region,
'secretId': QCLOUD_KEY,
'secretKey': QCLOUD_VALUE,
... | 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 | 错误,暴力回滚
except Exception as e:
logger.error(e)
transaction.savepoint_rollback(save_id)
return http.JsonResponse({'code': RETCODE.COMMITMENTERR, 'errmsg': err_msg[RETCODE.COMMITMENTERR]})
else:
# 提交事务
transaction.save... | 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 | onymous, bool):
return http.HttpResponseForbidden('参数is_anonymous错误')
# 以下操作数据库的操作,开启作为一次事务
with transaction.atomic():
# 在数据库操作前,创建保存点(数据库最初的状态)
save_id = transaction.savepoint()
try:
# 保存订单商品评价数据
OrderGoods.objects.filt... | e | conditional_block | |
views.py | 未被评价的商品信息
try:
uncomment_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False)
except Exception as e:
logger.error(e)
return http.HttpResponseServerError('订单商品信息出错')
# 构造待评价商品数据
uncomment_goods_list = []
for goods in uncommen... | 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 | 未被评价的商品信息
try:
uncomment_goods = OrderGoods.objects.filter(order_id=order_id, is_commented=False)
except Exception as e:
logger.error(e)
return http.HttpResponseServerError('订单商品信息出错')
# 构造待评价商品数据
uncomment_goods_list = []
for goods in uncommen... | save_id = transaction.savepoint()
try:
# 保存订单商品评价数据
OrderGoods.objects.filter(order_id=order_id, sku_id=sku_id, is_commented=False).update(
comment=comment,
score=score,
is_anonymous=is_anonymous,
... | 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 | egui.EndMenu()
egui.Menu("Help")
{
egui.AddMenuItem("About", 0, nil, "hwg_MsgInfo(hb_version()+chr(10)+chr(13)+hwg_version(),\"About\")")
}
egui.EndMenu()
}
egui.EndMenu()
pPanel := pWindow.AddWidget(&egui.Widget{Type: "paneltop", H: 40,
AProps: map[string]string{"HStyle": "st1"}})
pPanel.AddWidget... |
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 |
test1.go | (&egui.Widget{Type: "check", Name: "chk2", X: 24, Y: 148, W: 150, H: 24, Title: "Has children"})
pGroup := pDlg.AddWidget(&egui.Widget{Type: "radiogr", Name: "rg", X: 200, Y: 110, W: 180, H: 76, Title: "Radio"})
pDlg.AddWidget(&egui.Widget{Type: "radio", X: 224, Y: 124, W: 150, H: 24, Title: "Male"})
pDlg.AddWidget... | fmbox2 | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.