docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Insert or update R-Value in `self.r_df`.
Args:
state_key: The key of state.
r_value: R-Value(Reward).
action_key: The key of action if it is nesesary for the parametar of value function.
Exceptions:
TypeError: If the type of `r_value` i... | def save_r_df(self, state_key, r_value, action_key=None):
if action_key is not None:
add_r_df = pd.DataFrame([(state_key, action_key, r_value)], columns=["state_key", "action_key", "r_value"])
else:
add_r_df = pd.DataFrame([(state_key, r_value)], columns=["state_key", "r... | 368,866 |
Learning and searching the optimal solution.
Args:
state_key: Initial state.
limit: The maximum number of iterative updates based on value iteration algorithms. | def learn(self, state_key, limit=1000):
self.t = 1
while self.t <= limit:
next_action_list = self.extract_possible_actions(state_key)
if len(next_action_list):
action_key = self.select_action(
state_key=state_key,
n... | 368,869 |
Update Q-Value.
Args:
state_key: The key of state.
action_key: The key of action.
reward_value: R-Value(Reward).
next_max_q: Maximum Q-Value. | def update_q(self, state_key, action_key, reward_value, next_max_q):
# Now Q-Value.
q = self.extract_q_df(state_key, action_key)
# Update Q-Value.
new_q = q + self.alpha_value * (reward_value + (self.gamma_value * next_max_q) - q)
# Save updated Q-Value.
self.sav... | 368,870 |
Predict next action by Q-Learning.
Args:
state_key: The key of state in `self.t+1`.
next_action_list: The possible action in `self.t+1`.
Returns:
The key of action. | def predict_next_action(self, state_key, next_action_list):
if self.q_df is not None:
next_action_q_df = self.q_df[self.q_df.state_key == state_key]
next_action_q_df = next_action_q_df[next_action_q_df.action_key.isin(next_action_list)]
if next_action_q_df.shape[0] =... | 368,871 |
Initialization
Args:
arm_id_list: List of arms Master id. | def __init__(self, arm_id_list):
[self.__beta_dist_dict.setdefault(key, BetaDist()) for key in arm_id_list] | 368,873 |
Pull arms.
Args:
arm_id: Arms master id.
success: The number of success.
failure: The number of failure. | def pull(self, arm_id, success, failure):
self.__beta_dist_dict[arm_id].observe(success, failure) | 368,874 |
Listup arms and expected value.
Args:
limit: Length of the list.
Returns:
[Tuple(`Arms master id`, `expected value`)] | def recommend(self, limit=10):
expected_list = [(arm_id, beta_dist.expected_value()) for arm_id, beta_dist in self.__beta_dist_dict.items()]
expected_list = sorted(expected_list, key=lambda x: x[1], reverse=True)
return expected_list[:limit] | 368,875 |
Calculate similarity with the Tanimoto coefficient.
Concrete method.
Args:
token_list_x: [token, token, token, ...]
token_list_y: [token, token, token, ...]
Returns:
Similarity. | def calculate(self, token_list_x, token_list_y):
match_list = [tanimoto_value for tanimoto_value in token_list_x if tanimoto_value in token_list_y]
return float(len(match_list) / (len(token_list_x) + len(token_list_y) - len(match_list))) | 368,876 |
Select action by Q(state, action).
Concreat method for boltzmann distribution.
Args:
state_key: The key of state.
next_action_list: The possible action in `self.t+1`.
If the length of this list is 0, all action shou... | def select_action(self, state_key, next_action_list):
if self.q_df is None or self.q_df.shape[0] == 0:
return random.choice(next_action_list)
next_action_b_df = self.__calculate_boltzmann_factor(state_key, next_action_list)
if next_action_b_df.shape[0] == 1:
re... | 368,880 |
Calculate boltzmann factor.
Args:
state_key: The key of state.
next_action_list: The possible action in `self.t+1`.
If the length of this list is 0, all action should be possible.
Returns:
[(`The key of action`,... | def __calculate_boltzmann_factor(self, state_key, next_action_list):
sigmoid = self.__calculate_sigmoid()
q_df = self.q_df[self.q_df.state_key == state_key]
q_df = q_df[q_df.isin(next_action_list)]
q_df["boltzmann_factor"] = q_df["q_value"] / sigmoid
q_df["boltzmann_fact... | 368,882 |
Select action by Q(state, action).
Concreat method.
ε-greedy.
Args:
state_key: The key of state.
next_action_list: The possible action in `self.t+1`.
If the length of this list is 0, all action should be po... | def select_action(self, state_key, next_action_list):
epsilon_greedy_flag = bool(np.random.binomial(n=1, p=self.epsilon_greedy_rate))
if epsilon_greedy_flag is False:
action_key = random.choice(next_action_list)
else:
action_key = self.predict_next_actio... | 368,888 |
Init.
Args:
boltzmann_q_learning: is-a `BoltzmannQLearning`.
init_state_key: First state key. | def __init__(
self,
greedy_q_learning,
init_state_key
):
if isinstance(boltzmann_q_learning, BoltzmannQLearning):
self.__boltzmann_q_learning = boltzmann_q_learning
else:
raise TypeError()
self.__init_state_key = init_state_key | 368,889 |
Draws samples from the `fake` distribution.
Args:
observed_arr: `np.ndarray` of observed data points.
Returns:
`np.ndarray` of inferenced. | def inference(self, observed_arr):
_ = self.__lstm_model.inference(observed_arr)
return self.__lstm_model.get_feature_points() | 368,891 |
Update this Discriminator by ascending its stochastic gradient.
Args:
grad_arr: `np.ndarray` of gradients.
Returns:
`np.ndarray` of delta or gradients. | def learn(self, grad_arr):
if grad_arr.ndim > 3:
grad_arr = grad_arr.reshape((
grad_arr.shape[0],
grad_arr.shape[1],
-1
))
grad_arr = grad_arr[:, -1]
elif grad_arr.ndim == 3:
grad_arr = gra... | 368,892 |
Infernce Q-Value.
Args:
predicted_q_arr: `np.ndarray` of predicted Q-Values.
real_q_arr: `np.ndarray` of real Q-Values. | def learn_q(self, predicted_q_arr, real_q_arr):
self.__predicted_q_arr_list.append(predicted_q_arr)
while len(self.__predicted_q_arr_list) > self.__seq_len:
self.__predicted_q_arr_list = self.__predicted_q_arr_list[1:]
while len(self.__predicted_q_arr_list) < self.__seq_len:... | 368,894 |
Infernce Q-Value.
Args:
next_action_arr: `np.ndarray` of action.
Returns:
`np.ndarray` of Q-Values. | def inference_q(self, next_action_arr):
q_arr = next_action_arr.reshape((next_action_arr.shape[0], -1))
self.__q_arr_list.append(q_arr)
while len(self.__q_arr_list) > self.__seq_len:
self.__q_arr_list = self.__q_arr_list[1:]
while len(self.__q_arr_list) < self.__seq_... | 368,895 |
Init.
Args:
batch_size: Batch size.
seq_len: The length of sequneces.
The length corresponds to the number of `time` splited by `time_fraction`.
min_pitch: The minimum of note number.
max_pitch:... | def __init__(
self,
batch_size=20,
seq_len=10,
min_pitch=24,
max_pitch=108
):
self.__batch_size = batch_size
self.__seq_len = seq_len
self.__dim = max_pitch - min_pitch | 368,897 |
Compute distance.
Args:
x_arr: `np.ndarray` of vectors.
y_arr: `np.ndarray` of vectors.
Retruns:
`np.ndarray` of distances. | def compute(self, x_arr, y_arr):
return np.linalg.norm(x_arr - y_arr, axis=-1) | 368,899 |
Tokenize token list.
Args:
token_list: The list of tokens..
Returns:
[vector of token, vector of token, vector of token, ...] | def vectorize(self, token_list):
sentence_list = [token_list]
test_observed_arr = self.__setup_dataset(sentence_list, self.__token_master_list)
pred_arr = self.__controller.inference(test_observed_arr)
return self.__controller.get_feature_points() | 368,900 |
Learning.
Args:
iter_n: The number of training iterations.
k_step: The number of learning of the `discriminator`. | def learn(self, iter_n=500, k_step=10):
generative_model, discriminative_model = self.__GAN.train(
self.__true_sampler,
self.__generative_model,
self.__discriminative_model,
iter_n=iter_n,
k_step=k_step
)
self.__genera... | 368,902 |
Entry Point.
Args:
url: target url. | def Main(url):
# The object of Web-Scraping.
web_scrape = WebScraping()
# Execute Web-Scraping.
document = web_scrape.scrape(url)
# The object of NLP.
nlp_base = NlpBase()
# Set tokenizer. This is japanese tokenizer with MeCab.
nlp_base.tokenizable_doc = MeCabTokenizer()
senten... | 368,904 |
Filtering with std.
Args:
scored_list: The list of scoring.
Retruns:
The list of filtered result. | def filter(self, scored_list):
if len(scored_list) > 0:
avg = np.mean([s[1] for s in scored_list])
std = np.std([s[1] for s in scored_list])
else:
avg = 0
std = 0
limiter = avg + 0.5 * std
mean_scored = [(sent_idx, score) for (sent... | 368,908 |
Init.
Args:
function_approximator: is-a `FunctionApproximator`.
map_size: Size of map.
memory_num: The number of step of agent's memory.
repeating_penalty: The value of penalty in the case that agent revisit.
en... | def __init__(
self,
function_approximator,
batch_size=4,
map_size=(10, 10),
memory_num=4,
repeating_penalty=0.5,
enemy_num=2,
enemy_init_dist=5
):
self.__map_arr = self.__create_map(map_size)
self.__agent_pos = self.START_POS
... | 368,910 |
Infernce.
Args:
state_arr: `np.ndarray` of state.
limit: The number of inferencing.
Returns:
`list of `np.ndarray` of an optimal route. | def inference(self, state_arr, limit=1000):
self.__inferencing_flag = True
agent_x, agent_y = np.where(state_arr[0] == 1)
agent_x, agent_y = agent_x[0], agent_y[0]
self.__create_enemy(self.__map_arr)
result_list = [(agent_x, agent_y, 0.0)]
result_val_list = [age... | 368,911 |
Extract possible actions.
Args:
state_arr: `np.ndarray` of state.
Returns:
`np.ndarray` of actions.
The shape is:(
`batch size corresponded to each action key`,
`channel that is 1`,
`feature points1`,
... | def extract_possible_actions(self, state_arr):
agent_x, agent_y = np.where(state_arr[-1] == 1)
agent_x, agent_y = agent_x[0], agent_y[0]
possible_action_arr = None
for x, y in [
(-1, 0), (1, 0), (0, -1), (0, 1), (0, 0)
]:
next_x = agent_x + x
... | 368,912 |
Compute the reward value.
Args:
state_arr: `np.ndarray` of state.
action_arr: `np.ndarray` of action.
Returns:
Reward value. | def observe_reward_value(self, state_arr, action_arr):
if self.__check_goal_flag(action_arr) is True:
return 1.0
else:
self.__move_enemy(action_arr)
x, y = np.where(action_arr[-1] == 1)
x, y = x[0], y[0]
e_dist_sum = 0.0
... | 368,913 |
Check the end flag.
If this return value is `True`, the learning is end.
As a rule, the learning can not be stopped.
This method should be overrided for concreate usecases.
Args:
state_arr: `np.ndarray` of state in `self.t`.
Returns:
bool | def check_the_end_flag(self, state_arr):
if self.__check_goal_flag(state_arr) is True or self.__check_crash_flag(state_arr):
return True
else:
return False | 368,916 |
Calculate similarity with the Dice coefficient.
Concrete method.
Args:
token_list_x: [token, token, token, ...]
token_list_y: [token, token, token, ...]
Returns:
Similarity. | def calculate(self, token_list_x, token_list_y):
x, y = self.unique(token_list_x, token_list_y)
try:
result = 2 * len(x & y) / float(sum(map(len, (x, y))))
except ZeroDivisionError:
result = 0.0
return result | 368,919 |
Summarize input document.
Args:
test_arr: `np.ndarray` of observed data points..
vectorizable_token: is-a `VectorizableToken`.
sentence_list: `list` of all sentences.
limit: The number of selected abstract sentenc... | def summarize(self, test_arr, vectorizable_token, sentence_list, limit=5):
if isinstance(vectorizable_token, VectorizableToken) is False:
raise TypeError()
_ = self.inference(test_arr)
score_arr = self.__encoder_decoder_controller.get_reconstruction_error()
s... | 368,922 |
Draws samples from the `fake` distribution.
Args:
observed_arr: `np.ndarray` of observed data points.
Returns:
`np.ndarray` of inferenced. | def inference(self, observed_arr):
if observed_arr.ndim != 2:
observed_arr = observed_arr.reshape((observed_arr.shape[0], -1))
pred_arr = self.__nn.inference(observed_arr)
return pred_arr | 368,924 |
Update this Discriminator by ascending its stochastic gradient.
Args:
grad_arr: `np.ndarray` of gradients.
fix_opt_flag: If `False`, no optimization in this model will be done.
Returns:
`np.ndarray` of delta or gradients. | def learn(self, grad_arr, fix_opt_flag=False):
if grad_arr.ndim != 2:
grad_arr = grad_arr.reshape((grad_arr.shape[0], -1))
delta_arr = self.__nn.back_propagation(grad_arr)
if fix_opt_flag is False:
self.__nn.optimize(self.__learning_rate, 1)
... | 368,925 |
Init.
Args:
bar_gram: is-a `BarGram`.
midi_df_list: `list` of paths to MIDI data extracted by `MidiController`.
batch_size: Batch size.
seq_len: The length of sequneces.
The length correspon... | def __init__(
self,
bar_gram,
midi_df_list,
batch_size=20,
seq_len=10,
time_fraction=0.1,
conditional_flag=True
):
if isinstance(bar_gram, BarGram) is False:
raise TypeError()
self.__bar_gram = bar_gram
... | 368,926 |
Multi-Agent Learning.
Override.
Args:
initial_state_key: Initial state.
limit: Limit of the number of learning.
game_n: The number of games. | def learn(self, initial_state_key, limit=1000, game_n=1):
end_flag_list = [False] * len(self.q_learning_list)
for game in range(game_n):
state_key = copy.copy(initial_state_key)
self.t = 1
while self.t <= limit:
for i in range(len(self.q_learn... | 368,929 |
Init for Adaptive Simulated Annealing.
Args:
reannealing_per: How often will this model reanneals there per cycles.
thermostat: Thermostat.
t_min: The minimum temperature.
t_default: The default temperature. | def adaptive_set(
self,
reannealing_per=50,
thermostat=0.9,
t_min=0.001,
t_default=1.0
):
self.__reannealing_per = reannealing_per
self.__thermostat = thermostat
self.__t_min = t_min
self.__t_default = t_default | 368,934 |
Change temperature.
Override.
Args:
t: Now temperature.
Returns:
Next temperature. | def change_t(self, t):
t = super().change_t(t)
self.__now_cycles += 1
if self.__now_cycles % self.__reannealing_per == 0:
t = t * self.__thermostat
if t < self.__t_min:
t = self.__t_default
return t | 368,935 |
Training the model.
Args:
observed_arr: `np.ndarray` of observed data points.
target_arr: `np.ndarray` of target labeled data. | def learn(self, observed_arr, target_arr):
# Pre-learning.
if self.__pre_learning_epochs > 0:
self.__encoder_decoder_controller.learn(observed_arr, observed_arr)
learning_rate = self.__learning_rate
row_o = observed_arr.shape[0]
row_t = target_arr.sh... | 368,938 |
Learn features generated by `FeatureGenerator`.
Args:
feature_generator: is-a `FeatureGenerator`. | def learn_generated(self, feature_generator):
if isinstance(feature_generator, FeatureGenerator) is False:
raise TypeError("The type of `feature_generator` must be `FeatureGenerator`.")
# Pre-learning.
if self.__pre_learning_epochs > 0:
self.__encoder_dec... | 368,939 |
Infernece by the model.
Args:
observed_arr: `np.ndarray` of observed data points.
Returns:
`np.ndarray` of inferenced feature points. | def inference(self, observed_arr):
decoded_arr = self.__encoder_decoder_controller.inference(observed_arr)
encoded_arr = self.__encoder_decoder_controller.get_feature_points()
_ = self.__retrospective_encoder.inference(decoded_arr)
re_encoded_arr = self.__retrospective_enco... | 368,940 |
Summarize input document.
Args:
test_arr: `np.ndarray` of observed data points..
vectorizable_token: is-a `VectorizableToken`.
sentence_list: `list` of all sentences.
limit: The number of selected abstract sentenc... | def summarize(self, test_arr, vectorizable_token, sentence_list, limit=5):
if isinstance(vectorizable_token, VectorizableToken) is False:
raise TypeError()
_ = self.inference(test_arr)
_, loss_arr, _ = self.compute_retrospective_loss()
loss_list = loss_arr.... | 368,941 |
Back propagation.
Args:
delta_output_arr: Delta.
Returns:
Tuple data.
- decoder's `list` of gradations,
- encoder's `np.ndarray` of Delta,
- encoder's `list` of gradations. | def back_propagation(self, delta_arr):
re_encoder_delta_arr, delta_hidden_arr, re_encoder_grads_list = self.__retrospective_encoder.hidden_back_propagate(
delta_arr[:, -1]
)
re_encoder_grads_list.insert(0, None)
re_encoder_grads_list.insert(0, None)
... | 368,942 |
Back propagation.
Args:
re_encoder_grads_list: re-encoder's `list` of graduations.
decoder_grads_list: decoder's `list` of graduations.
encoder_grads_list: encoder's `list` of graduations.
learning_rate: Learning rate.
... | def optimize(
self,
re_encoder_grads_list,
decoder_grads_list,
encoder_grads_list,
learning_rate,
epoch
):
self.__retrospective_encoder.optimize(re_encoder_grads_list, learning_rate, epoch)
self.__encoder_decoder_controller.optimize(... | 368,943 |
Change dropout rate in Encoder/Decoder.
Args:
dropout_rate: The probalibity of dropout. | def __change_inferencing_mode(self, inferencing_mode):
self.__encoder_decoder_controller.decoder.opt_params.inferencing_mode = inferencing_mode
self.__encoder_decoder_controller.encoder.opt_params.inferencing_mode = inferencing_mode
self.__retrospective_encoder.opt_params.inferencin... | 368,945 |
Remember best parameters.
Args:
encoder_best_params_list: `list` of encoder's parameters.
decoder_best_params_list: `list` of decoder's parameters.
re_encoder_best_params_list: `list` of re-decoder's parameters. | def __remember_best_params(self, encoder_best_params_list, decoder_best_params_list, re_encoder_best_params_list):
if len(encoder_best_params_list) > 0 and len(decoder_best_params_list) > 0:
self.__encoder_decoder_controller.encoder.graph.weights_lstm_hidden_arr = encoder_best_params_lis... | 368,946 |
Entry Point.
Args:
url: PDF url. | def Main(url, similarity_mode="TfIdfCosine", similarity_limit=0.75):
# The object of Web-scraping.
web_scrape = WebScraping()
# Set the object of reading PDF files.
web_scrape.readable_web_pdf = WebPDFReading()
# Execute Web-scraping.
document = web_scrape.scrape(url)
if similarity_mod... | 368,948 |
Entry Point.
Args:
url: target url. | def Main(url):
# The object of Web-Scraping.
web_scrape = WebScraping()
# Execute Web-Scraping.
document = web_scrape.scrape(url)
# The object of NLP.
nlp_base = NlpBase()
# Set tokenizer. This is japanese tokenizer with MeCab.
nlp_base.tokenizable_doc = MeCabTokenizer()
senten... | 368,950 |
Tokenize vector.
Args:
vector_list: The list of vector of one token.
Returns:
token | def tokenize(self, vector_list):
if self.computable_distance is None:
self.computable_distance = EuclidDistance()
vector_arr = np.array(vector_list)
distance_arr = np.empty_like(vector_arr)
feature_arr = self.__dbm.get_feature_point(layer_number=0)
key... | 368,960 |
具象メソッド
モノラルビートを生成する
Args:
stream: PyAudioのストリーム
left_chunk: 左音源に対応するチャンク
right_chunk: 右音源に対応するチャンク
volume: 音量
Returns:
void | def write_stream(self, stream, left_chunk, right_chunk, volume):
if len(left_chunk) != len(right_chunk):
raise ValueError()
for i in range(len(left_chunk)):
chunk = (left_chunk[i] + right_chunk[i]) * volume
data = struct.pack("2f", chunk, chunk)
... | 368,963 |
具象メソッド
wavファイルに保存するモノラルビートを読み込む
Args:
left_chunk: 左音源に対応するチャンク
right_chunk: 右音源に対応するチャンク
volume: 音量
bit16: 整数化の条件
Returns:
フレームのlist | def read_stream(self, left_chunk, right_chunk, volume, bit16=32767.0):
if len(left_chunk) != len(right_chunk):
raise ValueError()
frame_list = []
for i in range(len(left_chunk)):
chunk = int((left_chunk[i] + right_chunk[i]) * bit16 * volume)
... | 368,964 |
Tokenize str.
Args:
sentence_str: tokenized string.
Returns:
[token, token, token, ...] | def tokenize(self, sentence_str):
mt = MeCab.Tagger("-Owakati")
wordlist = mt.parse(sentence_str)
token_list = wordlist.rstrip(" \n").split(" ")
return token_list | 368,965 |
Init.
Args:
gans_value_function: is-a `GANsValueFunction`. | def __init__(self, gans_value_function=None):
if gans_value_function is None:
gans_value_function = MiniMax()
if isinstance(gans_value_function, GANsValueFunction) is False:
raise TypeError("The type of `gans_value_function` must be `GANsValueFunction`.")
... | 368,966 |
Train the generative model as the Auto-Encoder.
Args:
generative_model: Generator which draws samples from the `fake` distribution.
a_logs_list: `list` of the reconstruction errors.
Returns:
The tuple data. The shape is...
- Gene... | def train_auto_encoder(self, generative_model, a_logs_list):
error_arr = generative_model.update()
if error_arr.ndim > 1:
error_arr = error_arr.mean()
a_logs_list.append(error_arr)
self.__logger.debug("The reconstruction error (mean): " + str(error_arr))
... | 368,968 |
Compute discriminator's reward.
Args:
true_posterior_arr: `np.ndarray` of `true` posterior inferenced by the discriminator.
generated_posterior_arr: `np.ndarray` of `fake` posterior inferenced by the discriminator.
Returns:
`np.ndarray` of ... | def compute_discriminator_reward(
self,
true_posterior_arr,
generated_posterior_arr
):
grad_arr = np.log(true_posterior_arr + 1e-08) + np.log(1 - generated_posterior_arr + 1e-08)
return grad_arr | 368,969 |
Select action by Q(state, action).
Args:
next_action_arr: `np.ndarray` of actions.
next_q_arr: `np.ndarray` of Q-Values.
Retruns:
Tuple(`np.ndarray` of action., Q-Value) | def select_action(self, next_action_arr, next_q_arr):
key_arr = self.select_action_key(next_action_arr, next_q_arr)
return next_action_arr[key_arr], next_q_arr[key_arr] | 368,974 |
Select action by Q(state, action).
Args:
next_action_arr: `np.ndarray` of actions.
next_q_arr: `np.ndarray` of Q-Values.
Retruns:
`np.ndarray` of keys. | def select_action_key(self, next_action_arr, next_q_arr):
epsilon_greedy_flag = bool(np.random.binomial(n=1, p=self.epsilon_greedy_rate))
if epsilon_greedy_flag is False:
key = np.random.randint(low=0, high=next_action_arr.shape[0])
else:
key = next_q_arr.argmax(... | 368,975 |
Return metadata for 1 ticker
Use TiingoClient.list_tickers() to get available options
Args:
ticker (str) : Unique identifier for stock | def get_ticker_metadata(self, ticker, fmt='json'):
url = "tiingo/daily/{}".format(ticker)
response = self._request('GET', url)
data = response.json()
if fmt == 'json':
return data
elif fmt == 'object':
return dict_to_object(data, "Ticker") | 369,040 |
Base class for interacting with RESTful APIs
Child class MUST have a ._base_url property!
Args:
config (dict): Arbitrary options that child classes can access | def __init__(self, config={}):
self._config = config
# The child class should override these properties or else the
# restclient won't work. Reevalute whether to do this as an abstract
# base class so it doesn't get used by itself.
self._headers = {}
self._base_... | 369,047 |
Make HTTP request and return response object
Args:
method (str): GET, POST, PUT, DELETE
url (str): path appended to the base_url to create request
**kwargs: passed directly to a requests.request object | def _request(self, method, url, **kwargs):
resp = self._session.request(method,
'{}/{}'.format(self._base_url, url),
headers=self._headers,
**kwargs)
try:
resp.raise_for_s... | 369,048 |
Retrieves information provided by the API root endpoint
``'/api/v1'``.
Args:
headers (dict): Optional headers to pass to the request.
Returns:
dict: Details of the HTTP API provided by the BigchainDB
server. | def api_info(self, headers=None):
return self.transport.forward_request(
method='GET',
path=self.api_prefix,
headers=headers,
) | 370,049 |
Submit a transaction to the Federation with the mode `async`.
Args:
transaction (dict): the transaction to be sent
to the Federation node(s).
headers (dict): Optional headers to pass to the request.
Returns:
dict: The transaction sent to the Federati... | def send_async(self, transaction, headers=None):
return self.transport.forward_request(
method='POST',
path=self.path,
json=transaction,
params={'mode': 'async'},
headers=headers) | 370,052 |
Retrieves the transaction with the given id.
Args:
txid (str): Id of the transaction to retrieve.
headers (dict): Optional headers to pass to the request.
Returns:
dict: The transaction with the given id. | def retrieve(self, txid, headers=None):
path = self.path + txid
return self.transport.forward_request(
method='GET', path=path, headers=None) | 370,053 |
Get the block that contains the given transaction id (``txid``)
else return ``None``
Args:
txid (str): Transaction id.
headers (dict): Optional headers to pass to the request.
Returns:
:obj:`list` of :obj:`int`: List of block heights. | def get(self, *, txid, headers=None):
block_list = self.transport.forward_request(
method='GET',
path=self.path,
params={'transaction_id': txid},
headers=headers,
)
return block_list[0] if len(block_list) else None | 370,055 |
Retrieves the block with the given ``block_height``.
Args:
block_height (str): height of the block to retrieve.
headers (dict): Optional headers to pass to the request.
Returns:
dict: The block with the given ``block_height``. | def retrieve(self, block_height, headers=None):
path = self.path + block_height
return self.transport.forward_request(
method='GET', path=path, headers=None) | 370,056 |
Retrieves the assets that match a given text search string.
Args:
search (str): Text search string.
limit (int): Limit the number of returned documents. Defaults to
zero meaning that it returns all the matching assets.
headers (dict): Optional headers to pass... | def get(self, *, search, limit=0, headers=None):
return self.transport.forward_request(
method='GET',
path=self.path,
params={'search': search, 'limit': limit},
headers=headers
) | 370,057 |
Fulfills the given transaction.
Args:
transaction (dict): The transaction to be fulfilled.
private_keys (:obj:`str` | :obj:`list` | :obj:`tuple`): One or
more private keys to be used for fulfilling the
transaction.
Returns:
dict: The fulfilled transaction payloa... | def fulfill_transaction(transaction, *, private_keys):
if not isinstance(private_keys, (list, tuple)):
private_keys = [private_keys]
# NOTE: Needed for the time being. See
# https://github.com/bigchaindb/bigchaindb/issues/797
if isinstance(private_keys, tuple):
private_keys = list(... | 370,061 |
Initializes a :class:`~bigchaindb_driver.connection.Connection`
instance.
Args:
node_url (str): Url of the node to connect to.
headers (dict): Optional headers to send with each request. | def __init__(self, *, node_url, headers=None):
self.node_url = node_url
self.session = Session()
if headers:
self.session.headers.update(headers)
self._retries = 0
self.backoff_time = None | 370,066 |
Picks a connection with the earliest backoff time.
As a result, the first connection is picked
for as long as it has no backoff time.
Otherwise, the connections are tried in a round robin fashion.
Args:
connections (:obj:list): List of
:class:`~bigc... | def pick(self, connections):
if len(connections) == 1:
return connections[0]
def key(conn):
return (datetime.min
if conn.backoff_time is None
else conn.backoff_time)
return min(*connections, key=key) | 370,070 |
Initializes a :class:`~bigchaindb_driver.pool.Pool` instance.
Args:
connections (list): List of
:class:`~bigchaindb_driver.connection.Connection` instances. | def __init__(self, connections, picker_class=RoundRobinPicker):
self.connections = connections
self.picker = picker_class() | 370,071 |
Initializes an instance of
:class:`~bigchaindb_driver.transport.Transport`.
Args:
nodes: each node is a dictionary with the keys `endpoint` and
`headers`
timeout (int): Optional timeout in seconds. | def __init__(self, *nodes, timeout=None):
self.nodes = nodes
self.timeout = timeout
self.connection_pool = Pool([Connection(node_url=node['endpoint'],
headers=node['headers'])
for node in nodes]) | 370,072 |
Validate all (nested) keys in `obj` by using `validation_fun`.
Args:
obj_name (str): name for `obj` being validated.
obj (dict): dictionary object.
validation_fun (function): function used to validate the value
of `key`.
Returns:
None: indica... | def validate_all_keys(obj_name, obj, validation_fun):
for key, value in obj.items():
validation_fun(obj_name, key)
if isinstance(value, dict):
validate_all_keys(obj_name, value, validation_fun) | 370,074 |
Validate value for all (nested) occurrence of `key` in `obj`
using `validation_fun`.
Args:
obj (dict): dictionary object.
key (str): key whose value is to be validated.
validation_fun (function): function used to validate the value
of `key`.
Rais... | def validate_all_values_for_key(obj, key, validation_fun):
for vkey, value in obj.items():
if vkey == key:
validation_fun(value)
elif isinstance(value, dict):
validate_all_values_for_key(value, key, validation_fun) | 370,075 |
Validate the transaction ID of a transaction
Args:
tx_body (dict): The Transaction to be transformed. | def validate_id(tx_body):
# NOTE: Remove reference to avoid side effects
tx_body = deepcopy(tx_body)
try:
proposed_tx_id = tx_body['id']
except KeyError:
raise InvalidHash('No transaction id found!')
tx_body['id'] = None
tx_body_serializ... | 370,081 |
Transforms a Python dictionary to a Transaction object.
Args:
tx_body (dict): The Transaction to be transformed.
Returns:
:class:`~bigchaindb.common.transaction.Transaction` | def from_dict(cls, tx):
inputs = [Input.from_dict(input_) for input_ in tx['inputs']]
outputs = [Output.from_dict(output) for output in tx['outputs']]
return cls(tx['operation'], tx['asset'], inputs, outputs,
tx['metadata'], tx['version'], hash_id=tx['id']) | 370,082 |
Initialize the dir entry with unset values.
Args:
filesystem: the fake filesystem used for implementation. | def __init__(self, filesystem):
self._filesystem = filesystem
self.name = ''
self.path = ''
self._inode = None
self._islink = False
self._isdir = False
self._statresult = None
self._statresult_symlink = None | 370,190 |
Return a stat_result object for this entry.
Args:
follow_symlinks: If False and the entry is a symlink, return the
result for the symlink, otherwise for the object it points to. | def stat(self, follow_symlinks=True):
if follow_symlinks:
if self._statresult_symlink is None:
file_object = self._filesystem.resolve(self.path)
if self._filesystem.is_windows_fs:
file_object.st_nlink = 0
self._statresult_s... | 370,192 |
Add the deprecated version of a member function to the given class.
Gives a deprecation warning on usage.
Args:
clss: the class where the deprecated function is to be added
func: the actual function that is called by the deprecated version
deprecated_name: the deprec... | def add(clss, func, deprecated_name):
@Deprecator(func.__name__, deprecated_name)
def _old_function(*args, **kwargs):
return func(*args, **kwargs)
setattr(clss, deprecated_name, _old_function) | 370,198 |
Make the path absolute, resolving all symlinks on the way and also
normalizing it (for example turning slashes into backslashes
under Windows).
Args:
strict: If False (default) no exception is raised if the path
does not exist.
New in Python 3.6.
... | def resolve(self, strict=None):
if sys.version_info >= (3, 6) or pathlib2:
if strict is None:
strict = False
else:
if strict is not None:
raise TypeError(
"resolve() got an unexpected keyword argument 'strict'")
... | 370,212 |
Sets the file contents and size.
Called internally after initial file creation.
Args:
contents: string, new content of file.
Returns:
True if the contents have been changed.
Raises:
IOError: if the st_size is not a non-negative integer,
... | def _set_initial_contents(self, contents):
contents = self._encode_contents(contents)
changed = self._byte_contents != contents
st_size = len(contents)
if self._byte_contents:
self.size = 0
current_size = self.st_size or 0
self.filesystem.change_disk... | 370,225 |
Resizes file content, padding with nulls if new size exceeds the
old size.
Args:
st_size: The desired size for the file.
Raises:
IOError: if the st_size arg is not a non-negative integer
or if st_size exceeds the available file system space | def size(self, st_size):
self._check_positive_int(st_size)
current_size = self.st_size or 0
self.filesystem.change_disk_usage(
st_size - current_size, self.name, self.st_dev)
if self._byte_contents:
if st_size < current_size:
self._byte_c... | 370,228 |
Adds a child FakeFile to this directory.
Args:
path_object: FakeFile instance to add as a child of this directory.
Raises:
OSError: if the directory has no write permission (Posix only)
OSError: if the file or directory to be added already exists | def add_entry(self, path_object):
if (not is_root() and not self.st_mode & PERM_WRITE and
not self.filesystem.is_windows_fs):
exception = IOError if IS_PY2 else OSError
raise exception(errno.EACCES, 'Permission Denied', self.path)
if path_object.name in ... | 370,238 |
Retrieves the specified child file or directory entry.
Args:
pathname_name: The basename of the child object to retrieve.
Returns:
The fake file or directory object.
Raises:
KeyError: if no child exists by the specified name. | def get_entry(self, pathname_name):
pathname_name = self._normalized_entryname(pathname_name)
return self.contents[pathname_name] | 370,239 |
Raises IOError.
The error message is constructed from the given error code and shall
start with the error in the real system.
Args:
errno: A numeric error code from the C variable errno.
filename: The name of the affected file, if any. | def raise_io_error(self, errno, filename=None):
raise IOError(errno, self._error_message(errno), filename) | 370,249 |
Add a new mount point for a filesystem device.
The mount point gets a new unique device number.
Args:
path: The root path for the new mount path.
total_size: The new total size of the added filesystem device
in bytes. Defaults to infinite size.
Returns:... | def add_mount_point(self, path, total_size=None):
path = self.absnormpath(path)
if path in self.mount_points:
self.raise_os_error(errno.EEXIST, path)
self._last_dev += 1
self.mount_points[path] = {
'idev': self._last_dev, 'total_size': total_size, 'used_s... | 370,251 |
Return the total, used and free disk space in bytes as named tuple,
or placeholder values simulating unlimited space if not set.
.. note:: This matches the return value of shutil.disk_usage().
Args:
path: The disk space is returned for the file system device where
`... | def get_disk_usage(self, path=None):
DiskUsage = namedtuple('usage', 'total, used, free')
if path is None:
mount_point = self.mount_points[self.root.name]
else:
mount_point = self._mount_point_for_path(path)
if mount_point and mount_point['total_size'] is... | 370,255 |
Changes the total size of the file system, preserving the used space.
Example usage: set the size of an auto-mounted Windows drive.
Args:
total_size: The new total size of the filesystem in bytes.
path: The disk space is changed for the file system device where
... | def set_disk_usage(self, total_size, path=None):
if path is None:
path = self.root.name
mount_point = self._mount_point_for_path(path)
if (mount_point['total_size'] is not None and
mount_point['used_size'] > total_size):
self.raise_io_error(errno.... | 370,256 |
Change the used disk space by the given amount.
Args:
usage_change: Number of bytes added to the used space.
If negative, the used space will be decreased.
file_path: The path of the object needing the disk space.
st_dev: The device ID for the respective fi... | def change_disk_usage(self, usage_change, file_path, st_dev):
mount_point = self._mount_point_for_device(st_dev)
if mount_point:
total_size = mount_point['total_size']
if total_size is not None:
if total_size - mount_point['used_size'] < usage_change:
... | 370,257 |
Return the os.stat-like tuple for the FakeFile object of entry_path.
Args:
entry_path: Path to filesystem object to retrieve.
follow_symlinks: If False and entry_path points to a symlink,
the link itself is inspected instead of the linked object.
Returns:
... | def stat(self, entry_path, follow_symlinks=True):
# stat should return the tuple representing return value of os.stat
try:
file_object = self.resolve(
entry_path, follow_symlinks, allow_fd=True)
self.raise_for_filepath_ending_with_separator(
... | 370,258 |
Change the permissions of a file as encoded in integer mode.
Args:
path: (str) Path to the file.
mode: (int) Permissions.
follow_symlinks: If `False` and `path` points to a symlink,
the link itself is affected instead of the linked object. | def chmod(self, path, mode, follow_symlinks=True):
try:
file_object = self.resolve(path, follow_symlinks, allow_fd=True)
except IOError as io_error:
if io_error.errno == errno.ENOENT:
self.raise_os_error(errno.ENOENT, path)
raise
if se... | 370,260 |
Add file_obj to the list of open files on the filesystem.
Used internally to manage open files.
The position in the open_files array is the file descriptor number.
Args:
file_obj: File object to be added to open files list.
Returns:
File descriptor number for t... | def _add_open_file(self, file_obj):
if self._free_fd_heap:
open_fd = heapq.heappop(self._free_fd_heap)
self.open_files[open_fd] = [file_obj]
return open_fd
self.open_files.append([file_obj])
return len(self.open_files) - 1 | 370,263 |
Remove file object with given descriptor from the list
of open files.
Sets the entry in open_files to None.
Args:
file_des: Descriptor of file object to be removed from
open files list. | def _close_open_file(self, file_des):
self.open_files[file_des] = None
heapq.heappush(self._free_fd_heap, file_des) | 370,264 |
Return an open file.
Args:
file_des: File descriptor of the open file.
Raises:
OSError: an invalid file descriptor.
TypeError: filedes is not an integer.
Returns:
Open file object. | def get_open_file(self, file_des):
if not is_int_type(file_des):
raise TypeError('an integer is required')
if (file_des >= len(self.open_files) or
self.open_files[file_des] is None):
self.raise_os_error(errno.EBADF, str(file_des))
return self.open... | 370,265 |
Return True if the given file object is in the list of open files.
Args:
file_object: The FakeFile object to be checked.
Returns:
`True` if the file is open. | def has_open_file(self, file_object):
return (file_object in [wrappers[0].get_object()
for wrappers in self.open_files if wrappers]) | 370,266 |
Return a normalized case version of the given path for
case-insensitive file systems. For case-sensitive file systems,
return path unchanged.
Args:
path: the file path to be transformed
Returns:
A version of path matching the case of existing path elements. | def _original_path(self, path):
def components_to_path():
if len(path_components) > len(normalized_components):
normalized_components.extend(
path_components[len(normalized_components):])
sep = self._path_separator(path)
normalize... | 370,269 |
Absolutize and minimalize the given path.
Forces all relative paths to be absolute, and normalizes the path to
eliminate dot and empty components.
Args:
path: Path to normalize.
Returns:
The normalized path relative to the current working directory,
... | def absnormpath(self, path):
path = self.normcase(path)
cwd = self._matching_string(path, self.cwd)
if not path:
path = self.path_separator
elif not self._starts_with_root_path(path):
# Prefix relative paths with cwd, if cwd is not root.
root_... | 370,270 |
Mimic os.path.splitpath using the specified path_separator.
Mimics os.path.splitpath using the path_separator that was specified
for this FakeFilesystem.
Args:
path: (str) The path to split.
Returns:
(str) A duple (pathname, basename) for which pathname does n... | def splitpath(self, path):
path = self.normcase(path)
sep = self._path_separator(path)
path_components = path.split(sep)
if not path_components:
return ('', '')
starts_with_drive = self._starts_with_drive_letter(path)
basename = path_components.pop()... | 370,271 |
Splits the path into the drive part and the rest of the path.
Taken from Windows specific implementation in Python 3.5
and slightly adapted.
Args:
path: the full path to be splitpath.
Returns:
A tuple of the drive part and the rest of the path, or of
... | def splitdrive(self, path):
path = make_string_path(path)
if self.is_windows_fs:
if len(path) >= 2:
path = self.normcase(path)
sep = self._path_separator(path)
# UNC path handling is here since Python 2.7.8,
# back-port... | 370,272 |
Mimic os.path.join using the specified path_separator.
Args:
*paths: (str) Zero or more paths to join.
Returns:
(str) The paths joined by the path separator, starting with
the last absolute path in paths. | def joinpaths(self, *paths):
if sys.version_info >= (3, 6):
paths = [os.fspath(path) for path in paths]
if len(paths) == 1:
return paths[0]
if self.is_windows_fs:
return self._join_paths_with_drive_support(*paths)
joined_path_segments = []
... | 370,274 |
Return True if file_path starts with a drive letter.
Args:
file_path: the full path to be examined.
Returns:
`True` if drive letter support is enabled in the filesystem and
the path starts with a drive letter. | def _starts_with_drive_letter(self, file_path):
colon = self._matching_string(file_path, ':')
return (self.is_windows_fs and len(file_path) >= 2 and
file_path[:1].isalpha and (file_path[1:2]) == colon) | 370,276 |
Return true if a path points to an existing file system object.
Args:
file_path: The path to examine.
Returns:
(bool) True if the corresponding object exists.
Raises:
TypeError: if file_path is None. | def exists(self, file_path, check_link=False):
if check_link and self.islink(file_path):
return True
file_path = make_string_path(file_path)
if file_path is None:
raise TypeError
if not file_path:
return False
if file_path == self.dev_... | 370,282 |
Search for the specified filesystem object within the fake
filesystem.
Args:
file_path: Specifies target FakeFile object to retrieve, with a
path that has already been normalized/resolved.
Returns:
The FakeFile object corresponding to file_path.
... | def get_object_from_normpath(self, file_path):
file_path = make_string_path(file_path)
if file_path == self.root.name:
return self.root
if file_path == self.dev_null.name:
return self.dev_null
file_path = self._original_path(file_path)
path_compo... | 370,289 |
Search for the specified filesystem object within the fake
filesystem.
Args:
file_path: Specifies the target FakeFile object to retrieve.
Returns:
The FakeFile object corresponding to `file_path`.
Raises:
IOError: if the object is not found. | def get_object(self, file_path):
file_path = make_string_path(file_path)
file_path = self.absnormpath(self._original_path(file_path))
return self.get_object_from_normpath(file_path) | 370,290 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.