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 |
|---|---|---|---|---|
lstm.py |
print(row)
# print(sql_select_Query)
# sql_select_Query="SELECT concat( year,Month) as Date , unit_price as data FROM oildata"
df = pd.read_sql(sql_select_Query, connection);
columnsNamesArr = df.columns.values
listOfColumnNames = list(columnsNamesArr)
print(listOfColumnNames)
print(len(listOfCol... | # print(df_proj)
#
# plt.figure(figsize=(20, 5))
# plt.plot(df_proj.index, df_proj['data'])
# plt.plot(df_proj.index, df_proj['Prediction'], color='r')
# plt.legend(loc='best', fontsize='xx-large')
# plt.xticks(fontsize=18)
# plt.yticks(fontsize=16)
# plt.show()
# #
# # scaler = MinMaxScaler(feature_range... | # index=future_dates[-n_input:].index, columns=['Prediction'])
#
# df_proj = pd.concat([df,df_predict], axis=1)
#
| random_line_split |
canvas.rs | // Write pixel data. Each pixel RGB value is written with a separating space or newline;
// new rows are written on new lines for human reading convenience, but lines longer than
// MAX_PPM_LINE_LENGTH must also be split.
let mut current_line = String::new();
for row in 0..self.height {... | lines.next().unwrap(),
"153 255 204 153 255 204 153 255 204 153 255 204 153"
);
assert_eq!(
lines.next().unwrap(),
"255 204 153 255 204 153 255 204 153 255 204 153 255 204 153 255 204"
);
assert_eq!(
lines.next().unwrap(),
... | {
let mut canvas = Canvas::new(10, 2);
let color = color!(1, 0.8, 0.6);
// TODO: maybe turn this into a function on canvas?
for row in 0..canvas.height {
for column in 0..canvas.width {
canvas.write_pixel(column, row, color);
}
}
le... | identifier_body |
canvas.rs | (&self, line: &mut String, ppm: &mut String) {
if line.len() < MAX_PPM_LINE_LENGTH - MAX_COLOR_VAL_STR_LEN {
(*line).push(' ');
} else {
ppm.push_str(&line);
ppm.push('\n');
line.clear();
}
}
// Return string containing PPM (portable pixel... | write_rgb_separator | identifier_name | |
canvas.rs | // Write pixel data. Each pixel RGB value is written with a separating space or newline;
// new rows are written on new lines for human reading convenience, but lines longer than
// MAX_PPM_LINE_LENGTH must also be split.
let mut current_line = String::new();
for row in 0..self.height {... | if i != self.width - 1 {
self.write_rgb_separator(&mut current_line, &mut ppm);
}
}
if !current_line.is_empty() {
ppm.push_str(¤t_line);
ppm.push('\n');
}
}
ppm
}
}
// TODO:... | current_line.push_str(&b.to_string());
// if not at end of row yet, write a space or newline if the next point will be on this line | random_line_split |
canvas.rs | Write pixel data. Each pixel RGB value is written with a separating space or newline;
// new rows are written on new lines for human reading convenience, but lines longer than
// MAX_PPM_LINE_LENGTH must also be split.
let mut current_line = String::new();
for row in 0..self.height {
... |
}
}
Ok(canvas)
}
fn clean_line(
(index, line): (usize, Result<String, std::io::Error>),
) -> Option<(usize, Result<String, std::io::Error>)> {
match line {
Ok(s) => {
let s = s.trim();
if s.starts_with("#") || s.is_empty() {
None
} el... | {
x = 0;
y += 1;
} | conditional_block |
caching.py | ()
s = self._queue.pop(0)
self._condition.notify_all()
s.execute()
@property
def connection(self):
if self._connection is None:
cache_dir = SETTINGS.get("cache-directory")
if not os.path.exists(cache_dir):
os.makedirs(c... | latest = self._latest_date()
for stmt in (
"SELECT * FROM cache WHERE size IS NOT NULL AND owner='orphans' AND creation_date < ?",
"SELECT * FROM cache WHERE size IS NOT NULL AND creation_date < ? ORDER BY last_access ASC",
):
for entr... |
with self.connection as db:
| random_line_split |
caching.py | s = self._queue.pop(0)
self._condition.notify_all()
s.execute()
@property
def | (self):
if self._connection is None:
cache_dir = SETTINGS.get("cache-directory")
if not os.path.exists(cache_dir):
os.makedirs(cache_dir, exist_ok=True)
cache_db = os.path.join(cache_dir, CACHE_DB)
LOG.debug("Cache database is %s", cache_db)
... | connection | identifier_name |
caching.py | s = self._queue.pop(0)
self._condition.notify_all()
s.execute()
@property
def connection(self):
if self._connection is None:
cache_dir = SETTINGS.get("cache-directory")
if not os.path.exists(cache_dir):
os.makedirs(cach... |
self._register_cache_file(
full,
"orphans",
None,
parent,
)
self._update_cache()
def _delete_file(self, path):
self._ensure_in_cache(path)
try:
if os.path.isdir(pa... | LOG.debug(
f"CliMetLab cache: orphan found: {full} with parent {parent}"
) | conditional_block |
caching.py | s = self._queue.pop(0)
self._condition.notify_all()
s.execute()
@property
def connection(self):
if self._connection is None:
cache_dir = SETTINGS.get("cache-directory")
if not os.path.exists(cache_dir):
os.makedirs(cach... | commit = True
if update:
db.executemany("UPDATE cache SET size=?, type=? WHERE path=?", update)
if update or commit:
db.commit()
def _housekeeping(self):
top = SETTINGS.get("cache-directory")
with self.connection as ... | """Update cache size and size of each file in the database ."""
with self.connection as db:
update = []
commit = False
for n in db.execute("SELECT path FROM cache WHERE size IS NULL"):
try:
path = n[0]
if os.path.isdir(p... | identifier_body |
resumeBuilder.js | '<li class="flex-item"><span class="orange-text">blog</span><span class="white-text">%data%</span></li>';
// var HTMLlocation = '<li class="flex-item"><span class="orange-text">location</span><span class="white-text">%data%</span></li>';
// var HTMLbioPic = '<img src="%data%" class="biopic">';
// var HTMLwelcomeMsg = ... | $("#workExperience").append(HTMLworkStart);
for (key in work.work){
if (work.work.hasOwnProperty(key)) {
var employerHTML = HTMLworkEmployer.replace("%data%", work.work[key].employer);
$(".work-entry:last").append(employerHTML);
var titleHTML = HTMLworkTitle.replace("%... | identifier_body | |
resumeBuilder.js | -item"><span class="orange-text">location</span><span class="white-text">%data%</span></li>';
// var HTMLbioPic = '<img src="%data%" class="biopic">';
// var HTMLwelcomeMsg = '<span class="welcome-message">%data%</span>';
// var HTMLskillsStart = '<h3 id="skills-h3">Skills at a Glance:</h3><ul id="skills" class="flex-c... | $("#projects").append(HTMLprojectStart);
for (key in projects.projects){ | random_line_split | |
resumeBuilder.js | _twitter = bio.contact_info[2];
// var contact_github = bio.contact_info[3];
// var contact_blog = bio.contact_info[4];
// var contact_location = bio.contact_info[5];
// var picture = bio.pic_url;
// var welcome_msg = bio.welcome_msg;
// var skill_start = HTMLskillsStart;
// var skills = bio.skills;
// var formattedNa... | for (image in projects.projects[key].images) {
var imagesHTML = HTMLprojectImage.replace("%data%",projects.projects
[key].images[image]);
$(".project-entry:last").append(imagesHTML);
}
}
| conditional_block | |
resumeBuilder.js | hr>';
// var HTMLcontactGeneric = '<li class="flex-item"><span class="orange-text">%contact%</span><span class="white-text">%data%</span></li>';
// var HTMLmobile = '<li class="flex-item"><span class="orange-text">mobile</span><span class="white-text">%data%</span></li>';
// var HTMLemail = '<li class="flex-item"><span... | layWork() { | identifier_name | |
task.go | task")
defer close(task.resultChan)
defer close(task.resultChanGet)
if err := task.run(ctx); err != nil {
task.err = err
task.UpdateStatus(StatusTaskFailure)
log.WithContext(ctx).WithError(err).Warnf("Task failed")
return nil
}
task.UpdateStatus(StatusTaskCompleted)
return nil
}
func (task *Task) ru... | random_line_split | ||
task.go | *userdata.ProcessRequest
// information user pastelid to retrieve userdata
userpastelid string // user pastelid
resultChanGet chan *userdata.ProcessRequest
}
// Run starts the task
func (task *Task) Run(ctx context.Context) error {
ctx = log.ContextWithPrefix(ctx, fmt.Sprintf("%s-%s", logPrefix, task.ID()))
... |
if err := primary.Session(ctx, true); err != nil {
return nil, err
}
primary.SetPrimary(true)
if len(nodes) == 1 {
// If the number of nodes only have 1 node, we use this primary node and return directly
meshNodes.Add(primary)
return meshNodes, nil
}
nextConnCtx, nextConnCancel := context.WithCancel(ct... | {
return nil, err
} | conditional_block |
task.go | *userdata.ProcessRequest
// information user pastelid to retrieve userdata
userpastelid string // user pastelid
resultChanGet chan *userdata.ProcessRequest
}
// Run starts the task
func (task *Task) | (ctx context.Context) error {
ctx = log.ContextWithPrefix(ctx, fmt.Sprintf("%s-%s", logPrefix, task.ID()))
log.WithContext(ctx).Debugf("Start task")
defer log.WithContext(ctx).Debugf("End task")
defer close(task.resultChan)
defer close(task.resultChanGet)
if err := task.run(ctx); err != nil {
task.err = err
... | Run | identifier_name |
task.go |
}
// TODO: Make this init and connect to super nodes to generic reusable function to avoid code duplication (1)
// Retrieve supernodes with highest ranks.
topNodes, err := task.pastelTopNodes(ctx, maxNode)
if err != nil {
return err
}
if len(topNodes) < maxNode {
task.UpdateStatus(StatusErrorNotEnoughMaste... | {
return task.resultChan
} | identifier_body | |
models.py | , **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(Category, self).save(*args, **kwargs)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['parent', 'title']
list_filter = ['parent']
list_per_page = 25
search_fields = ['title']
... |
def __unicode__(self):
trans = None
# This might be provided using a .extra() clause to avoid hundreds of extra queries:
if hasattr(self, "preferred_translation"):
trans = getattr(self, "preferred_translation", u"")
else:
try:
trans = unicod... | super(MediaFileBase, self).__init__(*args, **kwargs)
if self.file and self.file.path:
self._original_file_path = self.file.path | identifier_body |
models.py |
@classmethod
def register_filetypes(cls, *types):
cls.filetypes[0:0] = types
choices = [ t[0:2] for t in cls.filetypes ]
cls.filetypes_dict = dict(choices)
cls._meta.get_field('type').choices[:] = choices
def __init__(self, *args, **kwargs):
super(MediaFileBase, se... | if not storage:
messages.error(request, _("Could not access storage"))
return | random_line_split | |
models.py | ify(self.title)
super(Category, self).save(*args, **kwargs)
class CategoryAdmin(admin.ModelAdmin):
list_display = ['parent', 'title']
list_filter = ['parent']
list_per_page = 25
search_fields = ['title']
prepopulated_fields = { 'slug': ('title',), }
# ----------------... | Meta | identifier_name | |
models.py | def get_absolute_url(self):
return self.file.url
def file_type(self):
t = self.filetypes_dict[self.type]
if self.type == 'image':
try:
from django.core.files.images import get_image_dimensions
d = get_image_dimensions(self.file.file)
... | messages.error(request, _("No input file given")) | conditional_block | |
transformer.py | 0 1 2
-3 -2 -1 0 1 2
-3 -2 -1 0 1 2
to
0 1 2
-1 0 1
-2 -1 0
:param BD: batch_size x n_head x max_len x 2max_len
:return: batch_size x n_head x max_len x max_len
"""
bsz, n_head, max_len, _ = BD.size()
zero_pad = layers.zero... | attn_output = post_process_layer(enc_input, attn_output,
postprocess_cmd, prepostprocess_dropout)
ffd_output = positionwise_feed_forward( | random_line_split | |
transformer.py | len(keys.shape) == len(values.shape) == 3):
raise ValueError(
"Inputs: quries, keys and values should all be 3-D tensors."
)
def __compute_qkv(queries, keys, values, n_head, d_key, d_value):
"""
Add linear projection to queries, keys, and values.
"""
q =... |
# position bias for each head, shaped like [n_head, 2 X max_sequence_len].
# Then add two dimensions at `batch` and `maxlen`.
D_ = layers.matmul(x=r_w_bias, y=pos_enc, transpose_y=True)[None, :, None]
# position bias for each query, shaped like [batch, n_head, max_len, 2 X max_l... | """
Scaled Dot-Product Attention
Change:
- Different from the original one.
We will remove the scale factor math: \sqrt{d_k} according to the paper.
- Bias for attention and position encoding are added.
"""
# product = layers.matmul(x=q, y=k... | identifier_body |
transformer.py | 1
-2 -1 0
:param BD: batch_size x n_head x max_len x 2max_len
:return: batch_size x n_head x max_len x max_len
"""
bsz, n_head, max_len, _ = BD.size()
zero_pad = layers.zeros(shape=(bsz, n_head, max_len, 1))
BD = layers.reshape(x=layers.concat([BD, zero_pad], a... | encoder | identifier_name | |
transformer.py | =True)
v = transpose_layer(x=reshaped_v, perm=[0, 2, 1, 3])
if cache is not None: # only for faster inference
cache_, i = cache
if static_kv: # For encoder-decoder attention in inference
cache_k, cache_v = cache_["static_k"], cache_["static_v"]
# To init the... | if dropout_rate:
out = layers.dropout(
out,
dropout_prob=dropout_rate,
seed=dropout_seed,
is_test=False) | conditional_block | |
BlockChain.go | 一个地址所对应的TXout未花费,那么这个就应该被添加到数组中
func (blockchain *BlockChain) UnUTXOs(address string,txs []*Transaction)[]*UTXO{
var unUTXOs []*UTXO
spentTXOutputs := make(map[string][]int)
//
//pubKeyHash := Base58Decode([]byte(address))
//ripemd160Hash := pubKeyHash[1:len(pubKeyHash)-4]
//fmt.Printf("转换后%v\n",ripemd160Hash)
... | {
if bytes.Compare(tx.TxHash,txHash)==0{
return *tx,nil
}
}
hashInt.SetBytes(block.PrevBlockH | conditional_block | |
BlockChain.go | \n",time.Unix(block.Timestamp,0).Format("2006-01-02 15:04:05"))
fmt.Printf("Hash: %x\n",block.Hash)
fmt.Printf("Nonce: %d\n",block.Nonce)
fmt.Println("Txs:")
for _,tx := range block.Txs{
fmt.Printf("%x\n",tx.TxHash)
fmt.Println("Vins:")
for _,in:=range tx.Vins{
fmt.Printf("%x\n",in.TXHash)
fmt.... | return nil
})
} | random_line_split | |
BlockChain.go |
}
if b!=nil{
//创建一个coinbase transaction
txCoinbase := NewCoinbaseTransaction(address)
//创建创世区块
genesisBlock = CreateGenesisBlock([]*Transaction{txCoinbase})
//将创世区块放入数据库
err=b.Put(genesisBlock.Hash,genesisBlock.Serialize())
if err!=nil{
log.Panic(err)
}
//存储最新的区块的hash
err=b.Put([... |
os.Exit(1)
}
// 当数据库不存在时,创建创世区块链
fmt.Println("正在创建创世区块。。。")
dbName := fmt.Sprintf(dbName,nodeID)
db, err := bolt.Open(dbName, 0600, nil)
if err != nil {
log.Fatal(err)
}
//defer db.Close()
var genesisBlock *Block
err = db.Update(func(tx *bolt.Tx)error{
b,err := tx.CreateBucket([]byte(blockTableName... | identifier_body | |
BlockChain.go | err!=nil{
// log.Panic(err)
// }
// // 创建新区块并添加数据库
//
// err = blc.DB.Update(func(tx *bolt.Tx) error{
// b := tx.Bucket([]byte(blockTableName))
// if b!=nil{
// newBlock := NewBlock(txs,height,preHash)
// newBlockByte := newBlock.Serialize()
// //添加区块信息值数据库
// err :=b.Put(newBlock.Hash,newBlockByte)
// if... | ripemd160Hash) {
key := hex.EncodeToString(in.TXHash)
spentTXOutputs[key] = append(spentTXOutputs[key], in.Vout)
}
}
}
}
fmt.Println(spentTXOutputs)
for _,tx:=range txs{
//若当前的txHash都没有被记录消费
spentArray,ok:=spentTXOutputs[hex.EncodeToString(tx.TxHash)]
if ok==false{
for index,out := r... | 60Hash( | identifier_name |
processing.py | y, tx, ids, header, is_test):
"""
Split the given dataset such that only the data points with a certain
jet number remains, note that jet number is a discrete valued feature. In
other words, filter the dataset using the jet number.
:param y: known label data
:param tx: an array of training data... | change_labels_logistic | identifier_name | |
processing.py | ')
reader = csv.DictReader(read_file)
return reader.fieldnames
def analyze(tx):
"""
Analyze data by replacing null value, -999, with the median of non-null value in the
certain column. Also, handle outliers by placing original value with upper and lower bound
(mean +- std from a feature distri... |
def report_prediction_accuracy_logistic(y, tx, w_best, verbose=True):
"""
Report the percentage of correct predictions of a model that is applied
on a set of labels. This method specifically works for logistic regression
since the prediction assumes that labels are between 0 and 1.
:param y: labe... | """
Perform cross_validation for a specific test set from the partitioned set.
:param y: label data
:param augmented_tx: augmented features
:param k_indices: An array of k sub-indices that are randomly partitioned
:param k: number of folds
:param lambda_: regularization parameters
:param rep... | identifier_body |
processing.py | ')
reader = csv.DictReader(read_file)
return reader.fieldnames
def analyze(tx):
"""
Analyze data by replacing null value, -999, with the median of non-null value in the
certain column. Also, handle outliers by placing original value with upper and lower bound
(mean +- std from a feature distri... |
print("\n... finished.")
return tx, header
def create_csv(output_file, y, tx, ids, header, is_test):
"""
Split the given dataset such that only the data points with a certain
jet number remains, note that jet number is a discrete valued feature. In
other words, filter the dataset using the je... | tx = np.delete(tx, col - num_removed, 1)
header = np.delete(header, col - num_removed + 2)
num_removed += 1 | conditional_block |
processing.py | r')
reader = csv.DictReader(read_file)
return reader.fieldnames
def analyze(tx):
"""
Analyze data by replacing null value, -999, with the median of non-null value in the
certain column. Also, handle outliers by placing original value with upper and lower bound
(mean +- std from a feature distr... |
def split_data(y, tx, ids, jet_num):
"""
Split the given dataset such that only the data points with a certain
jet number remains, note that jet number is a discrete valued feature. In
other words, filter the dataset using the jet number.
:param y: known label data
:param tx: an array of traini... | for index in range(len(tx_row)):
dictionary[header[index + 2]] = float(tx_row[index])
writer.writerow(dictionary)
print('\n... finished.')
| random_line_split |
handshake.rs | Socket: AsyncRead + AsyncWrite + Unpin,
{
// perform the noise handshake
let socket = match origin {
ConnectionOrigin::Outbound => {
let remote_public_key = match remote_public_key {
Some(key) => key,
None if cfg!(any(test, feature ... | vec![(client_id, client_keys), (server_id, server_keys)]
.into_iter()
.collect(),
));
let client_auth = HandshakeAuthMode::mutual(trusted_peers.clone()); | random_line_split | |
handshake.rs | but as we use it to store a duration since UNIX_EPOCH we will never use more than 8 bytes.
const PAYLOAD_SIZE: usize = 8;
/// Noise handshake authentication mode.
pub enum HandshakeAuthMode {
/// In `Mutual` mode, both sides will authenticate each other with their
/// `trusted_peers` set. We also include repl... |
fn anti_replay_timestamps(&self) -> Option<&RwLock<AntiReplayTimestamps>> {
match &self {
HandshakeAuthMode::Mutual {
anti_replay_timestamps,
..
} => Some(&anti_replay_timestamps),
HandshakeAuthMode::ServerOnly => None,
}
}
... | {
HandshakeAuthMode::Mutual {
anti_replay_timestamps: RwLock::new(AntiReplayTimestamps::default()),
trusted_peers,
}
} | identifier_body |
handshake.rs | but as we use it to store a duration since UNIX_EPOCH we will never use more than 8 bytes.
const PAYLOAD_SIZE: usize = 8;
/// Noise handshake authentication mode.
pub enum HandshakeAuthMode {
/// In `Mutual` mode, both sides will authenticate each other with their
/// `trusted_peers` set. We also include repl... | <TSocket>(
&self,
socket: TSocket,
origin: ConnectionOrigin,
remote_public_key: Option<x25519::PublicKey>,
) -> io::Result<(x25519::PublicKey, NoiseStream<TSocket>)>
where
TSocket: AsyncRead + AsyncWrite + Unpin,
{
// perform the noise handshake
let so... | upgrade | identifier_name |
lib.rs | (red: u8, green: u8, blue:u8) -> Color {
return Color {r : red, g : green, b : blue};
}
/// Conctructor with random values for each color
pub fn new_random() -> Color {
let mut r = rand::thread_rng();
return Color {
r : r.gen::<u8>(),
g : r.gen::<u8>... | new | identifier_name | |
lib.rs | red, g : green, b : blue};
}
/// Conctructor with random values for each color
pub fn new_random() -> Color {
let mut r = rand::thread_rng();
return Color {
r : r.gen::<u8>(),
g : r.gen::<u8>(),
b : r.gen::<u8>()
}
}
/// Default... |
/// Width's getter
pub fn width(&self) -> u32 {
return self.width;
}
/// Height's getter
pub fn height(&self) -> u32 {
return self.height;
}
/// Pixels getter
pub fn pixels(&self) -> &Vec<Color> {
return &self.pixels;
}
/// Equals()
pub fn eq(&sel... | {
return Image {width : width, height : height, pixels : pixels};
} | identifier_body |
lib.rs | : red, g : green, b : blue};
}
/// Conctructor with random values for each color
pub fn new_random() -> Color {
let mut r = rand::thread_rng();
return Color {
r : r.gen::<u8>(),
g : r.gen::<u8>(),
b : r.gen::<u8>()
}
}
/// Defau... | pub fn blue(&self) -> u8 {
return self.b;
}
/// toString() to display a Color
pub fn display(&self) {
println!("r : {}, g : {}, b : {}", self.r, self.g, self.b);
}
/// Equals to determine if the two Color in parameters are equals.
/// Return true if self and other and equal... | }
/// Blue's getter | random_line_split |
main.py | os.path import isdir, join, isfile
from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Builder, Default,
DefaultEnvironment)
env = DefaultEnvironment()
platform = env.PioPlatform()
#overides the default upload.maximum_size value which is used to calculate how much of the m... | "$TARGET"
]), "disassembler Output -> $TARGET"),
suffix=".dis"
)
)
)
if not env.get("PIOFRAMEWORK"):
env.SConscript("frameworks/_bare.py")
#
# Target: Build executable and linkable firmware
#
target_firm_elf = None
target_firm_hex = None
object_dump... | "$SOURCES",
">",
| random_line_split |
main.py | from os.path import isdir, join, isfile
from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Builder, Default,
DefaultEnvironment)
env = DefaultEnvironment()
platform = env.PioPlatform()
#overides the default upload.maximum_size value which is used to calculate how much of t... | (env, source):
build_dir = env.subst("$BUILD_DIR")
if not isdir(build_dir):
makedirs(build_dir)
script_path = join(build_dir, "upload.jlink")
commands = [
"h",
"loadbin %s, %s" % (source, env.BoardConfig().get(
"upload.offset_ad... | _jlink_cmd_script | identifier_name |
main.py | from os.path import isdir, join, isfile
from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Builder, Default,
DefaultEnvironment)
env = DefaultEnvironment()
platform = env.PioPlatform()
#overides the default upload.maximum_size value which is used to calculate how much of t... |
env.Replace(
__jlink_cmd_script=_jlink_cmd_script,
UPLOADER="JLink.exe" if system() == "Windows" else "JLinkExe",
UPLOADERFLAGS=[
"-device", env.BoardConfig().get("debug", {}).get("jlink_device"),
"-speed", "4000",
"-if", ("jtag" if upload_protoc... | build_dir = env.subst("$BUILD_DIR")
if not isdir(build_dir):
makedirs(build_dir)
script_path = join(build_dir, "upload.jlink")
commands = [
"h",
"loadbin %s, %s" % (source, env.BoardConfig().get(
"upload.offset_address", "0x0")),
... | identifier_body |
main.py | os.path import isdir, join, isfile
from SCons.Script import (COMMAND_LINE_TARGETS, AlwaysBuild, Builder, Default,
DefaultEnvironment)
env = DefaultEnvironment()
platform = env.PioPlatform()
#overides the default upload.maximum_size value which is used to calculate how much of the m... |
env.Append(
BUILDERS=dict(
ElfToBin=Builder(
action=env.VerboseAction(" ".join([
"$OBJCOPY",
"-O",
"binary",
"$SOURCES",
"$TARGET"
]), "Bin Output -> $TARGET"),
suffix=".bin"
... | env.Replace(PROGNAME="firmware") | conditional_block |
wxController.go | ,
"code": sCode,
"grant_type": "authorization_code",
}
reqUrl := utils.BuildUrl(WxAuthUrl, params)
respData := utils.ReqGet(reqUrl, 10*time.Second)
result := make(map[string]string)
var ok bool
json.Unmarshal(respData, &result)
if _, exist := result["access_token"]; exist {
ok = true
} else {
ok =... | dxMap := woiIdx.(map[string]beans.WxOpenId)
var wxOpenId beans.WxOpenId
wxOpenId, bind = woiIdxMap[openId]
if bind {
userId := wxOpenId.UserId
uic, _ := ramcache.UserIdCard.Load(service.platform)
uicMap := uic.(map[int]beans.UserProfile)
userProfile := uicMap[userId]
userBean = xorm.Users{
Id: use... | form)
woiI | identifier_name |
wxController.go | Secret,
"code": sCode,
"grant_type": "authorization_code",
}
reqUrl := utils.BuildUrl(WxAuthUrl, params)
respData := utils.ReqGet(reqUrl, 10*time.Second)
result := make(map[string]string)
var ok bool
json.Unmarshal(respData, &result)
if _, exist := result["access_token"]; exist {
ok = true
} else {
... | Bean)
now := utils.GetNowTime()
var userUpdateBean = xorm.Users{
Token: token,
TokenCreated: now,
LastLoginTime: now,
}
var respUserBean xorm.Users
//开始事务
session := service.engine.NewSession()
err := session.Begin()
defer session.Close()
_, err = session.ID(userBean.Id).Update(userUpdateBean)
... | wxOpenId beans.WxOpenId
wxOpenId, bind = woiIdxMap[openId]
if bind {
userId := wxOpenId.UserId
uic, _ := ramcache.UserIdCard.Load(service.platform)
uicMap := uic.(map[int]beans.UserProfile)
userProfile := uicMap[userId]
userBean = xorm.Users{
Id: userId,
Phone: userProfile.Phone,
UserName:... | identifier_body |
wxController.go | Secret,
"code": sCode,
"grant_type": "authorization_code",
}
reqUrl := utils.BuildUrl(WxAuthUrl, params)
respData := utils.ReqGet(reqUrl, 10*time.Second)
result := make(map[string]string)
var ok bool
json.Unmarshal(respData, &result)
if _, exist := result["access_token"]; exist {
ok = true
} else {
... | rId: iUserId, Ip: service.ip, LoginTime: iNow, LoginFrom: service.loginFrom}
_, createErr = session.InsertOne(loginLog)
if createErr != nil {
session.Rollback()
//utils.ResFaiJSON(&ctx, createErr.Error(), "绑定微信失败", config.NOTGETDATA)
return userBean, createErr
}
err := services.PromotionAward(service.platfor... | Bean, createErr
}
loginLog := xorm.UserLoginLogs{Use | conditional_block |
wxController.go | Secret,
"code": sCode,
"grant_type": "authorization_code",
}
reqUrl := utils.BuildUrl(WxAuthUrl, params)
respData := utils.ReqGet(reqUrl, 10*time.Second)
result := make(map[string]string)
var ok bool
json.Unmarshal(respData, &result)
if _, exist := result["access_token"]; exist {
ok = true
} else {
... | utMap := ut.(map[string][]string)
sUserId := strconv.Itoa(iUserId)
utMap[userBean.UserName] = []string{sUserId, token, sTokenTime, "1"}
utils.UpdateUserIdCard(service.platform, iUserId, map[string]interface{}{
"Username": userBean.UserName,
"Token": userBean.Token,
"TokenCreated": sTokenTime, // 注意... | random_line_split | |
redcap2mysql.py | 100'})
if os.path.isfile(config_file) == True:
config.read(config_file)
else:
print("Can't find config file: " + config_file)
exit(1)
# --------------------------
# Parse configuration object
# --------------------------
data_path = config.get('global', 'data_path', 0)
log_timestamp_format = config.get('... | hash_file | identifier_name | |
redcap2mysql.py | 2mysql.cfg.example
# Configure parameters with defaults. Use a config file for most of these.
config = ConfigParser.SafeConfigParser(
{'data_path': 'data', 'log_file': 'redcap2mysql.log',
'log_timestamp_format': '%Y-%m-%d %H:%M:%S %Z',
'mysql_dsn': '', 'mysql_pwd': '', 'mysql_host': '',
'mysql_por... |
else:
print("Can't find config file: " + config_file)
exit(1)
# --------------------------
# Parse configuration object
# --------------------------
data_path = config.get('global', 'data_path', 0)
log_timestamp_format = config.get('global', 'log_timestamp_format', 0)
log_file = config.get('global', 'log_fil... | config.read(config_file) | conditional_block |
redcap2mysql.py | #
# For use with ODBC database connections, you will also want to install pyodbc:
#
# python -m pip install pyodbc
#
# Or, alternatively, for use with the MySQL Connector driver written in Python:
#
# python -m pip install mysql-connector
#
# On Windows, you will also need Microsoft Visual C++ Compiler for Python 2.7.
... | # python -m pip install gitpython
# python -m pip install git+https://github.com/alorenzo175/mylogin.git#egg=mylogin
# python -m pip install certifi | random_line_split | |
redcap2mysql.py | 2mysql.cfg.example
# Configure parameters with defaults. Use a config file for most of these.
config = ConfigParser.SafeConfigParser(
{'data_path': 'data', 'log_file': 'redcap2mysql.log',
'log_timestamp_format': '%Y-%m-%d %H:%M:%S %Z',
'mysql_dsn': '', 'mysql_pwd': '', 'mysql_host': '',
'mysql_por... |
return(prev_hash)
def parse_csv(csv_file):
"""Parse a CSV file with Pandas, with basic checks and error handling."""
if os.path.isfile(csv_file) == True:
num_lines = sum(1 for line in open(csv_file))
if num_lines > | """Get the sha1 hash of the previously uploaded data for a table."""
# See if the database contains the log_table (REDCap transfer log) table.
rs = sql.execute('SHOW TABLES LIKE "' + log_table + '";', conn)
row0 = rs.fetchone()
res = ''
if (row0 is not None) and (len(row0) != 0):
res = row0... | identifier_body |
messagecard.go | // Title is the title property of a section. This property is displayed
// in a font that stands out, while not as prominent as the card's title.
// It is meant to introduce the section and summarize its content,
// similarly to how the card's title property is meant to summarize the
// whole card.
Title string `j... | if s == nil {
return fmt.Errorf("func AddSection: nil MessageCardSection received")
}
// Perform validation of all MessageCardSection fields in an effort to
// avoid adding a MessageCardSection with zero value fields. This is
// done to avoid generating an empty sections JSON array since the
// Sections... | func (mc *MessageCard) AddSection(section ...*MessageCardSection) error {
for _, s := range section {
// bail if a completely nil section provided | random_line_split |
messagecard.go | Title is the title property of a section. This property is displayed
// in a font that stands out, while not as prominent as the card's title.
// It is meant to introduce the section and summarize its content,
// similarly to how the card's title property is meant to summarize the
// whole card.
Title string `jso... | (fact ...MessageCardSectionFact) error {
for _, f := range fact {
if f.Name == "" {
return fmt.Errorf("empty Name field received for new fact: %+v", f)
}
if f.Value == "" {
return fmt.Errorf("empty Name field received for new fact: %+v", f)
}
}
mcs.Facts = append(mcs.Facts, fact...)
return nil
}
/... | AddFact | identifier_name |
messagecard.go | Title is the title property of a section. This property is displayed
// in a font that stands out, while not as prominent as the card's title.
// It is meant to introduce the section and summarize its content,
// similarly to how the card's title property is meant to summarize the
// whole card.
Title string `jso... |
// AddFactFromKeyValue accepts a key and slice of values and converts them to
// MessageCardSectionFact values
func (mcs *MessageCardSection) AddFactFromKeyValue(key string, values ...string) error {
// validate arguments
if key == "" {
return errors.New("empty key received for new fact")
}
if len(values) < 1... | {
for _, f := range fact {
if f.Name == "" {
return fmt.Errorf("empty Name field received for new fact: %+v", f)
}
if f.Value == "" {
return fmt.Errorf("empty Name field received for new fact: %+v", f)
}
}
mcs.Facts = append(mcs.Facts, fact...)
return nil
} | identifier_body |
messagecard.go | // ActivitySubtitle is a property used to show brief, but extended
// information about an activity associated with a message card. Examples
// include the date and time the associated activity was taken or the
// handle of a person associated with the activity.
ActivitySubtitle string `json:"activitySubtitle,omite... | {
return fmt.Errorf("cannot add empty hero image URL")
} | conditional_block | |
timer.rs | fn from(v: c_int) -> Signal {
Signal(v)
}
}
/// When instantiating a Timer, it needs to have an event type associated with
/// it to be fired whenever the timer expires. Most of the time this will be a
/// `Signal`. Sometimes we need to be able to send signals to specific threads.
pub enum TimerEvent {
... | (v: libc::timespec) -> Option<Duration> {
if v.tv_sec == 0 && v.tv_nsec == 0 {
None
} else {
Some(Duration::new(v.tv_sec as u64, v.tv_nsec as u32))
}
}
impl TimerSpec {
// Helpers to convert between TimerSpec and libc::itimerspec
fn to_itimerspec(&self) -> libc::itimerspec {
... | timespec_to_opt_duration | identifier_name |
timer.rs | fn from(v: c_int) -> Signal {
Signal(v)
}
}
/// When instantiating a Timer, it needs to have an event type associated with
/// it to be fired whenever the timer expires. Most of the time this will be a
/// `Signal`. Sometimes we need to be able to send signals to specific threads.
pub enum TimerEvent {
... |
TimerEvent::ThreadSignal(tid, signo) => {
ev.sigev_signo = signo.0;
ev.sigev_notify = libc::SIGEV_THREAD_ID;
ev.sigev_notify_thread_id = tid.0;
}
TimerEvent::ThisThreadSignal(signo) => {
ev.sigev_signo = signo.0;
... | {
ev.sigev_signo = signo.0;
ev.sigev_notify = libc::SIGEV_SIGNAL;
} | conditional_block |
timer.rs | fn from(v: c_int) -> Signal {
Signal(v)
}
}
/// When instantiating a Timer, it needs to have an event type associated with
/// it to be fired whenever the timer expires. Most of the time this will be a
/// `Signal`. Sometimes we need to be able to send signals to specific threads.
pub enum TimerEvent {
... | },
}
}
fn timespec_to_opt_duration(v: libc::timespec) -> Option<Duration> {
if v.tv_sec == 0 && v.tv_nsec == 0 {
None
} else {
Some(Duration::new(v.tv_sec as u64, v.tv_nsec as u32))
}
}
impl TimerSpec {
// Helpers to convert between TimerSpec and libc::itimerspec
fn to_... | Some(value) => libc::timespec {
tv_sec: value.as_secs() as i64,
tv_nsec: value.subsec_nanos() as i64, | random_line_split |
Main.go |
}
err = TemplateSaveFile(ORACLEBAKPATHTL, ORACLEBAKPATH, oracledir)
if err != nil {
logger.Println("生成oracledir.bat 失败" + err.Error())
}
var oracledatatmp []string = strings.Split(info.OracleURL, "@")
if oracledatatmp == nil || len(oracledatatmp) < 2 {
logger.Println("读取oracle配置信息失败")
}
oracleddata :... | string{
"Dir": dir,
"OracleBakPath": OracleBakPath, | conditional_block | |
Main.go | )
//err = compress7zip(hashFilePath, ziptargetPath)
//
//if err != nil {
// return err
//}
return nil
}
//
//func copyFile(basePath, targetPath string) {
// defer func() {
// if err_p := recover(); err_p != nil {
// logger.Println("copyFile模块出错")
// }
// }()
//
// baseStat, err := os.Stat(basePath)
// if er... | path string, | identifier_name | |
Main.go |
//
//if err != nil {
// return err
//}
for _, value := range backinfo.BackPath {
////var targetPath = ""
//filepath.Walk(value, func(path string, f os.FileInfo, err error) error {
//
var err = xcopy(value, backinfo.TargetPath+"/"+lasttime+"/", time)
if err != nil {
return err
}
logger.Println(... | //调用7zip压缩
func compress7zip(frm, dst string) error {
cmd := exec.Command("7z/7z.exe", "a", "-mx=1", "-v5g", dst, frm) | random_line_split | |
Main.go | err
}
}
err = ex | //retur
n err
}
xcplasttime = "01-02-2006"
}
if err := tarpath(info, lasttime, xcplasttime); err != nil {
logger.Println("复制文件失败" + err.Error())
}
if err := zipfiles(info.TargetPath, lasttime); err != nil {
logger.Println("压缩文件失败" + err.Error())
}
var remoteSavePath = lastmoth + "^" + strings.Replac... | ecu(ORACLEBAKBATPATH)
if err != nil {
logger.Println("运行文件失败" + ORACLEBAKBATPATH + err.Error())
return err
}
return nil
}
func BakFiles(info Backinfo) error {
var xcplasttime = time.Now().AddDate(0, 0, -1).Format("01-02-2006")
var lasttime = time.Now().Format("2006-01-02")
var lastmoth = time.Now().Forma... | identifier_body |
spatial_ornstein_uhlenbeck.py | = "%prog -o ./simulation_results",
description = "This script simulates microbiome " +
"change over time using Ornstein-Uhlenbeck (OU) models. These are " +
"similar to Brownian motion models, with the exception that they " +
"include reversion to a mean. Output is a tab-delimited data table " +
"... |
elif header_lowercase in ("value", "values", "val", "vals"):
required_headers_checker["values"] = True
values = str(row[header]).split(",")
elif header_lowercase in ("update_mode", "update_modes",\
"update mode", "update modes"):
... | df = pd.read_csv(pert_file_path, sep = "\t")
headers_list = list(df)
for index, row in df.iterrows():
a_perturbation = {"start":perturbation_timepoint,\
"end":perturbation_timepoint + perturbation_duration}
required_headers_checker = {"params" : False, "values" : ... | conditional_block |
spatial_ornstein_uhlenbeck.py | = "%prog -o ./simulation_results",
description = "This script simulates microbiome " +
"change over time using Ornstein-Uhlenbeck (OU) models. These are " +
"similar to Brownian motion models, with the exception that they " +
"include reversion to a mean. Output is a tab-delimited data table " +
"... |
def ensure_exists(output_dir):
"""
Ensure that output_dir exists
:param output_dir: path to output directory
"""
try:
makedirs(output_dir)
except OSError:
if not isdir(output_dir):
raise
def write_options_to_log(log, opts):
"""
Writes user's input option... | """
Raise ValueError if perturbation_timepoint is < 0 or >n_timepoints
:param perturbation_timepoint: defined timepoint for perturbation application
:param n_timepoints: number of timepoints
"""
if perturbation_timepoint and perturbation_timepoint >= n_timepoints:
raise ValueError("Perturb... | identifier_body |
spatial_ornstein_uhlenbeck.py | = "%prog -o ./simulation_results",
description = "This script simulates microbiome " +
"change over time using Ornstein-Uhlenbeck (OU) models. These are " +
"similar to Brownian motion models, with the exception that they " +
"include reversion to a mean. Output is a tab-delimited data table " +
"... | (log, opts):
"""
Writes user's input options to log file
:param log: log filename
:param opts: options
"""
logfile = open(join(opts.output, log),"w+")
logfile_header = "#Karenina Simulation Logfile\n"
logfile.write(logfile_header)
logfile.write("Output folder: %s\n" %(str(opts.ou... | write_options_to_log | identifier_name |
spatial_ornstein_uhlenbeck.py | : %default]')
optional_options.add_option('--treatment_names',\
default="control,destabilizing_treatment",type="string",\
help="Comma seperated list of treatment named [default:%default]")
optional_options.add_option('-n','--n_individuals',\
default="35,35",type="string",\
help='Comma-separate... | #Set up the treatments to be applied
| random_line_split | |
config_unix.go | up waiting after this time).
// TODO: Rename with "gcp_" removed.
XMPPPingTimeout string `json:"gcp_xmpp_ping_timeout,omitempty"`
// XMPP ping interval (time between ping attempts).
// TODO: Rename with "gcp_" removed.
// TODO: Rename with "_default" removed.
XMPPPingInterval string `json:"gcp_xmpp_ping_interva... | (configMap map[string]interface{}) *Config {
b := *c.commonBackfill(configMap)
if _, exists := configMap["log_file_name"]; !exists {
b.LogFileName = DefaultConfig.LogFileName
}
if _, exists := configMap["log_file_max_megabytes"]; !exists {
b.LogFileMaxMegabytes = DefaultConfig.LogFileMaxMegabytes
}
if _, exi... | Backfill | identifier_name |
config_unix.go | CloudPrintingEnable bool `json:"cloud_printing_enable"`
// Associated with root account. XMPP credential.
XMPPJID string `json:"xmpp_jid,omitempty"`
// Associated with robot account. Used for acquiring OAuth access tokens.
RobotRefreshToken string `json:"robot_refresh_token,omitempty"`
// Associated with user ... | LocalPrintingEnable bool `json:"local_printing_enable"`
// Enable cloud discovery and printing. | random_line_split | |
config_unix.go | up waiting after this time).
// TODO: Rename with "gcp_" removed.
XMPPPingTimeout string `json:"gcp_xmpp_ping_timeout,omitempty"`
// XMPP ping interval (time between ping attempts).
// TODO: Rename with "gcp_" removed.
// TODO: Rename with "_default" removed.
XMPPPingInterval string `json:"gcp_xmpp_ping_interva... |
if xdgCF, err := xdg.Config.Find(cf); err == nil {
// File exists in an XDG directory.
return xdgCF, true
}
// Default to relative path. This is probably what the user expects if
// it wasn't found anywhere else.
return absCF, false
}
// Backfill returns a copy of this config with all missing keys set to d... | {
// File exists on relative path.
return absCF, true
} | conditional_block |
config_unix.go | range, high.
LocalPortHigh uint16 `json:"local_port_high,omitempty"`
// CUPS only: Where to place log file.
LogFileName string `json:"log_file_name"`
// CUPS only: Maximum log file size.
LogFileMaxMegabytes uint `json:"log_file_max_megabytes,omitempty"`
// CUPS only: Maximum log file quantity.
LogMaxFiles ui... | {
s := *c.commonSparse(context)
if !context.IsSet("log-file-max-megabytes") &&
s.LogFileMaxMegabytes == DefaultConfig.LogFileMaxMegabytes {
s.LogFileMaxMegabytes = 0
}
if !context.IsSet("log-max-files") &&
s.LogMaxFiles == DefaultConfig.LogMaxFiles {
s.LogMaxFiles = 0
}
if !context.IsSet("log-to-journal"... | identifier_body | |
ias_proxy_server.rs | = "isvEnclaveQuote")]
isv_enclave_quote: String,
#[serde(rename = "pseManifest")]
pse_manifest: String,
nonce: String,
}
/// ClientResponse decoded information stored in cache
#[derive(Debug, Clone)]
struct IasResponse {
body_string: String,
header_map: HeaderMap,
}
lazy_static! {
static ... | // Cache is present, it can be sent
Some(cache_present) => Ok(cache_present.clone()),
// Cache is not presnet, request from IAS and add to cache
None => {
let result = ias_client_obj.post_verify_attestation(
quote.as_bytes(),
Option::from(json_... | .lock()
.expect("Error acquiring AVR cache lock");
let cached_avr = attestation_cache_lock.get("e);
let avr = match cached_avr { | random_line_split |
ias_proxy_server.rs | send_response(StatusCode::NOT_FOUND, None, None),
}
}
/// Handle get request from the proxy, this should only be valid for getting signature revocation
/// list. Proxy server doesn't support other GET requests. See ```response_to_request()``` for
/// detailed description.
fn handle_get_request(req: &Request<Body>... | test_erraneous_ias_response_from_client_response | identifier_name | |
ias_proxy_server.rs | // Construct socket address, panics if binding fails
let socket_addr: SocketAddr = match SocketAddr::from_str(&path) {
Ok(address_bind_successful) => address_bind_successful,
Err(err) => panic!("Error binding the address: {}", err),
};
info!("Socket binding successful");... | {
// Start conversion, need to parse client_resposne
match client_response {
Ok(successful_response) => {
// If there's successful response, then read body to string
let body_string_result = client_utils::read_body_as_string(successful_response.body);
// If reading b... | identifier_body | |
mod.rs | FillBlack,
}
#[derive(Error,Debug,PartialEq)]
pub enum CrosswordError {
#[error("Adjacent cells {0:?} {1:?} incompatible - no word found that links them.")]
AdjacentCellsNoLinkWord(Location, Location),
#[error("Adjacent cells {0:?} {1:?} incompatible - should have a shared word which links them, but t... |
#[error("Attempted to fill a cell already marked as black")] | random_line_split | |
mod.rs | acentCellsMismatchedLinkWord(Location, Location, usize, usize),
#[error("Error updating cell at location {0:?}")]
CellError(Location, CellError),
#[error("Cell {0:?} at start/end of word not empty. Last/first cell in word is {1:?}")]
NonEmptyWordBoundary(Location, Location),
#[error("Cell not fou... | Graph {
let edges = self.get_all_intersections();
let mut graph = Graph::new_from_edges(edges);
for (word_id, _word) in self.word_map.iter().filter(|(_id, w)| w.is_placed()) {
graph.add_node(*word_id);
}
graph
}
pub fn to_string_with_coords(&self) -> String ... | elf) -> | identifier_name |
mod.rs | , other: &Location) -> bool {
self.0 == other.0 && self.1 == other.1
}
}
impl Location {
fn relative_location(&self, move_across: isize, move_down: isize) -> Location {
Location(self.0 + move_across, self.1 + move_down)
}
fn relative_location_directed(&self, move_size: isize, direction... | elf.unplace_word(word_id);
self.word_map.remove(&word_id);
}
pub f | identifier_body | |
parser.js | { traverse } from './traverse';
export var mdxProcessor = unified()
.use(remarkParse)
.use(remarkMdx)
.freeze();
export var AST_PROPS = ['body', 'comments', 'tokens'];
export var ES_NODE_TYPES = ['export', 'import', 'jsx'];
export var LOC_ERROR_PROPERTIES = ['column', 'index', 'lineNumber'];
export var DEF... |
Parser.prototype.normalizeJsxNode = function (node, parent, options) {
if (options === void 0) { options = this._options; }
var value = node.value;
if (node.type !== 'jsx' || isComment(value)) {
return node;
}
var commentContent = COMMENT_CONTENT_REGEX.exec(value... | {
// @internal
this._options = DEFAULT_PARSER_OPTIONS;
this.parse = this.parse.bind(this);
this.parseForESLint = this.parseForESLint.bind(this);
} | identifier_body |
parser.js | import { traverse } from './traverse';
export var mdxProcessor = unified()
.use(remarkParse)
.use(remarkMdx)
.freeze();
export var AST_PROPS = ['body', 'comments', 'tokens'];
export var ES_NODE_TYPES = ['export', 'import', 'jsx'];
export var LOC_ERROR_PROPERTIES = ['column', 'index', 'lineNumber'];
export v... | if (node.data && node.data.jsxType === 'JSXElementWithHTMLComments') {
this._services.JSXElementsWithHTMLComments.push(node);
}
var value = node.value;
// fix #4
if (isComment(value)) {
return;
}
var _a = normalizePosition(node.position), l... | var _this = this; | random_line_split |
parser.js | { traverse } from './traverse';
export var mdxProcessor = unified()
.use(remarkParse)
.use(remarkMdx)
.freeze();
export var AST_PROPS = ['body', 'comments', 'tokens'];
export var ES_NODE_TYPES = ['export', 'import', 'jsx'];
export var LOC_ERROR_PROPERTIES = ['column', 'index', 'lineNumber'];
export var DEF... | () {
// @internal
this._options = DEFAULT_PARSER_OPTIONS;
this.parse = this.parse.bind(this);
this.parseForESLint = this.parseForESLint.bind(this);
}
Parser.prototype.normalizeJsxNode = function (node, parent, options) {
if (options === void 0) { options = this._options; ... | Parser | identifier_name |
parser.js | { traverse } from './traverse';
export var mdxProcessor = unified()
.use(remarkParse)
.use(remarkMdx)
.freeze();
export var AST_PROPS = ['body', 'comments', 'tokens'];
export var ES_NODE_TYPES = ['export', 'import', 'jsx'];
export var LOC_ERROR_PROPERTIES = ['column', 'index', 'lineNumber'];
export var DEF... |
/* istanbul ignore else */
if (options.filePath && this._options !== options) {
Object.assign(this._options, options);
}
var program;
var parseError;
for (var _i = 0, _a = this._parsers; _i < _a.length; _i++) {
var parser_1 = _a[_i];
t... | {
this._parsers = normalizeParser(options.parser);
} | conditional_block |
ccp_project.py | and its returns
def optimization(print_date, start_date, end_date, freq,
X_macro, Y_assets, target_vol, periods, granularity, method,
thresholds, reduce_indic, rescale_vol, momentum_weighting):
# dates at which we optimize the portfolio
optimization_dates = pd.date_range(start=st... |
def period_names_list(periods):
"""Returns a list using function period_name."""
return [period_name(period) for period in periods]
#%%
#==============================================================================
# PARAMETRIZATION OF THE OPTIMIZATION
#=========================================... | """Returns a string in the form '1980 - 1989'."""
year_start = period[0][:4]
year_end = period[1][:4]
return year_start + " - " + year_end | identifier_body |
ccp_project.py | ON THE OPTIMIZATION DATES
for date in optimization_dates:
# displays the date to show where we are in the optimization
if print_date == True:
print date
# date t-1, on which we do the optimization
date_shifted = pd.DatetimeIndex(start=date, end=date, freq... | print(indicator)
strategy_results = []
params['X_macro'] = pd.DataFrame(X_macro[indicator])
for j, period in enumerate(optimization_periods):
params['start_date'], params['end_date'] = period
strategy_results.append(optimization(**params))
mydict[indic... | conditional_block | |
ccp_project.py | and its returns
def optimization(print_date, start_date, end_date, freq,
X_macro, Y_assets, target_vol, periods, granularity, method,
thresholds, reduce_indic, rescale_vol, momentum_weighting):
# dates at which we optimize the portfolio
optimization_dates = pd.date_range(start=st... | # center on 0
#momentum_scores = [a - np.average(momentum_scores) for a in momentum_scores]
momentum_weights = momentum_weighting * np.array(momentum_scores) + (1 - momentum_weighting) * momentum_weights
scaled_weights = np.dot(momentum_weig... | random_line_split | |
ccp_project.py | its returns
def optimization(print_date, start_date, end_date, freq,
X_macro, Y_assets, target_vol, periods, granularity, method,
thresholds, reduce_indic, rescale_vol, momentum_weighting):
# dates at which we optimize the portfolio
optimization_dates = pd.date_range(start=start_... | (optimization_periods, strategy_results, Y_assets, indicator='Sharpe Ratio'):
# histograms for analysis
my_df = strategy_analysis(optimization_periods, strategy_results, Y_assets, freq)
my_df.sort_index(axis=1).loc(axis=1) | histogram_analysis | identifier_name |
index.js | 1 > max) {
console.log(
`\nLiar, liar pants on fire! You said the number was lower than ${
max + 1
}, so it can't also be higher than ${guess}...\n`
);
return true;
}
}
if (modifyRange === "l" || modifyRange === "lower") {
/... | (min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
//intros the game
console.log(
"Let's play a game where I (computer) pick a number between 1 and 100, and you (human) try to guess it."
);
//declares wantToPlay variable to allow users to play multiple times
let wantToPlay = ... | chooseRandomNumber | identifier_name |
index.js | > max) {
console.log(
`\nLiar, liar pants on fire! You said the number was lower than ${
max + 1
}, so it can't also be higher than ${guess}...\n`
);
return true;
}
}
if (modifyRange === "l" || modifyRange === "lower") {
//... |
}
return false;
}
}
//intros the game
console.log(
"Let's play a game where you (human) pick a number between 1 and a maximum, and I (computer) try to guess it."
);
//declares wantToPlay variable to allow users to play multiple times
let wantToPlay = "y";
//while wantToPlay is yes ... | {
console.log(
`\nCheater, cheater pumpkin eater! You said the number was higher than ${
min - 1
}, so it can't also be lower than ${guess}!\n`
);
return true;
} | conditional_block |
index.js | 1 > max) {
console.log(
`\nLiar, liar pants on fire! You said the number was lower than ${
max + 1
}, so it can't also be higher than ${guess}...\n`
);
return true;
}
}
if (modifyRange === "l" || modifyRange === "lower") {
/... | //sanitizes wantToPlay
wantToPlay = wantToPlay.trim().toLowerCase();
//if the user does not want to play again the game exits
if (wantToPlay === "n" || wantToPlay === "no") {
console.log("\nGoodbye, thanks for playing!");
process.exit();
}
}
//if... | random_line_split | |
index.js |
//cheat detector function that will return true if there is an issue with the response based on known range (true ==> lying, false ==> not lying)
function cheatDetector(min, max, guess, secretNumber, modifyRange) {
//if the computer's guess is the secret number but the user has said no, the computer calls the... | {
return min + Math.floor((max - min) / 2);
} | identifier_body | |
codec.rs | (value: u64) -> usize {
struct NullWrite {};
impl std::io::Write for NullWrite {
fn write(&mut self, buf: &[u8]) -> std::result::Result<usize, std::io::Error> {
Ok(buf.len())
}
fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
Ok(())
}
}... | encoded_length | identifier_name | |
codec.rs |
// the header portion to go out in a single packet)
let mut buffer = Vec::with_capacity(len + encoded_length(masked_len));
leb128::write::unsigned(&mut buffer, masked_len)?;
leb128::write::unsigned(&mut buffer, serial)?;
leb128::write::unsigned(&mut buffer, ident)?;
buffer.extend_from_slice(da... | pub serial: u64,
pub pdu: Pdu,
}
/// If the serialized size is larger than this, then we'll consider compressing it
const COMPRESS_THRESH: usize = 32;
fn serialize<T: serde::Serialize>(t: &T) -> Result<(Vec<u8>, bool), Error> {
let mut uncompressed = Vec::new();
let mut encode = varbincode::Serializer... | #[derive(Debug, PartialEq)]
pub struct DecodedPdu { | random_line_split |
macro.rs | al, Zero, One};
type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("docopt", expand);
}
fn expand(cx: &mut ExtCtxt, span: codemap::Span, tts: &[tokenstream::TokenTree])
-> Box<MacResult+'static> {
let parsed = ... | let public = self.p.eat_keyword(symbol:: | random_line_split | |
macro.rs | let struct_name = self.struct_info.name;
let full_doc = &*self.doc.parser().full_doc;
its.push(quote_item!(cx,
impl $struct_name {
#[allow(dead_code)]
fn docopt() -> docopt::Docopt {
// The unwrap is justified here because this code... | {
let sp = codemap::DUMMY_SP;
let its = items.into_iter().map(|s| meta_item(cx, s.borrow())).collect();
let mi = cx.meta_list(sp, intern(name.borrow()), its);
cx.attribute(sp, mi)
} | identifier_body | |
macro.rs | , Zero, One};
type PResult<'a, T> = Result<T, DiagnosticBuilder<'a>>;
#[plugin_registrar]
pub fn plugin_registrar(reg: &mut Registry) {
reg.register_macro("docopt", expand);
}
fn expand(cx: &mut ExtCtxt, span: codemap::Span, tts: &[tokenstream::TokenTree])
-> Box<MacResult+'static> {
let parsed = ma... | (&self, cx: &ExtCtxt) -> Vec<ast::StructField> {
let mut fields: Vec<ast::StructField> = vec!();
for (atom, opts) in self.doc.parser().descs.iter() {
let name = ArgvMap::key_to_struct_field(&*atom.to_string());
let ty = match self.types.get(atom) {
None => self.pa... | struct_fields | identifier_name |
program.py | spy, Spy, friends, ChatMessage
# Importing steganography module
from steganography.steganography import Steganography
# List of status messages
STATUS_MESSAGES = ['Having Fun', 'Sunny Day', "Busy",
"Feeling Lazy", "Damm it it feels good to be a gangster", "Message only"]
print("Hel... |
return len(friends)
#Function to select a friend
def select_a_friend():
item_number = 0
for friend in friends:
print ('%d. %s %s aged %d with rating %.2f is online' % (item_number + 1, friend.salutation, friend.name, friend.age, friend.rating))
item_numb... | print("Sorry, the friend cannot be a spy!") | conditional_block |
program.py | , Spy, friends, ChatMessage
# Importing steganography module
from steganography.steganography import Steganography
# List of status messages
STATUS_MESSAGES = ['Having Fun', 'Sunny Day', "Busy",
"Feeling Lazy", "Damm it it feels good to be a gangster", "Message only"]
print("Hello!"... | ():
item_number = 0
for friend in friends:
print ('%d. %s %s aged %d with rating %.2f is online' % (item_number + 1, friend.salutation, friend.name, friend.age, friend.rating))
item_number = item_number + 1
friend_choice = raw_input("Choose the index of the frien... | select_a_friend | identifier_name |
program.py | , Spy, friends, ChatMessage
# Importing steganography module
from steganography.steganography import Steganography
# List of status messages
STATUS_MESSAGES = ['Having Fun', 'Sunny Day', "Busy",
"Feeling Lazy", "Damm it it feels good to be a gangster", "Message only"]
print("Hello!"... | else:
print ("Enter a valid spy rating")
else:
if spy.age <= 12:
print("Sorry, you are too young to become a spy!")
elif spy.ag... |
start_chat(spy)
| random_line_split |
program.py | , Spy, friends, ChatMessage
# Importing steganography module
from steganography.steganography import Steganography
# List of status messages
STATUS_MESSAGES = ['Having Fun', 'Sunny Day', "Busy",
"Feeling Lazy", "Damm it it feels good to be a gangster", "Message only"]
print("Hello!"... | return friend_choice_position
#Function to send a message
def send_a_message():
friend_choice = select_a_friend()
original_image = raw_input("What is the name of the image?: ")
output_path = "output.jpg"
text = raw_input("What do you want to say? ")
... | item_number = 0
for friend in friends:
print ('%d. %s %s aged %d with rating %.2f is online' % (item_number + 1, friend.salutation, friend.name, friend.age, friend.rating))
item_number = item_number + 1
friend_choice = raw_input("Choose the index of the friend: ")
... | identifier_body |
scr.py | .pfile.parse_pfile(case=[1,100])
Ex: Sync and set the run to have a timestep of 0.01 sec.
scr.pfile.sync(case=[1,100], tstep=0.01)
Ex: Sync and set the run to have an auto time step, defaults to 0.01 sec.
scr.pfile.sync(case=76, auto='yes')
Ex: Sync and set ... | if dof in self.ltm.acron_dofs:
i_dof = self.ltm.acron_dofs.index(dof)
elif dof in self.ltm.dofs:
i_dof = self.ltm.dofs.index(dof)
| random_line_split | |
scr.py |
def load_ltm(self, **kwargs):
"""Method to load the LTM into the analysis.
Ex: scr.load_ltm(ltm='xp93zz_scr.pch)"""
ltm = kwargs['ltm']
self.ltm = LTM(ltm)
self.ltm.label_ltm(self.hwlist)
def load_eig(self, **kwargs):
"""Method to load the eigenv... | """Method to load the Hardware List (HWLIST) into the analysis.
Ex: scr.load_hwlist(hwlist='xp_hwlist.xls')
"""
hwlist = kwargs['hwlist']
self.hwlist = HWLIST(hwlist) | identifier_body | |
scr.py | some threshold.
Ex: scr.load_pfile(pfile='ff_xp93s1sp0001.dat', filetype=['pfile' or 'matfile'])
Ex: Parse the text data into numbers.
scr.pfile.parse_pfile(case=[1,100])
Ex: Sync and set the run to have a timestep of 0.01 sec.
scr.pfile.sync(case=[1,100], ... |
else:
desc = ''
# Loop and plot each requested dof.
fig = figure()
ax = subplot(111)
for item in items:
if item.__len__() != 3:
raise Exception('!!! You must supply (case, acron, dof) to plot !!!')
c = item[0]
... | desc = kwargs['desc'] | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.