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 |
|---|---|---|---|---|
environment.py | output
def _get_k8s_volumes_to_delete():
# universal_newlines decodes output on Python 3.x
out = subprocess.check_output(['kubectl', 'get', 'pods', '-o', 'json'], universal_newlines=True)
j = json.loads(out)
volumes = []
for pod in j['items']:
pod_vols = pod['spec'].get('volumes', [])
... |
def _missing_api_token_warning(env_var_name):
if os.environ.get(env_var_name):
logger.info("OK: {name} environment is set and will be used as "
"authorization token".format(name=env_var_name))
else:
logger.info("Warning: the {name} environment variable is not"
... | random_line_split | |
environment.py | output
def _get_k8s_volumes_to_delete():
# universal_newlines decodes output on Python 3.x
out = subprocess.check_output(['kubectl', 'get', 'pods', '-o', 'json'], universal_newlines=True)
j = json.loads(out)
volumes = []
for pod in j['items']:
pod_vols = pod['spec'].get('volumes', [])
... | (gemini_api_url, accepted_codes={200}):
try:
url = '%s/api/v1/readiness' % gemini_api_url
res = requests.get(url)
if res.status_code in accepted_codes:
return True
except requests.exceptions.ConnectionError:
pass
return False
def _is_api_running_post(url):
t... | _is_gemini_api_running | identifier_name |
reactor.go | errorsForFSMCh,
}
fsm := NewFSM(startHeight, bcR)
bcR.fsm = fsm
bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR)
// bcR.swReporter = behaviour.NewSwitchReporter(bcR.BaseReactor.Switch)
return bcR
}
// bcReactorMessage is used by the reactor to send messages to the FSM.
type bcReactorMessage st... |
// processBlocksRoutine processes blocks until signlaed to stop over the stopProcessing channel
func (bcR *BlockchainReactor) processBlocksRoutine(stopProcessing chan struct{}) {
processReceivedBlockTicker := time.NewTicker(trySyncIntervalMS * time.Millisecond)
doProcessBlockCh := make(chan struct{}, 1)
lastHund... | {
msg := &bcproto.Message{}
err := proto.Unmarshal(msgBytes, msg)
if err != nil {
panic(err)
}
uw, err := msg.Unwrap()
if err != nil {
panic(err)
}
bcR.ReceiveEnvelope(p2p.Envelope{
ChannelID: chID,
Src: peer,
Message: uw,
})
} | identifier_body |
reactor.go | errorsForFSMCh,
}
fsm := NewFSM(startHeight, bcR)
bcR.fsm = fsm
bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR)
// bcR.swReporter = behaviour.NewSwitchReporter(bcR.BaseReactor.Switch)
return bcR
}
// bcReactorMessage is used by the reactor to send messages to the FSM.
type bcReactorMessage st... |
msgForFSM := bcReactorMessage{
event: blockResponseEv,
data: bReactorEventData{
peerID: e.Src.ID(),
height: bi.Height,
block: bi,
length: msg.Size(),
},
}
bcR.Logger.Info("Received", "src", e.Src, "height", bi.Height)
bcR.messagesForFSMCh <- msgForFSM
case *bcproto.NoBlockResponse:
... | {
bcR.Logger.Error("error transition block from protobuf", "err", err)
return
} | conditional_block |
reactor.go | (state sm.State, blockExec *sm.BlockExecutor, store *store.BlockStore,
fastSync bool) *BlockchainReactor {
if state.LastBlockHeight != store.Height() {
panic(fmt.Sprintf("state (%v) and store (%v) height mismatch", state.LastBlockHeight,
store.Height()))
}
const capacity = 1000
eventsFromFSMCh := make(chan ... | NewBlockchainReactor | identifier_name | |
reactor.go | bcR *BlockchainReactor) sendBlockToPeer(msg *bcproto.BlockRequest,
src p2p.Peer) (queued bool) {
block := bcR.store.LoadBlock(msg.Height)
if block != nil {
pbbi, err := block.ToProto()
if err != nil {
bcR.Logger.Error("Could not send block message to peer", "err", err)
return false
}
return p2p.TrySen... | // the FSM had already removed the peers
// } | random_line_split | |
mod.rs | ;
use crate::storage::{get_connection, DelfStorageConnection};
use crate::DelfYamls;
/// The DelfGraph is the core structure for delf's functionality. It contains the algorithm to traverse the graph, as well as metadata to perform the deletions.
#[derive(Debug)]
pub struct DelfGraph {
pub(crate) nodes: HashMap<S... | (&self, object_name: &String) -> &object::DelfObject {
let object_id = self.nodes.get(object_name).unwrap();
return self.graph.node_weight(*object_id).unwrap();
}
/// Given the object name and the id of the instance, delete the object
pub fn delete_object(&self, object_name: &String, id: &S... | get_object | identifier_name |
mod.rs | ;
use crate::storage::{get_connection, DelfStorageConnection};
use crate::DelfYamls;
/// The DelfGraph is the core structure for delf's functionality. It contains the algorithm to traverse the graph, as well as metadata to perform the deletions.
#[derive(Debug)]
pub struct DelfGraph {
pub(crate) nodes: HashMap<S... | for (_, node_id) in self.nodes.iter() {
let obj = self.graph.node_weight(*node_id).unwrap();
match obj.deletion {
object::DeleteType::ShortTTL
| object::DeleteType::Directly
| object::DeleteType::DirectlyOnly
| object::Delet... | // Starting from a directly deletable (or excepted) node, ensure all ndoes are reached.
fn reachability_analysis(&self) -> Result<(), String> {
let mut visited_nodes = HashSet::new(); | random_line_split |
mod.rs | ;
use crate::storage::{get_connection, DelfStorageConnection};
use crate::DelfYamls;
/// The DelfGraph is the core structure for delf's functionality. It contains the algorithm to traverse the graph, as well as metadata to perform the deletions.
#[derive(Debug)]
pub struct DelfGraph {
pub(crate) nodes: HashMap<S... | edges_to_insert.push((obj_name.clone(), delf_edge));
}
}
// add all the edges to the graph
for (from, e) in edges_to_insert.iter_mut() {
if !nodes.contains_key(&e.to.object_type) {
eprintln!("Error creating edge {:#?}: No object with name ... | {
let schema = &yamls.schema;
let config = &yamls.config;
let mut edges_to_insert = Vec::new();
let mut nodes = HashMap::<String, NodeIndex>::new();
let mut edges = HashMap::<String, EdgeIndex>::new();
let mut graph = Graph::<object::DelfObject, edge::DelfEdge>::new();
... | identifier_body |
exec.go | limit [%s] exceeded", cfg.TimeLimit.String()))
}
}()
}
// Т.к. атрибут "ptrace" включен, то, после запуска, начинаем ждать пока
// процесс изменит свой статус (остановится, завершится, подаст сигнал и т.д.)
var ws syscall.WaitStatus
waitPid, err := syscall.Wait4(-1, &ws, syscall.WALL, nil)
if err != nil {
... | wg.Wait()
return ws.ExitStatus(), nil
} | random_line_split | |
exec.go | является создание дочернего процесса:
// Если параметер "-Xacp" не установлен, то после попытки создать дочерний процесс
// функция (runProcess) завершится, сработает defer cmd.Process.Kill()
// (процесс будет убит), а т.к. в атрибутах запуска процесса стоит
// Pdeathsig: syscall.SIGKILL, то будут убиты все со... | conditional_block | ||
exec.go | является создание дочернего процесса:
// Если параметер "-Xacp" не установлен, то после попытки создать дочерний процесс
// функция (runProcess) завершится, сработает defer cmd.Process.Kill()
// (процесс будет убит), а т.к. в атрибутах запуска процесса стоит
// Pdeathsig: syscall.SIGKILL, то будут убиты все со... | identifier_body | ||
exec.go | является создание дочернего процесса:
// Если параметер "-Xacp" не установлен, то после попытки создать дочерний процесс
// функция (runProcess) завершится, сработает defer cmd.Process.Kill()
// (процесс будет убит), а т.к. в атрибутах запуска процесса стоит
// Pdeathsig: syscall.SIGKILL, то будут убиты все со... | identifier_name | ||
create-docker-context-for-node-component.js | .com/Maximus5/ConEmu/issues/958 and https://github.com/moby/moby/issues/28814
// So if we're running under ConEmu, we need to add an extra -cur_console:i parameter to disable
// ConEmu's hooks and also set ConEmuANSI to OFF so Docker doesn't do anything drastic.
const env = Object.assign({}, process.env);
const extraPa... | getPackageDependencies | identifier_name | |
create-docker-context-for-node-component.js | field in docker. Will use the same repository and name. Using this options causes the image to be pulled before build.",
type: "string"
}
})
// Because 'version is a default yargs thing we need to specifically override its normal parsing.
.version(false)
.array("version")
.help(... | {
return result;
} | conditional_block | |
create-docker-context-for-node-component.js | Image) {
// Pull this image into the docker daemon - if it fails we don't care, we'll just go from scratch.
const dockerPullProcess = childProcess.spawnSync(
"docker",
[...extraParameters, "pull", cacheFromImage],
{
stdio: "inherit",
en... | {
if (process.stdout) {
process.stdout.on("data", (data) => {
console.log(data.toString());
});
}
if (process.stderr) {
process.stderr.on("data", (data) => {
console.error(data.toString());
});
}
} | identifier_body | |
create-docker-context-for-node-component.js | _NAME
},
version: {
description:
"The version(s) to use in auto tag generation. Will default to the current version in package.json. Requires --tag=auto",
type: "string",
array: true,
default: process.env.MAGDA_DOCKER_VERSION
},
... |
return;
}
try {
// On Windows we can't create symlinks to files without special permissions.
// So just copy the file instead. Usually creating directory | getPackageList(packageDir, path.resolve(packageDir, "..")),
(package) => package.path
);
prepareNodeModules(src, dest, productionPackages); | random_line_split |
main.py | 0
time1 = 0
time2 = 0
dateGap = 0
def opencapture(count):
global img
global imgstring
cap = cv2.VideoCapture(-1)
while True:
ret, img = cap.read() # Read 결과와 frame
img = img[170:450, 40:600]
cv2.imshow("Battery_live", img)
cv2.waitKey(1)
if n... | global imgstring
global hStandard
global vStandard
global TotalunpassCount
global dateGap
Result_horizon, Result_vertical = Dot_Distance(p1[count][0], p1[count][1], p2[count][0], p2[count][1], p3[count][0], p3[count][1], p4[count][0], p4[count][1])
Unit_horizon.append(Result_horizon)
... | 바꿈
| identifier_name |
main.py | count = 0
Hadjust = 0
Vadjust = 0
### open_cv 스크립트 변수들
p_list = []
dot1=[]
dot2=[]
dot3=[]
dot4=[]
imgstring = ''
temperature = 0
### open_cv 스크립트 변수들 2020-11-03 옮김
hunpassCount = 0
vunpassCount = 0
a=0
TotalunpassCount = 0
time1 = 0
time2 = 0
dateGap = 0
def opencapture(count):
global img
... | hStandard = 0.0
vStandard = 0.0
| random_line_split | |
main.py |
time1 = 0
time2 = 0
dateGap = 0
def opencapture(count):
global img
global imgstring
cap = cv2.VideoCapture(-1)
while True:
ret, img = cap.read() # Read 결과와 frame
img = img[170:450, 40:600]
cv2.imshow("Battery_live", img)
cv2.waitKey(1)
if no... | time.sleep(1)
setServoPos2(125)
TotalunpassCount+=1
time.sleep(1)
elif Result_hpass == 0 and Result_vpass == 1: #가로만 불량
led_on(led3) #red
setServoPos1(45)
time.sleep(1)
setServoPos2(165)
TotalunpassCount+=1
time.sleep(1)
... | obal vStandard
global TotalunpassCount
global dateGap
Result_horizon, Result_vertical = Dot_Distance(p1[count][0], p1[count][1], p2[count][0], p2[count][1], p3[count][0], p3[count][1], p4[count][0], p4[count][1])
Unit_horizon.append(Result_horizon)
Unit_vertical.append(Result_vertical)
... | identifier_body |
main.py | = str(x) + ", " + str(y)
cv2.putText(img2, string, (x, y), font, 0.5, (0, 0, 255))
string_list = string.split(",")
string_list = list(map(int, string_list))
p_list.append(string_list)
i = i + 1
#time.sleep(0.5... | elif i == b:
p2.append(temp[i])
elif i == c:
p3.append(temp[i])
elif i == d:
p4.append(temp[i])
calculate(count)
led_off(led1)
| conditional_block | |
client.go | , error) {
uri := *host + ":" + *port + "/images"
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
if err != nil {
return nil, err
}
_, err = io.C... | if err != nil {
fmt.Println("\nError while downloading", url, "-", err)
return err
}
//fmt.Println(n, "bytes downloaded.")
//Hack: trivial check to ensure if file downloaded is not too small
if n < 100 {
return errors.New("Failed to pull image...")
}
return nil
}
func applyPull(image string) error {
... | {
output, err := os.Create(fileName)
if err != nil {
fmt.Println("\nError while creating", fileName, "-", err)
return err
}
defer output.Close()
response, err := http.Get(url)
if err != nil {
fmt.Println("\nError while downloading", url, "-", err)
return err
}
if response.StatusCode != 200 {
fmt.Prin... | identifier_body |
client.go | != nil {
log.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != 200 {
return errors.New("Failed to push image...")
}
}
fmt.Println("Successfully uploaded image: ", image, " to the Docket registry.")
os.Remove(filePath)
return nil
}
//Adapted from https://github.com/thbar/golang-playground/blob/mas... | {
fmt.Printf("\nERROR in downloading layers\n")
} | conditional_block | |
client.go | (params map[string]string, paramName, path string) (*http.Request, error) {
uri := *host + ":" + *port + "/images"
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
part, err := writer.CreateFormFile(paramName, filepath... | uploadFile | identifier_name | |
client.go | "net/url"
"os"
"os/exec"
"path/filepath"
"sync"
"regexp"
"strconv"
"strings"
"time"
)
var (
host = kingpin.Flag("host", "Set host of docket registry.").Short('h').Default("http://127.0.0.1").String()
port = kingpin.Flag("port", "Set port of docket registry.").Short('p').Default("8004").Strin... | "io"
"io/ioutil"
"log"
"mime/multipart"
"net/http" | random_line_split | |
context.rs | channel`.
///
/// The current thread is blocking and the passed in future is executed.
///
/// # Panics
///
/// This function panics if called within a [`Context`] thread.
#[track_caller]
pub fn block_on<Fut>(future: Fut) -> Fut::Output
where
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
if l... | /// of a [`Context`].
///
/// # Panic
///
/// This will block current thread and would panic if run
/// from the [`Context`].
#[track_caller]
pub fn enter<'a, F, O>(&'a self, f: F) -> O
where
F: FnOnce() -> O + Send + 'a,
O: Send + 'a,
{
if let Some(cur) =... |
/// Executes the provided function relatively to this [`Context`].
///
/// Usefull to initialize i/o sources and timers from outside | random_line_split |
context.rs | `.
///
/// The current thread is blocking and the passed in future is executed.
///
/// # Panics
///
/// This function panics if called within a [`Context`] thread.
#[track_caller]
pub fn block_on<Fut>(future: Fut) -> Fut::Output
where
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
if let Some... | } else {
gst::debug!(RUNTIME_CAT, "Entering Context {}", self.name());
}
self.0.enter(f)
}
pub fn spawn<Fut>(&self, future: Fut) -> JoinHandle<Fut::Output>
where
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
self.0.spawn(future)... | gst::warning!(
RUNTIME_CAT,
"Entering Context {} within {}",
self.name(),
cur.name()
);
}
| conditional_block |
context.rs | `.
///
/// The current thread is blocking and the passed in future is executed.
///
/// # Panics
///
/// This function panics if called within a [`Context`] thread.
#[track_caller]
pub fn block_on<Fut>(future: Fut) -> Fut::Output
where
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
if let Some... |
pub fn spawn<Fut>(&self, future: Fut) -> JoinHandle<Fut::Output>
where
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
self.0.spawn(future)
}
pub fn spawn_and_unpark<Fut>(&self, future: Fut) -> JoinHandle<Fut::Output>
where
Fut: Future + Send + 'sta... | if let Some(cur) = Context::current().as_ref() {
if cur == self {
panic!(
"Attempt to enter Context {} within itself, this would deadlock",
self.name()
);
} else {
gst::warning!(
R... | identifier_body |
context.rs | `.
///
/// The current thread is blocking and the passed in future is executed.
///
/// # Panics
///
/// This function panics if called within a [`Context`] thread.
#[track_caller]
pub fn block_on<Fut>(future: Fut) -> Fut::Output
where
Fut: Future + Send + 'static,
Fut::Output: Send + 'static,
{
if let Some... | andle: Handle) -> Self {
Context(handle)
}
}
#[cfg(test)]
mod tests {
use futures::channel::mpsc;
use futures::lock::Mutex;
use futures::prelude::*;
use std::net::{IpAddr, Ipv4Addr, SocketAddr, UdpSocket};
use std::sync::Arc;
use std::time::{Duration, Instant};
use super::supe... | om(h | identifier_name |
core.go | /1024/1024, " Mbytes")
runtime.GOMAXPROCS(coreNum)
//Create a new doble-linked list to act as LRU
lruList = list.New()
//Create the channels
lisChan = make(chan int, 1)
LRUChan = make(chan int, 1)
collectionChan = make(chan int, 1)
collections = make(map[string]collectionChannel)
//Read collections from d... | random_line_split | ||
core.go | collections map[string]collectionChannel
var config map[string]interface{}
const readWrite = "read-write"
// Init the system variables
func init() {
//Welcome Message
fmt.Println("------------------------------------------------------------------")
fmt.Println("Starting Natyla...")
fmt.Println("Version: 1.02")... | (valor string) (map[string]interface{}, error) {
//Create the Json element
d := json.NewDecoder(strings.NewReader(valor))
d.UseNumber()
var f interface{}
err := d.Decode(&f)
if err != nil {
return nil, err
}
//transform it to a map
m := f.(map[string]interface{})
return m, nil
}
//Create a token for th... | convertJSONToMap | identifier_name |
core.go | )
collectionChan = make(chan int, 1)
collections = make(map[string]collectionChannel)
//Read collections from disk
nRead := readAllFromDisk()
fmt.Println("Read", nRead, "entries from disk")
fmt.Println("Ready, API Listening on http://localhost:8080, Telnet on port 8081")
fmt.Println("-------------------------... | {
//Move the element
lisChan <- 1
lruList.MoveToFront(elemento)
<-lisChan
if enablePrint {
fmt.Println("LRU Updated")
}
} | identifier_body | |
core.go | .Number).Int64()
fmt.Println("Max memory defined as: ", maxMemBytes/1024/1024, " Mbytes")
runtime.GOMAXPROCS(coreNum)
//Create a new doble-linked list to act as LRU
lruList = list.New()
//Create the channels
lisChan = make(chan int, 1)
LRUChan = make(chan int, 1)
collectionChan = make(chan int, 1)
collecti... | {
fmt.Println("Purge Done: ", memBytes)
} | conditional_block | |
define.kChartDataManager.js | visibleListEndIndexOffsetFromLatest = Math.max(visibleListEndIndexOffsetFromLatest, 0);
visibleListEndIndexOffsetFromLatest = Math.min(visibleListEndIndexOffsetFromLatest, len);
return this;
};
/**
* 设置“可见数据的结束索引距离时间最晚的K线图数据的位移”
* @param {Integer} offset 新的位移
* @returns {KChartData}
*/
this... | * @param {Integer} visibleKDataCount 可见数据量
* @param {Integer} offset 位移在既有基础上的偏移量
* @returns {KChartData}
*/ | random_line_split | |
app.py | 6',
headers={
'kid': KEY_ID
})
return token_bytes.decode('utf-8')
# Configure API key authorization: jwt
smooch.configuration.api_key['Authorization'] = generate_jwt_token()
smooch.configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instan... | elif text == "Giving":
api_response = api_instance.post_message(APP_ID, user_id,
postText("Got it! How much did you spend?"))
elif text == "Repayments":
api_response = api_instance.post_message(APP_ID, user_id,
postText("Got it! How much did you spend?"))
elif text ... | random_line_split | |
app.py | ch.configuration.api_key['Authorization'] = generate_jwt_token()
smooch.configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instance = smooch.ConversationApi()
app_create_body = smooch.AppCreate() # AppCreate | Body for a createApp request.
### Health Checks
# IMAGES
... | parse_request_data | identifier_name | |
app.py | 6',
headers={
'kid': KEY_ID
})
return token_bytes.decode('utf-8')
# Configure API key authorization: jwt
smooch.configuration.api_key['Authorization'] = generate_jwt_token()
smooch.configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instan... |
elif text == "Weekly Allowance Spend":
api_response = api_instance.post_message(APP_ID, user_id,
postText("Got it! How much did you spend?"))
elif text == "Regular Spend":
api_response = api_instance.post_message(APP_ID, user_id,
postText("Got it! What did you spend mo... | api_response = api_instance.post_message(APP_ID, user_id,
postText("Got it!"))
api_response = api_instance.post_message(APP_ID, user_id,
postText("Ok, how much is your weekly allowance budget?")) | conditional_block |
app.py | 6',
headers={
'kid': KEY_ID
})
return token_bytes.decode('utf-8')
# Configure API key authorization: jwt
smooch.configuration.api_key['Authorization'] = generate_jwt_token()
smooch.configuration.api_key_prefix['Authorization'] = 'Bearer'
# create an instance of the API class
api_instan... |
def postCarousel(list):
message = smooch.MessagePost(role='appMaker', type='carousel')
items = []
for item in list:
actions = []
actions.append(smooch.Action(type='postback', text=item, payload=item))
part = smooch.MessageItem(title=item, actions=actions)
part.media_url =... | message = smooch.MessagePost(role='appMaker', type='file')
message.media_url = uri
return message | identifier_body |
google_spreadsheets.rs | #[derive(Deserialize, Debug)]
struct SpreadsheetValues {
range: String,
#[serde(rename = "majorDimension")]
major_dimension: String,
values: Vec<Vec<String>>,
}
// TODO: should we support optional column?
fn infer_value_type(v: &str) -> DataType {
// match order matters
match v {
// TOD... |
let uri = URIReference::try_from(uri_str)?;
let spreadsheet_id = uri.path().segments()[2].as_str();
let opt = t
.option
.as_ref()
. | {
return Err(ColumnQError::InvalidUri(uri_str.to_string()));
} | conditional_block |
google_spreadsheets.rs | )]
#[derive(Deserialize, Debug)]
struct SpreadsheetValues {
range: String,
#[serde(rename = "majorDimension")]
major_dimension: String,
values: Vec<Vec<String>>,
}
// TODO: should we support optional column?
fn infer_value_type(v: &str) -> DataType {
// match order matters
match v {
// ... | let fields: Vec<Field> = col_names
.iter()
.map(|col_name| {
let set = col_types.entry(col_name).or_insert_with(|| {
// TODO: this should never happen, maybe we should use panic instead?
let mut set = HashSet::new();
set.insert(DataType::Ut... | random_line_split | |
google_spreadsheets.rs | #[derive(Deserialize, Debug)]
struct SpreadsheetValues {
range: String,
#[serde(rename = "majorDimension")]
major_dimension: String,
values: Vec<Vec<String>>,
}
// TODO: should we support optional column?
fn infer_value_type(v: &str) -> DataType {
// match order matters
match v {
// TOD... |
fn coerce_type(l: DataType, r: DataType) -> DataType {
match (l, r) {
(DataType::Boolean, DataType::Boolean) => DataType::Boolean,
(DataType::Date32, DataType::Date32) => DataType::Date32,
(DataType::Date64, DataType::Date64)
| (DataType::Date64, DataType::Date32)
| (DataT... | {
Client::builder()
.build()
.map_err(|e| {
ColumnQError::GoogleSpreadsheets(format!(
"Failed to initialize HTTP client: {}",
e.to_string()
))
})?
.get(url)
.bearer_auth(token)
.send()
.await
.map... | identifier_body |
google_spreadsheets.rs | )]
#[derive(Deserialize, Debug)]
struct SpreadsheetValues {
range: String,
#[serde(rename = "majorDimension")]
major_dimension: String,
values: Vec<Vec<String>>,
}
// TODO: should we support optional column?
fn infer_value_type(v: &str) -> DataType {
// match order matters
match v {
// ... | (s: &str) -> bool {
s.eq_ignore_ascii_case("true")
}
fn sheet_values_to_record_batch(values: &[Vec<String>]) -> Result<RecordBatch, ColumnQError> {
let schema = infer_schema(values);
let arrays = schema
.fields()
.iter()
.enumerate()
.map(|(i, field)| {
// skip ... | parse_boolean | identifier_name |
end2end_test.go | : %v", result.Errors)
}
for name, mktransport := range map[string]func() transport.Transport{
"mqtt": func() transport.Transport { return mqtt.New() },
"mqtt-ws": func() transport.Transport { return mqtt.New(mqtt.WithWebSocket(true)) },
// TODO: "amqp": func() transport.Transport { return amqp.New() },
//... | {
t.Fatal(err)
} | conditional_block | |
end2end_test.go | , dc *iotdevice.Client) {
evsc := make(chan *iotservice.Event, 1)
errc := make(chan error, 2)
go func() {
errc <- sc.SubscribeEvents(context.Background(), func(ev *iotservice.Event) error {
if ev.ConnectionDeviceID == dc.DeviceID() {
evsc <- ev
}
return nil
})
}()
payload := []byte("hello")
prop... | genID | identifier_name | |
end2end_test.go | .Transport) (*iotdevice.Client, error)
only string
}{
// TODO: ca authentication
"x509": {
func(transport transport.Transport) (*iotdevice.Client, error) {
return iotdevice.NewFromX509FromFile(
transport,
"golang-iothub-self-signed",
sc.HostName(),
"testdata/device.... | }
select {
case state := <-sub.C(): | random_line_split | |
end2end_test.go | ,
"SubscribeTwin": testSubscribeTwin,
} {
if suite.only != "*" && suite.only != name {
continue
}
test, suite, mktransport := test, suite, mktransport
t.Run(auth+"/"+name, func(t *testing.T) {
dc, err := suite.init(mktransport())
if err != nil {
t.Fatal(err)
... | {
if err := dc.RegisterMethod(
context.Background(),
"sum",
func(v map[string]interface{}) (int, map[string]interface{}, error) {
return 222, map[string]interface{}{
"result": v["a"].(float64) + v["b"].(float64),
}, nil
},
); err != nil {
t.Fatal(err)
}
resc := make(chan *iotservice.MethodResul... | identifier_body | |
build_ionospheric_model.py | (xx, a0, c0, s0):
return a0 * (1/(s0*(np.sqrt(2*np.pi))))*(np.exp((-1.0/2.0)*(((xx-c0)/s0)**2)))
def _a_gaussian(xx, a0, c0, s0, sp ):
return _1gaussian(xx, a0, c0, s0 ) * (0.5 + (np.arctan(sp*(xx-c0))/np.pi))
def opt(f, x0, y0, p0):
popt, pcov = curve_fit(f, x0, y0, p0=p0)
... | _1gaussian | identifier_name | |
build_ionospheric_model.py |
def opt(f, x0, y0, p0):
popt, pcov = curve_fit(f, x0, y0, p0=p0)
perr = np.sqrt(np.diag(pcov))
return popt, perr
def estimate_skip_distance(popt):
xx = np.linspace(0,popt[1],30000)
yy = _a_gaussian(xx, popt_ag[0], popt_ag[1], popt_ag[2], popt_ag[3])
pri... | return _1gaussian(xx, a0, c0, s0 ) * (0.5 + (np.arctan(sp*(xx-c0))/np.pi)) | identifier_body | |
build_ionospheric_model.py | ):
return _1gaussian(xx, a0, c0, s0 ) * (0.5 + (np.arctan(sp*(xx-c0))/np.pi))
def opt(f, x0, y0, p0):
popt, pcov = curve_fit(f, x0, y0, p0=p0)
perr = np.sqrt(np.diag(pcov))
return popt, perr
def estimate_skip_distance(popt):
xx = np.linspace(0,popt[1],30000)
... | for beam in scan.beams:
if len(beam.slist) > 0:
setattr(beam, "slant_range", beam.frang + np.array(beam.slist.tolist()) * beam.rsep)
setattr(beam, "tfreq", np.round(beam.tfreq/1e3,1))
beams.append(beam)
# Extract oblique foF2 or... | random_line_split | |
build_ionospheric_model.py | return _1gaussian(xx, a0, c0, s0 ) * (0.5 + (np.arctan(sp*(xx-c0))/np.pi))
def opt(f, x0, y0, p0):
popt, pcov = curve_fit(f, x0, y0, p0=p0)
perr = np.sqrt(np.diag(pcov))
return popt, perr
def estimate_skip_distance(popt):
xx = np.linspace(0,popt[1],30000)
... |
du = pd.DataFrame()
du["p_l"], du["srange"] = p_l, srange
du = du[(du.srange>remove_first_range) & (du.srange<remove_last_range)]
fname = "images/{}.png".format(rscan[0].stime.strftime("%Y-%m-%d-%H-%M"))
if len(du) > 0:
sd = fit_lambda(du, pow... | if len(beam.slist) > 0:
p_l.extend(beam.p_l.tolist())
srange.extend(beam.slant_range.tolist())
tfrq.append(beam.tfreq)
if type(beam.elv) is list: angle.extend(beam.elv)
else: angle... | conditional_block |
actionitems.ts | {filterString: '', placeholder: 'Filter by subthread'}},
{title: 'Question', name: 'questionText', filtering: {filterString: '', placeholder: 'Filter by question'}},
// {title: 'Answer', name: 'currentAnswer', filtering: {filterString: '', placeholder: 'Filter by answer'}},
{title: 'Action', name: 'what', filter... | navToQuestion | identifier_name | |
actionitems.ts | ',
})
export class ActionitemsPage {
public data:any;
filterList: any = {};
unfilteredQuestions: any;
autoFilter = false;
public rows:Array<any> = [];
public columns:Array<any> = [
{title: 'Thread', name: 'threadName', filtering: {filterString: '', placeholder: 'Filter by thread'}},
{title: 'Subthread', na... | {
GoogleAnalytics.trackPage("actionitems");
} | identifier_body | |
actionitems.ts | Name
subThreadName
currentAnswer
questionId
answers {
when
who
risk
consequence
likelihood
what
reason
assumptionsNo
notesNo
answer
# technical
# schedule
# cost
}
}
file... |
public onChangeTable(config:any, page:any = {page: this.page, itemsPerPage: this.itemsPerPage}):any {
if (config.filtering) {
Object.assign(this.config.filtering, config.filtering);
}
if (config.sorting) {
Object.assign(this.config.sorting, config.sort |
return filteredData;
} | random_line_split |
actionitems.ts | Name
subThreadName
currentAnswer
questionId
answers {
when
who
risk
consequence
likelihood
what
reason
assumptionsNo
notesNo
answer
# technical
# schedule
# cost
}
}
file... |
});
var targetMRL = (<any>data.data).assessment.targetMRL;
this.attachments = (<any>data.data).assessment.files;
var newData:Array<any> = [];
console.log(this.no);
this.no.forEach( (element) => {
var newObj:any = {};
newObj.threadName = "" + element.t... | {
return a.answers[a.answers.length - 1].answer == "No"
} | conditional_block |
pm.rs | pbbsel: VolatileCell<u32>,
pbcsel: VolatileCell<u32>,
pbdsel: VolatileCell<u32>,
_reserved2: VolatileCell<u32>,
cpumask: VolatileCell<u32>, // 0x020
hsbmask: VolatileCell<u32>,
pbamask: VolatileCell<u32>,
pbbmask: VolatileCell<u32>,
pbcmask: VolatileCell<u32>,
pbdmask: VolatileCe... | mcctrl: VolatileCell<u32>,
cpusel: VolatileCell<u32>,
_reserved1: VolatileCell<u32>,
pbasel: VolatileCell<u32>, | random_line_split | |
pm.rs | {
HSB(HSBClock),
PBA(PBAClock),
PBB(PBBClock),
PBC(PBCClock),
PBD(PBDClock),
}
#[derive(Copy, Clone, Debug)]
pub enum HSBClock {
PDCA,
FLASHCALW,
FLASHCALWP,
USBC,
CRCCU,
APBA,
APBB,
APBC,
APBD,
AESA,
}
#[derive(Copy, Clone, Debug)]
pub enum PBAClock {
... | {
/// 16 MHz external oscillator
Frequency16MHz,
}
/// Configuration for the startup time of the external oscillator. In practice
/// we have found that some boards work with a short startup time, while others
/// need a slow start in order to properly wake from sleep. In general, we find
/// that for systems... | OscillatorFrequency | identifier_name |
hal.py | , machine.Pin.OUT)
### Sonar
# To average sonar sensor value
self.sonar_score = 0
# Sonar distance sensor
self.echo = machine.Pin(14, machine.Pin.IN)
self.trigger = machine.Pin(27, machine.Pin.OUT)
### ADCs
# Battery gauge
self.bat_status = 4.3 #... | return str(self.get_sonar_value()) + ',' \
+ str(self.get_line(LEFT)) + ',' \
+ str(self.get_line(RIGHT)) + ',' \
+ str(self.bat_charge.value()) + ',' \
+ str(self.get_battery_level()) | identifier_body | |
hal.py | # Bottom status LED is in reverse polarity
self.status_led.value(1)
# Sensor LEDs
self.sonar_led = machine.Pin(16, machine.Pin.OUT)
self.left_line_led = machine.Pin(17, machine.Pin.OUT)
self.right_line_led = machine.Pin(12, machine.Pin.OUT)
### Sonar
# To... | get_sensor_scope | identifier_name | |
hal.py | LEFT_LINE = 2
RIGHT_LINE = 3
# Directions
STOP = 0
LEFT = 1
RIGHT = 2
SEARCH = 3
FORWARD = 4
BACKWARD = 5
class Sumorobot(object):
# Constructor
def __init__(self):
# Open and parse the config file
with open('config.json', 'r') as config_file:
self.config = ujson.load(config_file)... | random_line_split | ||
hal.py | .PWM(machine.Pin(15), freq=50, duty=0),
RIGHT: machine.PWM(machine.Pin(4), freq=50, duty=0)
}
# Memorise previous servo speeds
self.prev_speed = {LEFT: 0, RIGHT: 0}
### LEDs
# Enable / Disable LED sensor feedback
self.sensor_feedback = True
# Bottom s... |
else:
self.move(RIGHT)
# Increase search counter
self.search_counter += 1
elif dir == FORWARD:
self.set_servo(LEFT, 100)
self.set_servo(RIGHT | self.move(LEFT) | conditional_block |
bdplatfrom.js | this.VideoAd1 = "6580222";
/*** 金币获取激励视频 */
this.VideoAd2 = "6580147";
/**签到双倍奖励视频 */
this.VideoAd3 = "6580146";
/**再来一份视频奖励 */
this.VideoAd4 = "6580145";
/**转盘获取次数奖励 */
this.VideoAd5 = "6580144";
/**转盘双倍奖励视频 */
this.VideoAd6= "6580143";
/**金币不足视频 */
this.VideoAd7= "6... | /*** 离线双倍奖励激励视频 */ | random_line_split | |
bdplatfrom.js | = sysInfo.windowHeight - e.height-32;
} else {
top = sysInfo.windowHeight - e.height - 32;
}
if (bannerAd) {
bannerAd.style.top = top;
bannerAd.style.left = (sysInfo.windowWidth - bannerAd.style.realWidth) * 0.5;
}
});
bannerAd.onLoad(() =>
{
bannerAd.show(... | var year = myDate.getFullYear();
// var month = myDate.getMonth() + 1;
// var date = myDate.getDate();
// var today = '' + year + '_' + month + '_' + date;
// return | identifier_body | |
bdplatfrom.js | Date();
// this.todayShareCount = this.getTodayShareCount();
}
/**登录 */
login(cb)
{
swan.login({
success:res =>
{
let data = {};
if (res.code)
{
data.code = 0;
data.wxcode = res.code;
... | fail(res)
{
console.log('bd.login fail !' + res.errMsg);
let data = {};
data.code = -1;
data.msg = res.errMsg;
cb && cb(data);
}
}
);
}
/**检查用户登录状态是否有效 */
checkSession()
{
swan.checkSession(
... | ;
data.code = -1;
data.msg = res.errMsg;
}
cb && cb(data);
},
| conditional_block |
bdplatfrom.js | 台配置******************************************** */
this.AppID = "17008570";
//正常标准广告
this.NormalAdunits = [
"6580232",
"6580230",
"6580229",
"6580225",
"6580224",
];
//弹窗
this.OtherAdunits = [
];
/*** 成功结算 */
/*** 离线双倍奖励激励视频 */
this.V... | /*****平 | identifier_name | |
blockparse.py | = prefix[:4]
blocksize = struct.unpack('<L', prefix[4:])[0]
logging.debug('yielding block of size %d', blocksize)
yield prefix + currentfile.read(blocksize)
def nextfile(filename):
'''
returns "next" filename in series from numbered files e.g. blk0001.dat
>>> nextfile(... |
elif height > maxheight:
logging.debug('height %d > maxheight %d', height, maxheight)
break # still executes `height += 1` below!
else:
logging.debug('height: %d', height)
height += 1
logging.debug('height: %d, maxheight: %d',... | logging.debug('height: %d', height)
logging.debug('magic: %s', binascii.b2a_hex(magic))
logging.debug('block type: %s', reversemagic.get(
magic, 'unknown'))
logging.debug('block size: %d', blocksize)
logging.debug('block header... | conditional_block |
blockparse.py | :36]
merkle_root = blockheader[36:68]
unix_time = blockheader[68:72]
nbits = blockheader[72:76]
nonce = blockheader[76:]
blockhash = get_hash(blockheader)
if len(nonce) != 4:
raise ValueError('Nonce wrong size: %d bytes' % len(nonce))
logging.info('block version: %s', show_long(versi... | parse_outputs | identifier_name | |
blockparse.py |
__str__ = __repr__
bytevalue = lambda byte: ord(byte)
bytevalues = lambda string: map(ord, string)
byte = chr
FileNotFoundError = IOError
else: # python3
bytevalue = lambda byte: byte
bytevalues = list
byte = lambda number: chr(number).encode('latin1')
LOGLEVEL = getattr(logging, ... | return 'b' + super(bytes, self).__repr__() | identifier_body | |
blockparse.py | = prefix[:4]
blocksize = struct.unpack('<L', prefix[4:])[0]
logging.debug('yielding block of size %d', blocksize)
yield prefix + currentfile.read(blocksize)
def nextfile(filename):
'''
returns "next" filename in series from numbered files e.g. blk0001.dat
>>> nextfile(... | try:
match = re.compile(pattern).match(filename).groupdict()
except AttributeError as match_failed:
raise ValueError('No numeric pattern found in {}'.format(filename))
newnumber = '{number:0{width}}'.format(
number=int(match['number']) + 1,
width=len(match['number']))
fil... | pattern = r'^(?P<prefix>[^0-9]*)(?P<number>[0-9]+)(?P<suffix>[^0-9]*)$'
directory, filename = os.path.split(filename) | random_line_split |
main.rs | let mut output_file = String::new();
let mut filter_size = 3usize;
if args.len() == 0 {
return Err(Error::new(
ErrorKind::InvalidInput,
"Tool run with no parameters.",
));
}
for i in 0..args.len() {
let mut arg = args[i].replace("\"", "");
arg = ... | for c in 0..num_cells {
zi = input[((row + dy[c] as isize), (col + dx[c] as isize))];
if zi != nodata {
xs.push(dx[c] as f64 * resolution);
ys.push(dy[c] as f64 * resolution);
... | let mut zs = vec![];
| random_line_split |
main.rs | (x4, x2y2, 0f64, 0f64, 0f64),
RowVector5::new(x2y2, x4, 0f64, 0f64, 0f64),
RowVector5::new(0f64,0f64,x2y2, 0f64, 0f64),
RowVector5::new(0f64, 0f64, 0f64, x2, 0f64),
RowVector5::new(0f64, 0f64,... | {
0f64
} | conditional_block | |
main.rs | fitted_surface.aspect();
prof_cs[col as usize] = fitted_surface.profile_convexity();
plan_cs[col as usize] = fitted_surface.plan_convexity();
long_cs[col as usize] = fitted_surface.longitudinal_curvature();
... | min_prof_convexity | identifier_name | |
main.rs | ));
}
for i in 0..args.len() {
let mut arg = args[i].replace("\"", "");
arg = arg.replace("\'", "");
let cmd = arg.split("="); // in case an equals sign was used
let vec = cmd.collect::<Vec<&str>>();
let mut keyval = false;
if vec.len() > 1 {
k... | {
let tool_name = get_tool_name();
let sep: String = path::MAIN_SEPARATOR.to_string();
// Read in the environment variables and get the necessary values
let configurations = whitebox_common::configs::get_configs()?;
let mut working_directory = configurations.working_directory.clone();
if !work... | identifier_body | |
Login.ts | Page: UI.Page;
private user: models.Login;
constructor(private redirectApp: defs.UI.IApp) {
super(key,onSigninStatChanged);
window['auth'] = this;
GData.user.OnMessage(
(s: bind.PropBinding, ev: bind.EventArgs<boolean, models.Login>) => onSigninStatCh... | >(callback: (v: boolean, param: T) => void, param: T) {
callback(GData.user.IsLogged, param);
}
private createSignupPage() {
var p = new UI.Page(this, 'Signup', 'Signup');
p.OnInitialized = p => p.Add(new UI.TControl('Client.signup', GData.user));
this.Ad... | Logged<T | identifier_name |
Login.ts | Page: UI.Page;
private user: models.Login;
constructor(private redirectApp: defs.UI.IApp) {
super(key,onSigninStatChanged);
window['auth'] = this;
GData.user.OnMessage(
(s: bind.PropBinding, ev: bind.EventArgs<boolean, models.Login>) => onSigninStatCh... |
this.dx = true;
GData.__data.Clear();
Api.RiseApi('log', { callback: null, data: null });
GData.requester.Push(models.IsAdmin, new models.IsAdmin(), null, (s, r, iss) => {
GData.spin.Start("Wait a moment");
GData.requester.Pus... | Notification.fire('ReLoadUserSetting', [models.UserSetting.Default]);
if (this.dx) {
GData.spin.Pause(); return;
} | random_line_split |
Login.ts | Page: UI.Page;
private user: models.Login;
constructor(private redirectApp: defs.UI.IApp) {
super(key,onSigninStatChanged);
window['auth'] = this;
GData.user.OnMessage(
(s: bind.PropBinding, ev: bind.EventArgs<boolean, models.Login>) => onSigninStatCh... | private createLoginPage() {
var p = new UI.Page(this, 'Login', 'Login');
p.OnInitialized = p => p.Add(new UI.TControl('Client.login', GData.user));
this.AddPage(this._loginPage = p);
}
private auth = thread.Dispatcher.cretaeJob(this.Login, [], this, true);
... | var p = new UI.Page(this, 'Signup', 'Signup');
p.OnInitialized = p => p.Add(new UI.TControl('Client.signup', GData.user));
this.AddPage(this._signupPage = p);
}
| identifier_body |
mod.rs | 00],
OAM: [0; 0x100],
registers: Registers {
LCDC: 0,
STAT: Mode::VBlank as u8,
SCY: 0,
SCX: 0,
LX: 0,
LY: 0,
LYC: 0,
WY: 0,
WX: 0,
... | self.registers.dma_counter += 1;
self.registers.dma_active = self.registers.dma_counter < DISPLAY_WIDTH;
} | random_line_split | |
mod.rs | Boy Talk"
const OAM_CYCLES: u16 = 20;
const DRAW_CYCLES: u16 = 43;
const HBLANK_CYCLES: u16 = 51;
const VBLANK_LINE_CYCLES: u16 = 114;
const SCREEN_CYCLES: u16 = VBLANK_LINE_CYCLES * VIRTUAL_DISPLAY_HEIGHT as u16;
#[repr(u8)]
#[derive(Debug, Copy, Clone, PartialEq)]
enum Mode {
HBlank = 0,
VBlank,
OAM,
... | () -> Self {
Self {
on: false,
mode: Mode::VBlank,
clock: 0,
pixel_buffer: [0x00; PITCH],
palette_buffer: [0xFFFFFF, 0xC0C0C0, 0x404040, 0x000000],
render_flag: true,
VRAM: [0; 0x2000],
OAM: [0; 0x100],
... | new | identifier_name |
addon.go | ListOptions) (*types.Addon, error) {
addon, err := getSingleAddonFromGit(git.URL, git.Path, name, git.Token, opt)
if err != nil {
return nil, err
}
return addon, nil
}
// ListAddons list addons' info from GitAddonSource
func ListAddons(git *GitAddonSource, opt ListOptions) ([]*types.Addon, error) {
gitAddons, ... | {
file, items, _, err := h.Client.Repositories.GetContents(context.Background(), h.Meta.Owner, h.Meta.Repo, path, nil)
if err != nil {
return nil, nil, WrapErrRateLimit(err)
}
return file, items, nil
} | identifier_body | |
addon.go | helps async read files of addon
type asyncReader struct {
addon *types.Addon
h *gitHelper
item *github.RepositoryContent
errChan chan error
}
// SetReadContent set which file to read
func (r *asyncReader) SetReadContent(content *github.RepositoryContent) {
r.item = content
}
// GetAddon get a addon i... | (wg *sync.WaitGroup, reader asyncReader, dirPath []string) {
defer wg.Done()
content, _, err := reader.h.readRepo(*reader.item.Path)
if err != nil {
reader.errChan <- err
return
}
b, err := content.GetContent()
if err != nil {
reader.errChan <- err
return
}
if reader.item.GetName() == "parameter.cue" {... | readResFile | identifier_name |
addon.go | Chan <- err
return
}
}
func createGitHelper(baseURL, dir, token string) (*gitHelper, error) {
var ts oauth2.TokenSource
if token != "" {
ts = oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token})
}
tc := oauth2.NewClient(context.Background(), ts)
tc.Timeout = time.Second * 10
cli := github.NewClient(t... | {
err := clt.Get(ctx, client.ObjectKey{
Namespace: types.DefaultKubeVelaNS,
Name: Convert2AppName(dep.Name),
}, &app)
if err != nil {
return false
}
} | conditional_block | |
addon.go | helps async read files of addon
type asyncReader struct {
addon *types.Addon
h *gitHelper
item *github.RepositoryContent
errChan chan error
}
// SetReadContent set which file to read
func (r *asyncReader) SetReadContent(content *github.RepositoryContent) {
r.item = content
}
// GetAddon get a addon i... | dirPath, err := cutPathUntil(dirPath, ResourcesDirName)
if err != nil {
reader.errChan <- err
}
_, items, err := reader.h.readRepo(*reader.item.Path)
if err != nil {
reader.errChan <- err
return
}
for _, item := range items {
switch item.GetType() {
case "file":
reader.SetReadContent(item)
wg.Ad... | defer wg.Done()
dirPath := strings.Split(reader.item.GetPath(), "/") | random_line_split |
cryptologer.py | ,bruteforce
from vigenere_enc import encrypt
from affine_enc import aff_enc
from bacon_enc import steak
from railfence_enc import rail
from atbash import atb
from polybius_enc import tsquaree
from substitution_enc import substitute
from rsa_encryptor import rivest
from rot import rotate,rotate_brute
from skip... |
elif args.railfence:
from enc.railfence_enc import rail
ciphertext=rail(plaintext)
elif args.rot:
from enc.rot import rotate
if args.key==None:
shift=input("enter shift:")
ciphertext=rotate(plaintext,shift)
elif args.rot47:
from enc.rot47 import rot47
ciphertext=rot47(pl... | from enc.bacon_enc import steak
ciphertext=steak(plaintext) | conditional_block |
cryptologer.py | #import operator
#import math
#import requests
#import json
#import binascii
#import os
#import time
'''
def whereami():
with open('/root/directory.txt','r') as f1:
location=f1.read()
return location
location=whereami()'''
#appending file paths
'''
import Encrypting as enc
import Decrypting as... | #import re
import argparse
| random_line_split | |
cryptologer.py | ,bruteforce
from vigenere_enc import encrypt
from affine_enc import aff_enc
from bacon_enc import steak
from railfence_enc import rail
from atbash import atb
from polybius_enc import tsquaree
from substitution_enc import substitute
from rsa_encryptor import rivest
from rot import rotate,rotate_brute
from skip... | ():
parser=argparse.ArgumentParser(description="Decryptor for Caeser, Vigenere, types of RSA and more...")
parser.add_argument("--decrypt","--dec","-d",help="Performs Decryption",action="store_true")
parser.add_argument("--encrypt","--enc","-e",help="Performs Encryption",action="store_true")
parser.add_argu... | initializeParser | identifier_name |
cryptologer.py | ,bruteforce
from vigenere_enc import encrypt
from affine_enc import aff_enc
from bacon_enc import steak
from railfence_enc import rail
from atbash import atb
from polybius_enc import tsquaree
from substitution_enc import substitute
from rsa_encryptor import rivest
from rot import rotate,rotate_brute
from skip... |
def read_chinese(filename):
with open(filename,"r") as f3:
line=f3.readline()
while line:
symbol=line[:2].lower()
if symbol=='n1':
n1=int(line[3:])
elif symbol=='n2':
n2=int(line[3:])
elif symbol=='n3':
n3=int(line[3:])
elif symbol=='c1':
c1=int(line[3:])
elif sym... | with open(filename,"r") as f2:
line=f2.readline()
e=0
while line:
symbol=line[0].lower()
if symbol=='n':
n=int(line[2:])
elif symbol=='e':
e=int(line[2:])
elif symbol=='c':
c=line[2:]
elif symbol=='m':
c=line[2:]
else:
raise Exception("the contents of the file c... | identifier_body |
metadata.rs | samples: if n_samples == 0 {
None
} else {
Some(n_samples)
},
md5sum: md5sum,
};
Ok(stream_info)
}
fn read_vorbis_comment_block<R: ReadBytes>(input: &mut R, length: u32) -> Result<VorbisComment> {
if length < 8 {
// We expect at a minimum a 32... | if self.done {
None
} else {
let block = self.read_next();
// After a failure, no more attempts to read will be made,
// because we don't know where we are in the stream.
if !block.is_ok() {
self.done = true;
}
... | identifier_body | |
metadata.rs | max_frame_size && max_frame_size != 0 {
return fmt_err("inconsistent bounds, min frame size > max frame size");
}
// A sample rate of 0 is invalid, and the maximum sample rate is limited by
// the structure of the frame headers to 655350 Hz.
if sample_rate == 0 || sample_rate > 655350 {
... | t: | identifier_name | |
metadata.rs | : u32,
/// The contents of the application block.
data: Vec<u8>,
},
/// A seek table block.
SeekTable(SeekTable),
/// A Vorbis comment block, also known as FLAC tags.
VorbisComment(VorbisComment),
/// A CUE sheet block.
CueSheet, // TODO
/// A picture block.
Picture, ... | 2 => {
let (id, data) = try!(read_application_block(input, length));
Ok(MetadataBlock::Application {
id: id,
data: data,
})
}
3 => {
// TODO: implement seektable reading. For now, pretend it is padding.
try!(inp... | try!(read_padding_block(input, length));
Ok(MetadataBlock::Padding { length: length })
}
| conditional_block |
metadata.rs | /// The number of padding bytes.
length: u32,
},
/// An application block with application-specific data.
Application {
/// The registered application ID.
id: u32,
/// The contents of the application block.
data: Vec<u8>,
},
/// A seek table block.
... | pub enum MetadataBlock {
/// A stream info block.
StreamInfo(StreamInfo),
/// A padding block (with no meaningful data).
Padding { | random_line_split | |
test.py | L2 regularization. '
'Default: False')
parser.add_argument('--silence_threshold', type=float,
default=SILENCE_THRESHOLD,
help='Volume threshold below which to trim the start '
'and the end from the training set samples.... | receptive_field-1, 0], [0, 0]])
raw_output = tf.concat([raw_output, raw_output, raw_output, raw_output], axis=1)
raw_output = tf.pad(raw_output, [[0, 0], [0, 6]])
raw_output = tf.expand_dims(raw_output, 0)
audio_batch = audio_batch - raw_output
... | conditional_block | |
test.py | 0], uvd_pt2[2, 1], uvd_pt2[2, 2], s=10, c='r')
ax.plot([uvd_pt2[0, 0], uvd_pt2[1, 0]],
[uvd_pt2[0, 1], uvd_pt2[1, 1]],
[uvd_pt2[0, 2], uvd_pt2[1, 2]], color='r', linewidth=1)
ax.plot([uvd_pt2[1, 0], uvd_pt2[2, 0]],
[uvd_pt2[1, 1], uvd_pt2[2, 1]],
[uvd_pt2[1, 2], ... | (args):
"""Validate and arrange directory related arguments."""
# Validation
if args.logdir and args.logdir_root:
raise ValueError("--logdir and --logdir_root cannot be "
"specified at the same time.")
if args.logdir and args.restore_from:
raise ValueError(
... | validate_directories | identifier_name |
test.py | 0], uvd_pt2[2, 1], uvd_pt2[2, 2], s=10, c='r')
ax.plot([uvd_pt2[0, 0], uvd_pt2[1, 0]],
[uvd_pt2[0, 1], uvd_pt2[1, 1]],
[uvd_pt2[0, 2], uvd_pt2[1, 2]], color='r', linewidth=1)
ax.plot([uvd_pt2[1, 0], uvd_pt2[2, 0]],
[uvd_pt2[1, 1], uvd_pt2[2, 1]],
[uvd_pt2[1, 2],... | 'the state and will continue training. '
'Cannot use with --logdir_root and --restore_from.')
parser.add_argument('--logdir_root', type=str, default=None,
help='Root directory to place the logging '
'output and generated... | def _str_to_bool(s):
"""Convert string to bool (in argparse context)."""
if s.lower() not in ['true', 'false']:
raise ValueError('Argument needs to be a '
'boolean, got {}'.format(s))
return {'true': True, 'false': False}[s.lower()]
parser = argparse... | identifier_body |
test.py | def validate_directories(args):
"""Validate and arrange directory related arguments."""
# Validation
if args.logdir and args.logdir_root:
raise ValueError("--logdir and --logdir_root cannot be "
"specified at the same time.")
if args.logdir and args.restore_from:
... | if step < args.num_steps*0.0:
muti_step_id = 0 | random_line_split | |
orgreminders.go | Test
http.HandleFunc("/", DefaultHandler)
http.HandleFunc("/newevent", NewEventHandler)
http.HandleFunc("/neworg", NewOrgHandler)
http.HandleFunc("/events", EventsHandler)
http.HandleFunc("/organizations", OrgsHandler)
http.HandleFunc("/saveevent", EventSaveHandler)
http.HandleFunc("/saveorg", OrgSaveHandler)
... | (w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
url, _ := user.LogoutURL(c, "/")
http.Redirect(w, r, url, http.StatusFound)
}
func DefaultHandler(w http.ResponseWriter, r *http.Request) {
u := UserLookup(w, r)
p, _ := NewPage(&u)
title := "home"
renderTemplate(w, title, p)
}
func NewOr... | LogoutHandler | identifier_name |
orgreminders.go | SuperUser bool
LoggedIn bool
UserEmail string
Orgs []string
Members map[string]Member
SavedEvent bool
SavedOrg bool
SavedMember bool
Member2Edit Member
Member2EditKey string
ScheduleHTML map[string][]string
}
func NewPage(u *User) (*Page, error) {
var resu... | AllowNewOrg bool | random_line_split | |
orgreminders.go | Test
http.HandleFunc("/", DefaultHandler)
http.HandleFunc("/newevent", NewEventHandler)
http.HandleFunc("/neworg", NewOrgHandler)
http.HandleFunc("/events", EventsHandler)
http.HandleFunc("/organizations", OrgsHandler)
http.HandleFunc("/saveevent", EventSaveHandler)
http.HandleFunc("/saveorg", OrgSaveHandler)
... |
func MemberEditHandler(w http.ResponseWriter, r *http.Request) {
u := UserLookup(w, r)
p, _ := NewPage(&u)
c := appengine.NewContext(r)
var ok bool
p.Member2EditKey = r.FormValue("id")
ok, p.Member2Edit = GetMemberByKey(c, p.Member2EditKey)
// Protect web users
if ok && p.Member2Edit.WebUser {
if u.Meta.E... | {
u := UserLookup(w, r)
p, _ := NewPage(&u)
title := "new-member"
for _, org := range u.Orgs {
p.Orgs = append(p.Orgs, org.Name)
}
sort.Strings(p.Orgs)
renderTemplate(w, title, p)
} | identifier_body |
orgreminders.go | ."
renderTemplate(w, "error", p)
}
}
func OrgSaveHandler(w http.ResponseWriter, r *http.Request) {
u := UserLookup(w, r)
p, _ := NewPage(&u)
c := appengine.NewContext(r)
org := NewOrganization()
org.Name = r.PostFormValue("name")
org.Description = r.PostFormValue("description")
org.Active = true
org.Expire... | {
if _, ok := seen[val]; !ok {
result = append(result, val)
seen[val] = val
}
} | conditional_block | |
index.ts | }
export type PhotoBuffObj = {
label: string;
description: string;
formattedDate: string;
base64Str: any;
}
export type SignatureObj = {
uri: string;
timeStamp: number;
formattedDate: string;
s3Key: string;
}
export type Signatures = {
nonWaiverInsuredSignature: SignatureObj;
nonWaiverAdjusterSig... | random_line_split | ||
jsonast.go | }}
// oneOf:
// - External ARM resources
// oneOf:
// allOf:
// $ref: {{ base resource for ARM specific stuff like locks, deployments, etc }}
// oneOf:
// - ARM specific resources. I'm not 100% sure why...
//
// allOf acts like composition which composites each schema from th... | (ctx context.Context, schema *gojsonschema.SubSchema, opts ...BuilderOption) ([]astmodel.TypeDefiner, error) {
ctx, span := tab.StartSpan(ctx, "GenerateDefinitions")
defer span.End()
for _, opt := range opts {
if err := opt(scanner); err != nil {
return nil, err
}
}
// get initial topic from ID and Title:... | GenerateDefinitions | identifier_name |
jsonast.go | .StartSpan(ctx, "refHandler")
defer span.End()
url := schema.Ref.GetUrl()
if url.Fragment == expressionFragment {
// skip expressions
return nil, nil
}
// make a new topic based on the ref URL
name, err := objectTypeOf(url)
if err != nil {
return nil, err
}
group, err := groupOf(url)
if err != nil {... | {
ctx, span := tab.StartSpan(ctx, "anyOfHandler")
defer span.End()
// See https://github.com/Azure/k8s-infra/issues/111 for details about why this is treated as oneOf
klog.Warningf("Handling anyOf type as if it were oneOf: %v\n", schema.Ref.GetUrl())
return generateOneOfUnionType(ctx, schema.AnyOf, scanner)
} | identifier_body |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.