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 |
|---|---|---|---|---|
index.ts | /*!
* Copyright 2019 Kopano and its contributors
*
* Use of this source code is governed by a MIT license
* that can be found in the LICENSE.txt file.
*
* @author Kopano <https://kopano.com>
* @license MIT
* @preserve
*/
import {
API,
Glue,
Controller,
ICallData,
IInitData,
IEmbeddOptions,
IEnableOp... |
if (options && options.timeout) {
state.retryTimer = setTimeout(() => {
if (!state.glue) {
retry();
}
}, options.timeout);
} else {
reject(new Error('glue timeout'));
}
});
append();
});
}
/**
* Enables glue for the provided sourceWindow with options.
*
* @param sourceWind... | {
delete state.glue;
} | conditional_block |
index.ts | /*!
* Copyright 2019 Kopano and its contributors
*
* Use of this source code is governed by a MIT license
* that can be found in the LICENSE.txt file.
*
* @author Kopano <https://kopano.com>
* @license MIT
* @preserve
*/
import {
API,
Glue,
Controller,
ICallData,
IInitData,
IEmbeddOptions,
IEnableOp... | (url: string, container: Element, options?: IEmbeddOptions): Promise<Glue> {
const state: {
glue?: Glue;
beforeInitResolve?: (value?: unknown) => void;
beforeInitReject?: (reason?: unknown) => void;
retryTimer?: ReturnType<typeof setTimeout>;
} = {};
return new Promise((resolve, reject) => {
// Add defau... | embed | identifier_name |
index.ts | /*!
* Copyright 2019 Kopano and its contributors
*
* Use of this source code is governed by a MIT license
* that can be found in the LICENSE.txt file.
*
* @author Kopano <https://kopano.com>
* @license MIT
* @preserve
*/
import {
API,
Glue,
Controller,
ICallData,
IInitData,
IEmbeddOptions,
IEnableOp... | }
frame.addEventListener('load', () => {
if (state.glue) {
delete state.glue;
}
if (options && options.timeout) {
state.retryTimer = setTimeout(() => {
if (!state.glue) {
retry();
}
}, options.timeout);
} else {
reject(new Error('glue timeout'));
}
});
append();
}... | }, 1000); // NOTE(longsleep): Retry time hardcoded - is it needed to have a configuration? | random_line_split |
index.ts | /*!
* Copyright 2019 Kopano and its contributors
*
* Use of this source code is governed by a MIT license
* that can be found in the LICENSE.txt file.
*
* @author Kopano <https://kopano.com>
* @license MIT
* @preserve
*/
import {
API,
Glue,
Controller,
ICallData,
IInitData,
IEmbeddOptions,
IEnableOp... |
export {
Glue,
Controller,
embed,
enable,
}
export default Glue;
| {
return new Promise((resolve, reject) => {
if (!sourceWindow) {
sourceWindow = window.parent;
}
// Get glue mode.
const mode = getGlueParameter('mode');
if (sourceWindow === self || mode === null) {
// Return empty Glue API if we are self, or glue mode is not set. It
// this means Glue is not act... | identifier_body |
day_14.rs | //! This is my solution for [Advent of Code - Day 14](https://adventofcode.com/2020/day/14) -
//! _Docking Data_
//!
//! This was themed around bitwise operations. The challenge was mostly parsing the puzzle
//! description into the bitwise operations needed. This was the first time I needed an Either
//! implementatio... | for &address in addresses.iter() {
new_addresses.insert(address | (1 << i));
}
for &new_address in new_addresses.iter() {
addresses.insert(new_address);
};
}
}
addresses
}
/// Sum a memory snapshot
///
/// Both puzzle par... | let mut new_addresses = HashSet::new();
| random_line_split |
day_14.rs | //! This is my solution for [Advent of Code - Day 14](https://adventofcode.com/2020/day/14) -
//! _Docking Data_
//!
//! This was themed around bitwise operations. The challenge was mostly parsing the puzzle
//! description into the bitwise operations needed. This was the first time I needed an Either
//! implementatio... |
#[test]
fn can_explode_addresses() {
let expected: HashSet<usize> = vec!(26usize, 27usize, 58usize, 59usize).into_iter().collect();
assert_eq!(
expected,
explode_addresses(
&Mask {
mask: 0b000000000000000000000000000000100001,
... | {
let mut expected: HashMap<usize, usize> = HashMap::new();
let program_1 = "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X\nmem[8] = 11";
expected.insert(8, 73);
assert_eq!(expected, run_program_v1(program_1));
let program_2 = "mask = XXXXXXXXXXXXXXXXXXXXXXXXXXXXX1XXXX0X
mem[8] =... | identifier_body |
day_14.rs | //! This is my solution for [Advent of Code - Day 14](https://adventofcode.com/2020/day/14) -
//! _Docking Data_
//!
//! This was themed around bitwise operations. The challenge was mostly parsing the puzzle
//! description into the bitwise operations needed. This was the first time I needed an Either
//! implementatio... | (line: &str) -> Either<Mask, Mem> {
let mut parts = line.split(" = ");
let inst = parts.next().expect("Invalid line");
let value = parts.next().expect("Invalid line");
if inst == "mask" {
let (mask, data) =
value.chars().fold(
(0usize, 0usize),
|(mask... | parse_line | identifier_name |
day_14.rs | //! This is my solution for [Advent of Code - Day 14](https://adventofcode.com/2020/day/14) -
//! _Docking Data_
//!
//! This was themed around bitwise operations. The challenge was mostly parsing the puzzle
//! description into the bitwise operations needed. This was the first time I needed an Either
//! implementatio... | else {
let re = Regex::new(r"^mem\[(\d+)]$").unwrap();
match re.captures(inst) {
Some(cap) => Right(Mem {
address: cap.get(1).unwrap().as_str().parse::<usize>().unwrap(),
value: value.parse::<usize>().unwrap(),
}),
None => panic!("Inv... | {
let (mask, data) =
value.chars().fold(
(0usize, 0usize),
|(mask, data), char| (
mask << 1 | if char == 'X' { 1 } else { 0 },
data << 1 | if char == '1' { 1 } else { 0 }
),
);
Left(Mask { ma... | conditional_block |
schedule.rs | use crate::{
borrow::{Exclusive, RefMut},
command::CommandBuffer,
resource::ResourceTypeId,
storage::ComponentTypeId,
world::World,
};
use bit_set::BitSet;
use itertools::izip;
use std::iter::repeat;
use std::{
collections::{HashMap, HashSet},
sync::atomic::{AtomicUsize, Ordering},
};
#[cfg... | let mut component_mutated = HashMap::<ComponentTypeId, Vec<usize>>::with_capacity(64);
for (i, system) in systems.iter().enumerate() {
log::debug!("Building dependency: {}", system.name());
let (read_res, read_comp) = system.reads();
let (write_r... | random_line_split | |
schedule.rs | use crate::{
borrow::{Exclusive, RefMut},
command::CommandBuffer,
resource::ResourceTypeId,
storage::ComponentTypeId,
world::World,
};
use bit_set::BitSet;
use itertools::izip;
use std::iter::repeat;
use std::{
collections::{HashMap, HashSet},
sync::atomic::{AtomicUsize, Ordering},
};
#[cfg... | (&mut self, world: &mut World) {
self.systems.iter_mut().for_each(|system| {
system.run(world);
});
// Flush the command buffers of all the systems
self.systems.iter().for_each(|system| {
system.command_buffer_mut().write(world);
});
}
/// Execut... | execute | identifier_name |
edge.rs | use delaunator::{Point, Triangulation};
use itertools::Itertools;
use std::collections::HashMap;
#[derive(Clone, Copy)]
pub struct Edge {
pub vertex1: usize,
pub vertex2: usize,
pub edge_type1: EdgeType,
pub edge_type2: EdgeType,
pub active: bool,
pub length: f64,
}
#[derive(PartialEq, Copy, Clone)]
pub enum Ed... |
pub fn calculate_connected_components(&mut self) {
let mut cc_index = 1;
while let Some(v) = self
.verticies
.iter_mut()
.position(|x| !x.edges.is_empty() && x.label == 0)
{
self.build_connected_component(v, cc_index);
cc_index += 1;
}
let groups = self.calculate_cc_sizes();
for (label, s... | {
if self.verticies[vertex_index].label != label {
self.verticies[vertex_index].label = label;
for i in 0..self.verticies[vertex_index].edges.len() {
let edge_index = self.verticies[vertex_index].edges[i];
if self.edge_is_active(edge_index)
&& self.verticies[self.active_edges[edge_index].other(vert... | identifier_body |
edge.rs | use delaunator::{Point, Triangulation};
use itertools::Itertools;
use std::collections::HashMap;
#[derive(Clone, Copy)]
pub struct Edge {
pub vertex1: usize,
pub vertex2: usize,
pub edge_type1: EdgeType,
pub edge_type2: EdgeType,
pub active: bool,
pub length: f64,
}
#[derive(PartialEq, Copy, Clone)]
pub enum Ed... | }
}
}
}
pub fn restore_edges(&mut self) {
struct LabelReference {
size: usize,
label: usize,
edge_index: usize,
};
let mut cc_sizes = self.calculate_cc_sizes();
let mut reassign_map: HashMap<usize, usize> = HashMap::new();
for i in 0..self.verticies.len() {
let short_edges: Vec<&Edge> ... | self.active_edges[edge].active = true;
}
if self.verticies[other].label != label {
self.active_edges[edge].active = false; | random_line_split |
edge.rs | use delaunator::{Point, Triangulation};
use itertools::Itertools;
use std::collections::HashMap;
#[derive(Clone, Copy)]
pub struct Edge {
pub vertex1: usize,
pub vertex2: usize,
pub edge_type1: EdgeType,
pub edge_type2: EdgeType,
pub active: bool,
pub length: f64,
}
#[derive(PartialEq, Copy, Clone)]
pub enum Ed... |
}
pub fn calculate_connected_components(&mut self) {
let mut cc_index = 1;
while let Some(v) = self
.verticies
.iter_mut()
.position(|x| !x.edges.is_empty() && x.label == 0)
{
self.build_connected_component(v, cc_index);
cc_index += 1;
}
let groups = self.calculate_cc_sizes();
for (label... | {
self.verticies[vertex_index].label = label;
for i in 0..self.verticies[vertex_index].edges.len() {
let edge_index = self.verticies[vertex_index].edges[i];
if self.edge_is_active(edge_index)
&& self.verticies[self.active_edges[edge_index].other(vertex_index)].label == 0
{
self.build_connect... | conditional_block |
edge.rs | use delaunator::{Point, Triangulation};
use itertools::Itertools;
use std::collections::HashMap;
#[derive(Clone, Copy)]
pub struct Edge {
pub vertex1: usize,
pub vertex2: usize,
pub edge_type1: EdgeType,
pub edge_type2: EdgeType,
pub active: bool,
pub length: f64,
}
#[derive(PartialEq, Copy, Clone)]
pub enum Ed... | {
size: usize,
label: usize,
edge_index: usize,
};
let mut cc_sizes = self.calculate_cc_sizes();
let mut reassign_map: HashMap<usize, usize> = HashMap::new();
for i in 0..self.verticies.len() {
let short_edges: Vec<&Edge> = self.verticies[i]
.edges
.iter()
.filter(|e| self.active_edges[... | LabelReference | identifier_name |
scheme_types.py | #!/usr/bin/env python3
import fractions
import sys
class Env(dict):
"""Context Environment."""
def __init__(self, parms=(), args=(), outer=None):
"""Initialize the environment with specific parameters."""
self._outer = outer
if isa(parms, Symbol):
# (lambda x (...))
... |
def append_str(*strs):
"""Append strings."""
return ''.join(list(strs))
def reverse_list(s_list):
"""Reverse a scheme list."""
require_type(isa(s_list, List), 'parameter of reverse must be a list')
new_list = s_list.members.copy()
new_list.reverse()
return List(new_list)
def is_procedure... | """Return substring from beg to end."""
require_type(isa(string, str), 'the first parameter of substring must be a string')
if beg < 0 or end >= len(string) or beg > end:
raise IndexError('the index of substring is invalid')
return string[beg:end] | identifier_body |
scheme_types.py | #!/usr/bin/env python3
import fractions
import sys
class Env(dict):
"""Context Environment."""
def __init__(self, parms=(), args=(), outer=None):
"""Initialize the environment with specific parameters."""
self._outer = outer
if isa(parms, Symbol):
# (lambda x (...))
... | def do_is(op_left, op_right):
"""Judge whether op_left is op_right."""
if isa(op_left, float) and isa(op_right, float):
return op_left == op_right
return op_left is op_right
def do_sqrt(num):
"""Compute square root of the number."""
if num < 0:
from cmath import sqrt
return ... | return result
| random_line_split |
scheme_types.py | #!/usr/bin/env python3
import fractions
import sys
class Env(dict):
"""Context Environment."""
def __init__(self, parms=(), args=(), outer=None):
"""Initialize the environment with specific parameters."""
self._outer = outer
if isa(parms, Symbol):
# (lambda x (...))
... | (*args):
"""Logical or."""
result = False
for i in args:
result = result or i
if result:
break
return result
def s_and(*args):
"""Logical and."""
result = True
for i in args:
result = result and i
if not result:
break
return result... | s_or | identifier_name |
scheme_types.py | #!/usr/bin/env python3
import fractions
import sys
class Env(dict):
"""Context Environment."""
def __init__(self, parms=(), args=(), outer=None):
"""Initialize the environment with specific parameters."""
self._outer = outer
if isa(parms, Symbol):
# (lambda x (...))
... |
return op_left is op_right
def do_sqrt(num):
"""Compute square root of the number."""
if num < 0:
from cmath import sqrt
return sqrt(num)
from math import sqrt
return sqrt(num)
def is_list(s_list):
"""Judge whether it's a list."""
return isa(s_list, List)
def is_pair(pair... | return op_left == op_right | conditional_block |
User.ts | /*!
* ISC License
*
* Copyright (c) 2018, Imqueue Sandbox
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS... |
else {
return await this.createUser(data, fields);
}
}
/**
* Returns number of cars registered for the user having given id or email
*
* @param {string} idOrEmail
* @return {Promise<number>}
*/
@profile()
@expose()
public async carsCount(idOrEm... | {
return await this.updateUser(data, fields);
} | conditional_block |
User.ts | /*!
* ISC License
*
* Copyright (c) 2018, Imqueue Sandbox
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS... | * @param {string} carId - car identifier
* @return {Promise<UserCarObject | null>}
*/
@profile()
@expose()
public async getCar(
userId: string,
carId: string,
): Promise<UserCarObject | null> {
return (await this.UserModel
.findOne({ _id: mongoose.Types... | * @param {string} userId - user identifier | random_line_split |
User.ts | /*!
* ISC License
*
* Copyright (c) 2018, Imqueue Sandbox
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS... | (idOrEmail: string): Promise<number> {
const field = isEmail(idOrEmail) ? 'email' : '_id';
const ObjectId = mongoose.Types.ObjectId;
if (field === '_id') {
idOrEmail = ObjectId(idOrEmail) as any;
}
return ((await this.UserModel.aggregate([
{ $match: { [f... | carsCount | identifier_name |
User.ts | /*!
* ISC License
*
* Copyright (c) 2018, Imqueue Sandbox
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS... |
}
| {
return (await this.UserModel
.findOne({ _id: mongoose.Types.ObjectId(userId) })
.select(['cars._id', 'cars.carId', 'cars.regNumber'])
.exec() || { cars: [] })
.cars
.find((car: UserCarObject) => String(car._id) === carId) || null;
} | identifier_body |
garmin_util.rs | use anyhow::{format_err, Error};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use fitparser::Value;
use flate2::{read::GzEncoder, Compression};
use futures::{Stream, TryStreamExt};
use log::{debug, error};
use num_traits::pow::Pow;
use postgres_query::{query, Error as PqError};
use rand::{
distri... | #[must_use]
pub fn days_in_year(year: i32) -> i64 {
(Date::from_calendar_date(year + 1, Month::January, 1).unwrap_or(date!(1969 - 01 - 01))
- Date::from_calendar_date(year, Month::January, 1).unwrap_or(date!(1969 - 01 - 01)))
.whole_days()
}
#[must_use]
pub fn days_in_month(year: i32, month: u32) -> i6... | random_line_split | |
garmin_util.rs | use anyhow::{format_err, Error};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use fitparser::Value;
use flate2::{read::GzEncoder, Compression};
use futures::{Stream, TryStreamExt};
use log::{debug, error};
use num_traits::pow::Pow;
use postgres_query::{query, Error as PqError};
use rand::{
distri... |
#[must_use]
pub fn expected_calories(weight: f64, pace_min_per_mile: f64, distance: f64) -> f64 {
let cal_per_mi = weight
* (0.0395
+ 0.003_27 * (60. / pace_min_per_mile)
+ 0.000_455 * (60. / pace_min_per_mile).pow(2.0)
+ 0.000_801
* ((weight / 154.0) * ... | {
let mut y1 = year;
let mut m1 = month + 1;
if m1 == 13 {
y1 += 1;
m1 = 1;
}
let month: Month = (month as u8).try_into().unwrap_or(Month::January);
let m1: Month = (m1 as u8).try_into().unwrap_or(Month::January);
(Date::from_calendar_date(y1, m1, 1).unwrap_or(date!(1969 - 01... | identifier_body |
garmin_util.rs | use anyhow::{format_err, Error};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use fitparser::Value;
use flate2::{read::GzEncoder, Compression};
use futures::{Stream, TryStreamExt};
use log::{debug, error};
use num_traits::pow::Pow;
use postgres_query::{query, Error as PqError};
use rand::{
distri... | <T, U, F>(f: T) -> Result<U, Error>
where
T: Fn() -> F,
F: Future<Output = Result<U, Error>>,
{
let mut timeout: f64 = 1.0;
let range = Uniform::from(0..1000);
loop {
match f().await {
Ok(resp) => return Ok(resp),
Err(err) => {
sleep(Duration::from_mil... | exponential_retry | identifier_name |
garmin_util.rs | use anyhow::{format_err, Error};
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
use fitparser::Value;
use flate2::{read::GzEncoder, Compression};
use futures::{Stream, TryStreamExt};
use log::{debug, error};
use num_traits::pow::Pow;
use postgres_query::{query, Error as PqError};
use rand::{
distri... |
Ok(())
}
/// # Errors
/// Return error if unzip fails
pub fn extract_zip_from_garmin_connect(
filename: &Path,
ziptmpdir: &Path,
) -> Result<PathBuf, Error> {
extract_zip(filename, ziptmpdir)?;
let new_filename = filename
.file_stem()
.ok_or_else(|| format_err!("Bad filename {}", f... | {
if let Some(mut f) = process.stdout.as_ref() {
let mut buf = String::new();
f.read_to_string(&mut buf)?;
error!("{}", buf);
}
return Err(format_err!("Failed with exit status {exit_status:?}"));
} | conditional_block |
views.py | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import os
import time
from .clipmanager import ClipManager
from .models import Channel, Clip, HighlightClip
import shutil
import traceback
from datetime import datetime
fro... | 1>所有直播的播放数已更新</h1>')
def macie_reviewed(response):
clips = []
if response.POST.get('start') is not None:
start = response.POST.get('start')
start = str(start) + "-00:00:00"
start_datetime = datetime.strptime(start, '%m/%d/%Y-%H:%M:%S')
if response.POST.get('end') is not None:
... | ip_view(item)
print("[UPDATE CLIP VIEWS]", count, ' of ', total)
if item.views > 5:
item.rejected = False
item.accepted = False
print("[New Commer!]")
if item.views < 6:
item.rejected = True
print(count, ' has been REJECTED')
it... | conditional_block |
views.py | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import os
import time
from .clipmanager import ClipManager
from .models import Channel, Clip, HighlightClip
import shutil
import traceback
from datetime import datetime
fro... | accepted=True, downloaded=False,channel=channel)
return render(response, 'blog/projects-grid-cards.html', {'clips': clips, 'review': False})
def macie_downloaded(response):
clips = []
if response.POST.get('start') is not None:
start = response.POST.get('st... | random_line_split | |
views.py | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import os
import time
from .clipmanager import ClipManager
from .models import Channel, Clip, HighlightClip
import shutil
import traceback
from datetime import datetime
fro... | clips = []
if response.POST.get('start') is not None:
start = response.POST.get('start')
start = str(start) + "-00:00:00"
start_datetime = datetime.strptime(start, '%m/%d/%Y-%H:%M:%S')
if response.POST.get('end') is not None:
end = response.POST.get('end')
en... | turn HttpResponse('<h1>Clips Download Started</h1>')
def macie(response):
| identifier_body |
views.py | from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
import os
import time
from .clipmanager import ClipManager
from .models import Channel, Clip, HighlightClip
import shutil
import traceback
from datetime import datetime
fro... | .GET)
if request.GET.get('action') is not None:
action = request.GET.get('action')
if request.GET.get('slug') is not None:
slug = request.GET.get('slug')
if action == 'accept':
clip = Clip.objects.filter(slug=slug)[0]
print('accepting ', clip.t... | nt(request | identifier_name |
main5.py | import tkinter
from collections import namedtuple
from tkinter import *
from tkinter.constants import *
from tkinter import ttk
from tkinter.ttk import *
import requests
import time
import datetime
import gui
import concurrent.futures
import logging
import json
import asyncio
logger = logging.getLogge... | (dev):
api_call = api_calls.get("active_app")
response = api_req(dev, "get", api_call)
act_app = response.get("active-app").get("app")
return act_app
def dev_status():
dev_states = []
for key,value in dev_list.items():
dev_url = value
result = pwr_status(value)
... | active_app | identifier_name |
main5.py | import tkinter
from collections import namedtuple
from tkinter import *
from tkinter.constants import *
from tkinter import ttk
from tkinter.ttk import *
import requests
import time
import datetime
import gui
import concurrent.futures
import logging
import json
import asyncio
logger = logging.getLogge... | stream_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
def logger_func(orig_func):
import logging
formatter2 = logging.Formatter("%(asctime)s:%(name)s:%(message)s")
file_handler2 = logging.FileHandler("RemoteKu.log")
file_handler2.setFormatter(f... | file_handler = logging.FileHandler("RemoteKu_mainLog.log")
file_handler.setLevel(logging.ERROR)
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
| random_line_split |
main5.py | import tkinter
from collections import namedtuple
from tkinter import *
from tkinter.constants import *
from tkinter import ttk
from tkinter.ttk import *
import requests
import time
import datetime
import gui
import concurrent.futures
import logging
import json
import asyncio
logger = logging.getLogge... |
### This is basics such as variables and holders for devices
global cur_hdmi
stats_counter = 30
counter = 0
running = False
timing = 0
result = "NULL"
msg_box_text = ""
api_port = ":8060"
cur_hdmi = 1
devices_listing = []
root = tkinter.Tk()
root.wm_iconbitmap(default='wicon.ico')
#root.tk_setPalette... | import logging
formatter2 = logging.Formatter("%(asctime)s:%(name)s:%(message)s")
file_handler2 = logging.FileHandler("RemoteKu.log")
file_handler2.setFormatter(formatter2)
logger.addHandler(file_handler2)
def wrapper(*args, **kwargs):
logger.debug("DEBUG log for Func {} with args:{} a... | identifier_body |
main5.py | import tkinter
from collections import namedtuple
from tkinter import *
from tkinter.constants import *
from tkinter import ttk
from tkinter.ttk import *
import requests
import time
import datetime
import gui
import concurrent.futures
import logging
import json
import asyncio
logger = logging.getLogge... |
@logger_func
def api_req(dev, api_call):
"""
Function for api GET calls
"""
import xmltodict
import logging
try:
r = requests.get(dev + ':8060' + api_call, timeout=5)
except Exception as exc:
response = ["ERR", exc]
return response[0]
except Co... | print("REQUEST WAS A SUCCESS. DEVICE {} RETURNED: {} ".format(n.get(), str(r)))
r2 = r.text
response = f'{r_code} - OK'
return msg_box(response) | conditional_block |
__init__.py | '''
Data I/O package. Used to import and export data to and from TSV and JSON
files.
.. seealso:: File format documentation in: `Segmentation Representation \
Specification <http://nlp.chrisfournier.ca/publications/#seg_spec>`_.
.. moduleauthor:: Chris Fournier <chris.m.fournier@gmail.com>
'''
#=====================... |
# If a data file was found
if datafile_found:
# If TSV files were found, load
for name, filepath in files.items():
data[name] = fnc_load(filepath)
else:
# If only dirs were found, recurse
for name, dirpath in dirs.items():
data[name] = load_nested_fol... | path = os.path.join(containing_dir, name)
# Found a directory
if os.path.isdir(path):
dirs[name] = path
# Found a file
elif os.path.isfile(path):
name, ext = os.path.splitext(name)
if len(ext) > 0 and ext.lower() in allowable_extensions:
... | conditional_block |
__init__.py | '''
Data I/O package. Used to import and export data to and from TSV and JSON
files.
.. seealso:: File format documentation in: `Segmentation Representation \
Specification <http://nlp.chrisfournier.ca/publications/#seg_spec>`_.
.. moduleauthor:: Chris Fournier <chris.m.fournier@gmail.com>
'''
#=====================... | for coder, positions in coder_positions.items():
coder_positions[coder] = convert_positions_to_masses(positions)
# Return
return coder_positions
def input_linear_mass_json(json_filename):
'''
Load a segment mass JSON file.
:param json_filename: path to the mass file containing seg... | coder_positions = input_linear_mass_tsv(tsv_filename, delimiter)
# Convert each segment position to masses | random_line_split |
__init__.py | '''
Data I/O package. Used to import and export data to and from TSV and JSON
files.
.. seealso:: File format documentation in: `Segmentation Representation \
Specification <http://nlp.chrisfournier.ca/publications/#seg_spec>`_.
.. moduleauthor:: Chris Fournier <chris.m.fournier@gmail.com>
'''
#=====================... |
def load_file(args):
'''
Load a file or set of directories from command line arguments.
:param args: Command line arguments
:type args: dict
:returns: The loaded values and whether a file was loaded or not.
:rtype: :func:`dict`, :func:`bool`
'''
values = None
input_... | '''
Loads TSV files from a file directory structure, which reflects the
directory structure in nested :func:`dict` with each directory name
representing a key in these :func:`dict`.
:param containing_dir: Root directory containing sub-directories which
contain segmentati... | identifier_body |
__init__.py | '''
Data I/O package. Used to import and export data to and from TSV and JSON
files.
.. seealso:: File format documentation in: `Segmentation Representation \
Specification <http://nlp.chrisfournier.ca/publications/#seg_spec>`_.
.. moduleauthor:: Chris Fournier <chris.m.fournier@gmail.com>
'''
#=====================... | (containing_dir, filetype):
'''
Loads TSV files from a file directory structure, which reflects the
directory structure in nested :func:`dict` with each directory name
representing a key in these :func:`dict`.
:param containing_dir: Root directory containing sub-directories which
... | load_nested_folders_dict | identifier_name |
report.py | import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib as mpl
from matplotlib import pyplot as plt
plt.style.use('seaborn-muted')
#from IPython import get_ipython
from IPython.display import HTML, Markdown
import air_cargo_problems as acp
problems = ['Air Cargo Problem 1',
'... | dflist = []
for f in pfiles:
df, err = get_results_df(f, problem)
if df is not None:
df = df.merge(specs)
df['index'] = df['Searcher'].apply(lambda x: SEARCHES.index(x)+1)
df['index'] = df['index'].astype(int)
df.set_index('index', drop=Tr... | return
| random_line_split |
report.py | import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib as mpl
from matplotlib import pyplot as plt
plt.style.use('seaborn-muted')
#from IPython import get_ipython
from IPython.display import HTML, Markdown
import air_cargo_problems as acp
problems = ['Air Cargo Problem 1',
'... |
else:
print(f'Error from get_results_df:\n\t{err}')
dfout = pd.concat(dflist, ignore_index=False)
dfout.sort_index(inplace=True)
if file_as_tsv:
df2tsv(dfout, fout, replace=replace)
return dfout
def get_results_df(fname, problem):
"""Process csv into... | df = df.merge(specs)
df['index'] = df['Searcher'].apply(lambda x: SEARCHES.index(x)+1)
df['index'] = df['index'].astype(int)
df.set_index('index', drop=True, inplace=True)
dflist.append(df)
del df | conditional_block |
report.py | import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib as mpl
from matplotlib import pyplot as plt
plt.style.use('seaborn-muted')
#from IPython import get_ipython
from IPython.display import HTML, Markdown
import air_cargo_problems as acp
problems = ['Air Cargo Problem 1',
'... | """
Wrap an html code str inside a div.
div_style: whatever follows style= within the <div>
Behaviour with `output_string=True`:
The cell is overwritten with the output string (but the cell mode is still in 'code' not 'markdown')
The only thing to do is change the cell mode to Markdown.
If ... | identifier_body | |
report.py | import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib as mpl
from matplotlib import pyplot as plt
plt.style.use('seaborn-muted')
#from IPython import get_ipython
from IPython.display import HTML, Markdown
import air_cargo_problems as acp
problems = ['Air Cargo Problem 1',
'... | (dflist):
"""
Output combined df for complete runs, Actions>0.
"""
dfall = pd.concat(dflist, ignore_index=False)
dfall.reset_index(drop=False, inplace=True)
dfall.rename(columns={'index': 'id'}, inplace=True)
# reduced
drop_cols = dfall.columns[-4:-1].tolist() + ['Problem','Minutes','Goa... | concat_all_dfs | identifier_name |
vpc_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License... |
}
}
//resource deleted in cloud, update the status
if tencentVpc == nil {
if strings.EqualFold(*vpc.Status.ResourceStatus.Status, "READY") {
*vpc.Status.ResourceStatus.RetryCount = 0
*vpc.Status.ResourceStatus.LastRetry = ""
*vpc.Status.ResourceStatus.Code = ""
*vpc.Status.ResourceStatus.Reason = ""... | {
r.Log.Info("vpc is in error status, and vpc id is empty, retry create")
return r.createVpc(vpc)
} | conditional_block |
vpc_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License... |
func (r *VpcReconciler) createVpc(vpc *networkv1alpha1.Vpc) error {
tencentClient, _ := tcvpc.NewClient(common.GerCredential(), *vpc.Spec.Region, profile.NewClientProfile())
request := tcvpc.NewCreateVpcRequest()
request.VpcName = vpc.Spec.VpcName
request.CidrBlock = vpc.Spec.CidrBlock
request.EnableMulticast = ... | {
// always check for finalizers
deleted := !vpc.GetDeletionTimestamp().IsZero()
pendingFinalizers := vpc.GetFinalizers()
finalizerExists := len(pendingFinalizers) > 0
if !finalizerExists && !deleted && !utils.Contains(pendingFinalizers, common.Finalizer) {
log.Println("Adding finalized &s to resource", common.F... | identifier_body |
vpc_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License... | (vpc *networkv1alpha1.Vpc) error {
// always check for finalizers
deleted := !vpc.GetDeletionTimestamp().IsZero()
pendingFinalizers := vpc.GetFinalizers()
finalizerExists := len(pendingFinalizers) > 0
if !finalizerExists && !deleted && !utils.Contains(pendingFinalizers, common.Finalizer) {
log.Println("Adding fi... | vpcReconcile | identifier_name |
vpc_controller.go | /*
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License... |
func (r *VpcReconciler) createVpc(vpc *networkv1alpha1.Vpc) error {
tencentClient, _ := tcvpc.NewClient(common.GerCredential(), *vpc.Spec.Region, profile.NewClientProfile())
request := tcvpc.NewCreateVpcRequest()
request.VpcName = vpc.Spec.VpcName
request.CidrBlock = vpc.Spec.CidrBlock
request.EnableMulticast = v... | }
return nil
} | random_line_split |
panorama.go | package panorama
import (
"log"
"math"
"time"
"github.com/ftl/hamradio/bandplan"
"github.com/ftl/panacotta/core"
)
// Panorama controller
type Panorama struct {
width core.Px
height core.Px
frequencyRange core.FrequencyRange
dbRange core.DBRange
vfo core.VFO
band ... |
// SetVFO in Hz
func (p *Panorama) SetVFO(vfo core.VFO) {
p.vfo = vfo
if !p.band.Contains(vfo.Frequency) {
band := bandplan.IARURegion1.ByFrequency(vfo.Frequency)
if band.Width() > 0 {
if p.band.Width() > 0 {
p.dbRangeAdjusted = false
}
p.band = band
}
}
log.Printf("vfo %v band %v", p.vfo, p.... | {
return p.frequencyRange.Width()
} | identifier_body |
panorama.go | package panorama
import (
"log"
"math"
"time"
"github.com/ftl/hamradio/bandplan"
"github.com/ftl/panacotta/core"
)
// Panorama controller
type Panorama struct {
width core.Px
height core.Px
frequencyRange core.FrequencyRange
dbRange core.DBRange
vfo core.VFO
band ... | }
const (
defaultFixedResolution = core.HzPerPx(100)
defaultCenteredResolution = core.HzPerPx(25)
)
// New returns a new instance of panorama.
func New(width core.Px, frequencyRange core.FrequencyRange, vfoFrequency core.Frequency) *Panorama {
result := Panorama{
width: width,
frequencyRange: frequ... | return peakKey(f / 100.0) | random_line_split |
panorama.go | package panorama
import (
"log"
"math"
"time"
"github.com/ftl/hamradio/bandplan"
"github.com/ftl/panacotta/core"
)
// Panorama controller
type Panorama struct {
width core.Px
height core.Px
frequencyRange core.FrequencyRange
dbRange core.DBRange
vfo core.VFO
band ... | () bool {
return p.signalDetectionActive
}
// ToggleViewMode switches to the other view mode.
func (p *Panorama) ToggleViewMode() {
if p.viewMode == core.ViewFixed {
p.viewMode = core.ViewCentered
} else {
p.viewMode = core.ViewFixed
}
p.updateFrequencyRange()
}
// ViewMode returns the currently active view ... | SignalDetectionActive | identifier_name |
panorama.go | package panorama
import (
"log"
"math"
"time"
"github.com/ftl/hamradio/bandplan"
"github.com/ftl/panacotta/core"
)
// Panorama controller
type Panorama struct {
width core.Px
height core.Px
frequencyRange core.FrequencyRange
dbRange core.DBRange
vfo core.VFO
band ... |
p.zoomTo(p.band.Expanded(1000))
}
func (p *Panorama) zoomTo(frequencyRange core.FrequencyRange) {
p.viewMode = core.ViewFixed
p.frequencyRange = frequencyRange
p.resolution[p.viewMode] = calcResolution(p.frequencyRange, p.width)
}
// ResetZoom to the default of the current view mode
func (p *Panorama) ResetZoom(... | {
return
} | conditional_block |
intrinsicck.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | (&self, def_id: DefId) -> bool {
let intrinsic = match ty::lookup_item_type(self.tcx, def_id).ty.sty {
ty::ty_bare_fn(_, ref bfty) => bfty.abi == RustIntrinsic,
_ => return false
};
if def_id.krate == ast::LOCAL_CRATE {
match self.tcx.map.get(def_id.node) {
... | def_id_is_transmute | identifier_name |
intrinsicck.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... |
}
impl<'a, 'tcx, 'v> Visitor<'v> for IntrinsicCheckingVisitor<'a, 'tcx> {
fn visit_fn(&mut self, fk: visit::FnKind<'v>, fd: &'v ast::FnDecl,
b: &'v ast::Block, s: Span, id: ast::NodeId) {
match fk {
visit::FkItemFn(..) | visit::FkMethod(..) => {
let param_env = ... | {
debug!("Pushing transmute restriction: {}", restriction.repr(self.tcx));
self.tcx.transmute_restrictions.borrow_mut().push(restriction);
} | identifier_body |
intrinsicck.rs | // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MI... | use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit::Visitor;
use syntax::visit;
pub fn check_crate(tcx: &ctxt) {
let mut visitor = IntrinsicCheckingVisitor {
tcx: tcx,
param_envs: Vec::new(),
dummy_sized_ty: tcx.types.isize,
dummy_unsized_ty: ty::mk_vec(tcx, tcx.... | use syntax::ast_map::NodeForeignItem; | random_line_split |
beautyleg7_spider.py | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import hashlib
import re
from datetime import datetime
import gevent
import requests
import scrapy
from gevent.pool import Pool
from lxml import etree
from scrapy.http import HtmlResponse
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
... | identifier_body | ||
beautyleg7_spider.py | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import hashlib
import re
from datetime import datetime
import gevent
import requests
import scrapy
from gevent.pool import Pool
from lxml import etree
from scrapy.http import HtmlResponse
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
... | :
number = number_group[0]
else:
number = "No.unknown"
create_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
album_item = AlbumItem()
album_item['category'] = category
album_item['album_url'] = album_url
album_item['album_url_object_id'] = alb... | se.css('.pic .item')
category = response.css('.sitepath a')[1].css('a::text').extract_first().strip()
# 判断最后一页的最后主题是否被持久化
is_persisted_last_item = self.redis_cmd.get(self.album_last_item_redis_unique_key)
is_last_item_finished = False
if is_persisted_last_ite... | conditional_block |
beautyleg7_spider.py | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import hashlib |
import gevent
import requests
import scrapy
from gevent.pool import Pool
from lxml import etree
from scrapy.http import HtmlResponse
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from ..items import Album, AlbumImageRelationItem, AlbumItem, AlbumImageItem
from ..utils.const import... | import re
from datetime import datetime | random_line_split |
beautyleg7_spider.py | #!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import hashlib
import re
from datetime import datetime
import gevent
import requests
import scrapy
from gevent.pool import Pool
from lxml import etree
from scrapy.http import HtmlResponse
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
... | else:
item_title = response.xpath('//div[@class="content"]/h1/text()')[0].strip()
publish_date = response.xpath('//div[@class="tit"]/span/text()')[0].split(":")[1]
image_link_list = response.xpath('//div[@class="contents"]/a/img')
image_link_list = [image_link.attrib['src... | )').extract()
| identifier_name |
output.rs | use std::io;
use std::string::ToString;
use std::thread::sleep;
use std::time::Duration;
use std::{collections::BTreeMap, path::PathBuf};
use anyhow::Result;
use comfy_table::presets::UTF8_HORIZONTAL_BORDERS_ONLY;
use comfy_table::*;
use snap::read::FrameDecoder;
use pueue::log::{get_log_file_handles, get_log_paths};... | (task_id: usize, settings: &Settings) {
let (mut stdout_log, mut stderr_log) =
match get_log_file_handles(task_id, &settings.shared.pueue_directory) {
Ok((stdout, stderr)) => (stdout, stderr),
Err(err) => {
println!("Failed to get log file handles: {}", err);
... | print_local_log_output | identifier_name |
output.rs | use std::io;
use std::string::ToString;
use std::thread::sleep;
use std::time::Duration;
use std::{collections::BTreeMap, path::PathBuf};
use anyhow::Result;
use comfy_table::presets::UTF8_HORIZONTAL_BORDERS_ONLY;
use comfy_table::*;
use snap::read::FrameDecoder;
use pueue::log::{get_log_file_handles, get_log_paths};... |
pub fn print_error(message: &str) {
let styled = style_text(message, Some(Color::Red), None);
println!("{}", styled);
}
pub fn print_groups(message: GroupResponseMessage) {
let mut text = String::new();
let mut group_iter = message.groups.iter().peekable();
while let Some((name, status)) = group_... | {
println!("{}", message);
} | identifier_body |
output.rs | use std::io;
use std::string::ToString;
use std::thread::sleep;
use std::time::Duration;
use std::{collections::BTreeMap, path::PathBuf};
use anyhow::Result;
use comfy_table::presets::UTF8_HORIZONTAL_BORDERS_ONLY;
use comfy_table::*;
use snap::read::FrameDecoder;
use pueue::log::{get_log_file_handles, get_log_paths};... | if group.eq("default") {
continue;
}
// Skip unwanted groups, if a single group is requested
if let Some(group_only) = &group_only {
if group_only != group {
continue;
}
}
let headline = get_group_headline(
... | while let Some((group, tasks)) = sorted_iter.next() {
// We always want to print the default group at the very top.
// That's why we print it outside of this loop and skip it in here. | random_line_split |
player.rs | use std::f32;
use nalgebra::{norm, zero, Point2, Rotation2, Vector2};
use specs::prelude::*;
use specs::storage::BTreeStorage;
use defs::{EntityId, GameInfo, PlayerId, PlayerInput, INVALID_ENTITY_ID};
use event::{self, Event};
use game::entity::hook;
use game::ComponentType;
use physics::collision::{self, CollisionG... | (
world: &mut World,
_inputs: &[(PlayerId, PlayerInput, Entity)],
) -> Result<(), repl::Error> {
hook::run_input_post_sim(&world)?;
world.write::<hook::CurrentInput>().clear();
world.write::<CurrentInput>().clear();
Ok(())
}
pub mod auth {
use super::*;
pub fn create(world: &mut Worl... | run_input_post_sim | identifier_name |
player.rs | use std::f32;
use nalgebra::{norm, zero, Point2, Rotation2, Vector2};
use specs::prelude::*;
use specs::storage::BTreeStorage;
use defs::{EntityId, GameInfo, PlayerId, PlayerInput, INVALID_ENTITY_ID};
use event::{self, Event};
use game::entity::hook;
use game::ComponentType;
use physics::collision::{self, CollisionG... |
pub mod auth {
use super::*;
pub fn create(world: &mut World, owner: PlayerId, pos: Point2<f32>) -> (EntityId, Entity) {
let (id, entity) = repl::entity::auth::create(world, owner, "player", |builder| {
builder.with(Position(pos))
});
let mut hooks = [INVALID_ENTITY_ID; N... | {
hook::run_input_post_sim(&world)?;
world.write::<hook::CurrentInput>().clear();
world.write::<CurrentInput>().clear();
Ok(())
} | identifier_body |
player.rs | use std::f32;
use nalgebra::{norm, zero, Point2, Rotation2, Vector2};
use specs::prelude::*;
use specs::storage::BTreeStorage;
use defs::{EntityId, GameInfo, PlayerId, PlayerInput, INVALID_ENTITY_ID};
use event::{self, Event};
use game::entity::hook;
use game::ComponentType;
use physics::collision::{self, CollisionG... |
if input.1[MOVE_RIGHT_KEY] {
state.dash(right);
}
if input.1[MOVE_LEFT_KEY] {
state.dash(-right);
}
state.update_dash(dt);
if let Some(dash_state) = state.dash_state.as_ref() {
velocity.0 += Vector... | {
state.dash(-forward);
} | conditional_block |
player.rs | use std::f32;
use nalgebra::{norm, zero, Point2, Rotation2, Vector2};
use specs::prelude::*;
use specs::storage::BTreeStorage;
use defs::{EntityId, GameInfo, PlayerId, PlayerInput, INVALID_ENTITY_ID};
use event::{self, Event};
use game::entity::hook;
use game::ComponentType;
use physics::collision::{self, CollisionG... | fn class(&self) -> event::Class {
event::Class::Order
}
}
/// Component that is attached whenever player input should be executed for an entity.
#[derive(Component, Clone, Debug)]
#[storage(BTreeStorage)]
pub struct CurrentInput(pub PlayerInput, [bool; NUM_TAP_KEYS]);
impl CurrentInput {
fn new(in... | impl Event for DashedEvent { | random_line_split |
Index.js | import React, {Component} from "react";
import "./Index.less";
import {
Button,
Card,
message,
LocaleProvider,
Col,
Select,
Row,
DatePicker,
Upload,
Divider,
Spin
} from "antd";
import BreadcrumbCustom from "../common/BreadcrumbCustom";
import zh_CN from "antd/lib/locale-prov... | ;
// 日期筛选
handleRangePicker = (rangePickerValue, dateString) => {
this.setState({
orderDate: rangePickerValue
});
applyData.current = 1;
customCondition.startTime = parseInt(new Date(new Date(rangePickerValue[0]).toLocaleDateString()).getTime()/1000);
customC... | {
this.getSubjectListFn()
this.getPlatformListFn()
connect(getToken('username'));
} | identifier_body |
Index.js | import React, {Component} from "react";
import "./Index.less";
import {
Button,
Card,
message,
LocaleProvider,
Col,
Select,
Row,
DatePicker,
Upload,
Divider,
Spin
} from "antd";
import BreadcrumbCustom from "../common/BreadcrumbCustom";
import zh_CN from "antd/lib/locale-prov... | const menus = [
{
path: '/app/dashboard/analysis',
name: '首页'
},
{
path: '#',
name: '线索I/O'
},
{
path: '/app/export/index',
name: '线索I/O'
}
... | spinning
} = this.state;
| random_line_split |
Index.js | import React, {Component} from "react";
import "./Index.less";
import {
Button,
Card,
message,
LocaleProvider,
Col,
Select,
Row,
DatePicker,
Upload,
Divider,
Spin
} from "antd";
import BreadcrumbCustom from "../common/BreadcrumbCustom";
import zh_CN from "antd/lib/locale-prov... | extends Component {
constructor(props) {
super(props);
this.state = {
orderDate: null,
subjectList: null,
platformList: null,
subjectValue: null,
platformValue: null,
newCampaignNums: 0,
countNums: 0,
newClueNums: 0,
... | exportList | identifier_name |
csv_to_json.py | import os
import sys
import argparse
import json
import csv
import collections
import copy
import ast
import datetime
import dateutil.parser
def get_args():
"""
Get arguments of the program
:return: arguments parsed
"""
parser = argparse.ArgumentParser(
"Create json file from csv... | (x):
"""
Infer type of a string input.
:param x: input as a string
:return: return x cast to type infered or x itself if no type was infered
"""
str_to_types = [ast.literal_eval,
int,
float,
lambda x: dateutil.parser.parse... | infer_type | identifier_name |
csv_to_json.py | import os
import sys
import argparse
import json
import csv
import collections
import copy
import ast
import datetime
import dateutil.parser
def get_args():
"""
Get arguments of the program
:return: arguments parsed
"""
parser = argparse.ArgumentParser(
"Create json file from csv... |
else:
if beg:
jsf.write('[\n')
jsf.write(
',\n'.join(json.dumps(i) for i in json_doc)
)
if end:
jsf.write('\n]')
else:
jsf.write(',\n')
def str_to_type(name_type):
"""
Get t... | jsf.write(
'\n'.join(json.dumps(i) for i in json_doc) + '\n'
) | conditional_block |
csv_to_json.py | import os
import sys
import argparse
import json
import csv
import collections
import copy
import ast
import datetime
import dateutil.parser
def get_args():
"""
Get arguments of the program
:return: arguments parsed
"""
parser = argparse.ArgumentParser(
"Create json file from csv... |
def dump_json(json_file, json_doc, per_line, beg=True, end=True):
"""
Dump a json in one file
:param json_file: path to output file wanted
:param json_doc: json document
:param per_line: if true, write one json per line (specific format)
:param beg: Add opening array
... | """
Create one json for a whole csv
:param csv_file: path to csv file
:param delimiter: delimiter of the nested json (delimiter inside a column)
:param cols_delimiter: delimiter of the columns in the csv
:param keep: if true write None values instead of skipping them
:pa... | identifier_body |
csv_to_json.py | import os
import sys
import argparse
import json
import csv
import collections
import copy
import ast
import datetime
import dateutil.parser
def get_args():
"""
Get arguments of the program
:return: arguments parsed
"""
parser = argparse.ArgumentParser(
"Create json file from csv... | :param name_type: string containing name_type
:return: type or function to cast to specific type
"""
if name_type == 'float' or name_type == 'Float':
return float
if name_type == 'bool':
return bool
if name_type == 'int':
return lambda x: int(float(x... | """
Get type from string
| random_line_split |
proto_utils.go | /*
* Copyright 2018- The Pixie 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... |
}
return outputRelations
}
// AgentRelationToVizierRelation converts the agent relation format to the Vizier relation format.
func AgentRelationToVizierRelation(relation *schemapb.Relation) *vizierpb.Relation {
var cols []*vizierpb.Relation_ColumnInfo
for _, c := range relation.Columns {
newCol := &vizierpb.Re... | {
for _, node := range fragment.Nodes {
if node.Op.OpType == planpb.GRPC_SINK_OPERATOR {
grpcSink := node.Op.GetGRPCSinkOp()
outputTableInfo := grpcSink.GetOutputTable()
if outputTableInfo == nil {
continue
}
relation := &schemapb.Relation{
Columns: []*schemapb.Relation_Colum... | conditional_block |
proto_utils.go | /*
* Copyright 2018- The Pixie 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... |
// StatusToError converts a statuspb.Status to a grpc error.
func StatusToError(s *statuspb.Status) error {
return status.Error(codes.Code(int32(s.ErrCode)), s.Msg)
}
// VizierStatusToError converts a vizierpb.Status to a grpc error.
func VizierStatusToError(s *vizierpb.Status) error {
return status.Error(codes.Co... | {
var results []*vizierpb.ExecuteScriptResponse
schemas := OutputSchemaFromPlan(planMap)
for tableName, schema := range schemas {
tableID, present := tableIDMap[tableName]
if !present {
return nil, fmt.Errorf("Table ID for table name %s not found in table map", tableName)
}
convertedRelation := AgentRel... | identifier_body |
proto_utils.go | /*
* Copyright 2018- The Pixie 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... | (i *typespb.UInt128) *vizierpb.UInt128 {
return &vizierpb.UInt128{
Low: i.Low,
High: i.High,
}
}
func colToVizierCol(col *schemapb.Column) (*vizierpb.Column, error) {
switch c := col.ColData.(type) {
case *schemapb.Column_BooleanData:
return &vizierpb.Column{
ColData: &vizierpb.Column_BooleanData{
Bo... | UInt128ToVizierUInt128 | identifier_name |
proto_utils.go | /*
* Copyright 2018- The Pixie 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... | }
}
// TableRelationResponses returns the query metadata table schemas as ExecuteScriptResponses.
func TableRelationResponses(queryID uuid.UUID, tableIDMap map[string]string,
planMap map[uuid.UUID]*planpb.Plan) ([]*vizierpb.ExecuteScriptResponse, error) {
var results []*vizierpb.ExecuteScriptResponse
schemas := Ou... | cols = append(cols, newCol)
}
return &vizierpb.Relation{
Columns: cols, | random_line_split |
setuptool.go | /*
Copyright 2018 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 writing, software
dis... |
func (e oauthServiceCredsEditor) edit(term *terminal) {
takeActionLoop(term,
newAction("Edit Client Id", e.setClientId),
newAction("Edit Client Secret", e.setClientSecret),
newAction("Edit Auth Url", e.setAuthURL),
newAction("Edit Token Url", e.setTokenURL),
newAction("Edit Scopes", e.setScopes),
)
}
fun... | {
e.setClientId(term)
e.setClientSecret(term)
e.setAuthURL(term)
e.setTokenURL(term)
e.setScopes(term)
} | identifier_body |
setuptool.go | /*
Copyright 2018 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 writing, software
dis... |
takeActionLoop(term,
newAction("Retrieve Account Key", e.retrieveAccountKey),
newAction("Edit Web Api Gateway Url", e.editUrl),
newAction("Add service", e.addService),
newAction("Edit service (including adding new accounts to an existing service)", e.editService),
newAction("Delete service", e.removeServic... | {
e.editUrl(term)
} | conditional_block |
setuptool.go | /*
Copyright 2018 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 writing, software
dis... | (f actionFunc) actionFunc {
return func(term *terminal) {
if term.readBoolean("Editing a name will break existing connections. Only do this if you're really ok with fixing everything! Continue with rename? (yes/no)> ") {
f(term)
} else {
fmt.Println("Cancelling name edit.")
}
}
}
func confirmNewClientC... | confirmRename | identifier_name |
setuptool.go | /*
Copyright 2018 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 writing, software
dis... | fmt.Println("Bad decode")
continue
}
j := struct {
Token string
State string
}{}
json.Unmarshal(jsonAuthCode, &j)
if j.State != state {
fmt.Printf("Bad state. Expected %s, got %s\n", state, j.State)
continue
}
token, err := oauthConf.Exchange(context.Background(), j.Token)
if err == ... | encodedAuthCode := term.readSimpleString()
jsonAuthCode, err := base64.StdEncoding.DecodeString(encodedAuthCode)
if err != nil { | random_line_split |
myAgents.py | # myAgents.py
# ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu... |
def getAction(self, state):
return self.findPathToClosestDot(state)[0]
class AnyFoodSearchProblem(PositionSearchProblem):
"""
A search problem for finding a path to any food.
This search problem is just like the PositionSearchProblem, but has a
different goal test, which you need to fill... | """
Returns a path (a list of actions) to the closest dot, starting from
gameState.
"""
# Here are some useful elements of the startState
startPosition = gameState.getPacmanPosition(self.index)
food = gameState.getFood()
walls = gameState.getWalls()
proble... | identifier_body |
myAgents.py | # myAgents.py
# ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu... | (PositionSearchProblem):
"""
A search problem for finding a path to any food.
This search problem is just like the PositionSearchProblem, but has a
different goal test, which you need to fill in below. The state space and
successor function do not need to be changed.
The class definition abov... | AnyFoodSearchProblem | identifier_name |
myAgents.py | # myAgents.py
# ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu... |
if not followPac:
return
followPac = max(followPac, key=lambda x: len(x))
last = followPac.pop()
followPac.append(last)
followPac.append('place')
followPac.append(reverse[last])
return followPac.copy()
cbfs = customBreadthFirstSearch
| i += 1
state = fringe.pop()
succ = state[0][0]
act = state[0][1]
cost = state[0][2]
dirList = state[1]
dirList.append(act)
if problem.isGoalState(succ):
return dirList
if problem.isPacman(succ):
followPac.append(dirList.cop... | conditional_block |
myAgents.py | # myAgents.py
# ---------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu... | self.path = None
if not self.path and MyAgent.foodLeft > 0:
problem = MySearchProblem(state, self.index, min(foodCount, MyAgent.foodLeft), MyAgent.customFood, MyAgent.specialWalls, MyAgent.finding)
self.path = cbfs(problem)
nx, ny = x, y
... | MyAgent.specialWalls[(x, y)] = self.path[1] | random_line_split |
user_mgt.go | // Copyright 2017 Google Inc. All Rights Reserved.
//
// 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 applicabl... | return fmt.Errorf("display name must be a non-empty string")
}
return nil
}
func validatePhotoURL(val string) error {
if val == "" {
return fmt.Errorf("photo url must be a non-empty string")
}
return nil
}
func validateEmail(email string) error {
if email == "" {
return fmt.Errorf("email must be a non-emp... | random_line_split | |
user_mgt.go | // Copyright 2017 Google Inc. All Rights Reserved.
//
// 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 applicabl... | (ic identitytoolkitCall) {
ic.Header().Set("X-Client-Version", c.version)
}
// UserInfo is a collection of standard profile information for a user.
type UserInfo struct {
DisplayName string
Email string
PhoneNumber string
PhotoURL string
// In the ProviderUserInfo[] ProviderID can be a short domain name... | setHeader | identifier_name |
user_mgt.go | // Copyright 2017 Google Inc. All Rights Reserved.
//
// 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 applicabl... |
}
if u.email {
if err := validateEmail(req.Email); err != nil {
return nil, err
}
}
if u.phoneNumber {
if err := validatePhone(req.PhoneNumber); err != nil {
return nil, err
}
}
if u.photoURL {
if err := validatePhotoURL(req.PhotoUrl); err != nil {
return nil, err
}
}
if req.Password != ""... | {
return nil, err
} | conditional_block |
user_mgt.go | // Copyright 2017 Google Inc. All Rights Reserved.
//
// 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 applicabl... |
var serverError = map[string]string{
"CONFIGURATION_NOT_FOUND": projectNotFound,
"DUPLICATE_EMAIL": emailAlreadyExists,
"DUPLICATE_LOCAL_ID": uidAlreadyExists,
"EMAIL_EXISTS": emailAlreadyExists,
"INSUFFICIENT_PERMISSION": insufficientPermission,
"PERMISSION_DENIED": insufficientPe... | {
return internal.HasErrorCode(err, userNotFound)
} | identifier_body |
bagpreparer.go | package workers
import (
"encoding/json"
"fmt"
"github.com/APTrust/bagman/bagman"
"github.com/nsqio/go-nsq"
"os"
"strings"
"time"
)
// Large file is ~50GB
const LARGE_FILE_SIZE = int64(50000000000)
// apt_prepare receives messages from nsqd describing
// items in the S3 receiving buckets. It fetches, untars,... | (message *nsq.Message) error {
message.DisableAutoResponse()
var s3File bagman.S3File
err := json.Unmarshal(message.Body, &s3File)
if err != nil {
bagPreparer.ProcUtil.MessageLog.Error("Could not unmarshal JSON data from nsq:",
string(message.Body))
message.Finish()
return nil
}
// If we're not reproces... | HandleMessage | identifier_name |
bagpreparer.go | package workers
import (
"encoding/json"
"fmt"
"github.com/APTrust/bagman/bagman"
"github.com/nsqio/go-nsq"
"os"
"strings"
"time"
)
// Large file is ~50GB
const LARGE_FILE_SIZE = int64(50000000000)
// apt_prepare receives messages from nsqd describing
// items in the S3 receiving buckets. It fetches, untars,... |
// -- Step 2 of 5 --
// This runs as a go routine to untar files downloaded from S3.
// We calculate checksums and create generic files during the unpack
// stage to avoid having to reprocess large streams of data several times.
func (bagPreparer *BagPreparer) doUnpack() {
for helper := range bagPreparer.UnpackChann... | {
for helper := range bagPreparer.FetchChannel {
result := helper.Result
result.NsqMessage.Touch()
s3Key := result.S3File.Key
// Disk needs filesize * 2 disk space to accomodate tar file & untarred files
err := bagPreparer.ProcUtil.Volume.Reserve(uint64(s3Key.Size * 2))
if err != nil {
// Not enough roo... | identifier_body |
bagpreparer.go | package workers
import (
"encoding/json"
"fmt"
"github.com/APTrust/bagman/bagman"
"github.com/nsqio/go-nsq"
"os"
"strings"
"time"
)
// Large file is ~50GB
const LARGE_FILE_SIZE = int64(50000000000)
// apt_prepare receives messages from nsqd describing
// items in the S3 receiving buckets. It fetches, untars,... | bagPreparer.ProcUtil.MessageLog.Warning("Nothing to unpack for %s",
result.S3File.Key.Key)
bagPreparer.ResultsChannel <- helper
} else {
// Unpacked! Now process the bag and touch message
// so nsqd knows we're making progress.
bagPreparer.ProcUtil.MessageLog.Info("Unpacking %s", result.S3File.Key.... | result := helper.Result
if result.ErrorMessage != "" {
// Unpack failed. Go to end. | random_line_split |
bagpreparer.go | package workers
import (
"encoding/json"
"fmt"
"github.com/APTrust/bagman/bagman"
"github.com/nsqio/go-nsq"
"os"
"strings"
"time"
)
// Large file is ~50GB
const LARGE_FILE_SIZE = int64(50000000000)
// apt_prepare receives messages from nsqd describing
// items in the S3 receiving buckets. It fetches, untars,... | else if bagPreparer.largeFile2 == result.S3File.BagName() {
bagPreparer.ProcUtil.MessageLog.Info("Done with largeFile2 %s", result.S3File.Key.Key)
bagPreparer.largeFile2 = ""
}
}
}
func (bagPreparer *BagPreparer) cleanupBag(helper *bagman.IngestHelper) {
result := helper.Result
if result.ErrorMessage == ""... | {
bagPreparer.ProcUtil.MessageLog.Info("Done with largeFile1 %s", result.S3File.Key.Key)
bagPreparer.largeFile1 = ""
} | conditional_block |
startService.py | #! /usr/bin/env python3.6
#coding=utf-8
import os
import subprocess
import threading
import time
import traceback
from enum import Enum
import grpc
from . import perfdog_pb2, perfdog_pb2_grpc
class SaveFormat(Enum):
NONE = 0,
JSON = 1,
PB = 2,
EXCEL = 3,
ALL = 4,
class PerfdogService():
pac... | 5bd1ec676cbef4b90435234786c1"
uuid = ""
pref = PerfdogService(package,path,token,"Test",uuid)
print(pref)
pref.StopPerf()
| identifier_body | |
startService.py | #! /usr/bin/env python3.6
#coding=utf-8
import os | from enum import Enum
import grpc
from . import perfdog_pb2, perfdog_pb2_grpc
class SaveFormat(Enum):
NONE = 0,
JSON = 1,
PB = 2,
EXCEL = 3,
ALL = 4,
class PerfdogService():
packageName = ''
PerfdogPath = ''
Token = ''
stub = None
device = None
caseName = ''
deviceUu... | import subprocess
import threading
import time
import traceback | random_line_split |
startService.py | #! /usr/bin/env python3.6
#coding=utf-8
import os
import subprocess
import threading
import time
import traceback
from enum import Enum
import grpc
from . import perfdog_pb2, perfdog_pb2_grpc
class SaveFormat(Enum):
NONE = 0,
JSON = 1,
PB = 2,
EXCEL = 3,
ALL = 4,
class PerfdogService():
pac... | e.fangzhidalu"
path = "C:/Work/PerfDog/PerfDogService(v4.3.200927-Win)/PerfDogService.exe"
token = "e8e5734ad2f74176b368c956173c9bfbb3a85bd1ec676cbef4b90435234786c1"
uuid = ""
pref = PerfdogService(package,path,token,"Test",uuid)
print(pref)
pref.StopPerf()
| self.SaveJSON()
else:
print("保存格式为NONE 不保存为文件")
print("13.停止测试")
self.stub.stopTest(perfdog_pb2.StopTestReq(device=self.device))
self.stub.killServer()
print("over")
except Exception as e:
traceback.print_exc()
... | conditional_block |
startService.py | #! /usr/bin/env python3.6
#coding=utf-8
import os
import subprocess
import threading
import time
import traceback
from enum import Enum
import grpc
from . import perfdog_pb2, perfdog_pb2_grpc
class | (Enum):
NONE = 0,
JSON = 1,
PB = 2,
EXCEL = 3,
ALL = 4,
class PerfdogService():
packageName = ''
PerfdogPath = ''
Token = ''
stub = None
device = None
caseName = ''
deviceUuid = ''
saveformat = SaveFormat.ALL
uploadServer = True
saveJsonPath = ''
def __i... | SaveFormat | identifier_name |
linktypes.rs | //! LINK-LAYER HEADER TYPE VALUES [https://www.tcpdump.org/linktypes.html](https://www.tcpdump.org/linktypes.html)
//!
//! LINKTYPE_ name | LINKTYPE_ value | Corresponding DLT_ name | Description
/// DLT_NULL BSD loopback encapsulation; the link layer header is a 4-byte field, in host byte order, containing a value of... | /// DLT_AX25_KISS AX.25 packet, with a 1-byte KISS header containing a type indicator.
pub const AX25_KISS: i32 = 202;
/// DLT_LAPD Link Access Procedures on the D Channel (LAPD) frames, as specified by ITU-T Recommendation Q.920 and ITU-T Recommendation Q.921, starting with the address field, with no pseudo-header.
pu... | pub const ERF: i32 = 197;
/// DLT_BLUETOOTH_HCI_H4_WITH_PHDR Bluetooth HCI UART transport layer; the frame contains a 4-byte direction field, in network byte order (big-endian), the low-order bit of which is set if the frame was sent from the host to the controller and clear if the frame was received by the host from t... | random_line_split |
storage.rs | //! A module encapsulating the Raft storage interface.
use actix::{
dev::ToEnvelope,
prelude::*,
};
use futures::sync::mpsc::UnboundedReceiver;
use failure::Fail;
use crate::{
proto,
raft::NodeId,
};
/// An error type which wraps a `dyn Fail` type coming from the storage layer.
///
/// This does requ... | /// state record; and the index of the last log applied to the state machine.
pub struct GetInitialState;
impl Message for GetInitialState {
type Result = StorageResult<InitialState>;
}
/// A struct used to represent the initial state which a Raft node needs when first starting.
pub struct InitialState {
/// ... | /// The storage impl may need to look in a few different places to accurately respond to this
/// request. That last entry in the log for `last_log_index` & `last_log_term`; the node's hard | random_line_split |
storage.rs | //! A module encapsulating the Raft storage interface.
use actix::{
dev::ToEnvelope,
prelude::*,
};
use futures::sync::mpsc::UnboundedReceiver;
use failure::Fail;
use crate::{
proto,
raft::NodeId,
};
/// An error type which wraps a `dyn Fail` type coming from the storage layer.
///
/// This does requ... | (pub Box<dyn Fail>);
/// The result type of all `RaftStorage` interfaces.
pub type StorageResult<T> = Result<T, StorageError>;
//////////////////////////////////////////////////////////////////////////////
// GetInitialState ///////////////////////////////////////////////////////////
/// An actix message type for re... | StorageError | identifier_name |
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... | {
value += '';
} else if (type === 'function') {
value = _helpers.$string(value());
} else {
value = '';
}
}
return value;
},
$escape: function (content) {
var m = {
"<": "<... | place(/\n/g, '\\n') + "'";
};
};
})();
////////////////////////////////////////////////////////////////////////
// 辅助方法集合
var _helpers = template.helpers = {
$include: template.render,
$string: function (value, type) {
if (typeof value !== 'string') {
type = typeof valu... | identifier_body |
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 {
var Render = _compile(id, source); //编译时错误
} catch (e) {
e.id = id || source;
e.name = 'Syntax Error';
_debug(e);
throw(e);
}
function render (data) {
try {
return new Render(dat... | {
source = params[0];
id = anonymous;
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.