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 |
|---|---|---|---|---|
main.rs | // main struggle problems in this section were 11 and 18, and to some extent, 12 and 14. 17 was annoying to debug, but not hard.
extern crate timings_proc_macro;
use timings_proc_macro::timings;
#[timings]
fn e11() {
let s: Vec<usize> = std::fs::read_to_string("src/e11.txt")
.unwrap()
.split_whites... | /// traverse the triangle picking the greatest value at the next binary choice
#[allow(dead_code)]
fn e18_naive_r(t: &[Vec<usize>], running_sum: usize, last_index: usize) -> usize {
if t.is_empty() {
running_sum
} else {
let (rs, li) = if t[0][last_index] > t[0][last_index + 1] {
(t[... |
let triangle: Vec<Vec<usize>> = std::fs::read_to_string("src/e18.txt")
.unwrap()
.lines()
.map(|l| {
l.split_whitespace()
.into_iter()
.map(|n| n.parse::<usize>().unwrap())
.collect::<Vec<usize>>()
})
.collect();
... | identifier_body |
main.rs | // main struggle problems in this section were 11 and 18, and to some extent, 12 and 14. 17 was annoying to debug, but not hard.
extern crate timings_proc_macro;
use timings_proc_macro::timings;
#[timings]
fn e11() {
let s: Vec<usize> = std::fs::read_to_string("src/e11.txt")
.unwrap()
.split_whites... | else {
let mut p_left = path.clone();
p_left.push((t[0][last_index], last_index));
let left = peek_ahead_r(
&t[1..],
running_sum + t[0][last_index],
last_index,
peek_dist - 1,
first_step.clone().unwrap_or(Dir::Left).into(),
... |
// 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 | // main struggle problems in this section were 11 and 18, and to some extent, 12 and 14. 17 was annoying to debug, but not hard.
extern crate timings_proc_macro;
use timings_proc_macro::timings;
#[timings]
fn e11() {
let s: Vec<usize> = std::fs::read_to_string("src/e11.txt")
.unwrap()
.split_whites... | }
}
}
#[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 | /*
* Module with common functions from all modules
* */
voiceBase = (function(VB, $) {
"use strict";
if (!Object.keys) {
Object.keys = (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
... |
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 | /*
* Module with common functions from all modules
* */
voiceBase = (function(VB, $) {
"use strict";
if (!Object.keys) {
Object.keys = (function() {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
... | array = Object.keys(unique_array);
return array;
},
hidePopup: function($popup){
$popup.fadeOut('fast', function(){
$(this).remove();
});
},
unEscapeHtml: function(phrase) {
return phrase
.repla... | var unique_array = {};
for (var i = 0; i < array.length; i++) {
unique_array[array[i]] = true;
} | random_line_split |
japari-bun-catch.js | import {
APP_WIDTH, APP_HEIGHT, TILE_SIZE, DIRECTIONS,
TIME_BETWEEN_BUNS, ROWS_FOR_BUNS, COLUMNS_FOR_BUNS,
STARTING_LIVES, MINIMUM_PAUSE_DURATION,
FONT_FAMILY,
} from './constants'
import { fillTextWithShadow } from './utility'
import ImageAsset from './image-asset'
import LuckyBeast from './entities/lucky-beas... |
// 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 | import {
APP_WIDTH, APP_HEIGHT, TILE_SIZE, DIRECTIONS,
TIME_BETWEEN_BUNS, ROWS_FOR_BUNS, COLUMNS_FOR_BUNS,
STARTING_LIVES, MINIMUM_PAUSE_DURATION,
FONT_FAMILY,
} from './constants'
import { fillTextWithShadow } from './utility'
import ImageAsset from './image-asset'
import LuckyBeast from './entities/lucky-beas... | --------------------------------------------------------------
*/
setupUI () {
this.html.canvas.width = this.canvasWidth
this.html.canvas.height = this.canvasHeight
// Prevent "touch and hold to open context menu" menu on touchscreens.
this.html.canvas.addEventListener('touchstart', stopEve... | {
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 | import {
APP_WIDTH, APP_HEIGHT, TILE_SIZE, DIRECTIONS,
TIME_BETWEEN_BUNS, ROWS_FOR_BUNS, COLUMNS_FOR_BUNS,
STARTING_LIVES, MINIMUM_PAUSE_DURATION,
FONT_FAMILY,
} from './constants'
import { fillTextWithShadow } from './utility'
import ImageAsset from './image-asset'
import LuckyBeast from './entities/lucky-beas... | }
}
/*
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 | import {
APP_WIDTH, APP_HEIGHT, TILE_SIZE, DIRECTIONS,
TIME_BETWEEN_BUNS, ROWS_FOR_BUNS, COLUMNS_FOR_BUNS,
STARTING_LIVES, MINIMUM_PAUSE_DURATION,
FONT_FAMILY,
} from './constants'
import { fillTextWithShadow } from './utility'
import ImageAsset from './image-asset'
import LuckyBeast from './entities/lucky-beas... |
Section: Gameplay
----------------------------------------------------------------------------
*/
/*
Start the game. Triggers when game loads, or reloads.
*/
startGame (resetScore = true) {
if (resetScore) {
this.lives = STARTING_LIVES
this.score = 0
}
this.difficulty = ... | S.EAST)
}
/* | identifier_name |
anime-face-detector.py | import sys
import time
import numpy as np
import cv2
from PIL import Image
import ailia
# import original modules
sys.path.append('../../util')
from arg_utils import get_base_parser, update_parser, get_savepath # noqa: E402
from model_utils import check_and_download_models # noqa: E402
from detector_u... |
def recognize_from_video(landmark_detector, face_detector):
video_file = args.video if args.video else args.input[0]
capture = get_capture(video_file)
assert capture.isOpened(), 'Cannot capture source'
# create video writer if savepath is specified as video format
f_h = int(capture.get(... | 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 | import sys
import time
import numpy as np
import cv2
from PIL import Image
import ailia
# import original modules
sys.path.append('../../util')
from arg_utils import get_base_parser, update_parser, get_savepath # noqa: E402
from model_utils import check_and_download_models # noqa: E402
from detector_u... | main() | conditional_block | |
anime-face-detector.py | import sys
import time
import numpy as np
import cv2
from PIL import Image
import ailia
# import original modules
sys.path.append('../../util')
from arg_utils import get_base_parser, update_parser, get_savepath # noqa: E402
from model_utils import check_and_download_models # noqa: E402
from detector_u... | (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 | import sys
import time
import numpy as np
import cv2
from PIL import Image
import ailia
# import original modules
sys.path.append('../../util')
from arg_utils import get_base_parser, update_parser, get_savepath # noqa: E402
from model_utils import check_and_download_models # noqa: E402
from detector_u... |
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 | package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/allan-simon/go-singleinstance"
"github.com/dlasky/gotk3-layershell/layershell"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
)
const vers... | () {
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 | package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/allan-simon/go-singleinstance"
"github.com/dlasky/gotk3-layershell/layershell"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
)
const vers... |
// 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 | package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/allan-simon/go-singleinstance"
"github.com/dlasky/gotk3-layershell/layershell"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
)
const vers... | println(fmt.Sprintf("UI created in %v ms. Thank you for your patience.", t.Sub(timeStart).Milliseconds()))
gtk.Main()
} | random_line_split | |
main.go | package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
"github.com/allan-simon/go-singleinstance"
"github.com/dlasky/gotk3-layershell/layershell"
"github.com/gotk3/gotk3/gdk"
"github.com/gotk3/gotk3/glib"
"github.com/gotk3/gotk3/gtk"
)
const vers... |
// 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 | // Copyright 2016 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 applicable... |
}
}
/// 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 | // Copyright 2016 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 applicable... | 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 | // Copyright 2016 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 applicable... | <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 | // Copyright 2016 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 applicable... |
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 | /* eslint-disable linebreak-style */
/* eslint-disable no-console */
const fordConnect = require('./fordConnect/fordConnect');
const { geo } = require('./geo');
let activeVehicle;
/**
* Updates the access token and sets the active vehicle to the vehicle with the
* vehicleAuthorizationIndicator set to 1.
*
* We h... | //
// TODO: We could do a more user friendly mapping. Right now we have voice responses like
// "DRIVER FRONT", "PASSENGER FRONT", "PASSENGER REAR LEFT", "HOOD DOOR",
// "PASSENGER INNER TAILGATE", etc.
? `${d.vehicleOccupantRole} ${d.vehicleDoor} is ${d.value}. `.replace(/UNSPECIFIED_|... | // 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 | /* eslint-disable linebreak-style */
/* eslint-disable no-console */
const fordConnect = require('./fordConnect/fordConnect');
const { geo } = require('./geo');
let activeVehicle;
/**
* Updates the access token and sets the active vehicle to the vehicle with the
* vehicleAuthorizationIndicator set to 1.
*
* We h... | (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 | /* eslint-disable linebreak-style */
/* eslint-disable no-console */
const fordConnect = require('./fordConnect/fordConnect');
const { geo } = require('./geo');
let activeVehicle;
/**
* Updates the access token and sets the active vehicle to the vehicle with the
* vehicleAuthorizationIndicator set to 1.
*
* We h... |
/**
* 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 | /* eslint-disable linebreak-style */
/* eslint-disable no-console */
const fordConnect = require('./fordConnect/fordConnect');
const { geo } = require('./geo');
let activeVehicle;
/**
* Updates the access token and sets the active vehicle to the vehicle with the
* vehicleAuthorizationIndicator set to 1.
*
* We h... |
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 | #!/usr/bin/env python
'''
@author : Mitchell Van Braeckel
@id : 1002297
@date : 10/10/2020
@version : python 3.8-32 / python 3.8.5
@course : CIS*4010 Cloud Computing
@brief : A1 Part 2 - AWS DynamoDB ; Q2 - Query OECD
@note :
Description: There are many CSV files containing info from the OECD about agricultural p... | (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 | #!/usr/bin/env python
'''
@author : Mitchell Van Braeckel
@id : 1002297
@date : 10/10/2020
@version : python 3.8-32 / python 3.8.5
@course : CIS*4010 Cloud Computing
@brief : A1 Part 2 - AWS DynamoDB ; Q2 - Query OECD
@note :
Description: There are many CSV files containing info from the OECD about agricultural p... | # 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 | #!/usr/bin/env python
'''
@author : Mitchell Van Braeckel
@id : 1002297
@date : 10/10/2020
@version : python 3.8-32 / python 3.8.5
@course : CIS*4010 Cloud Computing
@brief : A1 Part 2 - AWS DynamoDB ; Q2 - Query OECD
@note :
Description: There are many CSV files containing info from the OECD about agricultural p... |
############################################ FUNCTIONS ############################################
# Converts the label of a dict into its code key, returns None if not a label
def convert_dict_label_to_code_key(label, encodings_dict):
# Get the key of the label if the label exists in the dict as a value
if... | 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 | #!/usr/bin/env python
'''
@author : Mitchell Van Braeckel
@id : 1002297
@date : 10/10/2020
@version : python 3.8-32 / python 3.8.5
@course : CIS*4010 Cloud Computing
@brief : A1 Part 2 - AWS DynamoDB ; Q2 - Query OECD
@note :
Description: There are many CSV files containing info from the OECD about agricultural p... |
elif temp_can_usa_mex_value == na_value:
na_defn = 'CAN+USA+MEX'
temp_can_usa_mex += 1
else:
na_defn = 'Neither'
temp_neither += 1
# Print table row for current year
print(OUTPUT_FORMAT.format(year, na_value, can_value, usa_value, mex_val... | na_defn = 'CAN+USA'
temp_can_usa += 1 | conditional_block |
main.go | //go:generate statik -src=./ui
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"time"
log "github.com/Sirupsen/logrus"
"github.com/abbot/go-http-auth"
"github.com/briandowns/spinner"
"github.com/fatih/... | } else if "POST" == r.Method {
type Body struct {
Body string `json:"body"`
}
var body Body
err := json.NewDecoder(r.Body).Decode(&body)
if err != nil {
sendError(w, "E! "+ErrDataIsNotJson.Error())
} else {
previewContent = mail.ParseMailContent(body.Body)
sendSuccess(w, struct{}{}, previewC... | w.Write([]byte(previewContent)) | random_line_split |
main.go | //go:generate statik -src=./ui
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"time"
log "github.com/Sirupsen/logrus"
"github.com/abbot/go-http-auth"
"github.com/briandowns/spinner"
"github.com/fatih/... | (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 | //go:generate statik -src=./ui
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"time"
log "github.com/Sirupsen/logrus"
"github.com/abbot/go-http-auth"
"github.com/briandowns/spinner"
"github.com/fatih/... |
func getLocalIP() (ip string) {
ip = loopback
ifaces, err := net.Interfaces()
if err != nil {
return
}
for _, i := range ifaces {
addrs, err := i.Addrs()
if err != nil {
return
}
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() ... | {
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 | //go:generate statik -src=./ui
package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"time"
log "github.com/Sirupsen/logrus"
"github.com/abbot/go-http-auth"
"github.com/briandowns/spinner"
"github.com/fatih/... |
}
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 | use bio::io::{bed, gff};
use bio::utils::Strand;
use bio::utils::Strand::*;
use crate::lib::{Config, ConfigFeature};
use crate::lib::{Database, GeneNameEachReference, GeneNameTree, Region};
use rocks::rocksdb::*;
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};... | 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 | use bio::io::{bed, gff};
use bio::utils::Strand;
use bio::utils::Strand::*;
use crate::lib::{Config, ConfigFeature};
use crate::lib::{Database, GeneNameEachReference, GeneNameTree, Region};
use rocks::rocksdb::*;
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::{BufRead, BufReader};... | (
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 | package main
import (
"fmt"
"github.com/fatih/color"
"github.com/EndlessCheng/mahjong-helper/util"
"github.com/EndlessCheng/mahjong-helper/util/model"
"sort"
"time"
"github.com/EndlessCheng/mahjong-helper/platform/majsoul/proto/lq"
)
type majsoulMessage struct {
// 对应到服务器用户数据库中的ID,该值越小表示您的注册时间越早
AccountID in... | l) {
msg := d.msg
return d.parseWho(*msg.Seat), *msg.Moqie
}
// 在最后处理该项
func (d *majsoulRoundData) IsNewDora() bool {
msg := d.msg
// ActionDealTile
return d.isNewDora(msg.Doras)
}
func (d *majsoulRoundData) ParseNewDora() (kanDoraIndicator int) {
msg := d.msg
kanDoraIndicator, _ = d.mustParseMajsoulTile(msg.... | Tsumogiri boo | identifier_body |
majsoul.go | package main
import (
"fmt"
"github.com/fatih/color"
"github.com/EndlessCheng/mahjong-helper/util"
"github.com/EndlessCheng/mahjong-helper/util/model"
"sort"
"time"
"github.com/EndlessCheng/mahjong-helper/platform/majsoul/proto/lq"
)
type majsoulMessage struct {
// 对应到服务器用户数据库中的ID,该值越小表示您的注册时间越早
AccountID in... | 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 | package main
import (
"fmt"
"github.com/fatih/color"
"github.com/EndlessCheng/mahjong-helper/util"
"github.com/EndlessCheng/mahjong-helper/util/model"
"sort"
"time"
"github.com/EndlessCheng/mahjong-helper/platform/majsoul/proto/lq"
)
type majsoulMessage struct {
// 对应到服务器用户数据库中的ID,该值越小表示您的注册时间越早
AccountID in... |
func (d *majsoulRoundData) IsRoundWin() bool {
msg := d.msg
// ActionHule RecordHule
return msg.Hules != nil
}
func (d *majsoulRoundData) ParseRoundWin() (whos []int, points []int) {
msg := d.msg
for _, result := range msg.Hules {
who := d.parseWho(result.Seat)
whos = append(whos, d.parseWho(result.Seat))
... | } | random_line_split |
majsoul.go | package main
import (
"fmt"
"github.com/fatih/color"
"github.com/EndlessCheng/mahjong-helper/util"
"github.com/EndlessCheng/mahjong-helper/util/model"
"sort"
"time"
"github.com/EndlessCheng/mahjong-helper/platform/majsoul/proto/lq"
)
type majsoulMessage struct {
// 对应到服务器用户数据库中的ID,该值越小表示您的注册时间越早
AccountID in... | ewDora(msg.Doras) {
kanDoraIndicator, _ = d.mustParseMajsoulTile(msg.Doras[len(msg.Doras)-1])
}
return
}
func (d *majsoulRoundData) IsOpen() bool {
msg := d.msg
// ActionChiPengGang RecordChiPengGang || ActionAnGangAddGang RecordAnGangAddGang
return msg.Tiles != nil && len(d.normalTiles(msg.Tiles)) <= 4
}
func... | -1
if d.isN | identifier_name |
v0.rs | use rustc::hir;
use rustc::hir::def_id::{CrateNum, DefId};
use rustc::hir::map::{DefPathData, DisambiguatedDefPathData};
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Instance};
use rustc::ty::print::{Printer, Print};
use rustc::ty::subst::{GenericArg, Subst, GenericArgKind};
use rustc_data_structures::base_n;
use ru... |
fn path_append_ns(
mut self,
print_prefix: impl FnOnce(Self) -> Result<Self, !>,
ns: char,
disambiguator: u64,
name: &str,
) -> Result<Self, !> {
self.push("N");
self.out.push(ns);
self = print_prefix(self)?;
self.push_disambiguator(disam... | {
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 | use rustc::hir;
use rustc::hir::def_id::{CrateNum, DefId};
use rustc::hir::map::{DefPathData, DisambiguatedDefPathData};
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Instance};
use rustc::ty::print::{Printer, Print};
use rustc::ty::subst::{GenericArg, Subst, GenericArgKind};
use rustc_data_structures::base_n;
use ru... | self = self.print_def_path(def_id, &[])?;
}
ty::FnPtr(sig) => {
self.push("F");
self = self.in_binder(&sig, |mut cx, sig| {
if sig.unsafety == hir::Unsafety::Unsafe {
cx.push("U");
}
... | }
ty::Foreign(def_id) => { | random_line_split |
v0.rs | use rustc::hir;
use rustc::hir::def_id::{CrateNum, DefId};
use rustc::hir::map::{DefPathData, DisambiguatedDefPathData};
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Instance};
use rustc::ty::print::{Printer, Print};
use rustc::ty::subst::{GenericArg, Subst, GenericArgKind};
use rustc_data_structures::base_n;
use ru... | (
mut self,
predicates: &'tcx ty::List<ty::ExistentialPredicate<'tcx>>,
) -> Result<Self::DynExistential, Self::Error> {
for predicate in predicates {
match *predicate {
ty::ExistentialPredicate::Trait(trait_ref) => {
// Use a type that can't a... | print_dyn_existential | identifier_name |
v0.rs | use rustc::hir;
use rustc::hir::def_id::{CrateNum, DefId};
use rustc::hir::map::{DefPathData, DisambiguatedDefPathData};
use rustc::ty::{self, Ty, TyCtxt, TypeFoldable, Instance};
use rustc::ty::print::{Printer, Print};
use rustc::ty::subst::{GenericArg, Subst, GenericArgKind};
use rustc_data_structures::base_n;
use ru... |
// 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 | //! The executor runs on all nodes and is resonsible for reconciling the requested state (from the
//! cluster's master), and the locally running containers.
//!
//! When a new state is received, it queries Docker Engine to see if:
//! 1) any scheduled containers are not currently running
//! 2) and running containers ... | {
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 | //! The executor runs on all nodes and is resonsible for reconciling the requested state (from the
//! cluster's master), and the locally running containers.
//!
//! When a new state is received, it queries Docker Engine to see if:
//! 1) any scheduled containers are not currently running
//! 2) and running containers ... |
}
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 | //! The executor runs on all nodes and is resonsible for reconciling the requested state (from the
//! cluster's master), and the locally running containers.
//!
//! When a new state is received, it queries Docker Engine to see if:
//! 1) any scheduled containers are not currently running
//! 2) and running containers ... | .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 | const DB = require("./database.js");
//var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
//const Rooms = require("./roomsModel.js");
var CORE = {
num_clients: 0, //amount of connected clients
chatRooms: [], //has each room and the clients inside each
... |
}
}
} else {
for (var k = 0; k < clients.length; k++) {
if (clients[k].connection != connection) {
clients[k].connection.sendUTF(JSON.stringify(msg)); //*only stringify for chat messages
}
}
}
} | {
//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 | const DB = require("./database.js");
//var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
//const Rooms = require("./roomsModel.js");
var CORE = {
num_clients: 0, //amount of connected clients
chatRooms: [], //has each room and the clients inside each
... |
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 | const DB = require("./database.js");
//var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
//const Rooms = require("./roomsModel.js");
var CORE = {
num_clients: 0, //amount of connected clients
chatRooms: [], //has each room and the clients inside each
... | //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 | const DB = require("./database.js");
//var getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
//const Rooms = require("./roomsModel.js");
var CORE = {
num_clients: 0, //amount of connected clients
chatRooms: [], //has each room and the clients inside each
... | (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 | import sklearn
import datetime
from os import listdir
from os.path import isfile, join
from nlp_to_phenome import EDIRDoc
from annotation_docs import EDIRAnn
import reportreader as rr
import re
import utils
import logging
from operator import itemgetter
import xml.etree.ElementTree as ET
class eHostGenedDoc(EDIRDoc):... | (folder):
files = [f for f in listdir(folder) if isfile(join(folder, f))]
t2freq = {}
for f in files:
gen_doc = eHostGenedDoc(join(folder, f))
logging.debug('processing: %s / %s' % (folder, f))
for g in gen_doc.get_ess_entities():
logging.debug('validation label: %s' % g.... | summarise_validation_results | identifier_name |
ann_utils.py | import sklearn
import datetime
from os import listdir
from os.path import isfile, join
from nlp_to_phenome import EDIRDoc
from annotation_docs import EDIRAnn
import reportreader as rr
import re
import utils
import logging
from operator import itemgetter
import xml.etree.ElementTree as ET
class eHostGenedDoc(EDIRDoc):... | 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 | import sklearn
import datetime
from os import listdir
from os.path import isfile, join
from nlp_to_phenome import EDIRDoc
from annotation_docs import EDIRAnn
import reportreader as rr
import re
import utils
import logging
from operator import itemgetter
import xml.etree.ElementTree as ET
class eHostGenedDoc(EDIRDoc):... |
def summarise_validation_results(folder):
files = [f for f in listdir(folder) if isfile(join(folder, f))]
t2freq = {}
for f in files:
gen_doc = eHostGenedDoc(join(folder, f))
logging.debug('processing: %s / %s' % (folder, f))
for g in gen_doc.get_ess_entities():
loggin... | if key in d:
d[key] += 1
else:
d[key] = 1 | identifier_body |
ann_utils.py | import sklearn
import datetime
from os import listdir
from os.path import isfile, join
from nlp_to_phenome import EDIRDoc
from annotation_docs import EDIRAnn
import reportreader as rr
import re
import utils
import logging
from operator import itemgetter
import xml.etree.ElementTree as ET
class eHostGenedDoc(EDIRDoc):... |
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 | """"
Skrypt stanowi brame pomiedzy domoticzem a siecia HAPCAN - interfejs Ethernet
uruchomiony mosquitto
W domoticzu w sekcji sprzet dodajemy - MQTT Client Gateway with LAN interface port 1883 ip 127.0.0.1
uruchamiamy z konsoli: python3 hapcan_domo.py
"""
from __future__ import print_function
import paho.mq... | komendy = MAPOWANIE_HAP.get((modul, grupa, id_urzadzenia), None)
if komendy is not None:
idx = komendy['idx']
IGNOROWANIE[idx] = IGNOROWANIE.get(idx, 0) + 1
... | 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 | """"
Skrypt stanowi brame pomiedzy domoticzem a siecia HAPCAN - interfejs Ethernet
uruchomiony mosquitto
W domoticzu w sekcji sprzet dodajemy - MQTT Client Gateway with LAN interface port 1883 ip 127.0.0.1
uruchamiamy z konsoli: python3 hapcan_domo.py
"""
from __future__ import print_function
import paho.mq... |
if hap_crc(resp) == resp[13]:
modul = resp[3]
grupa = resp[4]
id_urzadzenia = resp[7]
stan = resp[8]
if resp[1] == 0x30: #rozkaz stanu
#print("Rozkaz stanu", "to hex",toHex(... | nie sumy kontrolnej
| conditional_block |
hap_to_domo.py | """"
Skrypt stanowi brame pomiedzy domoticzem a siecia HAPCAN - interfejs Ethernet
uruchomiony mosquitto
W domoticzu w sekcji sprzet dodajemy - MQTT Client Gateway with LAN interface port 1883 ip 127.0.0.1
uruchamiamy z konsoli: python3 hapcan_domo.py
"""
from __future__ import print_function
import paho.mq... | = {'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 | """"
Skrypt stanowi brame pomiedzy domoticzem a siecia HAPCAN - interfejs Ethernet
uruchomiony mosquitto
W domoticzu w sekcji sprzet dodajemy - MQTT Client Gateway with LAN interface port 1883 ip 127.0.0.1
uruchamiamy z konsoli: python3 hapcan_domo.py
"""
from __future__ import print_function
import paho.mq... | 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 | import argparse
import os
import json
import numpy as np
import random
from tqdm import tqdm
import torch
from torch.optim import SGD, Adam
import torch.utils.data as data
from torch.utils.data import DataLoader, Subset
import torch.nn.functional as F
from torch import nn
import torchnet as tnt
from torchnet.engine im... | 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 | import argparse
import os
import json
import numpy as np
import random
from tqdm import tqdm
import torch
from torch.optim import SGD, Adam
import torch.utils.data as data
from torch.utils.data import DataLoader, Subset
import torch.nn.functional as F
from torch import nn
import torchnet as tnt
from torchnet.engine im... |
else:
return F.cross_entropy(y, targets), y
else:
global counter
l = sample[0]
u = sample[1]
inputs_l = cast(l[0], args.dtype)
targets_l = cast(l[1], 'long')
inputs_u = cast(u[0], args.dtype)
y_l =... | return F.binary_cross_entropy_with_logits(y, targets.float()), y | conditional_block |
main.py | import argparse
import os
import json
import numpy as np
import random
from tqdm import tqdm
import torch
from torch.optim import SGD, Adam
import torch.utils.data as data
from torch.utils.data import DataLoader, Subset
import torch.nn.functional as F
from torch import nn
import torchnet as tnt
from torchnet.engine im... | (sample):
alpha = 1./num_classes
mu_prior = np.log(alpha) - 1/num_classes*num_classes*np.log(alpha)
sigma_prior = (1. / alpha * (1 - 2. / num_classes) + 1 / (num_classes ** 2) * num_classes / alpha)
log_det_sigma = num_classes * np.log(sigma_prior)
model_y.train()
if no... | compute_loss | identifier_name |
main.py | import argparse
import os
import json
import numpy as np
import random
from tqdm import tqdm
import torch
from torch.optim import SGD, Adam
import torch.utils.data as data
from torch.utils.data import DataLoader, Subset
import torch.nn.functional as F
from torch import nn
import torchnet as tnt
from torchnet.engine im... |
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 | package bluepay
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
uuid "github.com/satori/go.uuid"
"micro-loan/common/dao"
"micro-loan/common/lib/device... | beego.AppConfig.String("bluepay_secret_key")
encrypt := tools.Md5(fmt.Sprintf("productId=%s&npwp=%s%s", productId, npwp, keyStr))
reqParm := fmt.Sprintf("productId=%s&npwp=%s&encrypt=%s", productId, npwp, encrypt)
checkUrl := router + "/" + reqParm
logs.Debug(checkUrl)
reqHeaders := map[string]string{}
httpBod... | 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 | package bluepay
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
uuid "github.com/satori/go.uuid"
"micro-loan/common/dao"
"micro-loan/common/lib/device... |
func (c *BluepayApi) Disburse(datas map[string]interface{}) (res []byte, err error) {
orderId := datas["order_id"].(int64)
bankName := datas["bank_name"].(string)
bankCode, err := BankName2BluepaySupportCode(bankName)
if err != nil {
return []byte{}, err
}
accountHolderName := datas["account_name"].(string)
... | {
//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 | package bluepay
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
uuid "github.com/satori/go.uuid"
"micro-loan/common/dao"
"micro-loan/common/lib/device... | keyStr := beego.AppConfig.String("bluepay_secret_key")
logs.Debug("[NameValidator] hash:%s, keyStr:%s", hash, keyStr)
md5val := tools.Md5(fmt.Sprintf("productId=%s&data=%s%s", productId, hash, keyStr))
checkUrl = fmt.Sprintf("%s?productId=%s&data=%s&encrypt=%s", checkUrl, productId, hash, md5val)
logs.Debug(... | hash := OpenSSLEncrypt(paramStr) | random_line_split |
bluepay.go | package bluepay
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"strings"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
uuid "github.com/satori/go.uuid"
"micro-loan/common/dao"
"micro-loan/common/lib/device... | () 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 | "use strict";
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* ... |
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 | "use strict";
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* ... |
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 | "use strict";
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* ... | (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 | "use strict";
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* ... | }
break;
}
};
var analyticsEvent = function (payload) {
var event = payload.event;
if (!event)
return;
switch (event) {
case 'pinpointProvider_configured':
analyticsConfigured = true;
if (authConfigured && analyticsConfigured) {
... | if (authConfigured && analyticsConfigured) {
sendEvents(); | random_line_split |
miner_corrections.go | package nv4
import (
"bytes"
"context"
addr "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
cid "github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
miner "github.com/... | (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 | package nv4
import (
"bytes"
"context"
addr "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
cid "github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
miner "github.com/... | // Recompute active and faulty power for an expiration set.
// The active power for an expiration set should be the sum of the power of all its active sectors,
// where active means all sectors not labeled as a fault in the partition. Similarly, faulty power
// is the sum of faulty sectors.
// If a sector has been resc... | random_line_split | |
miner_corrections.go | package nv4
import (
"bytes"
"context"
addr "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
cid "github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
miner "github.com/... |
}
return nil
})
if err != nil {
return cid.Undef, expirationQueueStats{}, err
}
expirationQueueRoot, err := exq.Root()
if err != nil {
return cid.Undef, expirationQueueStats{}, err
}
return expirationQueueRoot, expirationQueueStats{
partitionActivePower,
partitionFaultyPower,
}, nil
}
// Recomp... | {
return err
} | conditional_block |
miner_corrections.go | package nv4
import (
"bytes"
"context"
addr "github.com/filecoin-project/go-address"
"github.com/filecoin-project/go-bitfield"
"github.com/filecoin-project/go-state-types/abi"
"github.com/filecoin-project/go-state-types/big"
cid "github.com/ipfs/go-cid"
cbor "github.com/ipfs/go-ipld-cbor"
miner "github.com/... |
// Recompute active and faulty power for an expiration set.
// The active power for an expiration set should be the sum of the power of all its active sectors,
// where active means all sectors not labeled as a fault in the partition. Similarly, faulty power
// is the sum of faulty sectors.
// If a sector has been re... | {
// 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 | /*
* Copyright 2016 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 applicable ... |
// Path templates
var PARENT_PATH_TEMPLATE = new gax.PathTemplate(
'projects/{project}');
var LOG_PATH_TEMPLATE = new gax.PathTemplate(
'projects/{project}/logs/{log}');
/**
* Returns a fully-qualified parent resource name string.
* @param {String} project
* @returns {String}
*/
LoggingServiceV2Api.pro... | {
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 | /*
* Copyright 2016 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 applicable ... | * [google.api.MonitoredResourceDescriptor]{@link external:"google.api.MonitoredResourceDescriptor"} on 'data' event.
* When the callback is specified or streaming is suppressed through options,
* it will return an event emitter to handle the call status and the callback
* will be called with the response ob... | * An object stream which emits an object representing | random_line_split |
logging_service_v2_api.js | /*
* Copyright 2016 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 applicable ... |
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 | /*
* Copyright 2016 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 applicable ... | (gaxGrpc) {
if (!(this instanceof LoggingServiceV2ApiBuilder)) {
return new LoggingServiceV2ApiBuilder(gaxGrpc);
}
var loggingServiceV2Client = gaxGrpc.load([{
root: require('google-proto-files')('..'),
file: 'google/logging/v2/logging.proto'
}]);
extend(this, loggingServiceV2Client.google.loggin... | LoggingServiceV2ApiBuilder | identifier_name |
mutableBag.go | // Copyright 2016 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
// 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 | // Copyright 2016 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... |
}
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 | // Copyright 2016 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | (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 | // Copyright 2016 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to i... | 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 | #! /usr/bin/env python3
# Copyright (c) 2021, The University of Southern California.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above co... |
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 | #! /usr/bin/env python3
# Copyright (c) 2021, The University of Southern California.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above co... |
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 | #! /usr/bin/env python3
# Copyright (c) 2021, The University of Southern California.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above co... |
if __name__ == "__main__":
argparser = argparse.ArgumentParser()
argparser.add_argument(
'--str', '-s',
help='Specify target filename',
default="The 'checksum' is zero",
)
argparser.add_argument(
'--check', '-c',
help='Check equivalent logic forms',
act... | """ 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 | #! /usr/bin/env python3
# Copyright (c) 2021, The University of Southern California.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above co... | (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 | package test
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"text/template"
argocd "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1"
corev1 "k8s.io/api/core/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/api... | (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 | package test
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"text/template"
argocd "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1"
corev1 "k8s.io/api/core/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/api... | 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 | package test
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"text/template"
argocd "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1"
corev1 "k8s.io/api/core/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/api... |
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 | package test
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"text/template"
argocd "github.com/argoproj/argo-cd/pkg/apis/application/v1alpha1"
corev1 "k8s.io/api/core/v1"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/api... | {
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 | //! Structures for some of the messages used in the Marionette protocol, these can
//! be used with the traits in serde to convert into the corresponding json.
//!
#![allow(non_snake_case)]
use std::fmt;
use std::path::Path;
use std::collections::HashMap;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
... | {
focus: bool,
element: Option<String>,
}
impl FrameSwitch {
/// Switch to the top level frame
pub fn top(focus: bool) -> Self {
FrameSwitch {
focus: focus,
element: None,
}
}
/// Switch to the frame given by passed element
pub fn from_element(focus... | FrameSwitch | identifier_name |
messages.rs | //! Structures for some of the messages used in the Marionette protocol, these can
//! be used with the traits in serde to convert into the corresponding json.
//!
#![allow(non_snake_case)]
use std::fmt;
use std::path::Path;
use std::collections::HashMap;
use serde::{Serialize, Serializer, Deserialize, Deserializer};
... | /// Switch to the frame given by passed element
pub fn from_element(focus: bool, element: Option<ElementRef>) -> Self {
FrameSwitch {
focus: focus,
element: element.map(|elem| elem.reference.to_owned()),
}
}
}
#[derive(Serialize, Debug)]
pub struct AddonInstall<'a> {... | random_line_split | |
rpc.rs | //! Types related the `ActorRef` Remote Procedure Call (RPC) mechanism.
//!
//! RPC is implemented by sending a [`RpcMessage`] to the actor, which contains
//! the request message and a [`RpcResponse`]. The `RpcResponse` allows the
//! receiving actor to send back a response to the sending actor.
//!
//! To support RPC... | //! [`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 | //! Types related the `ActorRef` Remote Procedure Call (RPC) mechanism.
//!
//! RPC is implemented by sending a [`RpcMessage`] to the actor, which contains
//! the request message and a [`RpcResponse`]. The `RpcResponse` allows the
//! receiving actor to send back a response to the sending actor.
//!
//! To support RPC... | <Req, Res> {
/// The request object.
pub request: Req,
/// A way to [`respond`] to the call.
///
/// [`respond`]: RpcResponse::respond
pub response: RpcResponse<Res>,
}
impl<Req, Res> RpcMessage<Req, Res> {
/// Convenience method to handle a `Req`uest and return a `Res`ponse.
///
//... | RpcMessage | identifier_name |
rpc.rs | //! Types related the `ActorRef` Remote Procedure Call (RPC) mechanism.
//!
//! RPC is implemented by sending a [`RpcMessage`] to the actor, which contains
//! the request message and a [`RpcResponse`]. The `RpcResponse` allows the
//! receiving actor to send back a response to the sending actor.
//!
//! To support RPC... |
}
/// Structure to respond to an [`Rpc`] request.
#[derive(Debug)]
pub struct RpcResponse<Res> {
sender: Sender<Res>,
}
impl<Res> RpcResponse<Res> {
/// Respond to a RPC request.
pub fn respond(self, response: Res) -> Result<(), SendError> {
self.sender.try_send(response).map_err(|_| SendError)
... | {
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 | __author__ = "alvaro barbeira"
import sys
import os
import logging
import gzip
import collections
import numpy
import pandas
import scipy
import math
import statsmodels.formula.api as smf
from sklearn.model_selection import KFold
from sklearn.metrics import r2_score
import pyarrow.parquet as pq
from genomic_tools_l... | (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 | __author__ = "alvaro barbeira"
import sys
import os
import logging
import gzip
import collections
import numpy
import pandas
import scipy
import math
import statsmodels.formula.api as smf
from sklearn.model_selection import KFold
from sklearn.metrics import r2_score
import pyarrow.parquet as pq
from genomic_tools_l... |
if args.chromosome and args.sub_batches:
logging.info("Trimming variants")
features_metadata = StudyUtilities.trim_variant_metadata_on_gene_annotation(features_metadata, data_annotation, args.window)
if args.rsid_whitelist:
logging.info("Filtering features annotation")
whiteli... | features_metadata = pq.ParquetFile(args.features_annotation).read_row_group(args.chromosome-1).to_pandas() | conditional_block |
model_training.py | __author__ = "alvaro barbeira"
import sys
import os
import logging
import gzip
import collections
import numpy
import pandas
import scipy
import math
import statsmodels.formula.api as smf
from sklearn.model_selection import KFold
from sklearn.metrics import r2_score
import pyarrow.parquet as pq
from genomic_tools_l... |
########################################################################################################################
def run(args):
wp = args.output_prefix + "_weights.txt.gz"
if os.path.exists(wp):
logging.info("Weights output exists already, delete it or move it")
return
sp = args.... | 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 | __author__ = "alvaro barbeira"
import sys
import os
import logging
import gzip
import collections
import numpy
import pandas
import scipy
import math
import statsmodels.formula.api as smf
from sklearn.model_selection import KFold
from sklearn.metrics import r2_score
import pyarrow.parquet as pq
from genomic_tools_l... | 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.chromosome, args.sub_batches, args.sub_batch)
data_annotation = data_annotation[data_annotation.gene_id.isin(available_data)]... | random_line_split | |
sevencow.py | # -*- coding: utf-8 -*-
import os
import hmac
import time
import json
import mimetypes
import functools
from urlparse import urlparse
from urllib import urlencode
from base64 import urlsafe_b64encode
from hashlib import sha1
import requests
version_info = (0, 1, 2)
VERSION = __version__ = '.'.join( map(str, version_... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.