file_name large_stringlengths 4 140 | prefix large_stringlengths 0 39k | suffix large_stringlengths 0 36.1k | middle large_stringlengths 0 29.4k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
normalizations.py | # Lint as: python3
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | (self, theta: NestedMap) -> Tuple[JTensor, JTensor]:
p = self.params
if p.use_moving_avg_in_training:
beta = 0.0
gamma = 1.0
else:
beta = theta.beta
gamma = theta.gamma + 1.0
return beta, gamma
def compute_and_update_moments(
self, theta: NestedMap, inputs: JTensor,
... | _get_beta_gamma | identifier_name |
xmp_dashboard.py | # -*- coding: UTF-8 -*-
# py_md5_xmp
# Scriptet tar en given xmp-fil och beräknar md5-summan för dess datafil.
#
# md5 summa i Adobe LR xmp-fil:
# PelleTags:PelleTag1_md5sum="935c0eb6242e80c95001368b9d53b421"
#
# Exiftool xmp-fil:
# <PelleTags:PelleTag1_md5sum>572737b08d11666255afb41b2c0443cb</PelleTags:P... | _folders = []
current_run_list = []
l3 = []
for main_folder in main_folders:
if combo_var[main_folder] == "New run":
new_run_folders.append(main_folder)
else:
if vital_stats: print("For folder " + main_folder + ": " + combo_var[main_folder])... |
new_run | identifier_name |
xmp_dashboard.py | # -*- coding: UTF-8 -*-
# py_md5_xmp
# Scriptet tar en given xmp-fil och beräknar md5-summan för dess datafil.
#
# md5 summa i Adobe LR xmp-fil:
# PelleTags:PelleTag1_md5sum="935c0eb6242e80c95001368b9d53b421"
#
# Exiftool xmp-fil:
# <PelleTags:PelleTag1_md5sum>572737b08d11666255afb41b2c0443cb</PelleTags:P... | le, '<PelleTags:PelleTag1_md5sum>'),
index_containing_substring(list_file, 'PelleTags:PelleTag1_md5sum=')]
if verbose: print(md5_index)
if any(md5_index): # xmp-filen innehåller en md5-summa.
res = [idx for idx, val in enumerate(md5_... | dex = [index_containing_substring(list_fi | conditional_block |
xmp_dashboard.py | # -*- coding: UTF-8 -*-
# py_md5_xmp
# Scriptet tar en given xmp-fil och beräknar md5-summan för dess datafil.
#
# md5 summa i Adobe LR xmp-fil:
# PelleTags:PelleTag1_md5sum="935c0eb6242e80c95001368b9d53b421"
#
# Exiftool xmp-fil:
# <PelleTags:PelleTag1_md5sum>572737b08d11666255afb41b2c0443cb</PelleTags:P... | col_8 = Label(master, relief=RIDGE, text = "Missing RAW")
col_9 = Label(master, relief=RIDGE, text = "Missing xmp")
col_10 = Label(master, relief=RIDGE, text = "Start/Restart")
# grid method to arrange labels in respective
# rows and columns as specified
col_1.grid(row = 0, col... | random_line_split | |
xmp_dashboard.py | # -*- coding: UTF-8 -*-
# py_md5_xmp
# Scriptet tar en given xmp-fil och beräknar md5-summan för dess datafil.
#
# md5 summa i Adobe LR xmp-fil:
# PelleTags:PelleTag1_md5sum="935c0eb6242e80c95001368b9d53b421"
#
# Exiftool xmp-fil:
# <PelleTags:PelleTag1_md5sum>572737b08d11666255afb41b2c0443cb</PelleTags:P... | _tracker
xmp_file_count = 0
for main_folder in main_folders:
for subdir, dirs, files in os.walk(main_folder):
for file in files:
if file[-3:] == 'xmp':
xmp_file_count += 1
xmp_tracker.append([main_folder,xmp_file_count])
if vit... | verbose
global xmp | identifier_body |
sensor_update.py | """
===============
=== Purpose ===
===============
Produces a signal for each flu digital surveillance source, which is then used
as a 'sensor' in the context of nowcasting through sensor fusion.
Each signal is updated over the following inclusive range of epiweeks:
- epiweek of most recently computed signal of th... | return AR3(location).predict(epiweek, valid=valid)
@staticmethod
def get_ghtj(location, epiweek, valid):
loc = 'US' if location == 'nat' else location
def justinfun(location, epiweek):
# Need to set an absolute path
main_driver = '/home/automation/ghtj/ghtj.R'
args = ['Rscript', main... | return ARCH(location).predict(epiweek, valid=valid)
@staticmethod
def get_ar3(location, epiweek, valid): | random_line_split |
sensor_update.py | """
===============
=== Purpose ===
===============
Produces a signal for each flu digital surveillance source, which is then used
as a 'sensor' in the context of nowcasting through sensor fusion.
Each signal is updated over the following inclusive range of epiweeks:
- epiweek of most recently computed signal of th... | (location, epiweek, valid):
fc = Epidata.check(Epidata.delphi('ec', epiweek))[0]
return fc['forecast']['data'][location]['x1']['point']
@staticmethod
def get_sar3(location, epiweek, valid):
return SAR3(location).predict(epiweek, valid=valid)
@staticmethod
def get_arch(location, epiweek, valid):
... | get_epic | identifier_name |
sensor_update.py | """
===============
=== Purpose ===
===============
Produces a signal for each flu digital surveillance source, which is then used
as a 'sensor' in the context of nowcasting through sensor fusion.
Each signal is updated over the following inclusive range of epiweeks:
- epiweek of most recently computed signal of th... |
def update_single(self, database, test_week, name, location):
train_week = flu.add_epiweeks(test_week, -1)
impl = self.implementations[name]
try:
value = impl(location, train_week, self.valid)
print(' %4s %5s %d -> %.3f' % (name, location, test_week, value))
except Exception as ex:
... | self.update_single(database, test_week, name, location) | conditional_block |
sensor_update.py | """
===============
=== Purpose ===
===============
Produces a signal for each flu digital surveillance source, which is then used
as a 'sensor' in the context of nowcasting through sensor fusion.
Each signal is updated over the following inclusive range of epiweeks:
- epiweek of most recently computed signal of th... |
def __init__(self, valid, database, implementations, epidata):
self.valid = valid
self.database = database
self.implementations = implementations
self.epidata = epidata
def update(self, sensors, first_week, last_week):
"""
Compute sensor readings and store them in the database.
"""
... | """
Return a new instance under the default configuration.
If `test_mode` is True, database changes will not be committed.
If `valid` is True, be punctilious about hiding values that were not known
at the time (e.g. run the model with preliminary ILI only). Otherwise, be
more lenient (e.g. fall ba... | identifier_body |
图像数据处理.py | 图像数据处理
使用TFRecord格式统一存储输入数据
message Example {
Features features = 1;
};
message Features {
map<string, Feature> feature = 1;
};
message Feature{
oneof kind {
ByteList bytes_list = 1;
FloatList float_list = 2;
Int64List int64_list = 3;
}
};
将数据存入TFRecord
import tensorflow as tf
from tensorflow.examples.... | ducer(['/path/to/output.tfrecords'])
#从队列中读取一个样例
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(#解析单个样例函数
serialized_example,
features={
'images_raw':tf.FixedLenFeature([],tf.string),#解析为一个tensor
'pixels':tf.FixedLenFeature([],tf.int64),
'label':t... | = tf.train.Example(features=tf.train.Feature(feature={
'pixels':_int_64_feature(pixels),
'label':_int_64_feature(np.argmax(labels[index])),
'images_raw':_bytes_features(images_raw)}
))
writer.write(example.SerializerToString())#写入TFRecord文件
writer.close()
读取TFRecord
import tensorflow ... | conditional_block |
图像数据处理.py | 图像数据处理
使用TFRecord格式统一存储输入数据
message Example {
Features features = 1;
};
message Features {
map<string, Feature> feature = 1;
};
message Feature{
oneof kind {
ByteList bytes_list = 1;
FloatList float_list = 2;
Int64List int64_list = 3;
}
};
将数据存入TFRecord
import tensorflow as tf
from tensorflow.examples.... |
sess = tf.Session()
#启动多线程处理输入数据
coord = tf.train.Coordinator(}
threads = tf.train.start_queue_runners(sess=sess, coord=coord}
#每次运行可以读取TFRecord 文件中的一个样例。当所有样例读完之后,在此样例中程序
#会再从头读取。
for i in range(10} :
print(sess.run([image, label, pixels]))
图像编码处理
import matplotlib.pyplot as plt
import tensorflow as tf
image_raw... |
image= tf.decode_raw(features[’image_raw’], tf.uint8}#将字符串tensor解析成数组
label = tf.cast(features[’label’], tf.int32}
pixels = tf.cast(features[’pixels’], tf.int32} | random_line_split |
图像数据处理.py | 图像数据处理
使用TFRecord格式统一存储输入数据
message Example {
Features features = 1;
};
message Features {
map<string, Feature> feature = 1;
};
message Feature{
oneof kind {
ByteList bytes_list = 1;
FloatList float_list = 2;
Int64List int64_list = 3;
}
};
将数据存入TFRecord
import tensorflow as tf
from tensorflow.examples.... | ))
#读取mnist数据
mnist = input_data.read_data_sets('/path', dtype=tf.uint8, one_hot=True)
images = mnist.train.images
labels = mnist.train.labels
pixels = images.shape[1]
num_examples = mnist.train.num_examples
filename = '/path/to/output.tfrecords'
#创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
... | t(value=[value] | identifier_name |
图像数据处理.py | 图像数据处理
使用TFRecord格式统一存储输入数据
message Example {
Features features = 1;
};
message Features {
map<string, Feature> feature = 1;
};
message Feature{
oneof kind {
ByteList bytes_list = 1;
FloatList float_list = 2;
Int64List int64_list = 3;
}
};
将数据存入TFRecord
import tensorflow as tf
from tensorflow.examples.... | True)
images = mnist.train.images
labels = mnist.train.labels
pixels = images.shape[1]
num_examples = mnist.train.num_examples
filename = '/path/to/output.tfrecords'
#创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
images_raw = images[index].tostring()#将每个图像转... | 据
mnist = input_data.read_data_sets('/path', dtype=tf.uint8, one_hot= | identifier_body |
functions_and_their_processes.rs | use rand::Rng;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn factorial(n: i128) -> i128 {
if n == 1 {
1
} else {
n * factorial(n - 1)
}
}
pub fn fact_iter(n: i128) -> i128 {
fn helper(p: i128, c: i128, max_count: i128) -> i128 {
if c > max_count {
p
} else {
helper(p * c, c + 1, ... | d_divisor(n: i128, test_divisor: i128) -> i128 {
if square(test_divisor) > n {
n
} else {
if devides(test_divisor, n) {
test_divisor
} else {
find_divisor(n, test_divisor + 1)
}
}
}
pub fn smallest_divisor(n: i128) -> i128 {
find_divisor(n, 2)
}
pub fn is_prime(n: i128) -> bool {
... | test_divisor == 0
}
fn fin | identifier_body |
functions_and_their_processes.rs | use rand::Rng;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn factorial(n: i128) -> i128 {
if n == 1 {
1
} else {
n * factorial(n - 1)
}
}
pub fn fact_iter(n: i128) -> i128 {
fn helper(p: i128, c: i128, max_count: i128) -> i128 {
if c > max_count {
p
} else {
helper(p * c, c + 1, ... | }
// Exercise 1.28 Miller-Rabin test
fn miller_rabin_test(n: i128, times: i128) -> bool {
fn expmod(base: i128, exp: i128, m: i128) -> i128 {
if exp == 0 {
1
} else {
if is_even(exp) {
// square after expmod, otherwise it will overflow easily
square(expmod(base, half(exp), m)) % m... | for i in 2..n {
if expmod(i, n, n) == i {
println!(" testing {}", i);
}
} | random_line_split |
functions_and_their_processes.rs | use rand::Rng;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn factorial(n: i128) -> i128 {
if n == 1 {
1
} else {
n * factorial(n - 1)
}
}
pub fn fact_iter(n: i128) -> i128 {
fn helper(p: i128, c: i128, max_count: i128) -> i128 {
if c > max_count {
p
} else {
helper(p * c, c + 1, ... | else {
ackermann(a - 1, ackermann(a, b - 1))
}
}
}
}
fn f(n: i128) -> i128 {
ackermann(0, n)
}
fn g(n: i128) -> i128 {
ackermann(1, n)
}
fn h(n: i128) -> i128 {
ackermann(2, n)
}
pub fn fac(n: i128) -> i128 {
if n == 1 {
1
} else {
n * fac(n - 1)
}
}
pub fn fib(n: i128) -> ... | {
2
} | conditional_block |
functions_and_their_processes.rs | use rand::Rng;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn factorial(n: i128) -> i128 {
if n == 1 {
1
} else {
n * factorial(n - 1)
}
}
pub fn fact_iter(n: i128) -> i128 {
fn helper(p: i128, c: i128, max_count: i128) -> i128 {
if c > max_count {
p
} else {
helper(p * c, c + 1, ... | (amount: i128, coin_kind: i8) -> i128 {
if amount == 0 {
1
} else {
if amount < 0 || coin_kind == 0 {
0
} else {
cc(amount, coin_kind - 1) + cc(amount - get_value(coin_kind), coin_kind)
}
}
}
fn get_value(coin_kind: i8) -> i128 {
match coin_kind {
6 => 100,
5 => 50,
4 =>... | cc | identifier_name |
lib.rs | #![allow(clippy::type_complexity)]
#![allow(clippy::question_mark)]
#![warn(rust_2018_idioms)]
#![warn(missing_docs)]
//! The salsa crate is a crate for incremental recomputation. It
//! permits you to define a "database" of queries with both inputs and
//! values derived from those inputs; as you set the inputs, you... | (&mut self, key: Q::Key, value: Q::Value)
where
Q::Storage: plumbing::InputQueryStorageOps<Q>,
{
self.set_with_durability(key, value, Durability::LOW);
}
/// Assign a value to an "input query", with the additional
/// promise that this value will **never change**. Must be used
/... | set | identifier_name |
lib.rs | #![allow(clippy::type_complexity)]
#![allow(clippy::question_mark)]
#![warn(rust_2018_idioms)]
#![warn(missing_docs)]
//! The salsa crate is a crate for incremental recomputation. It
//! permits you to define a "database" of queries with both inputs and
//! values derived from those inputs; as you set the inputs, you... |
/// Gives access to the underlying salsa runtime.
///
/// This method should not be overridden by `Database` implementors.
fn salsa_runtime(&self) -> &Runtime {
self.ops_salsa_runtime()
}
/// Gives access to the underlying salsa runtime.
///
/// This method should not be overri... | if pending_revision > current_revision {
runtime.unwind_cancelled();
}
} | random_line_split |
pwm.rs | use std::{
fmt::Display,
fs,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
use thiserror::Error;
use tracing::{debug, instrument};
/// Everything that can go wrong.
#[derive(Error, Debug)]
pub enum PwmError {
#[error("{0:?} not found")]
ControllerNotFound(Controller),
#[error... | if path.is_file() {
Ok(path)
} else {
Err(PwmError::ControllerNotFound(controller.clone()))
}
}
fn channel_dir(&self, controller: &Controller, channel: &Channel) -> Result<PathBuf> {
let n_pwm = self.npwm(controller)?;
if channel.0 >= n_pwm {
... | let path = self
.sysfs_root
.join(format!("pwmchip{}/{}", controller.0, fname)); | random_line_split |
pwm.rs | use std::{
fmt::Display,
fs,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
use thiserror::Error;
use tracing::{debug, instrument};
/// Everything that can go wrong.
#[derive(Error, Debug)]
pub enum PwmError {
#[error("{0:?} not found")]
ControllerNotFound(Controller),
#[error... | ormal,
Inversed,
}
impl Display for Polarity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use Polarity::*;
match *self {
Normal => write!(f, "normal"),
Inversed => write!(f, "inversed"),
}
}
}
impl FromStr for Polarity {
type Er... | {
N | identifier_name |
pwm.rs | use std::{
fmt::Display,
fs,
path::{Path, PathBuf},
str::FromStr,
time::Duration,
};
use thiserror::Error;
use tracing::{debug, instrument};
/// Everything that can go wrong.
#[derive(Error, Debug)]
pub enum PwmError {
#[error("{0:?} not found")]
ControllerNotFound(Controller),
#[error... | ve(Debug)]
pub enum Polarity {
Normal,
Inversed,
}
impl Display for Polarity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use Polarity::*;
match *self {
Normal => write!(f, "normal"),
Inversed => write!(f, "inversed"),
}
}
}
imp... | trim_end()
.parse::<u64>()
.map_err(|e| PwmError::NotADuration(s, e))
.map(Duration::from_nanos)
}
#[deri | identifier_body |
deckbuilder.py | import argparse
import parms
import pandas as pd
import textwrap
import os
import subprocess
import sys
from PIL import Image, ImageDraw, ImageFont
from fpdf import FPDF
from pathlib import Path
from Card import Card
from cust import cust_title
from cust import cust_description
FILE_EXT = parms.EXT_XLSX()
SHEETS =... | unicode_font = ImageFont.truetype("Arial.ttf")
y_text = draw_lines(draw, unicode_font, title, parms.DIM_TEXT_TOP_MARGIN())
# space between title and description
y_text += parms.DIM_TEXT_TOP_MARGIN()
# draw description
for p in str.split(description, "\p"):
for n in str.split(p, "\n"):
... | draw = ImageDraw.Draw(img)
# draw title | random_line_split |
deckbuilder.py | import argparse
import parms
import pandas as pd
import textwrap
import os
import subprocess
import sys
from PIL import Image, ImageDraw, ImageFont
from fpdf import FPDF
from pathlib import Path
from Card import Card
from cust import cust_title
from cust import cust_description
FILE_EXT = parms.EXT_XLSX()
SHEETS =... |
filename, ext = parms.FILE_SOURCE.split(".")
if ext.lower() not in (parms.EXT_XLS(), parms.EXT_XLSX(), parms.EXT_CSV()):
print("ERROR: Source file type is not supported")
return False
else:
global FILE_EXT
FILE_EXT = ext
if parms.FORMAT not in [parms.FORMAT_PDF()]:
... | print("ERROR: Source file path is invalid")
return False | conditional_block |
deckbuilder.py | import argparse
import parms
import pandas as pd
import textwrap
import os
import subprocess
import sys
from PIL import Image, ImageDraw, ImageFont
from fpdf import FPDF
from pathlib import Path
from Card import Card
from cust import cust_title
from cust import cust_description
FILE_EXT = parms.EXT_XLSX()
SHEETS =... | if sheet_path is not None:
print("Printing ...")
if sys.platform == "win32":
os.startfile(sheet_path, "print")
else:
lpr = subprocess.Popen("/usr/bin/lpr", stdin=subprocess.PIPE)
lpr.stdin.write(open(sheet_path, "rb").read())
def nvl(var, val):
if var ... | eet_path):
| identifier_name |
deckbuilder.py | import argparse
import parms
import pandas as pd
import textwrap
import os
import subprocess
import sys
from PIL import Image, ImageDraw, ImageFont
from fpdf import FPDF
from pathlib import Path
from Card import Card
from cust import cust_title
from cust import cust_description
FILE_EXT = parms.EXT_XLSX()
SHEETS =... | eet(sheet_title, deck):
main_directory = generate_sheet_directories(sheet_title)
pdf = None
if parms.FORMAT == parms.FORMAT_PDF():
pdf = FPDF()
card_paths = []
card_total_count = 0
for c in deck:
card_total_count += c.count
card_counter = 0
for i, card in enumerate(de... | g.size[0] + parms.DIM_CARD_BORDER() * 2, img.size[1] + parms.DIM_CARD_BORDER() * 2)
bordered_img = Image.new("RGB", new_size)
bordered_img.paste(img, (parms.DIM_CARD_BORDER(), parms.DIM_CARD_BORDER()))
return bordered_img
def save_sh | identifier_body |
bot.py | #!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
from telegram import InlineQueryResultPhoto, InlineQueryResultArticle, ParseMode
from telegram.ext import Updater, CommandHandler, InlineQueryHandler, MessageHandler, Filters
from telegram.utils.helpers import escape_markdown
import logging
import requests
from functool... |
def get_cat_image():
allowed_extension = ['jpg','jpeg','png']
file_extension = ''
while file_extension not in allowed_extension:
url = get_cat_url()
file_extension = re.search("([^.]*)$",url).group(1).lower()
return url
@restricted
def meow(update: 'Update', context: 'CallbackContext... | contents = requests.get('https://aws.random.cat/meow').json()
url = contents['file']
return url | identifier_body |
bot.py | #!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
from telegram import InlineQueryResultPhoto, InlineQueryResultArticle, ParseMode
from telegram.ext import Updater, CommandHandler, InlineQueryHandler, MessageHandler, Filters
from telegram.utils.helpers import escape_markdown
import logging
import requests
from functool... | (update: 'Update', context: 'CallbackContext'):
""" Add user to the whitelist. """
user_id = update.effective_user.id
chat_id = update.effective_chat.id
chats = get_chat_ids(DB)
if chat_id not in chats:
update.message.reply_text('Did not work. Run this command inside the Ko-Lab group.'... | addme | identifier_name |
bot.py | #!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
from telegram import InlineQueryResultPhoto, InlineQueryResultArticle, ParseMode
from telegram.ext import Updater, CommandHandler, InlineQueryHandler, MessageHandler, Filters
from telegram.utils.helpers import escape_markdown
import logging
import requests
from functool... |
@restricted
def inlinequery(update: 'Update', context: 'Context'):
"""Handle inline queries."""
query = update.inline_query.query
results = [
InlineQueryResultArticle(
id=uuid4(),
title="Caps",
input_message_content=InputTextMessageContent(
query... | return wrapped | random_line_split |
bot.py | #!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
from telegram import InlineQueryResultPhoto, InlineQueryResultArticle, ParseMode
from telegram.ext import Updater, CommandHandler, InlineQueryHandler, MessageHandler, Filters
from telegram.utils.helpers import escape_markdown
import logging
import requests
from functool... |
# send a link to the pixel paint app
try:
# TODO: try to open pixel paint url
url = "http://10.90.154.80/"
#response = requests.get(url)
update.message.reply_text("To paint the floor, go to {}".format(url))
except (ConnectionRefusedError, TimeoutError) as err:
msg =... | print("Trying to start LED floor...")
try:
publish.single("vloer/startscript", "paint", hostname="10.94.176.100",
auth={'username': 'vloer', 'password': 'ko-lab'},
port=1883, client_id="kolabbot")
print("LED floor...")
except (ConnectionRefusedEr... | conditional_block |
scrapedin.py | #!/usr/bin/env python
import sys
import argparse
import re
import csv
import os
import getpass
import platform
import logging
import time
try:
from tabulate import tabulate
except ImportError:
print('Missing required package: Tabulate')
sys.exit(os.EX_SOFTWARE)
try:
from selenium.webdriver.common.by i... |
while max_users > len(self.employee_data) and current_page < 100:
self.page.execute_script("window.scrollTo(0, document.body.scrollHeight);")
try:
WebDriverWait(self.page, 20).until(EC.visibility_of_element_located((By.CLASS_NAME, 'active')))
# Check if ... | max_users = float('inf') | conditional_block |
scrapedin.py | #!/usr/bin/env python
import sys
import argparse
import re
import csv
import os
import getpass
import platform
import logging
import time
try:
from tabulate import tabulate
except ImportError:
print('Missing required package: Tabulate')
sys.exit(os.EX_SOFTWARE)
try:
from selenium.webdriver.common.by i... |
def cycle_users(self, company, url, max_users=None):
'''
You must run the login method before cycle_users will run. Once the login method has run, cycle_users can
collect the names and titles of employees at the company you specify. This method requires the company name
and optio... | '''
Utilize the method within the cycle_users function to build different search
parameters such as location, geotag, company, job-title, etc.
This function will return the full URL.
:param str company: target company name
:param str url: default (or custom) linkedin url for fac... | identifier_body |
scrapedin.py | #!/usr/bin/env python
import sys
import argparse
import re
import csv
import os
import getpass
import platform
import logging
import time
try:
from tabulate import tabulate
except ImportError:
print('Missing required package: Tabulate')
sys.exit(os.EX_SOFTWARE)
try:
from selenium.webdriver.common.by i... | parser.add_argument('-U', dest='url', action='store', default=None,
help='Explicitly set the company URL to scrape from')
parser.add_argument('-g', dest='georegion', action='store', default=None,
help='Filter results by geographic region')
parser.add_argument... | random_line_split | |
scrapedin.py | #!/usr/bin/env python
import sys
import argparse
import re
import csv
import os
import getpass
import platform
import logging
import time
try:
from tabulate import tabulate
except ImportError:
print('Missing required package: Tabulate')
sys.exit(os.EX_SOFTWARE)
try:
from selenium.webdriver.common.by i... | (linkedin_title):
'''
Attempt to determine which department a given user belongs to based off of their title. If a title cannot
be reliably determined then it will return a blank string. It is advised to compare their raw untouched
titles to the output of dept_wizard(). Blindly trusting ... | dept_wizard | identifier_name |
snapshot.go | // Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"context"
"io"
"math"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/p... |
func (l *snapshotList) toSlice() []uint64 {
if l.empty() {
return nil
}
var results []uint64
for i := l.root.next; i != &l.root; i = i.next {
results = append(results, i.seqNum)
}
return results
}
func (l *snapshotList) pushBack(s *Snapshot) {
if s.list != nil || s.prev != nil || s.next != nil {
panic("... | {
v := uint64(math.MaxUint64)
if !l.empty() {
v = l.root.next.seqNum
}
return v
} | identifier_body |
snapshot.go | // Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"context"
"io"
"math"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/p... | return es.mu.vers != nil
}
// waitForFlush waits for a flush on any memtables that need to be flushed
// before this EFOS can transition to a file-only snapshot. If this EFOS is
// waiting on a flush of the mutable memtable, it forces a rotation within
// `dur` duration. For immutable memtables, it schedules a flush ... | // snapshot.
func (es *EventuallyFileOnlySnapshot) hasTransitioned() bool {
es.mu.Lock()
defer es.mu.Unlock() | random_line_split |
snapshot.go | // Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"context"
"io"
"math"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/p... | () bool {
es.mu.Lock()
defer es.mu.Unlock()
return es.mu.vers != nil
}
// waitForFlush waits for a flush on any memtables that need to be flushed
// before this EFOS can transition to a file-only snapshot. If this EFOS is
// waiting on a flush of the mutable memtable, it forces a rotation within
// `dur` duration. ... | hasTransitioned | identifier_name |
snapshot.go | // Copyright 2012 The LevelDB-Go and Pebble Authors. All rights reserved. Use
// of this source code is governed by a BSD-style license that can be found in
// the LICENSE file.
package pebble
import (
"context"
"io"
"math"
"sync"
"sync/atomic"
"time"
"github.com/cockroachdb/errors"
"github.com/cockroachdb/p... |
return iter.Value(), iter, nil
}
// NewIter returns an iterator that is unpositioned (Iterator.Valid() will
// return false). The iterator can be positioned via a call to SeekGE,
// SeekLT, First or Last.
func (es *EventuallyFileOnlySnapshot) NewIter(o *IterOptions) (*Iterator, error) {
return es.NewIterWithContext... | {
return nil, nil, firstError(iter.Close(), ErrNotFound)
} | conditional_block |
conteng_docker.go | /*
MIT License
Copyright (c) 2018 Max Kuznetsov <syhpoon@syhpoon.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, cop... | for contPort, hostPort := range params.Ports {
rawPorts = append(rawPorts, fmt.Sprintf("%d:%d", hostPort, contPort))
}
ports, bindings, err := nat.ParsePortSpecs(rawPorts)
if err != nil {
return "", errors.Wrapf(err, "Error parsing ports for %s", name)
}
// Environ
var environ []string
for k, v := range... |
// Ports
var rawPorts []string
| random_line_split |
conteng_docker.go | /*
MIT License
Copyright (c) 2018 Max Kuznetsov <syhpoon@syhpoon.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, cop... | (ctx context.Context, id string) error {
return de.cl.NetworkRemove(ctx, id)
}
func (de *DockerEngine) BuildImage(ctx context.Context, imgName string,
buildContext io.Reader) error {
opts := types.ImageBuildOptions{
NetworkMode: "bridge",
Tags: []string{imgName},
Remove: true,
ForceRem... | RemoveNetwork | identifier_name |
conteng_docker.go | /*
MIT License
Copyright (c) 2018 Max Kuznetsov <syhpoon@syhpoon.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, cop... |
func (de *DockerEngine) isErrorResponse(r io.Reader) error {
data, err := ioutil.ReadAll(r)
if err != nil {
return err
}
split := bytes.Split(data, []byte("\n"))
type errResp struct {
Error string
}
for i := range split {
e := errResp{}
if err := json.Unmarshal(split[i], &e); err == nil && e.Error... | {
de.cl.Close()
} | identifier_body |
conteng_docker.go | /*
MIT License
Copyright (c) 2018 Max Kuznetsov <syhpoon@syhpoon.ca>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, cop... |
netParams := types.NetworkCreate{
CheckDuplicate: true,
Driver: "bridge",
IPAM: &network.IPAM{
Config: []network.IPAMConfig{
{
Subnet: sub,
IPRange: sub,
},
},
},
}
r, err := de.cl.NetworkCreate(ctx, name, netParams)
if err != nil {
return "", "", errors.Wrapf(err, "Er... | {
return "", "", err
} | conditional_block |
marktree.js | /* MarkTree JavaScript code
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License i... | i) {
// added 12.7.2004 to prevent IE error when readonly mode==true
if (li==null) return null;
n=li;
while (1) {
n=n.parentNode;
if (n==null) return null;
if (is_list_node(n)) return n;
}
}
function getVisibleParents(id) {
var n = document.getElementById(id);
while(1) {
expand(n);
n ... | rent_listnode(l | identifier_name |
marktree.js | /* MarkTree JavaScript code
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License i... | return next_actual_sibling_listnode(n);
}
if (is_list_node(n)) return n;
temp=n;
}
}
function next_sibling_listnode(li) {
if (li==null) return null;
var result=null;
var temp=li;
if (is_col(temp)) return next_child_listnode(temp);
while (1) {
var n = temp.nextSibling;
if (n==null) ... | var n = temp.nextSibling;
if (n==null) {
n=parent_listnode(temp); | random_line_split |
marktree.js | /* MarkTree JavaScript code
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License i... |
function unFocus(node) {
// unfocuses potential link that is to be hidden (if a==null there is no link so it should not be blurred).
// tested with mozilla 1.7, 12.7.2004. /mn (
intemp=parent_listnode(node);
a = get_link(intemp); // added 6.4. to get keyboard working with
// moved be... | if (node.className=='col') {
node.className='exp';
setSubClass(node,'sub');
// getsub(node).className='sub';
}
var i;
if (node.childNodes!=null)
// for opera if (node.hasChildNodes())
for ( i = 0; i<node.childNodes.length; i++)
collapseAll(node.chi... | identifier_body |
xcb.rs | pub type AtomID = xcb::Atom;
pub type Color = u32;
pub type ScreenID = i32;
pub type WindowID = xcb::Window;
pub type DrawableID = xcb::Window;
pub type GraphicsContextID = xcb::Atom;
pub type EventKeyID = xcb::EventMask;
pub type ColorMapID = xcb::Atom;
pub... | self.screen.client.flush().unwrap();
let window = Window
{
screen: self.screen,
id : child_id,
};
window.map();
return Ok(window);
}
}
pub struct GraphicsContext<'client, 'conn>
{
id : GraphicsContextID,
client: &'client Client<'conn>
}
impl<'client, 'conn> GraphicsContext<'client, 'conn>... | return Err(Error{error_code: e.error_code()})
};
| conditional_block |
xcb.rs | pub type AtomID = xcb::Atom;
pub type Color = u32;
pub type ScreenID = i32;
pub type WindowID = xcb::Window;
pub type DrawableID = xcb::Window;
pub type GraphicsContextID = xcb::Atom;
pub type EventKeyID = xcb::EventMask;
pub type ColorMapID = xcb::Atom;
pub... | impl PropertyValue
{
pub fn get_type_atom_id(&self) -> AtomID
{
return match self
{
PropertyValue::String(_) => xcb::ATOM_STRING,
PropertyValue::I32(_) => xcb::ATOM_INTEGER,
PropertyValue::U32(_) => xcb::ATOM_CARDINAL,
PropertyValue::Atom(_) => xcb::ATOM_ATOM,
PropertyValue::UnknownAtom(atom_id) =>... | None,
Atom(AtomID),
UnknownAtom(AtomID),
}
| random_line_split |
xcb.rs | pub type AtomID = xcb::Atom;
pub type Color = u32;
pub type ScreenID = i32;
pub type WindowID = xcb::Window;
pub type DrawableID = xcb::Window;
pub type GraphicsContextID = xcb::Atom;
pub type EventKeyID = xcb::EventMask;
pub type ColorMapID = xcb::Atom;
pub... | ndow: &Window<'_, 'client, 'conn>, foreground: Color, background: Color) -> GraphicsContext<'client, 'conn>
{
let id = window.screen.client.generate_id();
xcb::create_gc_checked(
&window.screen.client.conn,
id,
window.id,
&[
(xcb::GC_FOREGROUND, foreground),
(xcb::GC_BACKGROUND, background),
... | erate(wi | identifier_name |
xcb.rs | pub type AtomID = xcb::Atom;
pub type Color = u32;
pub type ScreenID = i32;
pub type WindowID = xcb::Window;
pub type DrawableID = xcb::Window;
pub type GraphicsContextID = xcb::Atom;
pub type EventKeyID = xcb::EventMask;
pub type ColorMapID = xcb::Atom;
pub... |
pub fn send_message(&self, destination: &Window, event: Event)
{
match event
{
Event::ClientMessageEvent {window, event_type, data , ..} =>
{
let message_data = xcb::ffi::xproto::xcb_client_message_data_t::from_data32(data);
let event = xcb::Event::<xcb::ffi::xproto::xcb_client_message_event_t>::... | {
let event = match self.conn.poll_for_event()
{
Some(event) => event,
None => return None,
};
match event.response_type() & !0x80
{
xcb::EXPOSE => return Some(Event::ExposedEvent),
xcb::KEY_PRESS => return Some(Event::KeyEvent(KeyEvent::KeyPress)),
xcb::KEY_RELEASE => return Some(Event::KeyEv... | identifier_body |
models.py | '''
Updated Models for multilevel approvals
'''
from django.utils.encoding import python_2_unicode_compatible
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from django.utils.html import escape
import cbhooks
from accounts.models import Role
from or... |
def is_multilevel_approval(self):
"""
multilevel approvals need to display the roles that have order.approve permissions
based on a BPOI custom_field_value where the field name has an "_approver_id" at the
end, and a valid role exists on the Group for that cfv fie... | '''
in a multilevel approval, we need a get the GroupRoleMembership mappings
and exclude the default approvers role
as well, if there's only one role.name == approvers
'''
if not profile:
profile = self.owner
owned_grms = profile.groupro... | identifier_body |
models.py | '''
Updated Models for multilevel approvals
'''
from django.utils.encoding import python_2_unicode_compatible
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from django.utils.html import escape
import cbhooks
from accounts.models import Role
from or... | self.save()
history_msg = _("The '{order}' order has been approved.").format(order=escape(self))
self.add_event('APPROVED', history_msg, profile=self.owner)
# run pre order execution hook
try:
cbhooks.run_hooks("pre_order_execution", order=self)
exce... | self.approve_date = get_current_time()
| random_line_split |
models.py | '''
Updated Models for multilevel approvals
'''
from django.utils.encoding import python_2_unicode_compatible
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from django.utils.html import escape
import cbhooks
from accounts.models import Role
from or... | (self, request=None):
"""
This method determines what order process should be taken, and
takes it. By default, the process is to email the approvers, but
this can be overriden by customers to instead call out to a hook,
and that can be overridden by auto-approval (set on th... | start_approval_process | identifier_name |
models.py | '''
Updated Models for multilevel approvals
'''
from django.utils.encoding import python_2_unicode_compatible
from django.template.loader import render_to_string
from django.utils.translation import ugettext as _
from django.utils.html import escape
import cbhooks
from accounts.models import Role
from or... |
# some orders (like those duplicated by CIT) will not have owners
if self.is_multilevel_approval():
if self.has_all_approver_roles(self.owner, self.group):
return True
return False
else:
if self.owner and self.owner.has_permission('... | return True | conditional_block |
usage.py | # Generate reports showing AWS snapshots, AMIs, volumes, and instances; and their KEEP-tags and if PROD-tagged
# Snapshots report shows the associated AMIs and the KEEP-tags thereof
# Volumes report shows the associated instances and the KEEP-tags thereof
# Code borrowed heavily from Niall's previous script: volume... |
def getInstances(region):
creds = credentials()
try:
conn = ec2.connect_to_region(region, **creds)
instances = []
reservations = conn.get_all_reservations()
for reservation in reservations:
for instance in reservation.instances:
instances.append(ins... | return {"aws_access_key_id": os.environ['AWS_ACCESS_KEY'],
"aws_secret_access_key": os.environ['AWS_SECRET_KEY']} | identifier_body |
usage.py | # Generate reports showing AWS snapshots, AMIs, volumes, and instances; and their KEEP-tags and if PROD-tagged
# Snapshots report shows the associated AMIs and the KEEP-tags thereof
# Volumes report shows the associated instances and the KEEP-tags thereof
# Code borrowed heavily from Niall's previous script: volume... |
snapshotsDict = {"id": s.id,
"status": s.status,
"region": s.region.name,
"progress": s.progress,
"start_time": s.start_time,
"volume_id": s.volume_id,
"volume_... | for a in amis:
amiIds.append(a.id.encode())
amiKeeps.append(getKeepTag(a)) | conditional_block |
usage.py | # Generate reports showing AWS snapshots, AMIs, volumes, and instances; and their KEEP-tags and if PROD-tagged
# Snapshots report shows the associated AMIs and the KEEP-tags thereof
# Volumes report shows the associated instances and the KEEP-tags thereof
# Code borrowed heavily from Niall's previous script: volume... | "Description": s.description
}
snapshotsDicts.append(snapshotsDict)
return snapshotsDicts
def getVolumesD(region):
""" return a list of dictionaries representing volumes from one region """
volumes = getVolumes(region)
instances = getInstancesD... | "PROD": isProduction(s), | random_line_split |
usage.py | # Generate reports showing AWS snapshots, AMIs, volumes, and instances; and their KEEP-tags and if PROD-tagged
# Snapshots report shows the associated AMIs and the KEEP-tags thereof
# Volumes report shows the associated instances and the KEEP-tags thereof
# Code borrowed heavily from Niall's previous script: volume... | (regions):
""" Write volumes to file """
print "\nWriting volumes info to output file %s" % volumes_data_output_file
with open(volumes_data_output_file, 'w') as f1:
f1.write("VOLUMES\n")
f1.write(
"Name\tvolume_ID\tKEEP-tag_of_volume\tKEEP-tag_of_instance\tproduction?\tvolume_att... | generateInfoVolumes | identifier_name |
enum.go | // Copyright (c) 2017-2018 Alexander Eichhorn
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... | AppleStoreDMA AppleStoreCountry = 143545 // Dominica
AppleStoreGRD AppleStoreCountry = 143546 // Grenada
AppleStoreMSR AppleStoreCountry = 143547 // Montserrat
AppleStoreKNA AppleStoreCountry = 143548 // St. Kitts and Nevis
AppleStoreLCA AppleStoreCountry = 143549 // St. Lucia
AppleStoreVCT AppleStoreCountry = 14... | random_line_split | |
enum.go | // Copyright (c) 2017-2018 Alexander Eichhorn
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... |
type RatingCode int
const (
RatingCodeNone RatingCode = 0 // 0 = None
RatingCodeExplicit RatingCode = 1 // 1 = Explicit
RatingCodeClean RatingCode = 2 // 2 = Clean
RatingCodeExplicitOld RatingCode = 4 // 4 = Explicit (old)
)
type PlayGapMode int
const (
PlayGapInsertGap PlayGapMode = 0 // Inse... | {
switch x {
case MediaTypeHomeVideo:
return "Home Video"
case MediaTypeMusic:
return "Music"
case MediaTypeAudiobook:
return "Audiobook"
case MediaTypeBookmark:
return "Whacked Bookmark"
case MediaTypeMusicVideo:
return "Music Video"
case MediaTypeMovie:
return "Movie"
case MediaTypeTVShow:
retur... | identifier_body |
enum.go | // Copyright (c) 2017-2018 Alexander Eichhorn
//
// Licensed under the Apache License, Version 2.0 (the "License"): you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law ... | () string {
switch x {
case MediaTypeHomeVideo:
return "Home Video"
case MediaTypeMusic:
return "Music"
case MediaTypeAudiobook:
return "Audiobook"
case MediaTypeBookmark:
return "Whacked Bookmark"
case MediaTypeMusicVideo:
return "Music Video"
case MediaTypeMovie:
return "Movie"
case MediaTypeTVSho... | String | identifier_name |
insert_organisations.py | #!/usr/bin/env python3
# pylint: disable=wrong-import-position
# Adding working directory to system path
import sys
import time
import json
import logging
import argparse
import Levenshtein
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFoun... | (es, text_orig, context=None, just_search=False):
"""Returns False to skip"""
# pylint: disable=redefined-variable-type
# `org_id` may be `None`, `False` or string.
org_id = None
text_search = text_orig
while True:
if context and context.get("refresh", None):
# Necessarily ... | search_org | identifier_name |
insert_organisations.py | #!/usr/bin/env python3
# pylint: disable=wrong-import-position
# Adding working directory to system path
import sys
import time
import json
import logging
import argparse
import Levenshtein
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFoun... | for note_data in chunk["note"]:
if note_data["text"] in [note.text for note in org.note_list]:
continue
note = Note(
note_data["text"], note_data["source"],
moderation_user=user, public=None,
)
... | if "note" in chunk: | random_line_split |
insert_organisations.py | #!/usr/bin/env python3
# pylint: disable=wrong-import-position
# Adding working directory to system path
import sys
import time
import json
import logging
import argparse
import Levenshtein
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFoun... |
def get_org(orm, name):
name = name.lower()
query = orm.query(Org) \
.filter(func.lower(Org.name) == name)
try:
return query.one()
except NoResultFound:
pass
except MultipleResultsFound:
LOG.warning("Multiple results found for name '%s'.", name)
return q... | matches = set()
lower = orm.query(Org.name) \
.filter(Org.name > name) \
.order_by(Org.name.asc()) \
.limit(3) \
.all()
higher = orm.query(Org.name) \
.filter(Org.name < name) \
.order_by(Org.name.desc()) \
.limit(3) \
.all()
for (name2, ) in... | identifier_body |
insert_organisations.py | #!/usr/bin/env python3
# pylint: disable=wrong-import-position
# Adding working directory to system path
import sys
import time
import json
import logging
import argparse
import Levenshtein
from sqlalchemy import create_engine, func
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.exc import NoResultFoun... |
es = orm.get_bind().search
if es is None:
LOG.error("Cannot connect to Elasticsearch.")
sys.exit(1)
org_id = search_org(es, name, context=context)
if not org_id:
return org_id
try:
org = orm.query(Org).filter_by(org_id=org_id).one()
except NoResultFound as e:
... | return | conditional_block |
29.js | "1": "<sup>1</sup> Fjala e Zotit që iu drejtua Joelit, birit të Pethuelit.",
"2": "<sup>2</sup> Dëgjoni këtë, o pleq, dëgjoni, ju të gjithë banorë të vendit. A ka ndodhur vallë një gjë e tillë në ditët tuaja apo në ditët e etërve tuaj?",
"3": "<sup>3</sup> Tregojani bijve tuaj, dhe bijtë tuaj bijve të tyre, dh... | var book = {
"name": "Joeli",
"numChapters": 3,
"chapters": {
"1": { | random_line_split | |
simulationlf.py | from time import process_time
import numpy as np
from scipy.sparse import block_diag
from app.models.timestamp import Timestamp
import os
class SimulationLF:
def __init__(self, nb=1, tol=0.01, delta=Timestamp.QUARTERS):
"""
:param nb: for number of iterations to do for Monte Carlo
:param... | 'reactive': imag(flow)
}
def printMenu(self, network):
np.set_printoptions(threshold=np.nan, suppress=True, precision=10)
# import re
while True:
# This block is relevant if we use a timestamp.
# It will check the user's input.
# If yo... | flow = voltage * conj(intensity)
return {
'active': real(flow), | random_line_split |
simulationlf.py | from time import process_time
import numpy as np
from scipy.sparse import block_diag
from app.models.timestamp import Timestamp
import os
class SimulationLF:
def __init__(self, nb=1, tol=0.01, delta=Timestamp.QUARTERS):
"""
:param nb: for number of iterations to do for Monte Carlo
:param... |
def get_delta_time(self): return self.__delta_time
# SETTERS/MUTATORS
def set_nb_iterations(self, nb): self.__nb_iterations = nb
def set_tolerance(self, t): self.__tolerance = t
def set_delta_time(self, d): self.__delta_time = d
def grid_definition(self, network):
zeros = np.zeros
... | return self.__tolerance | identifier_body |
simulationlf.py | from time import process_time
import numpy as np
from scipy.sparse import block_diag
from app.models.timestamp import Timestamp
import os
class SimulationLF:
def __init__(self, nb=1, tol=0.01, delta=Timestamp.QUARTERS):
"""
:param nb: for number of iterations to do for Monte Carlo
:param... | (self): return self.__nb_iterations
def get_tolerance(self): return self.__tolerance
def get_delta_time(self): return self.__delta_time
# SETTERS/MUTATORS
def set_nb_iterations(self, nb): self.__nb_iterations = nb
def set_tolerance(self, t): self.__tolerance = t
def set_delta_time(self, d):... | get_nb_iterations | identifier_name |
simulationlf.py | from time import process_time
import numpy as np
from scipy.sparse import block_diag
from app.models.timestamp import Timestamp
import os
class SimulationLF:
def __init__(self, nb=1, tol=0.01, delta=Timestamp.QUARTERS):
"""
:param nb: for number of iterations to do for Monte Carlo
:param... |
Vbus = Vnl + np.dot(K.conj().T, Vbr)
V[:] = Vbus[:, :, np.newaxis]
I[:] = Ibr[:, :, np.newaxis]
Pbr = Qbr = np.array([[[0 for k in range(2)]for j in range(len(vec_phases_index))] for i in range(nb_brackets)])
for i in range(nb_brackets):
for j in range(len(vec_phases... | k += 1
bal = 0
for i in range(len(P)):
if k == 1:
Ibus[i] = -(np.matrix(np.complex(P[i], Q[i])/Vbus[i]).conj())
else:
Ibus[i] = -(np.matrix(np.complex(P[i], Q[i]) / Vbus[i]).conj())
if i % 3 == bat:
... | conditional_block |
mortgage_pandas.py | # Derived from https://github.com/fschlimb/scale-out-benchs
import numpy as np
import pandas as pd
from pymapd import connect
from pandas.api.types import CategoricalDtype
from io import StringIO
from glob import glob
import os
import time
import pathlib
import sys
import argparse
def run_pd_workflow(quarter=1, year=... |
avgExecTime /= args.iterations
avgTotalTime /= args.iterations
try:
with open(args.r, "w") as report:
print("BENCHMARK", benchName, "EXEC TIME", bestExecTime, "TOTAL TIME", bestTotalTime)
print("datafiles,fragment_size,query,query_exec_min,query_total_min,query_exec_max,query_total_max,query_exec... | dataFilesNumber = 0
time_ETL = time.time()
exec_time_total = 0
print("RUNNING BENCHMARK NUMBER", benchName, "ITERATION NUMBER", iii)
for quarter in range(0, args.df):
year = 2000 + quarter // 4
perf_file = perf_format_path % (str(year), str(quarter % 4 + 1))
files = [f for f in ... | conditional_block |
mortgage_pandas.py | # Derived from https://github.com/fschlimb/scale-out-benchs
import numpy as np
import pandas as pd
from pymapd import connect
from pandas.api.types import CategoricalDtype
from io import StringIO
from glob import glob
import os
import time
import pathlib
import sys
import argparse
def run_pd_workflow(quarter=1, year=... |
def join_perf_acq_pdfs(perf, acq, **kwargs):
return perf.merge(acq, how='left', on=['loan_id'])
def last_mile_cleaning(df, **kwargs):
#for col, dtype in df.dtypes.iteritems():
# if str(dtype)=='category':
# df[col] = df[col].cat.codes
df['delinquency_12'] = df['delinquency_12'] > 0
... | merged['timestamp_month'] = merged['monthly_reporting_period'].dt.month
merged['timestamp_month'] = merged['timestamp_month'].astype('int8')
merged['timestamp_year'] = merged['monthly_reporting_period'].dt.year
merged['timestamp_year'] = merged['timestamp_year'].astype('int16')
merged = merged.merge(joi... | identifier_body |
mortgage_pandas.py | # Derived from https://github.com/fschlimb/scale-out-benchs
import numpy as np
import pandas as pd
from pymapd import connect | import pathlib
import sys
import argparse
def run_pd_workflow(quarter=1, year=2000, perf_file="", **kwargs):
t1 = time.time()
names = pd_load_names()
year_string = str(year) + "Q" + str(quarter) + ".txt"
acq_file = os.path.join(data_directory, "acq", "Acquisition_" + year_string)
print("READING DAT... | from pandas.api.types import CategoricalDtype
from io import StringIO
from glob import glob
import os
import time | random_line_split |
mortgage_pandas.py | # Derived from https://github.com/fschlimb/scale-out-benchs
import numpy as np
import pandas as pd
from pymapd import connect
from pandas.api.types import CategoricalDtype
from io import StringIO
from glob import glob
import os
import time
import pathlib
import sys
import argparse
def run_pd_workflow(quarter=1, year=... | (acquisition_path, **kwargs):
""" Loads acquisition data
Returns
-------
PD DataFrame
"""
columns = [
'loan_id', 'orig_channel', 'seller_name', 'orig_interest_rate', 'orig_upb', 'orig_loan_term',
'orig_date', 'first_pay_date', 'orig_ltv', 'orig_cltv', 'num_borrowers', 'dti', 'b... | pd_load_acquisition_csv | identifier_name |
api.rs | use std::io::{self, Read, Error, ErrorKind};
use std::borrow::Cow;
use hyper;
use hyper::{client, Client, Url };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::time::Duration;
use serde_json;
use product;
use configs::{Configs, ApiConfigs, ProxyConfigs};
const HOST_URL: &'static str ... | {
error: String
}
#[derive(Serialize, Deserialize, Debug)]
struct ShaItem {
language: String,
prod_key: String,
version: String,
sha_value: String,
sha_method: String,
prod_type: Option<String>,
group_id: Option<String>,
artifact_id: Option<String>,
classifier: Option<String>,
... | ApiError | identifier_name |
api.rs | use std::io::{self, Read, Error, ErrorKind};
use std::borrow::Cow;
use hyper;
use hyper::{client, Client, Url };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::time::Duration;
use serde_json;
use product;
use configs::{Configs, ApiConfigs, ProxyConfigs};
const HOST_URL: &'static str ... |
// converts the response of product endpoint into ProductMatch struct
#[derive(Serialize, Deserialize, Debug)]
struct ProductItem {
name: String,
language: String,
prod_key: String,
version: String,
prod_type: String,
}
#[derive(Serialize, Deserialize, Debug)]
struct LicenseItem {
name: Strin... | {
if json_text.is_none() {
return Err(
Error::new(ErrorKind::Other, "No response from API")
)
}
let res: serde_json::Value = serde_json::from_str(json_text.unwrap().as_str())?;
if res.is_object() && res.get("error").is_some() {
let e = Error::new(
ErrorK... | identifier_body |
api.rs | use std::io::{self, Read, Error, ErrorKind};
use std::borrow::Cow;
use hyper;
use hyper::{client, Client, Url };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::time::Duration;
use serde_json;
use product;
use configs::{Configs, ApiConfigs, ProxyConfigs};
const HOST_URL: &'static str ... | .clear()
.append_pair("api_key", api_confs.key.clone().unwrap().as_str());
let json_txt = request_json( &resource_url, &confs.proxy );
process_sha_response(json_txt)
}
//replaces base64 special characters with HTML safe percentage encoding
//source: https://en.wikipedia.org/wiki/Base64#URL_ap... |
//attach query params
resource_url
.query_pairs_mut() | random_line_split |
api.rs | use std::io::{self, Read, Error, ErrorKind};
use std::borrow::Cow;
use hyper;
use hyper::{client, Client, Url };
use hyper::net::HttpsConnector;
use hyper_native_tls::NativeTlsClient;
use std::time::Duration;
use serde_json;
use product;
use configs::{Configs, ApiConfigs, ProxyConfigs};
const HOST_URL: &'static str ... | ,
Err(e) => Err(e)
}
}
pub fn fetch_product_by_sha(confs: &Configs, sha: &str)
-> Result<product::ProductMatch, io::Error> {
let api_confs = confs.api.clone();
let resource_path = format!("products/sha/{}", encode_sha(sha) );
let mut resource_url = match configs_to_url(&api_confs, resource_... | {
let sha = m.sha.expect("No product sha from SHA result");
let product = m.product.expect("No product info from SHA result");
match fetch_product( &confs, &product.language, &product.prod_key, &product.version ) {
Ok(mut m) => {
m.sha = Some(sha);... | conditional_block |
txn_ext.rs | // Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains everything related to transaction hook.
//!
//! This is the temporary (efficient) solution, it should be implemented as one
//! type of coprocessor.
use std::sync::{atomic::Ordering, Arc};
use crossbeam::atomic::AtomicCell;
u... |
// Returns whether we should propose another TransferLeader command. This is
// for:
// - Considering the amount of pessimistic locks can be big, it can reduce
// unavailable time caused by waiting for the transferee catching up logs.
// - Make transferring leader strictly after write commands t... | {
// If it is not leader, we needn't reactivate by tick. In-memory pessimistic
// lock will be enabled when this region becomes leader again.
if !self.is_leader() {
return;
}
let transferring_leader = self.raft_group().raft.lead_transferee.is_some();
let txn_... | identifier_body |
txn_ext.rs | // Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains everything related to transaction hook.
//!
//! This is the temporary (efficient) solution, it should be implemented as one
//! type of coprocessor.
use std::sync::{atomic::Ordering, Arc};
use crossbeam::atomic::AtomicCell;
u... | <T>(&mut self, ctx: &mut StoreContext<EK, ER, T>) {
// If it is not leader, we needn't reactivate by tick. In-memory pessimistic
// lock will be enabled when this region becomes leader again.
if !self.is_leader() {
return;
}
let transferring_leader = self.raft_group(... | on_reactivate_memory_lock_tick | identifier_name |
txn_ext.rs | // Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains everything related to transaction hook.
//!
//! This is the temporary (efficient) solution, it should be implemented as one
//! type of coprocessor.
use std::sync::{atomic::Ordering, Arc};
use crossbeam::atomic::AtomicCell;
u... | continue;
}
lock_count += 1;
encoder.put(CF_LOCK, key.as_encoded(), &lock.to_lock().to_bytes());
}
}
if lock_count == 0 {
// If the map is not empty but all locks are deleted, it is possible that a
//... | let pessimistic_locks = RwLockWriteGuard::downgrade(pessimistic_locks);
fail::fail_point!("invalidate_locks_before_transfer_leader");
for (key, (lock, deleted)) in &*pessimistic_locks {
if *deleted { | random_line_split |
txn_ext.rs | // Copyright 2023 TiKV Project Authors. Licensed under Apache-2.0.
//! This module contains everything related to transaction hook.
//!
//! This is the temporary (efficient) solution, it should be implemented as one
//! type of coprocessor.
use std::sync::{atomic::Ordering, Arc};
use crossbeam::atomic::AtomicCell;
u... |
}
// Returns whether we should propose another TransferLeader command. This is
// for:
// - Considering the amount of pessimistic locks can be big, it can reduce
// unavailable time caused by waiting for the transferee catching up logs.
// - Make transferring leader strictly after write comm... | {
drop(pessimistic_locks);
self.add_pending_tick(PeerTick::ReactivateMemoryLock);
} | conditional_block |
trx_mgr.go | package app
import (
"errors"
"fmt"
"github.com/coschain/contentos-go/common"
"github.com/coschain/contentos-go/common/constants"
"github.com/coschain/contentos-go/iservices"
"github.com/coschain/contentos-go/prototype"
"github.com/gogo/protobuf/proto"
"github.com/sirupsen/logrus"
"sync"
"sync/atomic"
"time... |
return nil
}
// CheckSignerKey checks if the transaction is signed by correct public key.
func (e *TrxEntry) CheckSignerKey(fetcher *AuthFetcher) error {
if err := fetcher.CheckPublicKey(e.signer, e.signerKey); err != nil {
return e.SetError(fmt.Errorf("signature failed: %s", err.Error()))
}
return nil
}
// Ch... | {
return e.SetError(fmt.Errorf("tapos failed: %s", err.Error()))
} | conditional_block |
trx_mgr.go | package app
import (
"errors"
"fmt"
"github.com/coschain/contentos-go/common"
"github.com/coschain/contentos-go/common/constants"
"github.com/coschain/contentos-go/iservices"
"github.com/coschain/contentos-go/prototype"
"github.com/gogo/protobuf/proto"
"github.com/sirupsen/logrus"
"sync"
"sync/atomic"
"time... | if ptrx := m.isProcessingTrx(trx); ptrx != nil {
needInitCheck = false
e.trxId = ptrx.trxId
e.size = ptrx.size
e.signer = ptrx.signer
e.signerKey = ptrx.signerKey
}
// do initial check if necessary
if needInitCheck {
err = e.InitCheck()
}
// do state-dependent check... | // if we have met this transaction before, skip initial check and fill up extra information.
// this voids doing the expensive public key recovery again. | random_line_split |
trx_mgr.go | package app
import (
"errors"
"fmt"
"github.com/coschain/contentos-go/common"
"github.com/coschain/contentos-go/common/constants"
"github.com/coschain/contentos-go/iservices"
"github.com/coschain/contentos-go/prototype"
"github.com/gogo/protobuf/proto"
"github.com/sirupsen/logrus"
"sync"
"sync/atomic"
"time... | () int {
m.waitingLock.RLock()
defer m.waitingLock.RUnlock()
return len(m.waiting)
}
// FetchTrx fetches a batch of transactions from waiting pool.
// Block producer should call FetchTrx to collect transactions of new blocks.
func (m *TrxMgr) FetchTrx(blockTime uint32, maxCount, maxSize int) (entries []*TrxEntry) {... | WaitingCount | identifier_name |
trx_mgr.go | package app
import (
"errors"
"fmt"
"github.com/coschain/contentos-go/common"
"github.com/coschain/contentos-go/common/constants"
"github.com/coschain/contentos-go/iservices"
"github.com/coschain/contentos-go/prototype"
"github.com/gogo/protobuf/proto"
"github.com/sirupsen/logrus"
"sync"
"sync/atomic"
"time... |
// Deliver calls entry's callback function.
func (e *TrxEntry) Deliver() {
if e.callback != nil {
e.callback(e.result)
}
}
// InitCheck fills extra information of the entry, and do a basic validation check.
// Note that InitCheck is independent from chain state. We should do it only once for each transaction.
fu... | {
e.result.Receipt.Status = prototype.StatusError
e.result.Receipt.ErrorInfo = err.Error()
return err
} | identifier_body |
mixhop_trainer.py |
# Standard imports.
import collections
import json
import os
import pickle
# Third-party imports.
from absl import app
from absl import flags
import numpy
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.python.keras import regularizers as keras_regularizers
# Project imports.
import mi... |
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
return params
class AccuracyMonitor(object):
"""Monitors and remembers model parameters @ best validation accuracy."""
def __init__(self, sess, early_stop_steps):... | tf.config.experimental.set_memory_growth(gpu, True) | conditional_block |
mixhop_trainer.py |
# Standard imports.
import collections
import json
import os
import pickle
# Third-party imports.
from absl import app
from absl import flags
import numpy
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.python.keras import regularizers as keras_regularizers
# Project imports.
import mi... |
def main(unused_argv):
encoded_params = GetEncodedParams()
output_results_file = os.path.join(
FLAGS.results_dir, encoded_params + '.json')
output_model_file = os.path.join(
FLAGS.train_dir, encoded_params + '.pkl')
if os.path.exists(output_results_file) and not FLAGS.retrain:
print('Exiting ... | sizes = [l[min(layer_index, len(l)-1)] for l in self._ratios]
sum_units = numpy.sum(sizes)
size_per_unit = total_dim / float(sum_units)
dims = []
for s in sizes[:-1]:
dim = int(numpy.round(s * size_per_unit))
dims.append(dim)
dims.append(total_dim - sum(dims))
return dims | identifier_body |
mixhop_trainer.py |
# Standard imports.
import collections
import json
import os
import pickle
# Third-party imports.
from absl import app
from absl import flags
import numpy
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.python.keras import regularizers as keras_regularizers
# Project imports.
import mi... | (self):
powers = FLAGS.adj_pows.split(',')
has_colon = None
self._powers = []
self._ratios = []
for i, p in enumerate(powers):
if i == 0:
has_colon = (':' in p)
else:
if has_colon != (':' in p):
raise ValueError(
'Error in flag --adj_pows. Either ... | __init__ | identifier_name |
mixhop_trainer.py | # Standard imports.
import collections
import json
import os
import pickle
# Third-party imports.
from absl import app
from absl import flags
import numpy
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.python.keras import regularizers as keras_regularizers
# Project imports.
import mix... | layer_dims = list(map(int, FLAGS.hidden_dims_csv.split(',')))
layer_dims.append(power_parser.output_capacity(dataset.ally.shape[1]))
for j, dim in enumerate(layer_dims):
if j != 0:
model.add_layer('tf.layers', 'dropout', FLAGS.layer_dropout,
pass_training=True)
ca... | model.add_layer('tf.nn', 'l2_normalize', axis=1)
power_parser = AdjacencyPowersParser() | random_line_split |
lib.rs | use std::fmt;
use std::time::{Duration, SystemTime, SystemTimeError};
/// Enum with the seven days of the week.
#[derive(Debug, Clone, Copy)]
pub enum Day {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
/// Maps the `Day` enum to a string representation, e.g. "Monday".
... | if year % 400 == 0 {
366
} else if year % 100 == 0 {
365
} else if year % 4 == 0 {
366
} else {
365
}
}
/// Takes in a year and month (e.g. 2020, February) and returns the number of days in that month.
pub fn days_in_month(year: u64, month: Month) -> u64 {
match ... | /// Takes in a year (e.g. 2019) and returns the number of days in that year.
pub fn days_in_year(year: u64) -> u64 { | random_line_split |
lib.rs | use std::fmt;
use std::time::{Duration, SystemTime, SystemTimeError};
/// Enum with the seven days of the week.
#[derive(Debug, Clone, Copy)]
pub enum Day {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
/// Maps the `Day` enum to a string representation, e.g. "Monday".
... |
/// Returns the number of milliseconds passed since the unix epoch.
pub fn milliseconds_since_epoch(&self) -> u128 {
self.delta.as_millis()
}
/// Returns the number of microseconds passed since the unix epoch.
pub fn microseconds_since_epoch(&self) -> u128 {
self.delta.as_micros()... | {
Self::from(&SystemTime::now())
} | identifier_body |
lib.rs | use std::fmt;
use std::time::{Duration, SystemTime, SystemTimeError};
/// Enum with the seven days of the week.
#[derive(Debug, Clone, Copy)]
pub enum Day {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
}
/// Maps the `Day` enum to a string representation, e.g. "Monday".
... | (month: Month) -> &'static str {
&month_string(month)[0..3]
}
impl fmt::Display for Month {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", month_string(*self))
}
}
/// Takes in a year (e.g. 2019) and returns the number of days in that year.
pub fn days_in_year(year: u64... | month_abbrev_string | identifier_name |
Main.py | '''
Author: 程东洲
Date: 2021-05-19 21:33:22
LastEditTime: 2021-06-11 11:16:35
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \testcamera\testCamera03.py
'''
from typing import List
import numpy as np
from PIL import Image
import base64
import time
from aip import AipFace, face
import os... |
class CollectPicture_Page( QDialog ):
mysignal = pyqtSignal( )
def __init__( self ):
super().__init__()
self.setWindowTitle('人脸数据集收集和训练')
self.resize( 1000 ,500 )
self.IsHome_button = QRadioButton( "本地收集" , self)
self.IsInternet_button = QRadioButton( "网络收集" ,self )... | random_line_split | |
Main.py | '''
Author: 程东洲
Date: 2021-05-19 21:33:22
LastEditTime: 2021-06-11 11:16:35
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \testcamera\testCamera03.py
'''
from typing import List
import numpy as np
from PIL import Image
import base64
import time
from aip import AipFace, face
import os... | 'r+')
real_dict = eval( fl.read() )
names = list( real_dict.keys() )
fl.close()
self.collect_name , ok = QInputDialog.getText( self , '请输入你的名字' ,'必须是已经注册的名字!' )
if self.collect_name in names:
self.face_id = names.index( self.collect_name ) + 1
#... | identifier_body | |
Main.py | '''
Author: 程东洲
Date: 2021-05-19 21:33:22
LastEditTime: 2021-06-11 11:16:35
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \testcamera\testCamera03.py
'''
from typing import List
import numpy as np
from PIL import Image
import base64
import time
from aip import AipFace, face
import os... | ge,cv2.COLOR_BGR2RGB ) #视频色彩转换回RGB,这样才是现实的颜色
#pyqt显示逻辑
showImage = QImage( self.image.data, self.image.shape[1] , self.image.shape[0], QImage.Format_RGB888 )
self.cameraLabel.setPixmap(QPixmap.fromImage(showImage))
#打开摄像头
def openCamera(self):
flag = self.cap.open( cap_id )
... | or(self.ima | identifier_name |
Main.py | '''
Author: 程东洲
Date: 2021-05-19 21:33:22
LastEditTime: 2021-06-11 11:16:35
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \testcamera\testCamera03.py
'''
from typing import List
import numpy as np
from PIL import Image
import base64
import time
from aip import AipFace, face
import os... | 代表着识别成功后就启动该功能
def Function_run( self ):
pass
#这个类主要是管理注册逻辑,这里为什么要用QDialog呢,当然也可以用Qwidget,这俩都是毛坯房,但是
#QDialog有exec方法,Qwidget是没有的。exec_()方法可以让窗口成为模态窗口,而调用show()方法,
#窗口是非模态的。模态窗口将程序控制权占据,只有对当前窗口关闭后才能操作其他窗口;
class Signin_Dialog( QDialog ):
def __init__( self ):
super().__init__()
#控件的... | cv2.putText(self.image, self.name , (x+5,y-5), font, 1, (255,255,255), 2 )
cv2.putText(self.image, str( self.score ), (x+5,y+h-5), font, 1, (255,255,0), 1 )
def closeCamera(self):
self.timer_camera.stop()
self.cap.release()
self.OnceBaiduAPI_flag = False
s... | conditional_block |
SPT_AGN_emcee_sampler_MPI.py | """
SPT_AGN_emcee_sampler_MPI.py
Author: Benjamin Floyd
This script will preform the Bayesian analysis on the SPT-AGN data to produce the posterior probability distributions
for all fitting parameters.
"""
import json
import os
from argparse import ArgumentParser
from time import time
import astropy.units as u
import... |
def model_rate_opted(params, cluster_id, r_r500, j_mag, integral=False):
"""
Our generating model.
Parameters
----------
params : tuple
Tuple of (theta, eta, zeta, beta, rc, C)
cluster_id : str
SPT ID of our cluster in the catalog dictionary
r_r500 : array-like
A ... | """
Assef+11 QLF using luminosity and density evolution.
Parameters
----------
abs_mag : astropy table-like
Rest-frame J-band absolute magnitude.
redshift : astropy table-like
Cluster redshift
Returns
-------
Phi : ndarray
Luminosity density
"""
# L/L_... | identifier_body |
SPT_AGN_emcee_sampler_MPI.py | """
SPT_AGN_emcee_sampler_MPI.py
Author: Benjamin Floyd
This script will preform the Bayesian analysis on the SPT-AGN data to produce the posterior probability distributions
for all fitting parameters.
"""
import json
import os
from argparse import ArgumentParser
from time import time
import astropy.units as u
import... |
# Define all priors
if (0.0 <= theta <= np.inf and
-6. <= eta <= 6. and
-3. <= zeta <= 3. and
-3. <= beta <= 3. and
0.05 <= rc <= 0.5 and
0.0 <= C < np.inf):
theta_lnprior = 0.0
eta_lnprior = 0.0
beta_lnprior = 0.0
zet... | theta, eta, zeta, beta, rc, C = params | conditional_block |
SPT_AGN_emcee_sampler_MPI.py | """
SPT_AGN_emcee_sampler_MPI.py
Author: Benjamin Floyd
This script will preform the Bayesian analysis on the SPT-AGN data to produce the posterior probability distributions
for all fitting parameters.
"""
import json
import os
from argparse import ArgumentParser
from time import time
import astropy.units as u
import... | (params, cluster_id, r_r500, j_mag, integral=False):
"""
Our generating model.
Parameters
----------
params : tuple
Tuple of (theta, eta, zeta, beta, rc, C)
cluster_id : str
SPT ID of our cluster in the catalog dictionary
r_r500 : array-like
A vector of radii of obje... | model_rate_opted | identifier_name |
SPT_AGN_emcee_sampler_MPI.py | """
SPT_AGN_emcee_sampler_MPI.py
Author: Benjamin Floyd
This script will preform the Bayesian analysis on the SPT-AGN data to produce the posterior probability distributions
for all fitting parameters.
"""
import json
import os
from argparse import ArgumentParser
from time import time
import astropy.units as u
import... | nwalkers = 6 * ndim
# Also, set the number of steps to run the sampler for.
nsteps = int(1e6)
# We will initialize our walkers in a tight ball near the initial parameter values.
if args.cluster_only:
pos0 = np.vstack([[np.random.uniform(0., 12.), # theta
np.random.uniform(-1., 6.), # eta
... | ndim = 5 if args.cluster_only else (1 if args.background_only else 6) | random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.