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 |
|---|---|---|---|---|
main.rs | biggest = (count_for_it, it);
}
}
println!("biggest seq len: {:?}, for n={:?}", biggest.0, biggest.1);
}
#[timings] //https://github.com/zacharydenton/euler/blob/master/014/collatz.rs
fn e14_zach_denton() {
let mut collatz: Vec<usize> = vec![0; 1_000_000];
collatz[1] = 1;
let max = (2..col... |
// if tie: prefer rightward motion, THIS IS A (temporarily acceptable) BUG
if t[0][last_index] > t[0][last_index + 1] {
path.push((t[0][last_index], last_index));
(
t[0][last_index] + running_sum,
first_step.unwrap_or(Dir::Left),
... | conditional_block | |
main.rs | });
println!("biggest: {}", big);
}
// v elegant: https://github.com/zacharydenton/euler/blob/master/011/grid.rs
// 1. include_str!("grid.txt") I could be using this macro instead.
// 2. .filter_map(|n| n.parse().ok()), well isn't that sweet.
// 3. his solution collects the maximum value in each direction in a... | }
}
}
#[timings]
fn e13() {
let s: Vec<String> = std::fs::read_to_string("src/e13.txt")
.unwrap()
.split_whitespace()
.map(|s| s.parse::<String>().unwrap())
.collect();
let s13: Vec<usize> = s
.iter()
.map(|l| l[..13].parse::<usize>().unwrap())
... | random_line_split | |
common.js | hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable'... |
if (share) {
addthis.toolbox("#vbc_share");
}
},
vbEditMenu: function(event, elem) {
var $this = $(elem);
var $editWrapper = $('.vbs-edit-mode-wrapper');
$("ul.vbs-vbcmenu").remove();
$editWrapper.find('.vbs-menu-... | {
$("#vbc_url").find('a').zclip({
path: VB.settings.zeroclipboard,
copy: url
});
} | conditional_block |
common.js | hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'proper... | array = Object.keys | var unique_array = {};
for (var i = 0; i < array.length; i++) {
unique_array[array[i]] = true;
} | random_line_split |
japari-bun-catch.js | Asset('assets/lucky-beast.png'),
}
this.luckyBeast = null
this.friend = null
this.entities = []
this.lives = 0
this.score = 0
this.difficulty = 0
this.timeToNextBun = 0
this.paused = false // Game is paused when a bun drops to the floor. Pausing due to the menu being open ... |
// Cleanup
this.entities = this.entities.filter(entity => !entity._expired)
}
paint () {
const c2d = this.canvas2d
c2d.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
// ----------------
// Draw background
// ----------------
if (this.assets.background) {
... | {
const DIFFICULTY_MODIFIER = 0.2
const timeToBun = TIME_BETWEEN_BUNS / (1 + this.difficulty * DIFFICULTY_MODIFIER)
this.timeToNextBun += timeToBun
const newCol = Math.floor(Math.random() * COLUMNS_FOR_BUNS)
const newBun = new Bun(this, newCol, this.difficulty)
this.entities.push(new... | conditional_block |
japari-bun-catch.js | Asset('assets/lucky-beast.png'),
}
this.luckyBeast = null
this.friend = null
this.entities = []
this.lives = 0
this.score = 0
this.difficulty = 0
this.timeToNextBun = 0
this.paused = false // Game is paused when a bun drops to the floor. Pausing due to the menu being open ... | const offsetX = 0
const offsetY = 0
for (let y = offsetY ; y < APP_HEIGHT ; y += TILE_SIZE) {
for (let x = offsetX ; x < APP_WIDTH ; x += TILE_SIZE) {
c2d.beginPath()
c2d.rect(x, y, TILE_SIZE, TILE_SIZE)
c2d.closePath()
c2d.stroke()
}
}
*/
// ----... | {
const c2d = this.canvas2d
c2d.clearRect(0, 0, this.canvasWidth, this.canvasHeight)
// ----------------
// Draw background
// ----------------
if (this.assets.background) {
const BACKGROUND_SIZE_X = 800
const BACKGROUND_SIZE_Y = 500
c2d.drawImage(this.assets.backgrou... | identifier_body |
japari-bun-catch.js | ImageAsset('assets/lucky-beast.png'),
}
this.luckyBeast = null
this.friend = null
this.entities = []
this.lives = 0
this.score = 0
this.difficulty = 0
this.timeToNextBun = 0
this.paused = false // Game is paused when a bun drops to the floor. Pausing due to the menu being... | }
}
/*
Section: General Logic
----------------------------------------------------------------------------
*/
main (time) {
const timeStep = (this.prevTime) ? time - this.prevTime : time
this.prevTime = time
if (this.initialised) {
this.play(timeStep)
this.paint()
... | if (allAssetsLoaded) {
this.initialised = true
this.showUI()
this.startGame() | random_line_split |
japari-bun-catch.js | {
this.initialised = true
this.showUI()
this.startGame()
}
}
/*
Section: General Logic
----------------------------------------------------------------------------
*/
main (time) {
const timeStep = (this.prevTime) ? time - this.prevTime : time
this.prevTime = time
... | S.EAST)
}
/* | identifier_name | |
anime-face-detector.py | (box[:2] + box[2:]) / 2
tl = center - new_size / 2
br = tl + new_size
pred_box[:4] = np.concatenate([tl, br])
boxes.append(pred_box)
return boxes
def xyxy2xywh(bbox_xyxy):
"""Transform the bbox format from x1y1x2y2 to xywh.
Args:
bbox_xyxy (np.ndarra... | for image_path in args.input:
logger.info(image_path)
# prepare input data
img = load_image(image_path)
img = cv2.cvtColor(img, cv2.COLOR_BGRA2BGR)
# inference
logger.info('Start inference...')
if args.benchmark:
logger.info('BENCHMARK mode... | identifier_body | |
anime-face-detector.py | )
scale = scale * 1.25
return center, scale
def detect_faces(img, face_detector):
shape = (IMAGE_YOLOV3_HEIGHT, IMAGE_YOLOV3_WIDTH) \
if args.detector == "yolov3" \
else (IMAGE_FASTERRCNN_HEIGHT, IMAGE_FASTERRCNN_WIDTH)
im_h, im_w = img.shape[:2]
img, pad_hw, resize... | main() | conditional_block | |
anime-face-detector.py |
DRAW_CONTOUR = True
SKIP_CONTOUR_WITH_LOW_SCORE = True
# ======================
# Arguemnt Parser Config
# ======================
parser = get_base_parser(
'Anime Face Detector', IMAGE_PATH, SAVE_IMAGE_PATH
)
parser.add_argument(
'-d', '--detector', default='yolov3', choices=('yolov3', 'faster-rc... | (box):
"""This encodes bbox(x,y,w,h) into (center, scale)
Args:
x, y, w, h
Returns:
tuple: A tuple containing center and scale.
- np.ndarray[float32](2,): Center of the bbox (x, y).
- np.ndarray[float32](2,): Scale of the bbox w & h.
"""
input_size = (2... | box2cs | identifier_name |
anime-face-detector.py |
DRAW_CONTOUR = True
SKIP_CONTOUR_WITH_LOW_SCORE = True
# ======================
# Arguemnt Parser Config
# ======================
parser = get_base_parser(
'Anime Face Detector', IMAGE_PATH, SAVE_IMAGE_PATH
)
parser.add_argument(
'-d', '--detector', default='yolov3', choices=('yolov3', 'faster-rc... |
def xyxy2xywh(bbox_xyxy):
"""Transform the bbox format from x1y1x2y2 to xywh.
Args:
bbox_xyxy (np.ndarray): Bounding boxes (with scores), shaped (n, 4) or
(n, 5). (left, top, right, bottom, [score])
Returns:
np.ndarray: Bounding boxes (with scores),
shape... | random_line_split | |
main.go | Game []string
listGraphics []string
listInternetAndNetwork []string
listOffice []string
listAudioVideo []string
listSystemTools []string
listOther []string
)
var desktopEntries []desktopEntry
// UI elements
var (
resultWindow *gtk.Scrol... | () {
timeStart := time.Now()
flag.Parse()
if *displayVersion {
fmt.Printf("nwg-drawer version %s\n", version)
os.Exit(0)
}
// Gentle SIGTERM handler thanks to reiki4040 https://gist.github.com/reiki4040/be3705f307d3cd136e85
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM)
g... | main | identifier_name |
main.go | Game []string
listGraphics []string
listInternetAndNetwork []string
listOffice []string
listAudioVideo []string
listSystemTools []string
listOther []string
)
var desktopEntries []desktopEntry
// UI elements
var (
resultWindow *gtk.Scrol... |
// Flags
var cssFileName = flag.String("s", "drawer.css", "Styling: css file name")
var targetOutput = flag.String("o", "", "name of the Output to display the drawer on (sway only)")
var displayVersion = flag.Bool("v", false, "display Version information")
var overlay = flag.Bool("ovl", false, "use OVerLay layer")
va... | {
s = strings.TrimSpace(s)
if s == "" {
return fallback
}
return s
} | identifier_body |
main.go | == nil {
println("Running instance found, sending SIGTERM and exiting...")
syscall.Kill(i, syscall.SIGTERM)
}
}
os.Exit(0)
}
defer lockFile.Close()
// LANGUAGE
if *lang == "" && os.Getenv("LANG") != "" {
*lang = strings.Split(os.Getenv("LANG"), ".")[0]
}
println(fmt.Sprintf("lang: %s", *lang))
... | random_line_split | ||
main.go | Game []string
listGraphics []string
listInternetAndNetwork []string
listOffice []string
listAudioVideo []string
listSystemTools []string
listOther []string
)
var desktopEntries []desktopEntry
// UI elements
var (
resultWindow *gtk.Scrol... |
// Gentle SIGTERM handler thanks to reiki4040 https://gist.github.com/reiki4040/be3705f307d3cd136e85
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM)
go func() {
for {
s := <-signalChan
if s == syscall.SIGTERM {
println("SIGTERM received, bye bye!")
gtk.MainQuit()
... | {
fmt.Printf("nwg-drawer version %s\n", version)
os.Exit(0)
} | conditional_block |
tabs.rs | };
use std::fs::File;
use std::sync::{Arc, Mutex};
use serde_json::value::Value;
use xi_rope::rope::Rope;
use editor::Editor;
use rpc::{CoreCommand, EditCommand};
use styles::{Style, StyleMap};
use MainPeer;
/// ViewIdentifiers are the primary means of routing messages between xi-core and a client view.
pub type View... |
}
}
/// Adds a new view to an existing editor instance.
#[allow(unreachable_code, unused_variables, dead_code)]
fn add_view(&mut self, view_id: &str, buffer_id: BufferIdentifier) {
panic!("add_view should not currently be accessible");
let editor = self.buffers.get(&buffer_id)... | {
// TODO: we should be reporting errors to the client
// (if this is even an error? we treat opening a non-existent file as a new buffer,
// but set the editor's path)
print_err!("unable to read file: {}, error: {:?}", buffer_id, err);
self... | conditional_block |
tabs.rs | };
use std::fs::File;
use std::sync::{Arc, Mutex};
use serde_json::value::Value;
use xi_rope::rope::Rope;
use editor::Editor;
use rpc::{CoreCommand, EditCommand};
use styles::{Style, StyleMap};
use MainPeer;
/// ViewIdentifiers are the primary means of routing messages between xi-core and a client view.
pub type View... | self.buffers.remove(&buf_id);
if let Some(path) = path {
self.open_files.remove(&path);
}
}
}
fn do_save(&mut self, view_id: &str, file_path: &str) -> Option<Value> {
let buffer_id = self.views.get(view_id)
.expect(&format!("missin... | (editor.has_views(), editor.get_path().map(PathBuf::from))
};
if !has_views { | random_line_split |
tabs.rs | };
use std::fs::File;
use std::sync::{Arc, Mutex};
use serde_json::value::Value;
use xi_rope::rope::Rope;
use editor::Editor;
use rpc::{CoreCommand, EditCommand};
use styles::{Style, StyleMap};
use MainPeer;
/// ViewIdentifiers are the primary means of routing messages between xi-core and a client view.
pub type View... | <P: AsRef<Path>>(&self, path: P) -> io::Result<String> {
let mut f = File::open(path)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
}
fn close_view(&mut self, view_id: &str) {
let buf_id = self.views.remove(view_id).expect("missing buffer id when clos... | read_file | identifier_name |
tabs.rs | };
use std::fs::File;
use std::sync::{Arc, Mutex};
use serde_json::value::Value;
use xi_rope::rope::Rope;
use editor::Editor;
use rpc::{CoreCommand, EditCommand};
use styles::{Style, StyleMap};
use MainPeer;
/// ViewIdentifiers are the primary means of routing messages between xi-core and a client view.
pub type View... |
fn close_view(&mut self, view_id: &str) {
let buf_id = self.views.remove(view_id).expect("missing buffer id when closing view");
let (has_views, path) = {
let editor = self.buffers.get(&buf_id).expect("missing editor when closing view");
let mut editor = editor.lock().u... | {
let mut f = File::open(path)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
Ok(s)
} | identifier_body |
vehicle.js | ).
* For success the .statusCode should be 202 and the body.commandStatus should be COMPLETED.
* Because of agressive timeouts it may still be PENDINGRESPONSE.
*/
async function cloudPush(vehicleId) {
const response = await fordConnect.doStatus(vehicleId);
if (response.statusCode === 202
&& response.body
... | // Delete the words "UNSPECIFIED_" AND "NOT_APPLICABLE". Replace underscore with spaces
// for better speach output. Per the FAQ the d.value is either OPEN or CLOSED. | random_line_split | |
vehicle.js | ORD_CODE or MYFORD_REFRESH.');
process.exit(1);
}
} else if (vehicles.statusCode === 500) {
// We got HTTP 500 during the hack and the request from Ford was to get a new token.
// Refreshing the access token with the old refresh token would succeed OAuth calls,
// but all calls to the FordConnec... | (vehicleId) {
let message;
// Start charging.
const response = await fordConnect.doStartCharge(vehicleId);
if (response.statusCode === 406) {
if (response.body && response.body.error && response.body.error.details) {
message = `Failed charging vehicle. ${response.body.error.details}.`;
} else {... | chargeVehicle | identifier_name |
vehicle.js | ORD_CODE or MYFORD_REFRESH.');
process.exit(1);
}
} else if (vehicles.statusCode === 500) {
// We got HTTP 500 during the hack and the request from Ford was to get a new token.
// Refreshing the access token with the old refresh token would succeed OAuth calls,
// but all calls to the FordConnec... |
/**
* Returns a message with the status of door locks (LOCKED, UNLOCKED) and the
* alarm (SET, NOT SET, ACTIVE, ERROR).
*
* @param {*} vehicleId The vehicle to check.
* @returns String. A message to speak about the status of the door locks and alarm.
*/
async function checkLocksAndAlarm(vehicleId) {
let messa... | {
let message;
await fordConnect.doLocation(vehicleId);
// REVIEW: The GET /location API doesn't require a commandId, so how do we know it is updated.
const response = await fordConnect.getLocation(vehicleId);
if (response.statusCode === 200 && response.body && response.body.status === 'SUCCESS' && response.... | identifier_body |
vehicle.js | ORD_CODE or MYFORD_REFRESH.');
process.exit(1);
}
} else if (vehicles.statusCode === 500) {
// We got HTTP 500 during the hack and the request from Ford was to get a new token.
// Refreshing the access token with the old refresh token would succeed OAuth calls,
// but all calls to the FordConnec... |
return undefined;
}
/**
* Returns a message about the fuel and battery levels.
*
* @param {*} vehicleInfo The .body.vehicle data from getDetails call.
* @returns String. A message to speak about the status of charging.
*/
function checkFuel(vehicleInfo) {
const energy = {
fuelLevel: null,
fuelDTE: n... | {
const { commandId } = response.body;
// NOTE: We get an HTTP 202 from the GET call not a 200.
const status = await fordConnect.getStatus(vehicleId, commandId);
return status;
} | conditional_block |
queryOECD.py | not a valid commodity code or label, exits program with error message
NOTE: NA definition hit refers to if the calculated sum from different tables of CAN, USA, MEX are equal to that of NA (CAN+USA, CAN+USA+MEX, or Neither)
'''
'''
IMPROVEMENT: Use 'encodings' table instead of the CSV file
'''
##########... | (table, commodity_code, variable):
response = table.scan(
FilterExpression = Attr('commodity').eq(commodity_code) & Attr('variable').eq(variable)
)
return response['Count'] > 0
# Retrieves and outputs table data based on commodity and variable and analyze for NA definition
def output_table(commodit... | has_commodity_and_variable | identifier_name |
queryOECD.py | not a valid commodity code or label, exits program with error message
NOTE: NA definition hit refers to if the calculated sum from different tables of CAN, USA, MEX are equal to that of NA (CAN+USA, CAN+USA+MEX, or Neither)
'''
'''
IMPROVEMENT: Use 'encodings' table instead of the CSV file
'''
##########... | # Open the encodings CSV file and read its contents
commodity_encodings_dict = {}
variable_encodings_dict = {}
with open(ENCODINGS_CSV, "r", newline='') as csv_file:
csv_content = csv.reader(csv_file, delimiter=',')
# if field is var or commodity, set a key-value pair between code and l... | mexico_table = dynamodb_resource.Table(MEXICO)
| random_line_split |
queryOECD.py | not a valid commodity code or label, exits program with error message
NOTE: NA definition hit refers to if the calculated sum from different tables of CAN, USA, MEX are equal to that of NA (CAN+USA, CAN+USA+MEX, or Neither)
'''
'''
IMPROVEMENT: Use 'encodings' table instead of the CSV file
'''
##########... | print("Error: Too many arguments.")
# Exit with usage statement if flag has been triggered for any reason
if bad_usage_flag:
sys.exit(USAGE_STATEMENT)
# ========== AWS DYNAMO DB ==========
# Init AWS DynamoDB client and resource (NOTE: these are global)
dynamodb_client = boto3... | global dynamodb_client
global dynamodb_resource
global na_table
global canada_table
global usa_table
global mexico_table
global total_can_usa
global total_can_usa_mex
global total_neither
# ========== ARGUMENTS ==========
# Collect command line arguments when executing this pyt... | identifier_body |
queryOECD.py | both key/label),
# look for all common variables between CAN, USA, and MEX, outputting all results (for all years) in a table,
# then output the specific NA definition 'hit' results and probable conclusion for NA definition
def main():
#globals
global dynamodb_client
global dynamodb_res... | na_defn = 'CAN+USA'
temp_can_usa += 1 | conditional_block | |
main.go | SubRouter.HandleFunc("/wslog", wsLogHandler)
statikFS, err := fs.New()
if err != nil {
log.Fatal(err)
}
router.PathPrefix("/").Handler(http.FileServer(statikFS))
http.ListenAndServe(":"+strconv.Itoa(portInUse), router)
}
app.Commands = []cli.Command{
{
Name: "clean",
Usage: "clean... | w.Write([]byte(previewContent)) | random_line_split | |
main.go | .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .Flags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}
{{if .Version}}
` + colorVersion + `
{{.Version}}
{{end}}{{if len .Authors}}
` + colorAuthor + `
{{range .Authors}}{{... | (w http.ResponseWriter, r *http.Request) {
if "GET" == r.Method {
lg, _ := lang.GetLang()
switch lg {
case "en", "zh":
sendSuccess(w, lg, "I! get lang success")
default:
sendSuccess(w, "en", "I! get lang success")
}
} else if "POST" == r.Method {
var lg lang.Lang
err := json.NewDecoder(r.Body)... | langHandler | identifier_name |
main.go | "+err.Error())
} else {
// empty struct
sendSuccess(w, struct{}{}, "I! send mail success")
}
}
}
func fileHandler(w http.ResponseWriter, r *http.Request) {
if "GET" == r.Method {
sendSuccess(w, struct{}{}, MAILMAN_IS_AWESOME)
} else if "POST" == r.Method {
if err := r.ParseMultipartForm(MAX_MEMORY... | {
if port < MIN_TCP_PORT || port > MAX_TCP_PORT {
return false
}
conn, err := net.Listen("tcp", ":"+strconv.Itoa(port))
if err != nil {
return false
}
conn.Close()
return true
} | identifier_body | |
main.go | UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .Flags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}
{{if .Version}}
` + colorVersion + `
{{.Version}}
{{end}}{{if len .Authors}}
` + colorAuthor + `
{{range .Authors}}{{ .... |
}
func fileHandler(w http.ResponseWriter, r *http.Request) {
if "GET" == r.Method {
sendSuccess(w, struct{}{}, MAILMAN_IS_AWESOME)
} else if "POST" == r.Method {
if err := r.ParseMultipartForm(MAX_MEMORY); err != nil {
sendError(w, "E! parse posted file fail: "+err.Error())
}
token := ""
for k, vs ... | {
var m mail.Mail
err := json.NewDecoder(r.Body).Decode(&m)
if err != nil {
sendError(w, "E! "+ErrDataIsNotJson.Error())
} else if err = mail.SendMail(m); err != nil {
sendError(w, "E! send mail fail: "+err.Error())
} else {
// empty struct
sendSuccess(w, struct{}{}, "I! send mail success")
}... | conditional_block |
features.rs | = HashMap<u64, Vec<Feature>>;
pub type FeatureDB = Vec<Features>;
// Move it to graph, needed.
type CoordToNodeId = HashMap<String, Vec<NodeId>>; // Vec<NodeId> required as sorted by coord.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct NodeId {
id: u64,
coord: u64,
}
#[derive(Debug, PartialEq, ... | Ok(rec) => match rec.feature_type() {
"gene" => {
let reg = match opt_strand_to_opt_bool(rec.strand()) {
Some(false) => Region {
path: rec.seqname().to_string(),
stop: *rec.start(),
... | for record in reader.records() {
index += 1;
match record { | random_line_split |
features.rs | = HashMap<u64, Vec<Feature>>;
pub type FeatureDB = Vec<Features>;
// Move it to graph, needed.
type CoordToNodeId = HashMap<String, Vec<NodeId>>; // Vec<NodeId> required as sorted by coord.
#[derive(Debug, PartialEq, Serialize, Deserialize)]
struct NodeId {
id: u64,
coord: u64,
}
#[derive(Debug, PartialEq, ... | (
record: bed::Record,
coord_map: &CoordToNodeId,
bed_id: u64,
chr_prefix: &Option<String>,
) -> HashMap<u64, Feature> {
let mut hash_map: HashMap<u64, Feature> = HashMap::new();
let chr = match *chr_prefix {
Some(ref k) => record.chrom().replace(k, ""),
None => record.chrom().to... | record_to_nodes | identifier_name |
majsoul.go | 下家, 2=对家, 3=上家
dealer = (4 - d.selfSeat) % 4
return
} else if len(msg.Tiles2) > 0 {
if len(msg.Tiles3) > 0 {
d.playerNumber = 4
} else {
d.playerNumber = 3
}
}
dealer = -1
roundNumber = 4*(*msg.Chang) + *msg.Ju
benNumber = *msg.Ben
if msg.Dora != "" {
doraIndicator, _ := d.mustParseMajsoulTile(... | Tsumogiri boo | identifier_body | |
majsoul.go | ":0,"tile":"1z","is_liqi":false,"operation":{"seat":1,"operation_list":[{"type":3,"combination":["1z|1z"]}],"time_add":0,"time_fixed":60000},"moqie":false,"zhenting":false,"is_wliqi":false}
// 吃 碰 和
// {"seat":0,"tile":"6p","is_liqi":false,"operation":{"seat":1,"operation_list":[{"type":2,"combination":["7p|8p"]},{"t... | untID > 0 && gameConf.isIDExist(accountID) {
// 找到了,更新当前使用的账号 ID
if gameConf.currentActiveMajsoulAccountID != accountID {
printAccountInfo(accountID)
gameConf.setMajsoulAccountID(accountID)
}
return
}
}
// 未找到缓存 ID
if gameConf.currentActiveMajsoulAccountID > 0 {
color.HiRed("尚未获取到... | 从对战 ID 列表中获取账号 ID
if seatList := msg.SeatList; seatList != nil {
// 尝试从中找到缓存账号 ID
for _, accountID := range seatList {
if acco | conditional_block |
majsoul.go | 您的账号 ID,请您刷新网页,或开启一局人机对战(错误信息:您的账号 ID %d 不在对战列表 %v 中)", gameConf.currentActiveMajsoulAccountID, msg.SeatList)
return
}
// 判断是否为人机对战,若为人机对战,则获取账号 ID
if !util.InInts(0, msg.SeatList) {
return
}
for _, accountID := range msg.SeatList {
if accountID > 0 {
gameConf.addMajsoulAccountID(accountID)
... | } | random_line_split | |
majsoul.go | , ok := _tile.(string)
if !ok {
panic(fmt.Sprintln("[normalTiles] 解析错误", tiles))
}
majsoulTiles[i] = _t
}
return majsoulTiles
}
func (d *majsoulRoundData) parseWho(seat int) int {
// 转换成 0=自家, 1=下家, 2=对家, 3=上家
// 对三麻四麻均适用
who := (seat + d.dealer - d.roundNumber%4 + 4) % 4
return who
}
func (d *majsoulR... | -1
if d.isN | identifier_name | |
v0.rs | fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
if let Some(x) = x.checked_sub(1) {
self.push(tag);
self.push_integer_62(x);
}
}
fn push_disambiguator(&mut self, dis: u64) {
self.push_opt_integer_62("s", dis);
}
fn push_ident(&mut self, ident:... | // Replace `-` with `_`.
if let Some(c) = punycode_bytes.iter_mut().rfind(|&&mut c| c == b'-') {
*c = b'_';
}
// FIXME(eddyb) avoid rechecking UTF-8 validity.
punycode_string = String::from_utf8(punycode_bytes).unwrap();
&punycode_... | {
let mut use_punycode = false;
for b in ident.bytes() {
match b {
b'_' | b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' => {}
0x80..=0xff => use_punycode = true,
_ => bug!("symbol_names: bad byte {} in ident {:?}", b, ident),
}
}
... | identifier_body |
v0.rs | Ok(self)
}
fn in_binder<T>(
mut self,
value: &ty::Binder<T>,
print_value: impl FnOnce(Self, &T) -> Result<Self, !>
) -> Result<Self, !>
where T: TypeFoldable<'tcx>
{
let regions = if value.has_late_bound_regions() {
self.tcx.collect_referenced_late_b... | }
ty::Foreign(def_id) => { | random_line_split | |
v0.rs | ;
type Region = Self;
type Type = Self;
type DynExistential = Self;
type Const = Self;
fn tcx(&self) -> TyCtxt<'tcx> {
self.tcx
}
fn print_def_path(
mut self,
def_id: DefId,
substs: &'tcx [GenericArg<'tcx>],
) -> Result<Self::Path, Self::Error> {
... | print_dyn_existential | identifier_name | |
v0.rs | fn push_opt_integer_62(&mut self, tag: &str, x: u64) {
if let Some(x) = x.checked_sub(1) {
self.push(tag);
self.push_integer_62(x);
}
}
fn push_disambiguator(&mut self, dis: u64) {
self.push_opt_integer_62("s", dis);
}
fn push_ident(&mut self, ident:... |
// FIXME(eddyb) avoid rechecking UTF-8 validity.
punycode_string = String::from_utf8(punycode_bytes).unwrap();
&punycode_string
} else {
ident
};
let _ = write!(self.out, "{}", ident.len());
// Write a separating `_` if necessary (leadi... | {
*c = b'_';
} | conditional_block |
executor.rs | is received, it queries Docker Engine to see if:
//! 1) any scheduled containers are not currently running
//! 2) and running containers aren't still scheduled
//!
//! This actor is not responsible for modifying the cluster state. For that, see Scheduler.
use crate::scheduler::*;
use actix::fut::{ActorFuture, WrapFut... | {
state: ClusterState,
node_id: NodeId,
system: sysinfo::System,
}
impl Executor {
fn join<S: ToSocketAddrs>(
&mut self,
join_host: S,
local_port: u16,
) -> impl Future<Item = (), Error = Error> {
let join_host = join_host.to_socket_addrs().unwrap().next().unwrap();... | Executor | identifier_name |
executor.rs | received, it queries Docker Engine to see if:
//! 1) any scheduled containers are not currently running
//! 2) and running containers aren't still scheduled
//!
//! This actor is not responsible for modifying the cluster state. For that, see Scheduler.
use crate::scheduler::*;
use actix::fut::{ActorFuture, WrapFuture... |
}
None => Err(err_msg("Master unknown.")),
}
}
}
/// Message requesting resource usage of the local node
pub struct GetNodeResources;
impl Message for GetNodeResources {
type Result = Result<NodeResources, Error>;
}
impl Handler<GetNodeResources> for Executor {
type Resul... | {
Ok(Some(master.cluster_address))
} | conditional_block |
executor.rs | is received, it queries Docker Engine to see if:
//! 1) any scheduled containers are not currently running
//! 2) and running containers aren't still scheduled
//!
//! This actor is not responsible for modifying the cluster state. For that, see Scheduler.
use crate::scheduler::*;
use actix::fut::{ActorFuture, WrapFut... | .map(move |_| info!("Image already pulled: {:?}", image))
.or_else(move |_| {
docker.images().pull(&pull_opts).for_each(|p| {
debug!("Pull: {:?}", p);
Ok(())
})
})
.and... | .inspect() | random_line_split |
core.js | .parse(message.utf8Data);
switch (msg.type) {
case 'aut': //autentication to enter a room
// if (connection.username) //case if was in a different room before
// leaveRoom(connection.username, connection.roomName, connection.roomIndex, connection); **no hace falta... | {
//if (msg.type != "text" || validDistance(clients[sendPos].pos, clients[k].pos)) { //only see if is in a valid distance for messages **Not used
clients[k].connection.sendUTF(JSON.stringify(msg)); //*only stringify for chat messages
//}
} | conditional_block | |
core.js | init: function() {
console.log("Inizialising CORE...");
},
onClientConnect: function(connection) {
connection.username = false; //starts as false until user logIn
let rooms = [];
CORE.chatRooms.forEach(room => {
rooms.push(room.roomName);
});
msg... |
function setRoom(room, username, connection, avatar, position, clientType) { //sets a connected user to a room
let roomIndex = CORE.chatRooms.findIndex(element => element.roomName == room);
let index = 0; //basic index if is a new room
let pos = position ? position : [0, 0.1, 0];
let cData = {};
... | {
CORE.chatRooms[connection.roomIndex].clients.forEach(client => {
if (client.connection == connection) {
if (username != undefined) {
client.username = connection.username = username;
}
if (avatar != undefined)
client.avatar = avatar;
... | identifier_body |
core.js |
init: function() {
console.log("Inizialising CORE...");
},
onClientConnect: function(connection) {
connection.username = false; //starts as false until user logIn
let rooms = [];
CORE.chatRooms.forEach(room => {
rooms.push(room.roomName);
});
m... | //console.log(` - ${connection.username || "'Unidentified User'"} sent us: ${JSON.stringify(message.utf8Data)}`);
let msg = JSON.parse(message.utf8Data);
switch (msg.type) {
case 'aut': //autentication to enter a room
// if (connection.username) //case if was in a d... | onNewMessage: async function(connection, message) { | random_line_split |
core.js | init: function() {
console.log("Inizialising CORE...");
},
onClientConnect: function(connection) {
connection.username = false; //starts as false until user logIn
let rooms = [];
CORE.chatRooms.forEach(room => {
rooms.push(room.roomName);
});
msg... | (user, text, inRoom, position) { //username, message, bool is in room
let pos = {};
if (position) {
pos = position
}
let info = { type: "info", username: user, content: text, exists: inRoom, pos: pos };
return info;
}
function broadcastFromUser(msg, connection) { //broadcas all people exce... | infoMsg | identifier_name |
ann_utils.py | :return:
"""
annotator1 = read_ehost_annotated_result(folder1, no_context=no_context)
annotator2 = read_ehost_annotated_result(folder2, no_context=no_context)
merged_keys = list(set(annotator1.keys()) | set(annotator2.keys()))
y1 = []
y2 = []
for key in merged_keys:
if key in annota... | summarise_validation_results | identifier_name | |
ann_utils.py | _path):
super(eHostAnnDoc, self).__init__(file_path)
def get_ess_entities(self, no_context=False):
if self._entities is not None:
return self._entities
root = self._root
entities = []
for e in root.findall('.//classMention'):
mcs = e.findall('./mentio... | text = utils.read_text_file_as_string(join(text_folder, f[0:-14]), encoding='cp1252')
sents = rr.get_sentences_as_anns(nlp, text)
for ann in anns:
for s in sents:
if ann.overlap(s):
abss = rr.AbstractedSentence(1)
abss.text = s.... | if len(anns) == 0:
logging.info('anns is empty for [{:s}]'.format(f)) | random_line_split |
ann_utils.py | :
:param no_context:
:return:
"""
annotator1 = read_ehost_annotated_result(folder1, no_context=no_context)
annotator2 = read_ehost_annotated_result(folder2, no_context=no_context)
merged_keys = list(set(annotator1.keys()) | set(annotator2.keys()))
y1 = []
y2 = []
for key in merged_ke... | if key in d:
d[key] += 1
else:
d[key] = 1 | identifier_body | |
ann_utils.py | _path):
super(eHostAnnDoc, self).__init__(file_path)
def get_ess_entities(self, no_context=False):
if self._entities is not None:
return self._entities
root = self._root
entities = []
for e in root.findall('.//classMention'):
mcs = e.findall('./mentio... |
mentions = root.findall('.//mention[@id="' + mention_id + '"]/..')
if len(mentions) > 0:
span = mentions[0].findall('./span')
ent_start = span[0].attrib['start']
ent_end = span[0].attrib['end']
... | cls = cls[cls.find('_')+1:] | conditional_block |
hap_to_domo.py | x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF]
# dane': [0xF0, 0xF0, 0x01, 0x01, 0x19, 0x0b, 0x00, 0xFF, 0xFF, 0xFF]},
# znajdz komenda dla danego idx i nvalue
#print("Otrzymałem od Domoticza", "idx", idx, "nvalue", nvalue, "svalue1", svalue1, payload)
komendy = MAPOWANIE_DOM.get(idx, None)
... | plik = open("errory.log", mode="a+")
plik.write(time.asctime() + ',' + str(bld) + '\n')
client.publish("domoticz/in", komenda)
# teraz odczyt termostatu (id_urza... | random_line_split | |
hap_to_domo.py | #print("Komenda to ...", komendy)
print("MAP HAP", MAPOWANIE_DOM)
indeks = 0
ks = list(MAPOWANIE_MOD.keys())
for key in ks:
indeks = indeks +1
map_temp ={'komunikat': 0x1090}
list_temp = [0xf0, 0xf0, 0xff, 0xff]
list_temp.append(key[0])
list_temp.append(key[1])
list_temp += [0xff... | nie sumy kontrolnej
| conditional_block | |
hap_to_domo.py | ':key}
map_temp.update(map_temp2)
#print("Klucze MAP to ::::::", MAPOWANIE_HAP[key], 'klucz', key)
MAPOWANIE_DOM[idx]= map_temp
#MAPOWANIE_HAP.update(map_temp)
#indeks = indeks +1
#komendy = MAPOWANIE_DOM.get(key, None)
#print("Komenda to ...", komendy)
print("MAP HAP", MAPOWANIE_DOM... | = {'nodes': nodes}
if nvalue < 2:
procent = 100 * nvalue
else:
procent = int(svalue1)
map_temp2 = {'procent': procent}
map_temp.update(map_temp2)
FLAGI[2] = map_temp
# FLAGI = {
#'dane': [0xf0, 0xf0, 0xff, 0xff, 0x28, 0x0e, 0xff, 0xff, 0xff, 0xff]},
print("@@@... | map_temp | identifier_name |
hap_to_domo.py | ':key}
map_temp.update(map_temp2)
#print("Klucze MAP to ::::::", MAPOWANIE_HAP[key], 'klucz', key)
MAPOWANIE_DOM[idx]= map_temp
#MAPOWANIE_HAP.update(map_temp)
#indeks = indeks +1
#komendy = MAPOWANIE_DOM.get(key, None)
#print("Komenda to ...", komendy)
print("MAP HAP", MAPOWANIE_DOM... | serdata, flags, rc):
print("Połączony z moskitem czyta domoticza... " + str(rc))
client.subscribe("domoticz/out")
def on_message(client, userdata, msg):
try:
payload = json.loads(msg.payload.decode('ascii'))
#print("wiadomosc od Domoticza ", payload)
idx = payload['idx']
... | cana",OKRES_CZASU, "Ignoruj", IGNOROWANIE)
OKRES_CZASU[1]=1
def on_connect(client, u | identifier_body |
main.py | parser.add_argument("--lp", action="store_true",
help="Add the learned prior (LP) loss")
parser.add_argument("--semantic_loss", action="store_true",
help="Add the semantic loss")
parser.add_argument("--unl_weight", type=float, default=0.1,
help="Weight for unl... | random_line_split | ||
main.py | form.
Args:
labels: (LongTensor) class labels, sized [N,].
num_classes: (int) number of classes.
Returns:
(tensor) encoded labels, sized [N, #classes].
"""
y = torch.eye(num_classes).to(device)
return y[labels]
def log_normal(x, m, log_v):
"""
Computes the elem-wise lo... | return F.binary_cross_entropy_with_logits(y, targets.float()), y | conditional_block | |
main.py | ="Add the semantic loss")
parser.add_argument("--unl_weight", type=float, default=0.1,
help="Weight for unlabelled regularizer loss")
parser.add_argument("--unl2_weight", type=float, default=0.1,
help="Weight for unlabelled regularizer loss")
parser.add_argument("--num_hidden", t... | (sample):
alpha = 1./num_classes
mu_prior = np.log(alpha) - 1/num_classes*num_classes*np.log(alpha)
sigma_prior = (1. / alpha * (1 - 2 | compute_loss | identifier_name |
main.py | ="Add the semantic loss")
parser.add_argument("--unl_weight", type=float, default=0.1,
help="Weight for unlabelled regularizer loss")
parser.add_argument("--unl2_weight", type=float, default=0.1,
help="Weight for unlabelled regularizer loss")
parser.add_argument("--num_hidden", t... |
class DecoderModel(nn.Module):
def __init__(self, num_classes, z_dim=2):
super().__init__()
self.mu = nn.Sequential(nn.Linear(num_classes, 50), nn.LeakyReLU(.2), nn.Linear(50, num_classes))
self.logvar = nn.Sequential(nn.Linear(num_classes, 50), nn.LeakyReLU(.2), nn.Linear(50, num_classe... | if type(m) == nn.Linear:
torch.nn.init.xavier_uniform(m.weight)
m.bias.data.fill_(0.01) | identifier_body |
bluepay.go | Name)
if err != nil {
return []byte{}, err
}
accountHolderName := datas["account_name"].(string)
accountNumber := datas["account_num"].(string)
amount := datas["amount"].(int64)
paramStr := fmt.Sprintf("transactionId=%d&promotionId=1000&payeeCountry=%s&payeeBankName=%s&payeeName=%s&payeeAccount=%s&payeeMsisdn=... | st(uuid.NewV4()).String()
paramStr := fmt.Sprintf("phoneNum=%s&customerName=%s&accountNo=%s&bankName=%s&transactionId=%s", tools.UrlEncode(accountBase.Mobile), tools.UrlEncode(name), tools.UrlEncode(bankNumber), tools.UrlEncode(bankCode), tools.UrlEncode(uuidStr))
logs.Debug(paramStr)
hash := OpenSSLEncrypt(par... | conditional_block | |
bluepay.go | IN",
"Bank Hana": "BANK HANA",
"Centratama Nasional Bank": "BANK CENTRATAMA NASIONAL",
"Bank Tabungan Pensiunan Nasional": "BANK TABUNGAN PENSIUNAN NASIONAL/BTPN",
}
func BluepayBankNameCodeMap() map[string]string {
return bluePayBankNameCodeMap
}
func BluepayBankName2Code(name stri... | orderId := datas["order_id"].(int64)
externalId := datas["account_id"].(int64)
virtualAccountsUrl = fmt.Sprintf("%s?msisdn=%s&price=%d&productId=%d&payType=atm&transactionId=%d&ui=none&promotionId=1000&bankType=%s", virtualAccountsUrl, mobile, price, productId, orderId, bankType)
client := &http.Client{}
req, er... | {
//curl 'http://120.76.101.146:21921/indonesia/express/gather/mo?price=30000&productId=1483&payType=atm&transactionId=14615984398y&ui=none&promotionId=1000&bankType=permata'
productId, _ := beego.AppConfig.Int64("bluepay_product_id")
virtualAccountsUrl := beego.AppConfig.String("bluepay_create_va_url")
bankName :... | identifier_body |
bluepay.go | := thirdparty.CalcFeeByApi(virtualAccountsUrl, "", string(body))
models.AddOneThirdpartyRecord(models.ThirdpartyBluepay, virtualAccountsUrl, externalId, "", string(body), responstType, fee, resp.StatusCode)
event.Trigger(&evtypes.CustomerStatisticEv{
UserAccountId: externalId,
OrderId: orderId,
ApiMd5: ... | hash := OpenSSLEncrypt(paramStr) | random_line_split | |
bluepay.go | IN",
"Bank Hana": "BANK HANA",
"Centratama Nasional Bank": "BANK CENTRATAMA NASIONAL",
"Bank Tabungan Pensiunan Nasional": "BANK TABUNGAN PENSIUNAN NASIONAL/BTPN",
}
func | () map[string]string {
return bluePayBankNameCodeMap
}
func BluepayBankName2Code(name string) (code string, err error) {
bankNameCodeMap := BluepayBankNameCodeMap()
if v, ok := bankNameCodeMap[name]; ok {
code = v
return
}
err = fmt.Errorf("bank code undefined")
return
}
func BankName2BluepaySupportCode(nam... | BluepayBankNameCodeMap | identifier_name |
Analytics.js | 1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f ... |
else {
this._pluggables.splice(idx, idx + 1);
return;
}
};
/**
* stop sending events
*/
AnalyticsClass.prototype.disable = function () {
this._disabled = true;
};
/**
* start sending events
*/
AnalyticsClass.prototype.enable = ... | {
logger.debug('No plugin found with providerName', providerName);
return;
} | conditional_block |
Analytics.js |
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __g... | { try { step(generator.next(value)); } catch (e) { reject(e); } } | identifier_body | |
Analytics.js | (result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) ... | step | identifier_name | |
Analytics.js | ._config['disabled']) {
this._disabled = true;
}
// turn on the autoSessionRecord if not specified
if (this._config['autoSessionRecord'] === undefined) {
this._config['autoSessionRecord'] = true;
}
this._pluggables.forEach(function (pluggable) {
... | if (authConfigured && analyticsConfigured) {
sendEvents(); | random_line_split | |
miner_corrections.go | (ctx context.Context, store cbor.IpldStore, head cid.Cid,
priorEpoch abi.ChainEpoch, a addr.Address) (*StateMigrationResult, error) {
result := &StateMigrationResult{
NewHead: head,
Transfer: big.Zero(),
}
epoch := priorEpoch + 1
var st miner.State
if err := store.Get(ctx, head, &st); err != nil {
return n... | CorrectState | identifier_name | |
miner_corrections.go | err
}
exqRoot, stats, err := m.correctExpirationQueue(exq, sectors, part.Terminated, part.Faults, sectorSize)
if err != nil {
return err
}
// if unmodified, we're done
if exqRoot.Equals(cid.Undef) {
return nil
}
if !part.ExpirationsEpochs.Equals(exqRoot) {
part.ExpirationsEpochs ... | random_line_split | ||
miner_corrections.go | (map[uint64]miner.Partition)
allFaultyPower := miner.NewPowerPairZero()
var part miner.Partition
err = partitions.ForEach(&part, func(partIdx int64) error {
exq, err := miner.LoadExpirationQueue(adt.WrapStore(ctx, store), part.ExpirationsEpochs, quantSpec)
if err != nil {
return err
}
exqRoot, st... | {
return err
} | conditional_block | |
miner_corrections.go | Store)
if err != nil {
return nil, err
}
if cronUpdate != nil {
result.PowerUpdates = append(result.PowerUpdates, cronUpdate)
}
}
newHead, err := store.Put(ctx, &st)
result.NewHead = newHead
return result, err
}
func (m *minerMigrator) correctForCCUpgradeThenFaultIssue(
ctx context.Context, store c... | return err
} else if !empty {
modified = true
exs.EarlySectors, err = bitfield.SubtractBitField(exs.EarlySectors, earlyDuplicates)
if err != nil {
return err
}
}
// Detect sectors that are terminating on time, but have either already terminated or duplicate
// an entry in the queue. The sect... | {
// processed expired sectors includes all terminated and all sectors seen in earlier expiration sets
processedExpiredSectors := allTerminated
expirationSetPowerSuspect := false
var exs miner.ExpirationSet
// Check for faults that need to be erased.
// Erased faults will be removed from bitfields and the power... | identifier_body |
logging_service_v2_api.js | null,
{'x-goog-api-client': googleApiClient});
var loggingServiceV2Stub = gaxGrpc.createStub(
servicePath,
port,
grpcClients.loggingServiceV2Client.google.logging.v2.LoggingServiceV2,
{sslCreds: sslCreds});
var loggingServiceV2StubMethods = [
'deleteLog',
'writeLogEntrie... | {
opts = opts || {};
var servicePath = opts.servicePath || SERVICE_ADDRESS;
var port = opts.port || DEFAULT_SERVICE_PORT;
var sslCreds = opts.sslCreds || null;
var clientConfig = opts.clientConfig || {};
var appName = opts.appName || 'gax';
var appVersion = opts.appVersion || gax.version;
var googleApi... | identifier_body | |
logging_service_v2_api.js | ax-nodejs/global.html#CallOptions} for the details.
*
* In addition, options may contain the following optional parameters.
* @param {string=} options.logName
* Optional. A default log resource name that is assigned to all log entries
* in `entries` that do not specify a value for `log_name`. Example:
* ... | * An object stream which emits an object representing | random_line_split | |
logging_service_v2_api.js | grpcClients.loggingServiceV2Client.google.logging.v2.LoggingServiceV2,
{sslCreds: sslCreds});
var loggingServiceV2StubMethods = [
'deleteLog',
'writeLogEntries',
'listLogEntries',
'listMonitoredResourceDescriptors'
];
loggingServiceV2StubMethods.forEach(function(methodName) {
this[... |
if ('labels' in options) {
req.labels = options.labels;
}
if ('partialSuccess' in options) {
req.partialSuccess = options.partialSuccess;
}
return this._writeLogEntries(req, options, callback);
};
/**
* Lists log entries. Use this method to retrieve log entries from Cloud
* Logging. For ways to ... | {
req.resource = options.resource;
} | conditional_block |
logging_service_v2_api.js | entry is not written, the response status will be the error associated
* with one of the failed entries and include error details in the form of
* WriteLogEntriesPartialErrors.
*
* @param {function(?Error, ?Object)=} callback
* The function which will be called with the result of the API call.
*
* The... | LoggingServiceV2ApiBuilder | identifier_name | |
mutableBag.go | MutableBag is a generic mechanism to read and write a set of attributes.
//
// Bags can be chained together in a parent/child relationship. A child bag
// represents a delta over a parent. By default a child looks identical to
// the parent. But as mutations occur to the child, the two start to diverge.
// Resetting a... |
// Done indicates the bag can be reclaimed.
func (mb *MutableBag) Done() {
mb.Reset()
mb.parent = nil
mutableBags.Put(mb)
}
// Get returns an attribute value.
func (mb *MutableBag) Get(name string) (interface{}, bool) {
var r interface{}
var b bool
if r, b = mb.values[name]; !b {
r, b = mb.parent.Get(name)
... | {
switch t := v.(type) {
case []byte:
c := make([]byte, len(t))
copy(c, t)
return c
case map[string]string:
c := make(map[string]string, len(t))
for k2, v2 := range t {
c[k2] = v2
}
return c
}
return v
} | identifier_body |
mutableBag.go | MutableBag is a generic mechanism to read and write a set of attributes.
//
// Bags can be chained together in a parent/child relationship. A child bag
// represents a delta over a parent. By default a child looks identical to
// the parent. But as mutations occur to the child, the two start to diverge.
// Resetting a... |
}
for k, v := range attrs.StringMapAttributes {
if _, present := dictionary[k]; !present {
e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k))
}
for k2 := range v.Map {
if _, present := dictionary[k2]; !present {
e = me.Append(e, fmt.Errorf("string map ind... | {
e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k))
} | conditional_block |
mutableBag.go | // MutableBag is a generic mechanism to read and write a set of attributes.
//
// Bags can be chained together in a parent/child relationship. A child bag
// represents a delta over a parent. By default a child looks identical to
// the parent. But as mutations occur to the child, the two start to diverge.
// Resetting... | (v interface{}) interface{} {
switch t := v.(type) {
case []byte:
c := make([]byte, len(t))
copy(c, t)
return c
case map[string]string:
c := make(map[string]string, len(t))
for k2, v2 := range t {
c[k2] = v2
}
return c
}
return v
}
// Done indicates the bag can be reclaimed.
func (mb *MutableBa... | copyValue | identifier_name |
mutableBag.go | // MutableBag is a generic mechanism to read and write a set of attributes.
//
// Bags can be chained together in a parent/child relationship. A child bag
// represents a delta over a parent. By default a child looks identical to
// the parent. But as mutations occur to the child, the two start to diverge.
// Resetting... | e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k))
}
}
for k := range attrs.BoolAttributes {
if _, present := dictionary[k]; !present {
e = me.Append(e, fmt.Errorf("attribute index %d is not defined in the current dictionary", k))
}
}
for k := range attrs.Ti... | random_line_split | |
parse_rfc.py | # modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions a... |
def record_logical_form_graphs(label_sent: str, logical_form_graphs: list, env: str,
msg_type: str, field: str):
""" Write logical forms and logical form graphs to metadata system.
Parameter:
label_sent (str): labelled sentence
logical_form_graphs (list): dicts of id (i... | except IndexError:
print('Failed to retrieve sentence and sentence_id')
sentence = ''
sentence_id = -1
return (sentence, sentence_id) | random_line_split |
parse_rfc.py | # modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions a... |
print('\n')
print(tabulate(result, headers=["Token", "Predicate", "Lexicon"]))
if __name__ == "__main__":
argparser = argparse.ArgumentParser()
argparser.add_argument(
'--str', '-s',
help='Specify target filename',
default="The 'checksum' is zero",
)
argparser.add_argu... | if is_quote_word(predicate):
lexicon_mapping[predicate] = 'NP'
mapped_lex = lexicon_mapping[predicate]
for mapping in mapped_lex:
result.append([token, predicate, mapping]) | conditional_block |
parse_rfc.py | # modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions a... | except:
continue
result = []
for token in new_sent:
predicates = string_to_predicate(token)
if not predicates:
print('Bad token:')
print(f'\t\"{token}\" has no predicate mapping')
new_sent.remove(token)
else:
for predica... | """ Debug and analyze how a sentence is parsed
Parameter:
cli_args (argparse.Namespace): parsed CLI args
"""
sent = cli_args.str
new_sent = preprocess_sent(sent)
print(f'Parsed sentence: {sent}')
print(f'Split the sentence: {new_sent}')
raw_lexicon = RAW_LEXICON.split("\n")
raw_lexi... | identifier_body |
parse_rfc.py | # modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions a... | (label_sent: str) -> tuple:
""" Retrieve sentence and id by labelled sentence
Parameter:
label_sent (str): labelled sentence
"""
sentence_db = sentence_record.SentenceDB()
mapping = sentence_db.get_mapping_by_label(label_sent)
try:
sentence = mapping[0][0]
sentence_id = mappi... | retrieve_sentence_and_id | identifier_name |
validation_test.go | (t *testing.T) {
targetRevisions := map[string]string{
"gcp": "release",
"neco-dev": "release",
"osaka0": "release",
"stage0": "stage",
"tokyo0": "release",
}
syncWaves := map[string]string{
"namespaces": "1",
"argocd": "2",
"local-pv-provisioner": "3",
"secrets"... | testApplicationResources | identifier_name | |
validation_test.go | release",
"stage0": "stage",
"tokyo0": "release",
}
syncWaves := map[string]string{
"namespaces": "1",
"argocd": "2",
"local-pv-provisioner": "3",
"secrets": "3",
"cert-manager": "4",
"external-dns": "4",
"metallb": "4",
"ingre... | expected, err := readSecret(f)
if err != nil {
t.Fatal(err)
}
OUTER:
for _, es := range expected {
var appeared bool
err = filepath.Walk(manifestDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
for _, exDir := range excludeDirs {
if string... | for _, f := range expectedSecretFiles { | random_line_split |
validation_test.go | ",
"stage0": "stage",
"tokyo0": "release",
}
syncWaves := map[string]string{
"namespaces": "1",
"argocd": "2",
"local-pv-provisioner": "3",
"secrets": "3",
"cert-manager": "4",
"external-dns": "4",
"metallb": "4",
"ingress": ... |
return nil
})
if err != nil {
t.Error(err)
}
t.Parallel()
for overlay, targetDir := range overlayDirs {
t.Run(overlay, func(t *testing.T) {
stdout, stderr, err := kustomizeBuild(targetDir)
if err != nil {
t.Error(fmt.Errorf("kustomize build faled. path: %s, stderr: %s, err: %v", targetDir, stderr... | {
overlayDirs[info.Name()] = path
} | conditional_block |
validation_test.go | Status *apiextensionsv1beta1.CustomResourceDefinitionStatus `json:"status"`
}
func testCRDStatus(t *testing.T) {
t.Parallel()
doCheckKustomizedYaml(t, func(t *testing.T, data []byte) {
var crd crdValidation
err := yaml.Unmarshal(data, &crd)
if err != nil {
// Skip because this YAML might not be custom res... | {
if os.Getenv("SSH_PRIVKEY") != "" {
t.Skip("SSH_PRIVKEY envvar is defined as running e2e test")
}
t.Run("ApplicationTargetRevision", testApplicationResources)
t.Run("CRDStatus", testCRDStatus)
t.Run("CertificateUsages", testCertificateUsages)
t.Run("GeneratedSecretName", testGeneratedSecretName)
t.Run("Aler... | identifier_body | |
messages.rs | #[derive(Deserialize, Debug, Serialize)]
pub struct Empty {}
/// Sets various timeout parameters (in ms)
#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq)]
pub struct Timeouts {
/// when to interrupt a script that is being evaluated
pub script: u64,
/// the timeout limit used to interrupt nav... | FrameSwitch | identifier_name | |
messages.rs | pub script: u64,
/// the timeout limit used to interrupt navigation of the browsing context
pub pageLoad: u64,
/// the timeout of when to abort when locating an element
pub implicit: u64,
}
/// Some responses use a type wrapped in a json object
/// with the value attribute
#[derive(Deserialize, Serial... | random_line_split | ||
rpc.rs | call, or [`RpcError`] in case of an error. | //! [`from_message`]: crate::from_message
//!
//! # Examples
//!
//! Using RPC to communicate with another actor.
//!
//! ```
//! # #![feature(never_type)]
//! #
//! use heph::actor;
//! use heph::actor_ref::{ActorRef, RpcMessage};
//! use heph::rt::{self, Runtime, ThreadLocal};
//! use heph::spawn::ActorOptions;
//! u... | //! | random_line_split |
rpc.rs | call, or [`RpcError`] in case of an error.
//!
//! [`from_message`]: crate::from_message
//!
//! # Examples
//!
//! Using RPC to communicate with another actor.
//!
//! ```
//! # #![feature(never_type)]
//! #
//! use heph::actor;
//! use heph::actor_ref::{ActorRef, RpcMessage};
//! use heph::rt::{self, Runtime, Thread... | <Req, Res> {
/// The request object.
pub request: Req,
/// A way to | RpcMessage | identifier_name |
rpc.rs | response.respond(count);
//! }
//! }
//!
//! /// Sending actor of the RPC.
//! async fn requester(_: actor::Context<!, ThreadLocal>, actor_ref: ActorRef<Add>) {
//! // Make the procedure call.
//! let response = actor_ref.rpc(10).await;
//! # assert!(response.is_ok());
//! match response {
//! ... | {
if self.response.is_connected() {
let response = f(self.request);
self.response.respond(response)
} else {
// If the receiving actor is no longer waiting we can skip the
// request.
Ok(())
}
} | identifier_body | |
model_training.py | (features_data_, features_, d_, data_annotation_, x_w=None, prune=True, nested_folds=10):
x = numpy.array([features_data_[v] for v in features_.id.values])
dimnames = robjects.ListVector(
[(1, robjects.StrVector(d_["individual"])), (2, robjects.StrVector(features_.id.values))])
x = robjects.r["matri... | train_elastic_net_wrapper | identifier_name | |
model_training.py | olds=nested_folds)
else:
res = train_elastic_net(y, x, penalty_factor=x_w, n_train_test_folds=nested_folds) # observation weights, not explanatory variable weight :( , x_weight = x_w)
return pandas2ri.ri2py(res[0]), pandas2ri.ri2py(res[1])
##############################################################... | features_metadata = pq.ParquetFile(args.features_annotation).read_row_group(args.chromosome-1).to_pandas() | conditional_block | |
model_training.py | _.id.values])
dimnames = robjects.ListVector(
[(1, robjects.StrVector(d_["individual"])), (2, robjects.StrVector(features_.id.values))])
x = robjects.r["matrix"](robjects.FloatVector(x.flatten()), ncol=features_.shape[0], dimnames=dimnames)
y = robjects.FloatVector(d_[data_annotation_.gene_id])
... | weights, summary = train(features_data_, features_, d_, data_annotation_, x_w, not args.dont_prune, nested_folds)
if weights.shape[0] == 0:
logging.log(9, "no weights, skipping")
return
logging.log(8, "saving")
weights = weights.assign(gene=data_annotation_.gene_id). \
merge(fe... | gene_id_ = data_annotation_.gene_id if postfix is None else "{}-{}".format(data_annotation_.gene_id, postfix)
logging.log(8, "loading data")
d_ = Parquet._read(data, [data_annotation_.gene_id])
features_ = Genomics.entries_for_gene_annotation(data_annotation_, args.window, features_metadata)
if x_weigh... | identifier_body |
model_training.py | _.id.values])
dimnames = robjects.ListVector(
[(1, robjects.StrVector(d_["individual"])), (2, robjects.StrVector(features_.id.values))])
x = robjects.r["matrix"](robjects.FloatVector(x.flatten()), ncol=features_.shape[0], dimnames=dimnames)
y = robjects.FloatVector(d_[data_annotation_.gene_id])
... | available_data = {x for x in data.metadata.schema.names}
logging.info("Loading data annotation")
data_annotation = StudyUtilities.load_gene_annotation(args.data_annotation, args | random_line_split | |
sevencow.py | .qbox.me'
UP_HOST = 'http://up.qbox.me'
RSF_HOST = 'http://rsf.qbox.me'
class CowException(Exception):
def __init__(self, url, status_code, reason, content):
self.url = url
self.status_code = status_code
self.reason = reason
self.content = content
Exception.__init__(self, '... | sert res.status_code == 200, res
return res.json() if res.text else ''
def list_buckets(self):
"""列出所有的buckets"""
url = '%s/buckets' % RS_HOST
return self.api_call(url)
def create_bucket(self, name):
"""不建议使用API建立bucket
测试发现API建立的bucket默认无法设置<bucket_name>.qiniu... | res = requests.post(url, headers=self.build_requests_headers(token))
as | conditional_block |
sevencow.py | rs.qbox.me'
UP_HOST = 'http://up.qbox.me'
RSF_HOST = 'http://rsf.qbox.me'
class CowException(Exception):
def __init__(self, url, status_code, reason, content):
self.url = url
self.status_code = status_code
self.reason = reason
self.content = content
Exception.__init__(self,... |
self.stat = functools.partial(self._stat_rm_handler, 'stat')
self.delete = functools.partial(self._stat_rm_handler, 'delete')
self.copy = functools.partial(self._cp_mv_handler, 'copy')
self.move = functools.partial(self._cp_mv_handler, 'move')
def get_bucket(self, bucket):
... | self.upload_tokens = {} | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.