blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
616
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 777
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 149
values | src_encoding
stringclasses 26
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 3
10.2M
| extension
stringclasses 188
values | content
stringlengths 3
10.2M
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
d10192ab95a1b46d604aa924f07a235b10ff2971 | 4fbd844113ec9d8c526d5f186274b40ad5502aa3 | /algorithms/python3/number_of_digit_one.py | 538d9b720619759dbae129533367a918a55ffec3 | [] | no_license | capric8416/leetcode | 51f9bdc3fa26b010e8a1e8203a7e1bcd70ace9e1 | 503b2e303b10a455be9596c31975ee7973819a3c | refs/heads/master | 2022-07-16T21:41:07.492706 | 2020-04-22T06:18:16 | 2020-04-22T06:18:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 510 | py | # !/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Given an integer n, count the total number of digit 1 appearing in all non-negative integers less than or equal to n.
Example:
Input: 13
Output: 6
Explanation: Digit 1 occurred in the following numbers: 1, 10, 11, 12, 13.
"""
""" ==================== body ==================== """
class Solution:
def countDigitOne(self, n):
"""
:type n: int
:rtype: int
"""
""" ==================== body ==================== """
| [
"[email protected]"
] | |
4afb6395738c94f6f3c5f69cd5aba31fac3f7ab9 | 23a56e0555d6b27aa444d8396ec32f9d2b678a39 | /07_ur_online/shifted_frames_setup/compas/packages/compas_fabrication/fabrication/grasshopper/utilities/sets.py | 0aa962839f412ffad8a96c1e5c3841c1df6bb963 | [
"MIT"
] | permissive | dtbinh/T1_python-exercises | 2ce1b01bc71f8032bbe8fb4ef8f71b648dcde1c5 | f4710c3dc2ba8ddb3e3e9069ab8d65df674463ab | refs/heads/master | 2020-04-04T20:00:52.191601 | 2018-01-09T08:14:36 | 2018-01-09T08:14:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,129 | py | from Grasshopper import DataTree as Tree
from Grasshopper.Kernel.Data import GH_Path as Path
from System import Array
def list_to_tree(alist, none_and_holes=False, base_path=[0]):
"""
Transforms nestings of lists or tuples to a Grasshopper DataTree
Usage:
mytree = [ [1,2], 3, [],[ 4,[5]] ]
a = list_to_tree(mytree)
b = list_to_tree(mytree, none_and_holes=True, base_path=[7,1])
"""
def process_one_item(alist, tree, track):
path = Path(Array[int](track))
if len(alist) == 0 and none_and_holes:
tree.EnsurePath(path)
return
for i,item in enumerate(alist):
if hasattr(item, '__iter__'): #if list or tuple
track.append(i)
process_one_item(item, tree, track)
track.pop()
else:
if none_and_holes:
tree.Insert(item, path, i)
elif item is not None:
tree.Add(item, path)
tree = Tree[object]()
if alist is not None:
process_one_item(alist, tree, base_path[:])
return tree | [
"rusenova"
] | rusenova |
18a6e21aeda01c6a19f315813bff0d01b04146e0 | b66450f669095b0ad013ea82cb1ae575b83d74c3 | /Interview Preparation 2/maze.py | eae0d33ab121c0679d4a9e3e440d6211bec9b2ad | [] | no_license | aulb/ToAsk | 2649a3fad357820e3c8809816967dfb274704735 | 1e54c76ab9f7772316186db74496735ca1da65ce | refs/heads/master | 2021-05-01T20:35:14.062678 | 2020-02-23T07:44:29 | 2020-02-23T07:44:29 | 33,289,737 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,032 | py | Implement a function to generate a maze.
from random import randint
import enum
class Condition(enum):
CLEAR = 0
RIGHT = 1
BOTTOM = 2
class Direction(enum):
RIGHT = 0
LEFT = 1
UP = 2
DOWN = 3
# Create maze from top left to bottom right
def generate_maze(row, col):
if row < 0 or col < 0: return []
# create a fresh matrix of all zeroes
maze = [[0 for _ in range(col)] for _ in range(row)]
def get_direction(condition=Condition.CLEAR):
direction = randint(1, 10)
if 1 <= direction <= 4:
if Condition.CLEAR: return Direction.RIGHT
elif Condition.RIGHT: return Direction.DOWN
else: return Direction.RIGHT
elif 5 <= direction <= 8:
if Condition.CLEAR: return Direction.DOWN
elif Condition.RIGHT: return Direction.DOWN
else: return Direction.RIGHT
elif direction == 9:
if Condition.CLEAR: return Direction.LEFT
elif Condition.RIGHT: return Direction.DOWN
else: return Direction.UP
else:
if Condition.CLEAR: return Direction.UP
elif Condition.RIGHT: return Direction.DOWN
else: return Direction.RIGHT
def create_key(cell):
return ‘{},{}’.format(cell[0], cell[1])
def create_path(maze):
# [[i, j]]
path = {‘0,0’: True}
visited_rows = [0 for _ in range(len(maze))]
# randomly pick direction
current_cell = [0, 0]
condition = Condition.CLEAR
while current_cell != [len(maze) - 1, len(maze[0]) - 1]:
new_direction = get_direction(condition)
if new_direction == Direction.RIGHT:
# check if we can go right
if current_cell[1] + 1 <= len(maze[0]) - 1:
current_cell[1] += 1
path.append(current_cell[:])
if new_direction == Direction.LEFT:
# check if we can go right
if current_cell[1] - 1 >= 0:
current_cell[1] -= 1
path.append(current_cell[:])
if new_direction == Direction.UP:
# check if we can go right
if current_cell[0] - 1 >= 0:
current_cell[0] -= 1
path.append(current_cell[:])
if new_direction == Direction.DOWN:
# check if we can go right
if current_cell[0] + 1 <= len(maze) - 1:
current_cell[0] += 1
path.append(current_cell[:])
return path
def draw_wall(maze, path):
pass
| [
"[email protected]"
] | |
742f8a6dd2aee367cca6f94262b5612485524064 | 868b90e85541f1f76e1805346f18c2cb7675ffc8 | /cnn/02_introductory_cnn.py | 1eac1abda98b5a9c829bc11f7f50f4ba5b7d7589 | [] | no_license | WOW5678/tensorflow_study | a9a447c39c63a751046d4776eedc17589324634e | 39e202b102cd2ebc1ba16f793acc8ebe9ea0e752 | refs/heads/master | 2020-03-19T15:49:24.729778 | 2018-10-19T06:45:26 | 2018-10-19T06:45:26 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,639 | py | # Introductory CNN Model: MNIST Digits
#---------------------------------------
#
# In this example, we will download the MNIST handwritten
# digits and create a simple CNN network to predict the
# digit category (0-9)
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
from tensorflow.python.framework import ops
ops.reset_default_graph()
# Start a graph session
sess = tf.Session()
# Load data
data_dir = 'temp'
mnist = read_data_sets(data_dir)
# Convert images into 28x28 (they are downloaded as 1x784)
train_xdata = np.array([np.reshape(x, (28,28)) for x in mnist.train.images])
test_xdata = np.array([np.reshape(x, (28,28)) for x in mnist.test.images])
# Convert labels into one-hot encoded vectors
train_labels = mnist.train.labels
test_labels = mnist.test.labels
# Set model parameters
batch_size = 100
learning_rate = 0.005
evaluation_size = 500
image_width = train_xdata[0].shape[0]
image_height = train_xdata[0].shape[1]
target_size = max(train_labels) + 1
num_channels = 1 # greyscale = 1 channel
generations = 500
eval_every = 5
conv1_features = 25
conv2_features = 50
max_pool_size1 = 2 # NxN window for 1st max pool layer
max_pool_size2 = 2 # NxN window for 2nd max pool layer
fully_connected_size1 = 100
# Declare model placeholders
x_input_shape = (batch_size, image_width, image_height, num_channels)
x_input = tf.placeholder(tf.float32, shape=x_input_shape)
y_target = tf.placeholder(tf.int32, shape=(batch_size))
eval_input_shape = (evaluation_size, image_width, image_height, num_channels)
eval_input = tf.placeholder(tf.float32, shape=eval_input_shape)
eval_target = tf.placeholder(tf.int32, shape=(evaluation_size))
# Declare model parameters
conv1_weight = tf.Variable(tf.truncated_normal([4, 4, num_channels, conv1_features],
stddev=0.1, dtype=tf.float32))
conv1_bias = tf.Variable(tf.zeros([conv1_features], dtype=tf.float32))
conv2_weight = tf.Variable(tf.truncated_normal([4, 4, conv1_features, conv2_features],
stddev=0.1, dtype=tf.float32))
conv2_bias = tf.Variable(tf.zeros([conv2_features], dtype=tf.float32))
# fully connected variables
resulting_width = image_width // (max_pool_size1 * max_pool_size2)
resulting_height = image_height // (max_pool_size1 * max_pool_size2)
full1_input_size = resulting_width * resulting_height * conv2_features
full1_weight = tf.Variable(tf.truncated_normal([full1_input_size, fully_connected_size1],
stddev=0.1, dtype=tf.float32))
full1_bias = tf.Variable(tf.truncated_normal([fully_connected_size1], stddev=0.1, dtype=tf.float32))
full2_weight = tf.Variable(tf.truncated_normal([fully_connected_size1, target_size],
stddev=0.1, dtype=tf.float32))
full2_bias = tf.Variable(tf.truncated_normal([target_size], stddev=0.1, dtype=tf.float32))
# Initialize Model Operations
def my_conv_net(input_data):
# First Conv-ReLU-MaxPool Layer
conv1 = tf.nn.conv2d(input_data, conv1_weight, strides=[1, 1, 1, 1], padding='SAME')
relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_bias))
max_pool1 = tf.nn.max_pool(relu1, ksize=[1, max_pool_size1, max_pool_size1, 1],
strides=[1, max_pool_size1, max_pool_size1, 1], padding='SAME')
# Second Conv-ReLU-MaxPool Layer
conv2 = tf.nn.conv2d(max_pool1, conv2_weight, strides=[1, 1, 1, 1], padding='SAME')
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_bias))
max_pool2 = tf.nn.max_pool(relu2, ksize=[1, max_pool_size2, max_pool_size2, 1],
strides=[1, max_pool_size2, max_pool_size2, 1], padding='SAME')
# Transform Output into a 1xN layer for next fully connected layer
final_conv_shape = max_pool2.get_shape().as_list()
final_shape = final_conv_shape[1] * final_conv_shape[2] * final_conv_shape[3]
flat_output = tf.reshape(max_pool2, [final_conv_shape[0], final_shape])
# First Fully Connected Layer
fully_connected1 = tf.nn.relu(tf.add(tf.matmul(flat_output, full1_weight), full1_bias))
# Second Fully Connected Layer
final_model_output = tf.add(tf.matmul(fully_connected1, full2_weight), full2_bias)
return(final_model_output)
model_output = my_conv_net(x_input)
test_model_output = my_conv_net(eval_input)
# Declare Loss Function (softmax cross entropy)
loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=model_output, labels=y_target))
# Create a prediction function
prediction = tf.nn.softmax(model_output)
test_prediction = tf.nn.softmax(test_model_output)
# Create accuracy function
def get_accuracy(logits, targets):
batch_predictions = np.argmax(logits, axis=1)
num_correct = np.sum(np.equal(batch_predictions, targets))
return(100. * num_correct/batch_predictions.shape[0])
# Create an optimizer
my_optimizer = tf.train.MomentumOptimizer(learning_rate, 0.9)
train_step = my_optimizer.minimize(loss)
# Initialize Variables
init = tf.global_variables_initializer()
sess.run(init)
# Start training loop
train_loss = []
train_acc = []
test_acc = []
for i in range(generations):
rand_index = np.random.choice(len(train_xdata), size=batch_size)
rand_x = train_xdata[rand_index]
rand_x = np.expand_dims(rand_x, 3)
rand_y = train_labels[rand_index]
train_dict = {x_input: rand_x, y_target: rand_y}
sess.run(train_step, feed_dict=train_dict)
temp_train_loss, temp_train_preds = sess.run([loss, prediction], feed_dict=train_dict)
temp_train_acc = get_accuracy(temp_train_preds, rand_y)
if (i+1) % eval_every == 0:
eval_index = np.random.choice(len(test_xdata), size=evaluation_size)
eval_x = test_xdata[eval_index]
eval_x = np.expand_dims(eval_x, 3)
eval_y = test_labels[eval_index]
test_dict = {eval_input: eval_x, eval_target: eval_y}
test_preds = sess.run(test_prediction, feed_dict=test_dict)
temp_test_acc = get_accuracy(test_preds, eval_y)
# Record and print results
train_loss.append(temp_train_loss)
train_acc.append(temp_train_acc)
test_acc.append(temp_test_acc)
acc_and_loss = [(i+1), temp_train_loss, temp_train_acc, temp_test_acc]
acc_and_loss = [np.round(x,2) for x in acc_and_loss]
print('Generation # {}. Train Loss: {:.2f}. Train Acc (Test Acc): {:.2f} ({:.2f})'.format(*acc_and_loss))
# Matlotlib code to plot the loss and accuracies
eval_indices = range(0, generations, eval_every)
# Plot loss over time
plt.plot(eval_indices, train_loss, 'k-')
plt.title('Softmax Loss per Generation')
plt.xlabel('Generation')
plt.ylabel('Softmax Loss')
plt.show()
# Plot train and test accuracy
plt.plot(eval_indices, train_acc, 'k-', label='Train Set Accuracy')
plt.plot(eval_indices, test_acc, 'r--', label='Test Set Accuracy')
plt.title('Train and Test Accuracy')
plt.xlabel('Generation')
plt.ylabel('Accuracy')
plt.legend(loc='lower right')
plt.show()
# Plot some samples
# Plot the 6 of the last batch results:
actuals = rand_y[0:6]
predictions = np.argmax(temp_train_preds,axis=1)[0:6]
images = np.squeeze(rand_x[0:6])
Nrows = 2
Ncols = 3
for i in range(6):
plt.subplot(Nrows, Ncols, i+1)
plt.imshow(np.reshape(images[i], [28,28]), cmap='Greys_r')
plt.title('Actual: ' + str(actuals[i]) + ' Pred: ' + str(predictions[i]),
fontsize=10)
frame = plt.gca()
frame.axes.get_xaxis().set_visible(False)
frame.axes.get_yaxis().set_visible(False)
| [
"[email protected]"
] | |
86c22ca4ca7fe3b67919b54097bc9189805b71f3 | e4066b34668bbf7fccd2ff20deb0d53392350982 | /project_scrapy/spiders/grammarly.py | 19c27a8c3349910b1bd4ad1227155e4b6ced0815 | [] | no_license | sushma535/WebSites | 24a688b86e1c6571110f20421533f0e7fdf6e1a8 | 16a3bfa44e6c7e22ae230f5b336a059817871a97 | refs/heads/master | 2023-08-18T09:09:16.052555 | 2021-10-11T00:41:50 | 2021-10-11T00:41:50 | 415,621,279 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,541 | py | import scrapy
from scrapy.crawler import CrawlerProcess
import os
import csv
from csv import reader
import re
total_data = {}
class SimilarWeb(scrapy.Spider):
name = 'SW'
user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'
start_urls = ['https://www.grammarly.com/', 'https://www.similarsites.com/site/grammarly.com/']
csv_columns = ['Category', 'Description', 'Name', 'Url']
csv_file = 'websites1_data.csv'
count = 0
def parse(self, response):
data, desc, cat = '', '', ''
print('response url:', response.url)
if response.url == self.start_urls[0]:
data = response.css('title::text').get()
if data:
data = re.sub("\n\t\t", '', data)
total_data['Name'] = data
self.count += 1
elif response.url == self.start_urls[1]:
cat = response.css(
'div[class="StatisticsCategoriesDistribution__CategoryTitle-fnuckk-6 jsMDeK"]::text').getall()
desc = response.css('div[class="SiteHeader__Description-sc-1ybnx66-8 hhZNQm"]::text').get()
if cat:
cat = ": ".join(cat[:])
total_data['Category'] = cat
total_data['Description'] = desc
total_data['Url'] = self.start_urls[0]
self.count += 1
if self.count == 2:
print("total data", total_data)
new_data = [total_data['Category'], total_data['Description'], total_data['Name'],
total_data['Url']]
print("new data", new_data)
self.row_appending_to_csv_file(new_data)
def row_appending_to_csv_file(self, data):
if os.path.exists(self.csv_file):
need_to_add_headers = False
with open(self.csv_file, 'a+', newline='') as file:
file.seek(0)
csv_reader = reader(file)
if len(list(csv_reader)) == 0:
need_to_add_headers = True
csv_writer = csv.writer(file)
if need_to_add_headers:
csv_writer.writerow(self.csv_columns)
csv_writer.writerow(data)
else:
with open(self.csv_file, 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerow(self.csv_columns) # header
csv_writer.writerow(data)
process = CrawlerProcess()
process.crawl(SimilarWeb)
process.start()
| [
"[email protected]"
] | |
700a9fbcb89b1b66f52a940e26430e4a1f4c5494 | c96d9a76fe28630fe1b4cd7efa22e12fdce0399f | /kaggle/Song_popularity/optimize.py | a81690bd13b858784678e25cf5a75a1761a95589 | [] | no_license | tarunbhavnani/ml_diaries | 858839e8ab8817caae3d56d3dad6d4ee9176ddbe | 8d0700211a2881279df60ab2bea7095ef95ea8dc | refs/heads/master | 2023-08-18T08:28:50.881356 | 2023-08-16T09:39:34 | 2023-08-16T09:39:34 | 157,958,911 | 0 | 1 | null | 2023-03-13T05:17:52 | 2018-11-17T06:52:34 | Python | UTF-8 | Python | false | false | 1,620 | py | #!/usr/bin/env python3
"""
optimize.py
"""
import optuna
import optuna.integration.lightgbm as lgb
import pandas as pd
from lightgbm import early_stopping, log_evaluation
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
def objective(trial: optuna.Trial):
df = pd.read_csv("train-knn3.csv")
train_x, test_x, train_y, test_y = train_test_split(
df.drop(columns="song_popularity"), df["song_popularity"], test_size=0.2, stratify= df["song_popularity"], random_state=1
)
params = {
"metric": "auc",
"objective": "binary",
"reg_alpha": trial.suggest_float("reg_alpha", 1e-8, 10.0, log=True),
"reg_lambda": trial.suggest_float("reg_lambda", 1e-8, 10.0, log=True),
"n_estimators": trial.suggest_int("n_estimators", 1, 100),
"num_leaves": trial.suggest_int("num_leaves", 2, 256),
"feature_fraction": trial.suggest_float("feature_fraction", 0.4, 1.0),
"bagging_fraction": trial.suggest_float("bagging_fraction", 0.4, 1.0),
"min_child_samples": trial.suggest_int("min_child_samples", 5, 100),
}
dtrain = lgb.Dataset(train_x, label=train_y)
dval = lgb.Dataset(test_x, label=test_y)
model = lgb.train(
params,
dtrain,
valid_sets=[dtrain, dval],
callbacks=[early_stopping(100), log_evaluation(100)],
)
prediction = model.predict(test_x, num_iteration=model.best_iteration)
return roc_auc_score(test_y, prediction)
study = optuna.create_study()
study.optimize(objective, n_jobs=-1, n_trials=100)
print(study.best_params)
| [
"[email protected]"
] | |
f10cf0c87250140ac5312dc31eb6fb3097b38031 | 5983bf3f4cbd49e222a4448f6e738946c1012553 | /aicall/apps/info/migrations/0002_auto_20210322_1329.py | eb91fe911bbbd8d6a9721e302847df2eb2ef5cea | [] | no_license | RympeR/aciall | 7fa88eaf6799444aef84dba1ce9974de858ddfd4 | ca238234160d93a1058f725121e1f3fbe71be33c | refs/heads/master | 2023-04-04T14:45:39.390609 | 2021-04-05T10:02:00 | 2021-04-05T10:02:00 | 354,790,599 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 474 | py | # Generated by Django 3.1.7 on 2021-03-22 11:29
from django.db import migrations
import imagekit.models.fields
class Migration(migrations.Migration):
dependencies = [
('info', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='talkthemes',
name='image_svg',
field=imagekit.models.fields.ProcessedImageField(blank=True, null=True, upload_to='', verbose_name='ImageSVG'),
),
]
| [
"[email protected]"
] | |
cd70acfcb63726d43d38f161933d4473e020bcb4 | 416ea1127f3e3a1a8e64dd980e59c7bf585379a0 | /read_favorite_number.py | 13e6938ce6b8bf90c1ab89faddd39721b21296a8 | [] | no_license | jocogum10/learning_python_crash_course | 6cf826e4324f91a49da579fb1fcd3ca623c20306 | c159d0b0de0be8e95eb8777a416e5010fbb9e2ca | refs/heads/master | 2020-12-10T02:55:40.757363 | 2020-01-13T01:22:44 | 2020-01-13T01:22:44 | 233,486,206 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 180 | py | import json
filename = 'favorite_number.json'
with open(filename) as file_object:
message = json.load(file_object)
print("I know your favorite number! It's " + message + "!")
| [
"[email protected]"
] | |
5ccb0de7903a5ad587a6809250f6a95518d6d850 | 2151544cd386b550b137c4c738a6e57af542f50a | /src/pipelinex/extras/datasets/pillow/images_dataset.py | e787712d4c62212e94e720b17a91161cc9b33575 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | MarchRaBBiT/pipelinex | b82725b7307a58f28d7d663f5072b969a2c9591d | ea8def32a71752b667f9f3522acba3fd79102fe1 | refs/heads/master | 2023-01-05T22:41:58.241802 | 2020-11-08T13:18:19 | 2020-11-08T13:18:19 | 311,065,793 | 0 | 0 | NOASSERTION | 2020-11-08T13:18:20 | 2020-11-08T13:12:11 | null | UTF-8 | Python | false | false | 9,864 | py | import copy
from pathlib import Path
from typing import Any, Dict, Union
from PIL import Image
import logging
import numpy as np
from ..core import AbstractVersionedDataSet, DataSetError, Version
from ...ops.numpy_ops import to_channel_first_arr, to_channel_last_arr, ReverseChannel
log = logging.getLogger(__name__)
class ImagesLocalDataSet(AbstractVersionedDataSet):
""" Loads/saves a dict of numpy 3-D or 2-D arrays from/to a folder containing images.
Works like ``kedro.extras.datasets.pillow.ImageDataSet`` and
``kedro.io.PartitionedDataSet`` with conversion between numpy arrays and Pillow images.
"""
def __init__(
self,
path: str,
load_args: Dict[str, Any] = None,
save_args: Dict[str, Any] = {"suffix": ".jpg"},
channel_first=False,
reverse_color=False,
version: Version = None,
) -> None:
"""
Args:
path: The folder path containing images
load_args: Args fed to:
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.open
save_args:
Args including:
`suffix`: File suffix such as ".jpg"
upper: If provided, used as the upper pixel value corresponding to 0xFF (255)
for linear scaling to ensure the pixel value is between 0 and 255.
lower: If provided, used as the lower pixel value corresponding to 0x00 (0)
for linear scaling to ensure the pixel value is between 0 and 255.
`mode` fed to:
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.fromarray
Other args fed to:
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.save
channel_first: If true, the first dimension of 3-D array is
treated as channel (color) as in PyTorch.
If false, the last dimenstion of the 3-D array is
treated as channel (color) as in TensorFlow, Pillow, and OpenCV.
reverse_color: If true, the order of channel (color) is reversed
(RGB to BGR when loading, BGR to RGB when saving).
Set true to use packages wuch as OpenCV which uses BGR order natively.
version: If specified, should be an instance of
``kedro.io.core.Version``. If its ``load`` attribute is
None, the latest version will be loaded. If its ``save``
attribute is None, save version will be autogenerated.
"""
super().__init__(
filepath=Path(path), version=version, exists_function=self._exists,
)
self._load_args = load_args
self._save_args = save_args
self._channel_first = channel_first
self._reverse_color = reverse_color
def _load(self) -> Any:
load_path = Path(self._get_load_path())
load_args = copy.deepcopy(self._load_args)
load_args = load_args or dict()
dict_structure = load_args.pop("dict_structure", True)
as_numpy = load_args.pop("as_numpy", True)
channel_first = self._channel_first
reverse_color = self._reverse_color
if load_path.is_dir():
images_dict = {}
for p in load_path.glob("*"):
img = load_image(
p,
load_args,
as_numpy=as_numpy,
channel_first=channel_first,
reverse_color=reverse_color,
)
images_dict[p.stem] = img
if dict_structure is None:
return list(images_dict.values())
if dict_structure == "sep_names":
return dict(
images=list(images_dict.values()), names=list(images_dict.keys())
)
return images_dict
else:
return load_image(
load_path,
load_args,
as_numpy=self.as_numpy,
channel_first=channel_first,
reverse_color=reverse_color,
)
def _save(self, data: Union[dict, list, np.ndarray, type(Image.Image)]) -> None:
save_path = Path(self._get_save_path())
save_path.parent.mkdir(parents=True, exist_ok=True)
p = save_path
save_args = copy.deepcopy(self._save_args)
save_args = save_args or dict()
suffix = save_args.pop("suffix", ".jpg")
mode = save_args.pop("mode", None)
upper = save_args.pop("upper", None)
lower = save_args.pop("lower", None)
to_scale = (upper is not None) or (lower is not None)
if isinstance(data, dict):
images = list(data.values())
names = list(data.keys())
if "names" in names and "images" in names:
images = data.get("images")
names = data.get("names")
else:
images = data
names = None
if hasattr(images, "save"):
if not to_scale:
img = images
img.save(p, **save_args)
return None
else:
images = np.asarray(images)
if isinstance(images, np.ndarray):
if self._channel_first:
images = to_channel_last_arr(images)
if self._reverse_color:
images = ReverseChannel(channel_first=self._channel_first)(images)
if images.ndim in {2, 3}:
img = images
img = scale(lower=lower, upper=upper)(img)
img = np.squeeze(img)
img = Image.fromarray(img, mode=mode)
img.save(p, **save_args)
return None
elif images.ndim in {4}:
images = scale(lower=lower, upper=upper)(images)
dataset = Np3DArrDataset(images)
else:
raise ValueError(
"Unsupported number of dimensions: {}".format(images.ndim)
)
elif hasattr(images, "__getitem__") and hasattr(images, "__len__"):
if not to_scale:
p.mkdir(parents=True, exist_ok=True)
for i, img in enumerate(images):
if isinstance(img, np.ndarray):
if self._channel_first:
img = to_channel_last_arr(img)
if self._reverse_color:
img = ReverseChannel(channel_first=self._channel_first)(img)
img = np.squeeze(img)
img = Image.fromarray(img)
name = names[i] if names else "{:05d}".format(i)
s = p / "{}{}".format(name, suffix)
img.save(s, **save_args)
return None
else:
dataset = Np3DArrDatasetFromList(
images, transform=scale(lower=lower, upper=upper)
)
else:
raise ValueError("Unsupported data type: {}".format(type(images)))
p.mkdir(parents=True, exist_ok=True)
for i in range(len(dataset)):
img = dataset[i]
if isinstance(img, (tuple, list)):
img = img[0]
if self._channel_first:
img = to_channel_last_arr(img)
if self._reverse_color:
img = ReverseChannel(channel_first=self._channel_first)(img)
img = np.squeeze(img)
img = Image.fromarray(img, mode=mode)
name = names[i] if names else "{:05d}".format(i)
s = p / "{}{}".format(name, suffix)
img.save(s, **save_args)
return None
def _describe(self) -> Dict[str, Any]:
return dict(
filepath=self._filepath,
load_args=self._save_args,
save_args=self._save_args,
channel_first=self._channel_first,
reverse_color=self._reverse_color,
version=self._version,
)
def _exists(self) -> bool:
try:
path = self._get_load_path()
except DataSetError:
return False
return Path(path).exists()
def load_image(
load_path, load_args, as_numpy=False, channel_first=False, reverse_color=False
):
with load_path.open("rb") as local_file:
img = Image.open(local_file, **load_args)
if as_numpy:
img = np.asarray(img)
if channel_first:
img = to_channel_first_arr(img)
if reverse_color:
img = ReverseChannel(channel_first=channel_first)(img)
return img
def scale(**kwargs):
def _scale(a):
lower = kwargs.get("lower")
upper = kwargs.get("upper")
if (lower is not None) or (upper is not None):
max_val = a.max()
min_val = a.min()
stat_dict = dict(max_val=max_val, min_val=min_val)
log.info(stat_dict)
upper = upper or max_val
lower = lower or min_val
a = (
((a - min_val) / (max_val - min_val)) * (upper - lower) + lower
).astype(np.uint8)
return a
return _scale
class Np3DArrDataset:
def __init__(self, a):
self.a = a
def __getitem__(self, index):
return self.a[index, ...]
def __len__(self):
return len(self.a)
class Np3DArrDatasetFromList:
def __init__(self, a, transform=None):
self.a = a
self.transform = transform
def __getitem__(self, index):
item = np.asarray(self.a[index])
if self.transform:
item = self.transform(item)
return item
def __len__(self):
return len(self.a)
| [
"[email protected]"
] | |
13423cd0e461c0cae46874f40a88916e7e259d73 | 13c404b0f6e45049ed1f2dc788f5c55129c8bd57 | /TriblerGUI/widgets/settingspage.py | c2e60ceb1f7ad236ba96b0d0d482a0d5c9f5610e | [] | no_license | brussee/tribler | 5a849e7b260a5f95e360c2b079e4d7f5d065d7af | d1a1d0ba08ba4a3fca9ef99aad3e74859a7454e3 | refs/heads/android-app | 2021-01-24T01:10:49.293465 | 2016-12-02T16:32:38 | 2016-12-02T16:32:38 | 46,921,190 | 0 | 2 | null | 2016-05-19T13:48:56 | 2015-11-26T10:53:45 | Python | UTF-8 | Python | false | false | 11,404 | py | import json
from PyQt5.QtWidgets import QWidget
from TriblerGUI.defs import PAGE_SETTINGS_GENERAL, PAGE_SETTINGS_CONNECTION, PAGE_SETTINGS_BANDWIDTH, \
PAGE_SETTINGS_SEEDING, PAGE_SETTINGS_ANONYMITY, BUTTON_TYPE_NORMAL
from TriblerGUI.dialogs.confirmationdialog import ConfirmationDialog
from TriblerGUI.tribler_request_manager import TriblerRequestManager
from TriblerGUI.utilities import seconds_to_string, string_to_minutes, get_gui_setting
class SettingsPage(QWidget):
"""
This class is responsible for displaying and adjusting the settings present in Tribler.
"""
def __init__(self):
QWidget.__init__(self)
self.settings = None
self.settings_request_mgr = None
self.saved_dialog = None
def initialize_settings_page(self):
self.window().settings_tab.initialize()
self.window().settings_tab.clicked_tab_button.connect(self.clicked_tab_button)
self.window().settings_save_button.clicked.connect(self.save_settings)
self.window().developer_mode_enabled_checkbox.stateChanged.connect(self.on_developer_mode_checkbox_changed)
self.window().download_settings_anon_checkbox.stateChanged.connect(self.on_anon_download_state_changed)
def on_developer_mode_checkbox_changed(self, _):
self.window().gui_settings.setValue("debug", self.window().developer_mode_enabled_checkbox.isChecked())
self.window().left_menu_button_debug.setHidden(not self.window().developer_mode_enabled_checkbox.isChecked())
def on_anon_download_state_changed(self, _):
if self.window().download_settings_anon_checkbox.isChecked():
self.window().download_settings_anon_seeding_checkbox.setChecked(True)
self.window().download_settings_anon_seeding_checkbox.setEnabled(
not self.window().download_settings_anon_checkbox.isChecked())
def initialize_with_settings(self, settings):
self.settings = settings
settings = settings["settings"]
gui_settings = self.window().gui_settings
# General settings
self.window().developer_mode_enabled_checkbox.setChecked(get_gui_setting(gui_settings, "debug",
False, is_bool=True))
self.window().family_filter_checkbox.setChecked(settings['general']['family_filter'])
self.window().download_location_input.setText(settings['downloadconfig']['saveas'])
self.window().always_ask_location_checkbox.setChecked(
get_gui_setting(gui_settings, "ask_download_settings", True, is_bool=True))
self.window().download_settings_anon_checkbox.setChecked(get_gui_setting(
gui_settings, "default_anonymity_enabled", True, is_bool=True))
self.window().download_settings_anon_seeding_checkbox.setChecked(
get_gui_setting(gui_settings, "default_safeseeding_enabled", True, is_bool=True))
self.window().watchfolder_enabled_checkbox.setChecked(settings['watch_folder']['enabled'])
self.window().watchfolder_location_input.setText(settings['watch_folder']['watch_folder_dir'])
# Connection settings
self.window().firewall_current_port_input.setText(str(settings['general']['minport']))
self.window().lt_proxy_type_combobox.setCurrentIndex(settings['libtorrent']['lt_proxytype'])
if settings['libtorrent']['lt_proxyserver']:
self.window().lt_proxy_server_input.setText(settings['libtorrent']['lt_proxyserver'][0])
self.window().lt_proxy_port_input.setText(settings['libtorrent']['lt_proxyserver'][1])
if settings['libtorrent']['lt_proxyauth']:
self.window().lt_proxy_username_input.setText(settings['libtorrent']['lt_proxyauth'][0])
self.window().lt_proxy_password_input.setText(settings['libtorrent']['lt_proxyauth'][1])
self.window().lt_utp_checkbox.setChecked(settings['libtorrent']['utp'])
max_conn_download = settings['libtorrent']['max_connections_download']
if max_conn_download == -1:
max_conn_download = 0
self.window().max_connections_download_input.setText(str(max_conn_download))
# Bandwidth settings
self.window().upload_rate_limit_input.setText(str(settings['Tribler']['maxuploadrate']))
self.window().download_rate_limit_input.setText(str(settings['Tribler']['maxdownloadrate']))
# Seeding settings
getattr(self.window(), "seeding_" + settings['downloadconfig']['seeding_mode'] + "_radio").setChecked(True)
self.window().seeding_time_input.setText(seconds_to_string(settings['downloadconfig']['seeding_time']))
ind = self.window().seeding_ratio_combobox.findText(str(settings['downloadconfig']['seeding_ratio']))
if ind != -1:
self.window().seeding_ratio_combobox.setCurrentIndex(ind)
# Anonymity settings
self.window().allow_exit_node_checkbox.setChecked(settings['tunnel_community']['exitnode_enabled'])
self.window().number_hops_slider.setValue(int(settings['Tribler']['default_number_hops']) - 1)
self.window().multichain_enabled_checkbox.setChecked(settings['multichain']['enabled'])
def load_settings(self):
self.settings_request_mgr = TriblerRequestManager()
self.settings_request_mgr.perform_request("settings", self.initialize_with_settings)
def clicked_tab_button(self, tab_button_name):
if tab_button_name == "settings_general_button":
self.window().settings_stacked_widget.setCurrentIndex(PAGE_SETTINGS_GENERAL)
elif tab_button_name == "settings_connection_button":
self.window().settings_stacked_widget.setCurrentIndex(PAGE_SETTINGS_CONNECTION)
elif tab_button_name == "settings_bandwidth_button":
self.window().settings_stacked_widget.setCurrentIndex(PAGE_SETTINGS_BANDWIDTH)
elif tab_button_name == "settings_seeding_button":
self.window().settings_stacked_widget.setCurrentIndex(PAGE_SETTINGS_SEEDING)
elif tab_button_name == "settings_anonymity_button":
self.window().settings_stacked_widget.setCurrentIndex(PAGE_SETTINGS_ANONYMITY)
def save_settings(self):
# Create a dictionary with all available settings
settings_data = {'general': {}, 'Tribler': {}, 'downloadconfig': {}, 'libtorrent': {}, 'watch_folder': {},
'tunnel_community': {}, 'multichain': {}}
settings_data['general']['family_filter'] = self.window().family_filter_checkbox.isChecked()
settings_data['downloadconfig']['saveas'] = self.window().download_location_input.text()
settings_data['watch_folder']['enabled'] = self.window().watchfolder_enabled_checkbox.isChecked()
if settings_data['watch_folder']['enabled']:
settings_data['watch_folder']['watch_folder_dir'] = self.window().watchfolder_location_input.text()
settings_data['general']['minport'] = self.window().firewall_current_port_input.text()
settings_data['libtorrent']['lt_proxytype'] = self.window().lt_proxy_type_combobox.currentIndex()
if len(self.window().lt_proxy_server_input.text()) > 0 and len(self.window().lt_proxy_port_input.text()) > 0:
settings_data['libtorrent']['lt_proxyserver'] = [None, None]
settings_data['libtorrent']['lt_proxyserver'][0] = self.window().lt_proxy_server_input.text()
settings_data['libtorrent']['lt_proxyserver'][1] = self.window().lt_proxy_port_input.text()
if len(self.window().lt_proxy_username_input.text()) > 0 and \
len(self.window().lt_proxy_password_input.text()) > 0:
settings_data['libtorrent']['lt_proxyauth'] = [None, None]
settings_data['libtorrent']['lt_proxyauth'][0] = self.window().lt_proxy_username_input.text()
settings_data['libtorrent']['lt_proxyauth'][1] = self.window().lt_proxy_password_input.text()
settings_data['libtorrent']['utp'] = self.window().lt_utp_checkbox.isChecked()
try:
max_conn_download = int(self.window().max_connections_download_input.text())
except ValueError:
ConfirmationDialog.show_error(self.window(), "Invalid number of connections",
"You've entered an invalid format for the maximum number of connections.")
return
if max_conn_download == 0:
max_conn_download = -1
settings_data['libtorrent']['max_connections_download'] = max_conn_download
if self.window().upload_rate_limit_input.text():
settings_data['Tribler']['maxuploadrate'] = self.window().upload_rate_limit_input.text()
if self.window().download_rate_limit_input.text():
settings_data['Tribler']['maxdownloadrate'] = self.window().download_rate_limit_input.text()
seeding_modes = ['forever', 'time', 'never', 'ratio']
selected_mode = 'forever'
for seeding_mode in seeding_modes:
if getattr(self.window(), "seeding_" + seeding_mode + "_radio").isChecked():
selected_mode = seeding_mode
break
settings_data['downloadconfig']['seeding_mode'] = selected_mode
settings_data['downloadconfig']['seeding_ratio'] = self.window().seeding_ratio_combobox.currentText()
try:
settings_data['downloadconfig']['seeding_time'] = string_to_minutes(self.window().seeding_time_input.text())
except ValueError:
ConfirmationDialog.show_error(self.window(), "Invalid seeding time",
"You've entered an invalid format for the seeding time (expected HH:MM)")
return
settings_data['tunnel_community']['exitnode_enabled'] = self.window().allow_exit_node_checkbox.isChecked()
settings_data['Tribler']['default_number_hops'] = self.window().number_hops_slider.value() + 1
settings_data['multichain']['enabled'] = self.window().multichain_enabled_checkbox.isChecked()
self.settings_request_mgr = TriblerRequestManager()
self.settings_request_mgr.perform_request("settings", self.on_settings_saved,
method='POST', data=json.dumps(settings_data))
def on_settings_saved(self, _):
# Now save the GUI settings
self.window().gui_settings.setValue("ask_download_settings",
self.window().always_ask_location_checkbox.isChecked())
self.window().gui_settings.setValue("default_anonymity_enabled",
self.window().download_settings_anon_checkbox.isChecked())
self.window().gui_settings.setValue("default_safeseeding_enabled",
self.window().download_settings_anon_seeding_checkbox.isChecked())
self.saved_dialog = ConfirmationDialog(TriblerRequestManager.window, "Settings saved",
"Your settings have been saved.", [('close', BUTTON_TYPE_NORMAL)])
self.saved_dialog.button_clicked.connect(self.on_dialog_cancel_clicked)
self.saved_dialog.show()
self.window().fetch_settings()
def on_dialog_cancel_clicked(self, _):
self.saved_dialog.setParent(None)
self.saved_dialog = None
| [
"[email protected]"
] | |
3734e13259f4b245375820776dc260e0f60a01d5 | 2455062787d67535da8be051ac5e361a097cf66f | /Producers/BSUB/TrigProd_amumu_a5_dR5/trigger_amumu_producer_cfg_TrigProd_amumu_a5_dR5_129.py | 7569fce71cd2fd69603dc29210d1978acc440b9c | [] | no_license | kmtos/BBA-RecoLevel | 6e153c08d5ef579a42800f6c11995ee55eb54846 | 367adaa745fbdb43e875e5ce837c613d288738ab | refs/heads/master | 2021-01-10T08:33:45.509687 | 2015-12-04T09:20:14 | 2015-12-04T09:20:14 | 43,355,189 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,360 | py | import FWCore.ParameterSet.Config as cms
process = cms.Process("PAT")
#process.load("BBA/Analyzer/bbaanalyzer_cfi")
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.load('Configuration.EventContent.EventContent_cff')
process.load("Configuration.Geometry.GeometryRecoDB_cff")
process.load("Configuration.StandardSequences.FrontierConditions_GlobalTag_cff")
process.load("PhysicsTools.PatAlgos.producersLayer1.patCandidates_cff")
process.load("PhysicsTools.PatAlgos.selectionLayer1.selectedPatCandidates_cff")
from Configuration.AlCa.GlobalTag import GlobalTag
process.GlobalTag = GlobalTag(process.GlobalTag, 'MCRUN2_71_V1::All', '')
process.load("Configuration.StandardSequences.MagneticField_cff")
####################
# Message Logger
####################
process.MessageLogger.cerr.FwkReport.reportEvery = cms.untracked.int32(100)
process.options = cms.untracked.PSet( wantSummary = cms.untracked.bool(True) )
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
## switch to uncheduled mode
process.options.allowUnscheduled = cms.untracked.bool(True)
process.maxEvents = cms.untracked.PSet(
input = cms.untracked.int32(500)
)
####################
# Input File List
####################
# Input source
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring('root://eoscms//eos/cms/store/user/ktos/RECO_Step3_amumu_a5/RECO_Step3_amumu_a5_129.root'),
secondaryFileNames = cms.untracked.vstring()
)
############################################################
# Defining matching in DeltaR, sorting by best DeltaR
############################################################
process.mOniaTrigMatch = cms.EDProducer("PATTriggerMatcherDRLessByR",
src = cms.InputTag( 'slimmedMuons' ),
matched = cms.InputTag( 'patTrigger' ), # selections of trigger objects
matchedCuts = cms.string( 'type( "TriggerMuon" ) && path( "HLT_Mu16_TkMu0_dEta18_Onia*")' ), # input does not yet have the 'saveTags' parameter in HLT
maxDPtRel = cms.double( 0.5 ), # no effect here
maxDeltaR = cms.double( 0.3 ), #### selection of matches
maxDeltaEta = cms.double( 0.2 ), # no effect here
resolveAmbiguities = cms.bool( True ),# definition of matcher output
resolveByMatchQuality = cms.bool( True )# definition of matcher output
)
# talk to output module
process.out = cms.OutputModule("PoolOutputModule",
fileName = cms.untracked.string("file:RECO_Step3_amumu_a5_TrigProd_129.root"),
outputCommands = process.MINIAODSIMEventContent.outputCommands
)
process.out.outputCommands += [ 'drop *_*_*_*',
'keep *_*slimmed*_*_*',
'keep *_pfTausEI_*_*',
'keep *_hpsPFTauProducer_*_*',
'keep *_hltTriggerSummaryAOD_*_*',
'keep *_TriggerResults_*_HLT',
'keep *_patTrigger*_*_*',
'keep *_prunedGenParticles_*_*',
'keep *_mOniaTrigMatch_*_*'
]
################################################################################
# Running the matching and setting the the trigger on
################################################################################
from PhysicsTools.PatAlgos.tools.trigTools import *
switchOnTrigger( process ) # This is optional and can be omitted.
switchOnTriggerMatching( process, triggerMatchers = [ 'mOniaTrigMatch'
])
process.outpath = cms.EndPath(process.out)
| [
"[email protected]"
] | |
50b38f5aa112634f69a1964367b345d28107fa78 | 62153e297ca84bf9d76eef56b28408f5337113f9 | /tasks/migrations/0005_announcements_picture.py | 470373d027006370d1516280f097642bee71c5a1 | [] | no_license | zarif007/HRTaskManager | 22b72c80d2cac99fa9d3f7f0cfd480cb832ff910 | 4c7e7f04b82f138a7177f659bb347c7e189c6220 | refs/heads/main | 2023-06-23T22:05:33.812024 | 2021-07-31T19:55:11 | 2021-07-31T19:55:11 | 373,304,992 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 408 | py | # Generated by Django 3.2.4 on 2021-07-26 12:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tasks', '0004_announcements'),
]
operations = [
migrations.AddField(
model_name='announcements',
name='picture',
field=models.ImageField(blank=True, null=True, upload_to=''),
),
]
| [
"[email protected]"
] | |
fd0816dae9157631a8d5823e89d9650f7806a979 | 75ce5b7fee397fe4e67ed15a58f4cd42e0f8de9f | /PythonMasterclass/HelloWorld/Strings.py | 3b45aebdb6a60836687406b37ebae58981f463c5 | [] | no_license | lukbast/stuff | 7fd03b7e035394802c307682a25621dfd667960b | 160e1d77d1b592fac099b9c7139fb4e2f7f8dbbe | refs/heads/main | 2023-08-06T21:39:55.334812 | 2021-09-23T17:37:47 | 2021-09-23T17:37:47 | 409,684,114 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,083 | py | greeting = 'Hello'
name = 'Bruce'
# print(greeting+' ' + name)
# sample comment
# name2 = input('Please enter your name')
# print(greeting + ' ' + name2)
# splitString = 'This string has been\nsplit\nover\nseveral\nlines'
# print(splitString)
tabbedStrings = '1\t2\t3\t4\t5'
print(tabbedStrings)
print('The pet shop owner said "No, no, \'e \'s uh,...he\'s resting".')
# or
print("The pet shop owner said \"No, no, 'e 's uh,...he's resting\".")
# or
print('''The pet shop owner said "Oh, no, 'e 's uh,...he's resting".''')
anotherSplitString = '''This string has been
split over
several
lines'''
# print(anotherSplitString)
# parrot = 'Norwegian blue'
# print(parrot[3])
# print(parrot[len(parrot)-1])
# print()
# print(parrot[3])
# print(parrot[6])
# print(parrot[8])
#
# print()
#
# print(parrot[-11])
# print(parrot[-1])
# print()
# print(parrot[-11])
# print(parrot[-8])
# print(parrot[-6])
#
# print(parrot[10:len(parrot)])
num = 666
wordd = f'fbfbff {num} bbfgbfbfgbg ngngngng'
word = "ssddsdsvs {0} fnfgfngfn {1:} fnfggff {2:.3f}".format(1, 2+2, 11/7)
print(wordd)
| [
"[email protected]"
] | |
8380622bbde43b92e00ac4f96152d1afa7c46f30 | bb4241ec40d0f3bc7484957a3aad2c7921f3ab5f | /src/tracewhack/log.py | c21fc7cf7481ebc5c882c0be2775dba2f2ae8ccc | [
"BSD-3-Clause"
] | permissive | wingu/tracewhack | a17b7e54cbe7cc74cc99511cdf490cd2f12e4184 | a324705c23ddd8921ed829152f07fa9ff758de0f | refs/heads/master | 2020-06-04T17:25:08.534182 | 2013-01-28T15:29:20 | 2013-01-28T15:29:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 354 | py | """
Logging utilities.
"""
# LATER Right now these are just dumb placeholders.
def warn(msg):
"""
Log a warning.
"""
print msg
def verbose(msg, options):
"""
Log only if verbose mode
"""
if options and options.get('verbose', False):
print msg
def error(msg):
"""
Log an error.
"""
print msg
| [
"[email protected]"
] | |
3444f7edd6f1163f10d9be2255fc8f130c62da24 | 9ae6ce54bf9a2a86201961fdbd5e7b0ec913ff56 | /google/ads/googleads/v11/errors/types/asset_group_listing_group_filter_error.py | 0aa4caab0394edc17f6c1870dd1f51adb4f736d5 | [
"Apache-2.0"
] | permissive | GerhardusM/google-ads-python | 73b275a06e5401e6b951a6cd99af98c247e34aa3 | 676ac5fcb5bec0d9b5897f4c950049dac5647555 | refs/heads/master | 2022-07-06T19:05:50.932553 | 2022-06-17T20:41:17 | 2022-06-17T20:41:17 | 207,535,443 | 0 | 0 | Apache-2.0 | 2019-09-10T10:58:55 | 2019-09-10T10:58:55 | null | UTF-8 | Python | false | false | 1,792 | py | # -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v11.errors",
marshal="google.ads.googleads.v11",
manifest={"AssetGroupListingGroupFilterErrorEnum",},
)
class AssetGroupListingGroupFilterErrorEnum(proto.Message):
r"""Container for enum describing possible asset group listing
group filter errors.
"""
class AssetGroupListingGroupFilterError(proto.Enum):
r"""Enum describing possible asset group listing group filter
errors.
"""
UNSPECIFIED = 0
UNKNOWN = 1
TREE_TOO_DEEP = 2
UNIT_CANNOT_HAVE_CHILDREN = 3
SUBDIVISION_MUST_HAVE_EVERYTHING_ELSE_CHILD = 4
DIFFERENT_DIMENSION_TYPE_BETWEEN_SIBLINGS = 5
SAME_DIMENSION_VALUE_BETWEEN_SIBLINGS = 6
SAME_DIMENSION_TYPE_BETWEEN_ANCESTORS = 7
MULTIPLE_ROOTS = 8
INVALID_DIMENSION_VALUE = 9
MUST_REFINE_HIERARCHICAL_PARENT_TYPE = 10
INVALID_PRODUCT_BIDDING_CATEGORY = 11
CHANGING_CASE_VALUE_WITH_CHILDREN = 12
SUBDIVISION_HAS_CHILDREN = 13
CANNOT_REFINE_HIERARCHICAL_EVERYTHING_ELSE = 14
__all__ = tuple(sorted(__protobuf__.manifest))
| [
"[email protected]"
] | |
4d3e87116d6556c0d297a5c799aedc741f817923 | 1854841ff9de3391f1c858fcb9f5ccd7dc5488eb | /backend/aidin_27554/wsgi.py | 989a9b46785cae5d98a29e68726486205737a9bf | [] | no_license | crowdbotics-apps/aidin-27554 | 84f8ddd4e63ebfa233fc8d4a2b617af399371b50 | fd1e1768ee18919395a1740c70bbcd337360174e | refs/heads/master | 2023-05-05T15:50:29.989821 | 2021-05-29T14:26:12 | 2021-05-29T14:26:12 | 371,992,096 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 399 | py | """
WSGI config for aidin_27554 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'aidin_27554.settings')
application = get_wsgi_application()
| [
"[email protected]"
] | |
2600ae63925448ced497283cd025918eceef3b18 | 81221fd4c09d828fac08229b3640398a39bd0b5b | /c0923/p0602.py | cb72dd108a4760175c5a410dcd87b7e33136c627 | [] | no_license | Jill-rong/practice-python | e60148294f59e256b70d531669ad86dcb0c92320 | c8f44a3d3d8f5c2b87e36e171cc042d16350908a | refs/heads/master | 2020-08-01T17:38:16.664386 | 2019-09-26T10:33:44 | 2019-09-26T10:33:44 | 211,063,114 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 55 | py | a = input('請輸入:')
print(a[0])
print(a[len(a)-1]) | [
"[email protected]"
] | |
862e50035f6c13d3f48ac50c598fab378f1734e0 | 9edaf93c833ba90ae9a903aa3c44c407a7e55198 | /netex/models/timing_point_in_journey_pattern.py | 22366d74aaa3b679bdbaf7bc59fc9c56bf9ca822 | [] | no_license | tefra/xsdata-samples | c50aab4828b8c7c4448dbdab9c67d1ebc519e292 | ef027fe02e6a075d8ed676c86a80e9647d944571 | refs/heads/main | 2023-08-14T10:31:12.152696 | 2023-07-25T18:01:22 | 2023-07-25T18:01:22 | 222,543,692 | 6 | 1 | null | 2023-06-25T07:21:04 | 2019-11-18T21:00:37 | Python | UTF-8 | Python | false | false | 373 | py | from dataclasses import dataclass
from .timing_point_in_journey_pattern_versioned_child_structure import TimingPointInJourneyPatternVersionedChildStructure
__NAMESPACE__ = "http://www.netex.org.uk/netex"
@dataclass
class TimingPointInJourneyPattern(TimingPointInJourneyPatternVersionedChildStructure):
class Meta:
namespace = "http://www.netex.org.uk/netex"
| [
"[email protected]"
] | |
5f7d3b174e463bba868cbf3615002a82f700e4a7 | cafefb0b182567e5cabe22c44578bb712385e9f5 | /lib/gcloud/search/index.py | c9014b24817e8f19ade1e9fdffd86991f1fc12d3 | [
"BSD-3-Clause"
] | permissive | gtaylor/evennia-game-index | fe0088e97087c0aaa0c319084e28b2c992c2c00b | b47f27f4dff2a0c32991cee605d95911946ca9a5 | refs/heads/master | 2022-11-25T20:28:23.707056 | 2022-11-07T17:47:25 | 2022-11-07T17:47:25 | 55,206,601 | 2 | 2 | BSD-3-Clause | 2018-04-19T05:41:12 | 2016-04-01T05:40:15 | Python | UTF-8 | Python | false | false | 10,736 | py | # Copyright 2015 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Define API Indexes."""
from gcloud.search.document import Document
class Index(object):
"""Indexes are containers for documents.
See:
https://cloud.google.com/search/reference/rest/v1/indexes
:type name: string
:param name: the name of the index
:type client: :class:`gcloud.dns.client.Client`
:param client: A client which holds credentials and project configuration
for the index (which requires a project).
"""
def __init__(self, name, client):
self.name = name
self._client = client
self._properties = {}
@classmethod
def from_api_repr(cls, resource, client):
"""Factory: construct an index given its API representation
:type resource: dict
:param resource: index resource representation returned from the API
:type client: :class:`gcloud.dns.client.Client`
:param client: Client which holds credentials and project
configuration for the index.
:rtype: :class:`gcloud.dns.index.Index`
:returns: Index parsed from ``resource``.
"""
name = resource.get('indexId')
if name is None:
raise KeyError(
'Resource lacks required identity information: ["indexId"]')
index = cls(name, client=client)
index._set_properties(resource)
return index
@property
def project(self):
"""Project bound to the index.
:rtype: string
:returns: the project (derived from the client).
"""
return self._client.project
@property
def path(self):
"""URL path for the index's APIs.
:rtype: string
:returns: the path based on project and dataste name.
"""
return '/projects/%s/indexes/%s' % (self.project, self.name)
def _list_field_names(self, field_type):
"""Helper for 'text_fields', etc.
"""
fields = self._properties.get('indexedField', {})
return fields.get(field_type)
@property
def text_fields(self):
"""Names of text fields in the index.
:rtype: list of string, or None
:returns: names of text fields in the index, or None if no
resource information is available.
"""
return self._list_field_names('textFields')
@property
def atom_fields(self):
"""Names of atom fields in the index.
:rtype: list of string, or None
:returns: names of atom fields in the index, or None if no
resource information is available.
"""
return self._list_field_names('atomFields')
@property
def html_fields(self):
"""Names of html fields in the index.
:rtype: list of string, or None
:returns: names of html fields in the index, or None if no
resource information is available.
"""
return self._list_field_names('htmlFields')
@property
def date_fields(self):
"""Names of date fields in the index.
:rtype: list of string, or None
:returns: names of date fields in the index, or None if no
resource information is available.
"""
return self._list_field_names('dateFields')
@property
def number_fields(self):
"""Names of number fields in the index.
:rtype: list of string, or None
:returns: names of number fields in the index, or None if no
resource information is available.
"""
return self._list_field_names('numberFields')
@property
def geo_fields(self):
"""Names of geo fields in the index.
:rtype: list of string, or None
:returns: names of geo fields in the index, or None if no
resource information is available.
"""
return self._list_field_names('geoFields')
def _set_properties(self, api_response):
"""Update properties from resource in body of ``api_response``
:type api_response: httplib2.Response
:param api_response: response returned from an API call
"""
self._properties.clear()
self._properties.update(api_response)
def list_documents(self, max_results=None, page_token=None,
view=None):
"""List documents created within this index.
See:
https://cloud.google.com/search/reference/rest/v1/projects/indexes/documents/list
:type max_results: int
:param max_results: maximum number of indexes to return, If not
passed, defaults to a value set by the API.
:type page_token: string
:param page_token: opaque marker for the next "page" of indexes. If
not passed, the API will return the first page of
indexes.
:type view: string
:param view: One of 'ID_ONLY' (return only the document ID; the
default) or 'FULL' (return the full resource
representation for the document, including field
values)
:rtype: tuple, (list, str)
:returns: list of :class:`gcloud.dns.document.Document`, plus a
"next page token" string: if the token is not None,
indicates that more indexes can be retrieved with another
call (pass that value as ``page_token``).
"""
params = {}
if max_results is not None:
params['pageSize'] = max_results
if page_token is not None:
params['pageToken'] = page_token
if view is not None:
params['view'] = view
path = '%s/documents' % (self.path,)
connection = self._client.connection
resp = connection.api_request(method='GET', path=path,
query_params=params)
indexes = [Document.from_api_repr(resource, self)
for resource in resp['documents']]
return indexes, resp.get('nextPageToken')
def document(self, name, rank=None):
"""Construct a document bound to this index.
:type name: string
:param name: Name of the document.
:type rank: integer
:param rank: Rank of the document (defaults to a server-assigned
value based on timestamp).
:rtype: :class:`gcloud.search.document.Document`
:returns: a new ``Document`` instance
"""
return Document(name, index=self, rank=rank)
def search(self,
query,
max_results=None,
page_token=None,
field_expressions=None,
order_by=None,
matched_count_accuracy=None,
scorer=None,
scorer_size=None,
return_fields=None):
"""Search documents created within this index.
See:
https://cloud.google.com/search/reference/rest/v1/projects/indexes/search
:type query: string
:param query: query string (see https://cloud.google.com/search/query).
:type max_results: int
:param max_results: maximum number of indexes to return, If not
passed, defaults to a value set by the API.
:type page_token: string
:param page_token: opaque marker for the next "page" of indexes. If
not passed, the API will return the first page of
indexes.
:type field_expressions: dict, or ``NoneType``
:param field_expressions: mapping of field name -> expression
for use in 'order_by' or 'return_fields'
:type order_by: sequence of string, or ``NoneType``
:param order_by: list of field names (plus optional ' desc' suffix)
specifying ordering of results.
:type matched_count_accuracy: integer or ``NoneType``
:param matched_count_accuracy: minimum accuracy for matched count
returned
:type return_fields: sequence of string, or ``NoneType``
:param return_fields: list of field names to be returned.
:type scorer: string or ``NoneType``
:param scorer: name of scorer function (e.g., "generic").
:type scorer_size: integer or ``NoneType``
:param scorer_size: max number of top results pass to scorer function.
:rtype: tuple, (list, str, int)
:returns: list of :class:`gcloud.dns.document.Document`, plus a
"next page token" string, and a "matched count". If the
token is not None, indicates that more indexes can be
retrieved with another call (pass that value as
``page_token``). The "matched count" indicates the total
number of documents matching the query string.
"""
params = {'query': query}
if max_results is not None:
params['pageSize'] = max_results
if page_token is not None:
params['pageToken'] = page_token
if field_expressions is not None:
params['fieldExpressions'] = field_expressions
if order_by is not None:
params['orderBy'] = order_by
if matched_count_accuracy is not None:
params['matchedCountAccuracy'] = matched_count_accuracy
if scorer is not None:
params['scorer'] = scorer
if scorer_size is not None:
params['scorerSize'] = scorer_size
if return_fields is not None:
params['returnFields'] = return_fields
path = '%s/search' % (self.path,)
connection = self._client.connection
resp = connection.api_request(method='GET', path=path,
query_params=params)
indexes = [Document.from_api_repr(resource, self)
for resource in resp['results']]
return indexes, resp.get('nextPageToken'), resp.get('matchedCount')
| [
"[email protected]"
] | |
2308fad2814b489f253f4b87ca63706bb82054c9 | dfbd3e12a7a7ed28c13715b2fa0c964d0745c8cb | /python/day04/solve.py | a0ee63dd7b81c99836e716257b0c5ef859f13a1f | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | ijanos/advent2017 | 3a90c479bf4f1689264576fb2c4468883458b911 | db7ba6c3f2abbe206e47f25480c24d2bade709bb | refs/heads/master | 2021-08-31T23:20:35.637440 | 2017-12-23T12:09:55 | 2017-12-23T12:09:55 | 112,766,905 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 324 | py | #!/usr/bin/env python3
import fileinput
p1 = 0
p2 = 0
for line in fileinput.input():
line = line.strip().split()
if len(set(line)) == len(line):
p1 += 1
line = [''.join(sorted(word)) for word in line]
if len(set(line)) == len(line):
p2 += 1
print(f"Part 1: {p1}")
print(f"Part 2: {p2}")
| [
"[email protected]"
] | |
5b891f3d735e0b91211908f1f7706d84e34478f9 | 88906fbe13de27413a51da917ebe46b473bec1b9 | /Part-I/Chapter 6 - Dictionaries/favourite_languages.py | 6c94cb510f855c612346614864fa12fd8c159746 | [] | no_license | lonewolfcub/Python-Crash-Course | 0b127e40f5029d84ad036263fd9153f6c88c2420 | 322388dfb81f3335eeffabcdfb8f9c5a1db737a4 | refs/heads/master | 2021-01-01T16:45:50.617189 | 2017-10-27T14:23:58 | 2017-10-27T14:23:58 | 97,911,584 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 235 | py | # A dictionary of similar objects
favourite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
print("Sarah's favourite language is " +
favourite_languages['sarah'].title() + ".") | [
"[email protected]"
] | |
9896a8d751a0cc983347cfab70f1606a7af16e7d | fa2fdfcf180507344be8de71da75af2fe72101b2 | /train_and_run_experiments_bc.py | 771396e09f5607ebe7f7628cd776c4f2b3cc08e2 | [] | no_license | sarahwie/AttentionExplanation | 48b49c1769324fe40015b8a96f862753f559e329 | 919fe5c710be5d1721ef1803cd46c731e1953088 | refs/heads/master | 2020-05-16T12:46:31.184833 | 2019-04-23T16:39:04 | 2019-04-23T16:39:04 | 183,055,153 | 1 | 0 | null | 2019-04-23T16:31:19 | 2019-04-23T16:31:19 | null | UTF-8 | Python | false | false | 1,163 | py | import argparse
parser = argparse.ArgumentParser(description='Run experiments on a dataset')
parser.add_argument('--dataset', type=str, required=True)
parser.add_argument("--data_dir", type=str, required=True)
parser.add_argument("--output_dir", type=str)
parser.add_argument('--encoder', type=str, choices=['cnn', 'lstm', 'average', 'all'], required=True)
parser.add_argument('--attention', type=str, choices=['tanh', 'dot'], required=True)
args, extras = parser.parse_known_args()
args.extras = extras
from Transparency.Trainers.DatasetBC import *
from Transparency.ExperimentsBC import *
dataset = datasets[args.dataset](args)
if args.output_dir is not None :
dataset.output_dir = args.output_dir
encoders = ['cnn', 'lstm', 'average'] if args.encoder == 'all' else [args.encoder]
if args.attention == 'tanh' :
train_dataset_on_encoders(dataset, encoders)
generate_graphs_on_encoders(dataset, encoders)
elif args.attention == 'dot' :
encoders = [e + '_dot' for e in encoders]
train_dataset_on_encoders(dataset, encoders)
generate_graphs_on_encoders(dataset, encoders)
else :
raise LookupError("Attention not found ...")
| [
"[email protected]"
] | |
051003ddbbd931a6739cad35f09979734ace6342 | f5ffd566166948c4202eb1e66bef44cf55a70033 | /openapi_client/model/single_taxonomy.py | 218f06214ff6263cea99e00dd25b9ad43a1967fd | [] | no_license | skyportal/skyportal_client | ed025ac6d23589238a9c133d712d4f113bbcb1c9 | 15514e4dfb16313e442d06f69f8477b4f0757eaa | refs/heads/master | 2023-02-10T02:54:20.757570 | 2021-01-05T02:18:03 | 2021-01-05T02:18:03 | 326,860,562 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 8,666 | py | """
Fritz: SkyPortal API
SkyPortal provides an API to access most of its underlying functionality. To use it, you will need an API token. This can be generated via the web application from your profile page or, if you are an admin, you may use the system provisioned token stored inside of `.tokens.yaml`. ### Accessing the SkyPortal API Once you have a token, you may access SkyPortal programmatically as follows. #### Python ```python import requests token = 'ea70a5f0-b321-43c6-96a1-b2de225e0339' def api(method, endpoint, data=None): headers = {'Authorization': f'token {token}'} response = requests.request(method, endpoint, json=data, headers=headers) return response response = api('GET', 'http://localhost:5000/api/sysinfo') print(f'HTTP code: {response.status_code}, {response.reason}') if response.status_code in (200, 400): print(f'JSON response: {response.json()}') ``` #### Command line (curl) ```shell curl -s -H 'Authorization: token ea70a5f0-b321-43c6-96a1-b2de225e0339' http://localhost:5000/api/sysinfo ``` ### Response In the above examples, the SkyPortal server is located at `http://localhost:5000`. In case of success, the HTTP response is 200: ``` HTTP code: 200, OK JSON response: {'status': 'success', 'data': {}, 'version': '0.9.dev0+git20200819.84c453a'} ``` On failure, it is 400; the JSON response has `status=\"error\"` with the reason for the failure given in `message`: ```js { \"status\": \"error\", \"message\": \"Invalid API endpoint\", \"data\": {}, \"version\": \"0.9.1\" } ``` # Authentication <!-- ReDoc-Inject: <security-definitions> --> # noqa: E501
The version of the OpenAPI document: 0.9.dev0+git20201221.76627dd
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
import nulltype # noqa: F401
from openapi_client.model_utils import ( # noqa: F401
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
from openapi_client.model.taxonomy import Taxonomy
globals()['Taxonomy'] = Taxonomy
class SingleTaxonomy(ModelNormal):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
discriminator_value_class_map (dict): A dict to go from the discriminator
variable value to the discriminator class name.
validations (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
that stores validations for max_length, min_length, max_items,
min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum,
inclusive_minimum, and regex.
additional_properties_type (tuple): A tuple of classes accepted
as additional properties values.
"""
allowed_values = {
('status',): {
'SUCCESS': "success",
},
}
validations = {
}
additional_properties_type = None
_nullable = False
@cached_property
def openapi_types():
"""
This must be a method because a model may have properties that are
of type self, this must run after the class is loaded
Returns
openapi_types (dict): The key is attribute name
and the value is attribute type.
"""
lazy_import()
return {
'status': (str,), # noqa: E501
'message': (str,), # noqa: E501
'data': (Taxonomy,), # noqa: E501
}
@cached_property
def discriminator():
return None
attribute_map = {
'status': 'status', # noqa: E501
'message': 'message', # noqa: E501
'data': 'data', # noqa: E501
}
_composed_schemas = {}
required_properties = set([
'_data_store',
'_check_type',
'_spec_property_naming',
'_path_to_item',
'_configuration',
'_visited_composed_classes',
])
@convert_js_args_to_python_args
def __init__(self, *args, **kwargs): # noqa: E501
"""SingleTaxonomy - a model defined in OpenAPI
Args:
Keyword Args:
status (str): defaults to "success", must be one of ["success", ] # noqa: E501
_check_type (bool): if True, values for parameters in openapi_types
will be type checked and a TypeError will be
raised if the wrong type is input.
Defaults to True
_path_to_item (tuple/list): This is a list of keys or values to
drill down to the model in received_data
when deserializing a response
_spec_property_naming (bool): True if the variable names in the input data
are serialized names, as specified in the OpenAPI document.
False if the variable names in the input data
are pythonic names, e.g. snake case (default)
_configuration (Configuration): the instance to use when
deserializing a file_type parameter.
If passed, type conversion is attempted
If omitted no type conversion is done.
_visited_composed_classes (tuple): This stores a tuple of
classes that we have traveled through so that
if we see that class again we will not use its
discriminator again.
When traveling through a discriminator, the
composed schema that is
is traveled through is added to this set.
For example if Animal has a discriminator
petType and we pass in "Dog", and the class Dog
allOf includes Animal, we move through Animal
once using the discriminator, and pick Dog.
Then in Dog, we will make an instance of the
Animal class but this time we won't travel
through its discriminator because we passed in
_visited_composed_classes = (Animal,)
message (str): [optional] # noqa: E501
data (Taxonomy): [optional] # noqa: E501
"""
status = kwargs.get('status', "success")
_check_type = kwargs.pop('_check_type', True)
_spec_property_naming = kwargs.pop('_spec_property_naming', False)
_path_to_item = kwargs.pop('_path_to_item', ())
_configuration = kwargs.pop('_configuration', None)
_visited_composed_classes = kwargs.pop('_visited_composed_classes', ())
if args:
raise ApiTypeError(
"Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % (
args,
self.__class__.__name__,
),
path_to_item=_path_to_item,
valid_classes=(self.__class__,),
)
self._data_store = {}
self._check_type = _check_type
self._spec_property_naming = _spec_property_naming
self._path_to_item = _path_to_item
self._configuration = _configuration
self._visited_composed_classes = _visited_composed_classes + (self.__class__,)
self.status = status
for var_name, var_value in kwargs.items():
if var_name not in self.attribute_map and \
self._configuration is not None and \
self._configuration.discard_unknown_keys and \
self.additional_properties_type is None:
# discard variable.
continue
setattr(self, var_name, var_value)
| [
"[email protected]"
] | |
b2e460a9d9de520b845d05370218279875c2e09e | b76fa48d4931cbf926a2660ad7fb84c9b70f7e40 | /venv/bin/pip | 16348f15aa2d5ef6d948db31ed37151446b21c4f | [] | no_license | pydjango-dev/flask | e94ac2550f2d3df5c02348c31440e396f714747c | d2492c49a06587b377fa61eab26ae73e4ac96e4d | refs/heads/master | 2022-04-12T11:35:43.737423 | 2020-04-07T11:18:32 | 2020-04-07T11:18:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 399 | #!/Users/macair/PycharmProjects/Blog/venv/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==10.0.1','console_scripts','pip'
__requires__ = 'pip==10.0.1'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('pip==10.0.1', 'console_scripts', 'pip')()
)
| [
"[email protected]"
] | ||
826972294e6a434d16ec6b57db5baf36e50f6c3f | 13617cd87821cab9a4f0b1fb0a8355dfd145a43a | /CSW/csw_post_request.py | cba597d4d043f355c9dc3c7b105137a414bf190f | [
"GFDL-1.1-only",
"MIT"
] | permissive | petercunning/notebook | a84acf2ba22c053cf2dfd912387ab66dfe1668c7 | 5b26f2dc96bcb36434542b397de6ca5fa3b61a0a | refs/heads/master | 2021-01-15T03:54:00.227967 | 2020-02-25T00:02:23 | 2020-02-25T00:02:23 | 242,869,782 | 0 | 0 | MIT | 2020-02-24T23:56:41 | 2020-02-24T23:56:40 | null | UTF-8 | Python | false | false | 13,391 | py |
# coding: utf-8
# # Try some "RAW" requests to pycsw
# In[1]:
import requests, json
# In[2]:
headers = {'Content-Type': 'application/xml'}
# ### Try apiso:serviceType query
# In[3]:
input = '''
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
outputSchema="http://www.opengis.net/cat/csw/2.0.2" outputFormat="application/xml"
version="2.0.2" service="CSW" resultType="results" maxRecords="1000"
xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd">
<csw:Query typeNames="csw:Record">
<csw:ElementSetName>summary</csw:ElementSetName>
<csw:Constraint version="1.1.0">
<ogc:Filter>
<ogc:PropertyIsLike wildCard="*" singleChar="?" escapeChar="\">
<ogc:PropertyName>apiso:ServiceType</ogc:PropertyName>
<ogc:Literal>*WMS*</ogc:Literal>
</ogc:PropertyIsLike>
</ogc:Filter>
</csw:Constraint>
</csw:Query>
</csw:GetRecords>
'''
# Geoport pycsw instance
# In[4]:
endpoint = 'http://geoport.whoi.edu/csw'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# Geonode pycsw instance
# In[ ]:
endpoint = 'http://geonode.wfp.org/catalogue/csw'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# geodata.gov.gr pycsw instance
# In[ ]:
endpoint = 'http://geodata.gov.gr/csw'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# Data.Gov pycsw instance
# In[5]:
endpoint = 'http://catalog.data.gov/csw-all'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# PACIOOS pycsw instance
# In[6]:
endpoint = 'http://oos.soest.hawaii.edu/pacioos/ogc/csw.py'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# Data.ioos.us endpoint
# In[7]:
endpoint = 'http://data.ioos.us/csw'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# ### Try using both apiso:AnyText and apiso:ServiceType queries
# In[ ]:
input = '''
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
xmlns:ogc="http://www.opengis.net/ogc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
outputSchema="http://www.opengis.net/cat/csw/2.0.2" outputFormat="application/xml"
version="2.0.2" service="CSW" resultType="results" maxRecords="1000"
xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd">
<csw:Query typeNames="csw:Record">
<csw:ElementSetName>summary</csw:ElementSetName>
<csw:Constraint version="1.1.0">
<ogc:Filter>
<ogc:And>
<ogc:PropertyIsLike wildCard="*" singleChar="?" escapeChar="\">
<ogc:PropertyName>apiso:AnyText</ogc:PropertyName>
<ogc:Literal>*coawst*</ogc:Literal>
</ogc:PropertyIsLike>
<ogc:PropertyIsLike wildCard="*" singleChar="?" escapeChar="\">
<ogc:PropertyName>apiso:ServiceType</ogc:PropertyName>
<ogc:Literal>*OPeNDAP*</ogc:Literal>
</ogc:PropertyIsLike>
</ogc:And>
</ogc:Filter>
</csw:Constraint>
</csw:Query>
</csw:GetRecords>
'''
# In[ ]:
endpoint = 'http://geoport.whoi.edu/csw'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# In[ ]:
endpoint = 'http://catalog.data.gov/csw-all'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# In[ ]:
endpoint = 'http://data.ioos.us/csw'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# In[ ]:
endpoint = 'http://catalog.data.gov/csw-all'
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:2000]
# ### BBOX query on NGDC Geoportal Server CSW
# In[ ]:
endpoint = 'http://www.ngdc.noaa.gov/geoportal/csw'
# In[ ]:
input='''
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ogc="http://www.opengis.net/ogc"
xmlns:gml="http://www.opengis.net/gml" outputSchema="http://www.opengis.net/cat/csw/2.0.2"
outputFormat="application/xml" version="2.0.2" service="CSW" resultType="results"
maxRecords="1000"
xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd">
<csw:Query typeNames="csw:Record">
<csw:ElementSetName>full</csw:ElementSetName>
<csw:Constraint version="1.1.0">
<ogc:Filter>
<ogc:And>
<ogc:BBOX>
<ogc:PropertyName>ows:BoundingBox</ogc:PropertyName>
<gml:Envelope srsName="urn:ogc:def:crs:OGC:1.3:CRS84">
<gml:lowerCorner> -158.4 20.7</gml:lowerCorner>
<gml:upperCorner> -157.2 21.6</gml:upperCorner>
</gml:Envelope>
</ogc:BBOX>
<ogc:PropertyIsLessThanOrEqualTo>
<ogc:PropertyName>apiso:TempExtent_begin</ogc:PropertyName>
<ogc:Literal>2014-12-01T16:43:00Z</ogc:Literal>
</ogc:PropertyIsLessThanOrEqualTo>
<ogc:PropertyIsGreaterThanOrEqualTo>
<ogc:PropertyName>apiso:TempExtent_end</ogc:PropertyName>
<ogc:Literal>2014-12-01T16:43:00Z</ogc:Literal>
</ogc:PropertyIsGreaterThanOrEqualTo>
<ogc:PropertyIsLike wildCard="*" singleChar="?" escapeChar="\\">
<ogc:PropertyName>apiso:AnyText</ogc:PropertyName>
<ogc:Literal>*sea_water_salinity*</ogc:Literal>
</ogc:PropertyIsLike>
</ogc:And>
</ogc:Filter>
</csw:Constraint>
</csw:Query>
</csw:GetRecords>
''';
# In[ ]:
xml_string=requests.post(endpoint, data=input, headers=headers).text
print xml_string[:650]
# ## BBOX query on PACIOOS pyCSW
# In[ ]:
input='''
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ogc="http://www.opengis.net/ogc"
xmlns:gml="http://www.opengis.net/gml" outputSchema="http://www.opengis.net/cat/csw/2.0.2"
outputFormat="application/xml" version="2.0.2" service="CSW" resultType="results"
maxRecords="1000"
xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd">
<csw:Query typeNames="csw:Record">
<csw:ElementSetName>full</csw:ElementSetName>
<csw:Constraint version="1.1.0">
<ogc:Filter>
<ogc:And>
<ogc:BBOX>
<ogc:PropertyName>ows:BoundingBox</ogc:PropertyName>
<gml:Envelope srsName="urn:x-ogc:def:crs:EPSG:6.11:4326">
<gml:lowerCorner> 20.7 -158.4</gml:lowerCorner>
<gml:upperCorner> 21.6 -157.2</gml:upperCorner>
</gml:Envelope>
</ogc:BBOX>
<ogc:PropertyIsLessThanOrEqualTo>
<ogc:PropertyName>apiso:TempExtent_begin</ogc:PropertyName>
<ogc:Literal>2014-12-01T16:43:00Z</ogc:Literal>
</ogc:PropertyIsLessThanOrEqualTo>
<ogc:PropertyIsGreaterThanOrEqualTo>
<ogc:PropertyName>apiso:TempExtent_end</ogc:PropertyName>
<ogc:Literal>2014-12-01T16:43:00Z</ogc:Literal>
</ogc:PropertyIsGreaterThanOrEqualTo>
<ogc:PropertyIsLike wildCard="*" singleChar="?" escapeChar="\\">
<ogc:PropertyName>apiso:AnyText</ogc:PropertyName>
<ogc:Literal>*sea_water_salinity*</ogc:Literal>
</ogc:PropertyIsLike>
</ogc:And>
</ogc:Filter>
</csw:Constraint>
</csw:Query>
</csw:GetRecords>
''';
# In[ ]:
endpoint='http://oos.soest.hawaii.edu/pacioos/ogc/csw.py'
# In[ ]:
xml_string=requests.post(endpoint, data=input, headers=headers).text
# In[ ]:
print xml_string[:2000]
# ## Query COMT pycsw
# ### Try (lat,lon) order of bounding box with `srsName=EPSG:4326`
# In[ ]:
input='''
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ogc="http://www.opengis.net/ogc"
xmlns:gml="http://www.opengis.net/gml" outputSchema="http://www.opengis.net/cat/csw/2.0.2"
outputFormat="application/xml" version="2.0.2" service="CSW" resultType="results"
maxRecords="1000"
xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd">
<csw:Query typeNames="csw:Record">
<csw:ElementSetName>full</csw:ElementSetName>
<csw:Constraint version="1.1.0">
<ogc:Filter>
<ogc:And>
<ogc:BBOX>
<ogc:PropertyName>ows:BoundingBox</ogc:PropertyName>
<gml:Envelope srsName="urn:x-ogc:def:crs:EPSG:6.11:4326">
<gml:lowerCorner> 27 -100</gml:lowerCorner>
<gml:upperCorner> 30 -97</gml:upperCorner>
</gml:Envelope>
</ogc:BBOX>
<ogc:PropertyIsLessThanOrEqualTo>
<ogc:PropertyName>apiso:TempExtent_begin</ogc:PropertyName>
<ogc:Literal>2008-12-01T16:43:00Z</ogc:Literal>
</ogc:PropertyIsLessThanOrEqualTo>
<ogc:PropertyIsGreaterThanOrEqualTo>
<ogc:PropertyName>apiso:TempExtent_end</ogc:PropertyName>
<ogc:Literal>2008-06-01T16:43:00Z</ogc:Literal>
</ogc:PropertyIsGreaterThanOrEqualTo>
<ogc:PropertyIsLike wildCard="*" singleChar="?" escapeChar="\\">
<ogc:PropertyName>apiso:AnyText</ogc:PropertyName>
<ogc:Literal>*FVCOM*</ogc:Literal>
</ogc:PropertyIsLike>
</ogc:And>
</ogc:Filter>
</csw:Constraint>
</csw:Query>
</csw:GetRecords>
''';
# In[ ]:
endpoint='http://comt.sura.org:8000/pycsw/csw.py'
# In[ ]:
xml_string=requests.post(endpoint, data=input, headers=headers).text
xml_string[:2000]
# ### Try (lon,lat) order of bounding box with `srsName=CRS84`
# In[ ]:
input='''
<csw:GetRecords xmlns:csw="http://www.opengis.net/cat/csw/2.0.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ogc="http://www.opengis.net/ogc"
xmlns:gml="http://www.opengis.net/gml" outputSchema="http://www.opengis.net/cat/csw/2.0.2"
outputFormat="application/xml" version="2.0.2" service="CSW" resultType="results"
maxRecords="1000"
xsi:schemaLocation="http://www.opengis.net/cat/csw/2.0.2 http://schemas.opengis.net/csw/2.0.2/CSW-discovery.xsd">
<csw:Query typeNames="csw:Record">
<csw:ElementSetName>full</csw:ElementSetName>
<csw:Constraint version="1.1.0">
<ogc:Filter>
<ogc:And>
<ogc:BBOX>
<ogc:PropertyName>ows:BoundingBox</ogc:PropertyName>
<gml:Envelope srsName="urn:ogc:def:crs:OGC:1.3:CRS84">
<gml:lowerCorner>-100 27</gml:lowerCorner>
<gml:upperCorner> -97 30</gml:upperCorner>
</gml:Envelope>
</ogc:BBOX>
<ogc:PropertyIsLessThanOrEqualTo>
<ogc:PropertyName>apiso:TempExtent_begin</ogc:PropertyName>
<ogc:Literal>2008-12-01T16:43:00Z</ogc:Literal>
</ogc:PropertyIsLessThanOrEqualTo>
<ogc:PropertyIsGreaterThanOrEqualTo>
<ogc:PropertyName>apiso:TempExtent_end</ogc:PropertyName>
<ogc:Literal>2008-06-01T16:43:00Z</ogc:Literal>
</ogc:PropertyIsGreaterThanOrEqualTo>
<ogc:PropertyIsLike wildCard="*" singleChar="?" escapeChar="\\">
<ogc:PropertyName>apiso:AnyText</ogc:PropertyName>
<ogc:Literal>*FVCOM*</ogc:Literal>
</ogc:PropertyIsLike>
</ogc:And>
</ogc:Filter>
</csw:Constraint>
</csw:Query>
</csw:GetRecords>
''';
# In[ ]:
xml_string=requests.post(endpoint, data=input, headers=headers).text
xml_string[:2000]
# ### Woo hoo! We get 4 records returned with both (lat,lon) EPSG:4326 and (lon,lat) CRS84 queries! Success!!
# In[ ]:
endpoint='http://geoport.whoi.edu/pycsw'
# In[ ]:
xml_string=requests.post(endpoint, data=input, headers=headers).text
xml_string[:2000]
# In[ ]:
| [
"[email protected]"
] | |
2ca58914081b89507b7e4b2db63b231eb16c13dc | 5a113e0758da14ccf3e7f4b6b0eb3abddd4adf39 | /tests/test_models/test_user.py | abb3c1ef9d5527f2de5cbc1764f4e25d0ee323bd | [] | no_license | Esteban1891/AirBnB_clone | 22a64c45d1e0c997c842ae907ea216ab662639fd | 5860cf7ae43afe6e2fee96be60fcfb0b67d1d2fc | refs/heads/master | 2022-11-30T06:41:54.718592 | 2020-08-13T22:58:50 | 2020-08-13T22:58:50 | 275,320,501 | 5 | 7 | null | null | null | null | UTF-8 | Python | false | false | 1,734 | py | #!/usr/bin/python3
"""Module for test User class"""
import unittest
import json
import pep8
import datetime
from models.user import User
from models.base_model import BaseModel
class TestUser(unittest.TestCase):
"""Test User class implementation"""
def test_doc_module(self):
"""Module documentation"""
doc = User.__doc__
self.assertGreater(len(doc), 1)
def test_pep8_conformance_base_model(self):
"""Test that models/user.py conforms to PEP8."""
pep8style = pep8.StyleGuide(quiet=True)
result = pep8style.check_files(['models/user.py'])
self.assertEqual(result.total_errors, 0,
"Found code style errors (and warnings).")
def test_pep8_conformance_test_base_model(self):
"""Test that tests/test_models/test_user.py conforms to PEP8."""
pep8style = pep8.StyleGuide(quiet=True)
res = pep8style.check_files(['tests/test_models/test_user.py'])
self.assertEqual(res.total_errors, 0,
"Found code style errors (and warnings).")
def test_doc_constructor(self):
"""Constructor documentation"""
doc = User.__init__.__doc__
self.assertGreater(len(doc), 1)
def test_class(self):
"""Validate the types of the attributes an class"""
with self.subTest(msg='Inheritance'):
self.assertTrue(issubclass(User, BaseModel))
with self.subTest(msg='Attributes'):
self.assertIsInstance(User.email, str)
self.assertIsInstance(User.password, str)
self.assertIsInstance(User.first_name, str)
self.assertIsInstance(User.last_name, str)
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
21922a99ad639c61627562fe098fa13350d8bffa | dc54a813f0e5d3b1ea44b38e10f8e5f8ef4764d4 | /sciwing/api/api.py | 22b7a61170cfdaa45f4dcf65700bbe3d6c5ec570 | [
"MIT"
] | permissive | dragomirradev/sciwing | fc0a33b25d19ea0e11170e4930442eb0f8d05da4 | b3f4e6831b2dadf20e3336821ca8d50db1248ee7 | refs/heads/master | 2022-04-18T14:03:31.275169 | 2020-04-13T04:48:44 | 2020-04-13T04:48:44 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 366 | py | import sciwing.api.conf as config
from fastapi import FastAPI
from sciwing.api.routers import parscit
from sciwing.api.routers import citation_intent_clf
app = FastAPI()
@app.get("/")
def root():
return {"message": "Welcome To SciWING API"}
# add the routers to the main app
app.include_router(parscit.router)
app.include_router(citation_intent_clf.router)
| [
"[email protected]"
] | |
b2192129c1bf5e2df3ed5fee141a2932e0af8440 | 09e57dd1374713f06b70d7b37a580130d9bbab0d | /data/p3BR/R2/benchmark/startQiskit335.py | 99346e8c0d944fc6842431c4a000ef35f61d00ed | [
"BSD-3-Clause"
] | permissive | UCLA-SEAL/QDiff | ad53650034897abb5941e74539e3aee8edb600ab | d968cbc47fe926b7f88b4adf10490f1edd6f8819 | refs/heads/main | 2023-08-05T04:52:24.961998 | 2021-09-19T02:56:16 | 2021-09-19T02:56:16 | 405,159,939 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,145 | py | # qubit number=3
# total number=66
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'
def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/questions/3943/how-do-you-implement-the-toffoli-gate-using-only-single-qubit-and-cnot-gates
# https://quantumcomputing.stackexchange.com/questions/2177/how-can-i-implement-an-n-bit-toffoli-gate
controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
# oracle.barrier()
# oracle.draw('mpl', filename=(kernel + '-oracle.png'))
return oracle
def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the Bernstein-Vazirani circuit
zero = np.binary_repr(0, n)
b = f(zero)
# initial n + 1 bits
input_qubit = QuantumRegister(n+1, "qc")
classicals = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classicals)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(input_qubit[n])
# circuit begin
prog.h(input_qubit[1]) # number=1
prog.h(input_qubit[2]) # number=38
prog.cz(input_qubit[0],input_qubit[2]) # number=39
prog.h(input_qubit[2]) # number=40
prog.h(input_qubit[2]) # number=59
prog.cz(input_qubit[0],input_qubit[2]) # number=60
prog.h(input_qubit[2]) # number=61
prog.h(input_qubit[2]) # number=42
prog.cz(input_qubit[0],input_qubit[2]) # number=43
prog.h(input_qubit[2]) # number=44
prog.h(input_qubit[2]) # number=48
prog.cz(input_qubit[0],input_qubit[2]) # number=49
prog.h(input_qubit[2]) # number=50
prog.h(input_qubit[2]) # number=63
prog.cz(input_qubit[0],input_qubit[2]) # number=64
prog.h(input_qubit[2]) # number=65
prog.x(input_qubit[2]) # number=55
prog.cx(input_qubit[0],input_qubit[2]) # number=56
prog.cx(input_qubit[0],input_qubit[2]) # number=47
prog.cx(input_qubit[0],input_qubit[2]) # number=37
prog.h(input_qubit[2]) # number=51
prog.cz(input_qubit[0],input_qubit[2]) # number=52
prog.h(input_qubit[2]) # number=53
prog.h(input_qubit[2]) # number=25
prog.cz(input_qubit[0],input_qubit[2]) # number=26
prog.h(input_qubit[2]) # number=27
prog.h(input_qubit[1]) # number=7
prog.cz(input_qubit[2],input_qubit[1]) # number=8
prog.rx(0.17592918860102857,input_qubit[2]) # number=34
prog.rx(-0.3989822670059037,input_qubit[1]) # number=30
prog.h(input_qubit[1]) # number=9
prog.h(input_qubit[1]) # number=18
prog.rx(2.3310617489636263,input_qubit[2]) # number=58
prog.cz(input_qubit[2],input_qubit[1]) # number=19
prog.h(input_qubit[1]) # number=20
prog.x(input_qubit[1]) # number=62
prog.y(input_qubit[1]) # number=14
prog.h(input_qubit[1]) # number=22
prog.cz(input_qubit[2],input_qubit[1]) # number=23
prog.rx(-0.9173450548482197,input_qubit[1]) # number=57
prog.h(input_qubit[1]) # number=24
prog.z(input_qubit[2]) # number=3
prog.z(input_qubit[1]) # number=41
prog.x(input_qubit[1]) # number=17
prog.y(input_qubit[2]) # number=5
prog.x(input_qubit[2]) # number=21
# apply H to get superposition
for i in range(n):
prog.h(input_qubit[i])
prog.h(input_qubit[n])
prog.barrier()
# apply oracle O_f
oracle = build_oracle(n, f)
prog.append(
oracle.to_gate(),
[input_qubit[i] for i in range(n)] + [input_qubit[n]])
# apply H back (QFT on Z_2^n)
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
# measure
return prog
def get_statevector(prog: QuantumCircuit) -> Any:
state_backend = Aer.get_backend('statevector_simulator')
statevec = execute(prog, state_backend).result()
quantum_state = statevec.get_statevector()
qubits = round(log2(len(quantum_state)))
quantum_state = {
"|" + np.binary_repr(i, qubits) + ">": quantum_state[i]
for i in range(2 ** qubits)
}
return quantum_state
def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:
# Q: which backend should we use?
# get state vector
quantum_state = get_statevector(prog)
# get simulate results
# provider = IBMQ.load_account()
# backend = provider.get_backend(backend_str)
# qobj = compile(prog, backend, shots)
# job = backend.run(qobj)
# job.result()
backend = Aer.get_backend(backend_str)
# transpile/schedule -> assemble -> backend.run
results = execute(prog, backend, shots=shots).result()
counts = results.get_counts()
a = Counter(counts).most_common(1)[0][0][::-1]
return {
"measurements": counts,
# "state": statevec,
"quantum_state": quantum_state,
"a": a,
"b": b
}
def bernstein_test_1(rep: str):
"""011 . x + 1"""
a = "011"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
def bernstein_test_2(rep: str):
"""000 . x + 0"""
a = "000"
b = "0"
return bitwise_xor(bitwise_dot(a, rep), b)
def bernstein_test_3(rep: str):
"""111 . x + 1"""
a = "111"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
if __name__ == "__main__":
n = 2
a = "11"
b = "1"
f = lambda rep: \
bitwise_xor(bitwise_dot(a, rep), b)
prog = build_circuit(n, f)
sample_shot =4000
writefile = open("../data/startQiskit335.csv", "w")
# prog.draw('mpl', filename=(kernel + '.png'))
backend = BasicAer.get_backend('qasm_simulator')
circuit1 = transpile(prog, FakeYorktown())
circuit1.h(qubit=2)
circuit1.x(qubit=3)
circuit1.measure_all()
info = execute(circuit1,backend=backend, shots=sample_shot).result().get_counts()
print(info, file=writefile)
print("results end", file=writefile)
print(circuit1.depth(), file=writefile)
print(circuit1, file=writefile)
writefile.close()
| [
"[email protected]"
] | |
5da9e788a3db46e978e8273bd81283efdec746fe | b6b04c3bc6afe61e3c3128f552417091c451ba69 | /flink-ml-python/pyflink/examples/ml/feature/elementwiseproduct_example.py | 2dd8ffff654fb21c9023ca110ebb26cfa02623ee | [
"Apache-2.0"
] | permissive | apache/flink-ml | d15365e1b89b82eb451b99af0050d66dff279f0c | 5619c3b8591b220e78a0a792c1f940e06149c8f0 | refs/heads/master | 2023-08-31T04:08:10.287875 | 2023-08-24T06:40:12 | 2023-08-24T06:40:12 | 351,617,021 | 288 | 85 | Apache-2.0 | 2023-09-07T08:03:42 | 2021-03-26T00:42:03 | Java | UTF-8 | Python | false | false | 2,548 | py | ################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
# Simple program that creates a ElementwiseProduct instance and uses it for feature
# engineering.
from pyflink.common import Types
from pyflink.datastream import StreamExecutionEnvironment
from pyflink.ml.linalg import Vectors, DenseVectorTypeInfo
from pyflink.ml.feature.elementwiseproduct import ElementwiseProduct
from pyflink.table import StreamTableEnvironment
# create a new StreamExecutionEnvironment
env = StreamExecutionEnvironment.get_execution_environment()
# create a StreamTableEnvironment
t_env = StreamTableEnvironment.create(env)
# generate input data
input_data_table = t_env.from_data_stream(
env.from_collection([
(1, Vectors.dense(2.1, 3.1)),
(2, Vectors.dense(1.1, 3.3))
],
type_info=Types.ROW_NAMED(
['id', 'vec'],
[Types.INT(), DenseVectorTypeInfo()])))
# create an elementwise product object and initialize its parameters
elementwise_product = ElementwiseProduct() \
.set_input_col('vec') \
.set_output_col('output_vec') \
.set_scaling_vec(Vectors.dense(1.1, 1.1))
# use the elementwise product object for feature engineering
output = elementwise_product.transform(input_data_table)[0]
# extract and display the results
field_names = output.get_schema().get_field_names()
for result in t_env.to_data_stream(output).execute_and_collect():
input_value = result[field_names.index(elementwise_product.get_input_col())]
output_value = result[field_names.index(elementwise_product.get_output_col())]
print('Input Value: ' + str(input_value) + '\tOutput Value: ' + str(output_value))
| [
"[email protected]"
] | |
9d110fbcb12c9f90b00998d9551a69ce4a763ec7 | fd67592b2338105e0cd0b3503552d188b814ad95 | /test/test_models/test_catalog.py | b7209c829133250b36b1bc84e473cacaa134d2c9 | [] | no_license | E-goi/sdk-python | 175575fcd50bd5ad426b33c78bdeb08d979485b7 | 5cba50a46e1d288b5038d18be12af119211e5b9f | refs/heads/master | 2023-04-29T20:36:02.314712 | 2023-04-18T07:42:46 | 2023-04-18T07:42:46 | 232,095,340 | 5 | 2 | null | null | null | null | UTF-8 | Python | false | false | 5,014 | py | # coding: utf-8
"""
APIv3 (New)
# Introduction This is our new version of API. We invite you to start using it and give us your feedback # Getting Started E-goi can be integrated with many environments and programming languages via our REST API. We've created a developer focused portal to give your organization a clear and quick overview of how to integrate with E-goi. The developer portal focuses on scenarios for integration and flow of events. We recommend familiarizing yourself with all of the content in the developer portal, before start using our rest API. The E-goi APIv3 is served over HTTPS. To ensure data privacy, unencrypted HTTP is not supported. Request data is passed to the API by POSTing JSON objects to the API endpoints with the appropriate parameters. BaseURL = api.egoiapp.com # RESTful Services This API supports 5 HTTP methods: * <b>GET</b>: The HTTP GET method is used to **read** (or retrieve) a representation of a resource. * <b>POST</b>: The POST verb is most-often utilized to **create** new resources. * <b>PATCH</b>: PATCH is used for **modify** capabilities. The PATCH request only needs to contain the changes to the resource, not the complete resource * <b>PUT</b>: PUT is most-often utilized for **update** capabilities, PUT-ing to a known resource URI with the request body containing the newly-updated representation of the original resource. * <b>DELETE</b>: DELETE is pretty easy to understand. It is used to **delete** a resource identified by a URI. # Authentication We use a custom authentication method, you will need a apikey that you can find in your account settings. Below you will see a curl example to get your account information: #!/bin/bash curl -X GET 'https://api.egoiapp.com/my-account' \\ -H 'accept: application/json' \\ -H 'Apikey: <YOUR_APY_KEY>' Here you can see a curl Post example with authentication: #!/bin/bash curl -X POST 'http://api.egoiapp.com/tags' \\ -H 'accept: application/json' \\ -H 'Apikey: <YOUR_APY_KEY>' \\ -H 'Content-Type: application/json' \\ -d '{`name`:`Your custom tag`,`color`:`#FFFFFF`}' # SDK Get started quickly with E-goi with our integration tools. Our SDK is a modern open source library that makes it easy to integrate your application with E-goi services. * <a href='https://github.com/E-goi/sdk-java'>Java</a> * <a href='https://github.com/E-goi/sdk-php'>PHP</a> * <a href='https://github.com/E-goi/sdk-python'>Python</a> * <a href='https://github.com/E-goi/sdk-ruby'>Ruby</a> * <a href='https://github.com/E-goi/sdk-javascript'>Javascript</a> * <a href='https://github.com/E-goi/sdk-csharp'>C#</a> # Stream Limits Stream limits are security mesures we have to make sure our API have a fair use policy, for this reason, any request that creates or modifies data (**POST**, **PATCH** and **PUT**) is limited to a maximum of **20MB** of content length. If you arrive to this limit in one of your request, you'll receive a HTTP code **413 (Request Entity Too Large)** and the request will be ignored. To avoid this error in importation's requests, it's advised the request's division in batches that have each one less than 20MB. # Timeouts Timeouts set a maximum waiting time on a request's response. Our API, sets a default timeout for each request and when breached, you'll receive an HTTP **408 (Request Timeout)** error code. You should take into consideration that response times can vary widely based on the complexity of the request, amount of data being analyzed, and the load on the system and workspace at the time of the query. When dealing with such errors, you should first attempt to reduce the complexity and amount of data under analysis, and only then, if problems are still occurring ask for support. For all these reasons, the default timeout for each request is **10 Seconds** and any request that creates or modifies data (**POST**, **PATCH** and **PUT**) will have a timeout of **60 Seconds**. Specific timeouts may exist for specific requests, these can be found in the request's documentation. # Callbacks A callback is an asynchronous API request that originates from the API server and is sent to the client in response to a previous request sent by that client. The API will make a **POST** request to the address defined in the URL with the information regarding the event of interest and share data related to that event. <a href='/usecases/callbacks/' target='_blank'>[Go to callbacks documentation]</a> ***Note:*** Only http or https protocols are supported in the Url parameter. <security-definitions/> # noqa: E501
The version of the OpenAPI document: 3.0.0
Generated by: https://openapi-generator.tech
"""
import unittest
import egoi_api
from egoi_api.model.catalog import Catalog
from egoi_api import configuration
class TestCatalog(unittest.TestCase):
"""Catalog unit test stubs"""
_configuration = configuration.Configuration()
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
95dcb275b4a638f2ba8f0094654be362d6d3ae3f | 5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d | /alipay/aop/api/domain/KoubeiCateringPosDishcateTransferModel.py | 095ca8346512b61fba41d3997f22f02f7c9433ae | [
"Apache-2.0"
] | permissive | alipay/alipay-sdk-python-all | 8bd20882852ffeb70a6e929038bf88ff1d1eff1c | 1fad300587c9e7e099747305ba9077d4cd7afde9 | refs/heads/master | 2023-08-27T21:35:01.778771 | 2023-08-23T07:12:26 | 2023-08-23T07:12:26 | 133,338,689 | 247 | 70 | Apache-2.0 | 2023-04-25T04:54:02 | 2018-05-14T09:40:54 | Python | UTF-8 | Python | false | false | 2,652 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class KoubeiCateringPosDishcateTransferModel(object):
def __init__(self):
self._cate_id = None
self._cook_id = None
self._dish_ids = None
self._shop_id = None
@property
def cate_id(self):
return self._cate_id
@cate_id.setter
def cate_id(self, value):
self._cate_id = value
@property
def cook_id(self):
return self._cook_id
@cook_id.setter
def cook_id(self, value):
self._cook_id = value
@property
def dish_ids(self):
return self._dish_ids
@dish_ids.setter
def dish_ids(self, value):
if isinstance(value, list):
self._dish_ids = list()
for i in value:
self._dish_ids.append(i)
@property
def shop_id(self):
return self._shop_id
@shop_id.setter
def shop_id(self, value):
self._shop_id = value
def to_alipay_dict(self):
params = dict()
if self.cate_id:
if hasattr(self.cate_id, 'to_alipay_dict'):
params['cate_id'] = self.cate_id.to_alipay_dict()
else:
params['cate_id'] = self.cate_id
if self.cook_id:
if hasattr(self.cook_id, 'to_alipay_dict'):
params['cook_id'] = self.cook_id.to_alipay_dict()
else:
params['cook_id'] = self.cook_id
if self.dish_ids:
if isinstance(self.dish_ids, list):
for i in range(0, len(self.dish_ids)):
element = self.dish_ids[i]
if hasattr(element, 'to_alipay_dict'):
self.dish_ids[i] = element.to_alipay_dict()
if hasattr(self.dish_ids, 'to_alipay_dict'):
params['dish_ids'] = self.dish_ids.to_alipay_dict()
else:
params['dish_ids'] = self.dish_ids
if self.shop_id:
if hasattr(self.shop_id, 'to_alipay_dict'):
params['shop_id'] = self.shop_id.to_alipay_dict()
else:
params['shop_id'] = self.shop_id
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = KoubeiCateringPosDishcateTransferModel()
if 'cate_id' in d:
o.cate_id = d['cate_id']
if 'cook_id' in d:
o.cook_id = d['cook_id']
if 'dish_ids' in d:
o.dish_ids = d['dish_ids']
if 'shop_id' in d:
o.shop_id = d['shop_id']
return o
| [
"[email protected]"
] | |
da2db0a6d1935e5fd45ba13f2ae2e27b96afb0b0 | 090324db0c04d8c30ad6688547cfea47858bf3af | /soko/perception/policy.py | bb1cb833033df50bbc170434ebf153d81461f29b | [] | no_license | fidlej/sokobot | b82c4c36d73e224d0d0e1635021ca04485da589e | d3d04753a5043e6a22dafd132fa633d8bc66b9ea | refs/heads/master | 2021-01-21T13:14:29.523501 | 2011-06-12T07:34:14 | 2011-06-12T07:34:14 | 32,650,745 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,752 | py |
import logging
from soko.solver.solver import Solver
from soko.perception import perceiving, saving
from libctw import factored, modeling
class PerceptSolver(Solver):
"""A sokoban solver.
It converts the seen states to a sequence of bits.
It then predicts the next action to take.
It is used to show the predicted paths.
"""
def solve(self, env):
"""Returns a rollout path for testing.
The path does not have to be a solution.
"""
policy = PerceptPolicy()
s = env.init()
num_steps = 100
path = []
for i in xrange(num_steps):
policy.add_history(env, s)
actions = env.get_actions(s)
a = policy.next_action(actions)
if a is None:
logging.warn("ending the path because of an invalid action")
return path
path.append(a)
s = env.predict(s, a)
return path
def _prepare_model(perceiver, num_remembered_steps):
num_action_bits = perceiver.get_num_action_bits()
return _get_trained_agent(perceiver.get_num_percept_bits(),
num_action_bits, num_remembered_steps)
class PerceptPolicy:
def __init__(self):
self.num_remembered_steps = 2
self.perceiver = perceiving.SokobanPerceiver()
self.agent_model = _prepare_model(self.perceiver,
self.num_remembered_steps)
def init_history(self, env, node):
self.agent_model.switch_history()
self._show_history(env, self.agent_model, node)
def _show_history(self, env, agent_model, node):
from soko.env.env import Action
sas = [node.s]
for i in xrange(self.num_remembered_steps):
if node.prev_node is None:
break
sas.insert(0, node.a)
sas.insert(0, node.prev_node.s)
node = node.prev_node
for item in sas:
if isinstance(item, Action):
bits = self.perceiver.encode_action(item)
else:
bits = self.perceiver.encode_state(env, item)
agent_model.see_added(bits)
def next_action(self, actions):
"""Returns a valid action or None.
"""
action_bits = _advance(self.agent_model,
self.perceiver.get_num_action_bits())
try:
action = self.perceiver.decode_action(action_bits)
except ValueError, e:
logging.warn("predicted invalid action_bits: %s", action_bits)
return None
if action.cmd not in [a.cmd for a in actions]:
logging.info("predicted impossible action: %s", action_bits)
return None
return action
def add_history(self, env, s):
percept = self.perceiver.encode_state(env, s)
self.agent_model.see_added(percept)
def _advance(model, num_bits):
return [_advance_bit(model) for i in xrange(num_bits)]
def _advance_bit(model):
one_p = model.predict_one()
assert 0 <= one_p <= 1.0, "invalid P: %s" % one_p
if one_p >= 0.5:
bit = 1
else:
bit = 0
model.see_added([bit])
return bit
def _get_trained_agent(num_percept_bits, num_action_bits,
num_remembered_steps):
train_seqs = saving.load_training_seqs()
#TEST: don't limit the number of used seqs
train_seqs = train_seqs[:15]
max_depth = (num_remembered_steps * (num_percept_bits + num_action_bits) +
num_action_bits)
agent_model = factored.create_model(max_depth=max_depth)
source_info = modeling.Interlaced(num_percept_bits, num_action_bits)
modeling.train_model(agent_model, train_seqs, bytes=False,
source_info=source_info)
return agent_model
| [
"[email protected]"
] | |
75f7278194a9195bc7423d26c1cab9ce1d07c3a7 | f305f84ea6f721c2391300f0a60e21d2ce14f2a5 | /11_动态规划/dp优化/kitamasa法.py | 38f9a2c16abdaad119175126f6cd40ebaaf09584 | [] | no_license | 981377660LMT/algorithm-study | f2ada3e6959338ae1bc21934a84f7314a8ecff82 | 7e79e26bb8f641868561b186e34c1127ed63c9e0 | refs/heads/master | 2023-09-01T18:26:16.525579 | 2023-09-01T12:21:58 | 2023-09-01T12:21:58 | 385,861,235 | 225 | 24 | null | null | null | null | UTF-8 | Python | false | false | 1,638 | py | # 常系数线性递推
# https://tjkendev.github.io/procon-library/python/series/kitamasa.html
# !O(k^2logn) 求线性递推式的第n项 (比矩阵快速幂快一个k)
# 線形漸化式 dp[i+k] = c0*dp[i] + c1*dp[i+1] + ... + ci+k-1*dp[i+k-1] (i>=0) の第n項を求める
# C: 系数 c0,c1,...,ci+k-1
# A: dp[0]-dp[k-1] 初始值
# n: 第n项
from typing import List
MOD = int(1e9 + 7)
def kitamasa(C: List[int], A: List[int], n: int) -> int:
if n == 0:
return A[0]
assert len(C) == len(A)
k = len(C)
C0 = [0] * k
C1 = [0] * k
C0[1] = 1
def inc(k, C0, C1):
C1[0] = C0[k - 1] * C[0] % MOD
for i in range(k - 1):
C1[i + 1] = (C0[i] + C0[k - 1] * C[i + 1]) % MOD
def dbl(k, C0, C1):
D0 = [0] * k
D1 = [0] * k
D0[:] = C0[:]
for j in range(k):
C1[j] = C0[0] * C0[j] % MOD
for i in range(1, k):
inc(k, D0, D1)
for j in range(k):
C1[j] += C0[i] * D1[j] % MOD
D0, D1 = D1, D0
for i in range(k):
C1[i] %= MOD
p = n.bit_length() - 1
while p:
p -= 1
dbl(k, C0, C1)
C0, C1 = C1, C0
if (n >> p) & 1:
inc(k, C0, C1)
C0, C1 = C1, C0
res = 0
for i in range(k):
res = (res + C0[i] * A[i]) % MOD
return res
# 斐波那契
def fib(n: int) -> int:
"""0 1 1 2 3 5 8 13 21 34 55"""
return kitamasa([1, 1], [0, 1], n)
K, N = map(int, input().split())
print(kitamasa([1] * K, [1] * K, N - 1))
| [
"[email protected]"
] | |
1cff3f3f0a3735895b7b13a5a9cfffbe43591a22 | 9c0f26c54cd36139758993fc8310345596373e15 | /pyatmos/utils/atmosphere.py | f979e70516960e0a2066208ec2d7de606e4af22a | [
"BSD-3-Clause"
] | permissive | 214929177/pyatmos | e02f5e2fe040e8a1738c833586b23a62d9657a0b | 433a5055077e211dc3f34c2a2b65bee24b8e8e4b | refs/heads/master | 2022-04-20T20:02:59.594669 | 2020-04-15T17:21:19 | 2020-04-15T17:21:19 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 14,674 | py | """
Contains the following atmospheric functions:
- density = atm_density(alt, mach)
- mach = atm_mach(alt, velocity)
- velocity = atm_velocity(alt, mach)
- pressure = atm_pressure(alt)
- temperature = atm_temperature(alt)
- sos = atm_speed_of_sound(alt)
- mu = atm_dynamic_viscosity_mu(alt)
- nu = atm_kinematic_viscosity_nu(alt)
- eas = atm_equivalent_airspeed(alt, mach)
All the default units are in English units because the source equations
are in English units.
"""
import sys
from math import log, exp
import numpy as np
from pyatmos.utils.unitless import speed_of_sound, dynamic_pressure_p_mach
from pyatmos.utils.unit_conversion import (
convert_altitude, convert_density, convert_velocity,
_rankine_to_temperature_units, _psfs_to_dvisc_units, _ft2s_to_kvisc_units,
_altitude_factor, _pressure_factor, _velocity_factor,
_reynolds_factor)
def atm_temperature(alt: float, alt_units: str='ft', temperature_units: str='R') -> float:
r"""
Freestream Temperature \f$ T_{\infty} \f$
Parameters
----------
alt : float
Altitude in alt_units
alt_units : str; default='ft'
the altitude units; ft, kft, m
temperature_units : str; default='R'
the altitude units; R, K
Returns
-------
T : float
temperature in degrees Rankine or Kelvin (SI)
.. note ::
from BAC-7006-3352-001-V1.pdf\n
A Manual for Determining Aerodynamic Heating of High Speed Aircraft\n
page ~236 - Table C.1\n
These equations were used because they are valid to 300k ft.\n
Extrapolation is performed above that.
"""
z = alt * _altitude_factor(alt_units, 'ft')
if z < 36151.725:
T = 518.0 - 0.003559996 * z
elif z < 82344.678:
T = 389.988
elif z < 155347.756:
T = 389.988 + .0016273286 * (z - 82344.678)
elif z < 175346.171:
T = 508.788
elif z < 249000.304:
T = 508.788 - .0020968273 * (z - 175346.171)
elif z < 299515.564:
T = 354.348
else:
#print("alt=%i kft > 299.5 kft" % (z / 1000.))
T = 354.348
#raise AtmosphereError("altitude is too high")
factor = _rankine_to_temperature_units(temperature_units)
T2 = T * factor
return T2
def atm_pressure(alt: float, alt_units: str='ft', pressure_units: str='psf') -> float:
r"""
Freestream Pressure \f$ p_{\infty} \f$
Parameters
----------
alt : float
Altitude in alt_units
alt_units : str; default='ft'
the altitude units; ft, kft, m
pressure_units : str; default='psf'
the pressure units; psf, psi, Pa, kPa, MPa
Returns
-------
pressure : float
Returns pressure in pressure_units
.. note ::
from BAC-7006-3352-001-V1.pdf\n
A Manual for Determining Aerodynamic Heating of High Speed Aircraft\n
page ~236 - Table C.1\n
These equations were used b/c they are valid to 300k ft.\n
Extrapolation is performed above that.\n
"""
alt_ft = convert_altitude(alt, alt_units, 'ft')
ln_pressure = _log_pressure(alt_ft)
p = exp(ln_pressure)
factor = _pressure_factor('psf', pressure_units)
return p * factor
def _log_pressure(alt_ft):
"""calculates the log(pressure) in psf given altitude in feet"""
if alt_ft < 36151.725:
ln_pressure = 7.657389 + 5.2561258 * log(1 - 6.8634634E-6 * alt_ft)
elif alt_ft < 82344.678:
ln_pressure = 6.158411 - 4.77916918E-5 * (alt_ft - 36151.725)
elif alt_ft < 155347.756:
ln_pressure = 3.950775 - 11.3882724 * log(1.0 + 4.17276598E-6 * (alt_ft - 82344.678))
elif alt_ft < 175346.171:
ln_pressure = 0.922461 - 3.62635373E-5*(alt_ft - 155347.756)
elif alt_ft < 249000.304:
ln_pressure = 0.197235 + 8.7602095 * log(1.0 - 4.12122002E-6 * (alt_ft - 175346.171))
elif alt_ft < 299515.564:
ln_pressure = -2.971785 - 5.1533546650E-5 * (alt_ft - 249000.304)
else:
#print("alt=%i kft > 299.5 kft" % (alt_ft / 1000.))
ln_pressure = -2.971785 - 5.1533546650E-5 * (alt_ft - 249000.304)
return ln_pressure
def atm_dynamic_pressure(alt: float, mach: float, alt_units: str='ft', pressure_units: str='psf') -> float:
r"""
Freestream Dynamic Pressure \f$ q_{\infty} \f$
Parameters
----------
alt : float
Altitude in alt_units
mach : float
Mach Number \f$ M \f$
alt_units : str; default='ft'
the altitude units; ft, kft, m
pressure_units : str; default='psf'
the pressure units; psf, psi, Pa, kPa, MPa
Returns
-------
dynamic_pressure : float
Returns dynamic pressure in pressure_units
The common method that requires many calculations...
\f[ \large q = \frac{1}{2} \rho V^2 \f]
\f[ \large p = \rho R T \f]
\f[ \large M = \frac{V}{a} \f]
\f[ \large a = \sqrt{\gamma R T} \f]
so...
\f[ \large q = \frac{\gamma}{2} p M^2 \f]
"""
z = alt * _altitude_factor(alt_units, 'ft')
p = atm_pressure(z)
q = dynamic_pressure_p_mach(p, mach)
factor = _pressure_factor('psf', pressure_units)
q2 = q * factor
return q2
def atm_speed_of_sound(alt: float, alt_units: str='ft', velocity_units: str='ft/s', gamma: float=1.4) -> float:
r"""
Freestream Speed of Sound \f$ a_{\infty} \f$
Parameters
----------
alt : float
Altitude in alt_units
alt_units : str; default='ft'
the altitude units; ft, kft, m
velocity_units : str; default='ft/s'
the velocity units; ft/s, m/s, in/s, knots
gamma : float, default=1.4
Air heat capacity ratio.
Returns
-------
speed_of_sound, a : float
Returns speed of sound in velocity_units
\f[ \large a = \sqrt{\gamma R T} \f]
"""
# converts everything to English units first
z = alt * _altitude_factor(alt_units, 'ft')
T = atm_temperature(z)
R = 1716. # 1716.59, dir air, R=287.04 J/kg*K
a = speed_of_sound(T, R=R, gamma=gamma)
factor = _velocity_factor('ft/s', velocity_units) # ft/s to m/s
a2 = a * factor
return a2
def atm_velocity(alt: float, mach: float, alt_units: str='ft', velocity_units: str='ft/s') -> float:
r"""
Freestream Velocity \f$ V_{\infty} \f$
Parameters
----------
alt : float
altitude in alt_units
Mach : float
Mach Number \f$ M \f$
alt_units : str; default='ft'
the altitude units; ft, kft, m
velocity_units : str; default='ft/s'
the velocity units; ft/s, m/s, in/s, knots
Returns
-------
velocity : float
Returns velocity in velocity_units
\f[ \large V = M a \f]
"""
a = atm_speed_of_sound(alt, alt_units=alt_units, velocity_units=velocity_units)
V = mach * a # units=ft/s or m/s
return V
def atm_equivalent_airspeed(alt: float, mach: float, alt_units: str='ft', eas_units: str='ft/s') -> float:
"""
Freestream equivalent airspeed
Parameters
----------
alt : float
altitude in alt_units
Mach : float
Mach Number \f$ M \f$
alt_units : str; default='ft'
the altitude units; ft, kft, m
eas_units : str; default='ft/s'
the equivalent airspeed units; ft/s, m/s, in/s, knots
Returns
-------
eas : float
equivalent airspeed in eas_units
EAS = TAS * sqrt(rho/rho0)
p = rho * R * T
rho = p/(RT)
rho/rho0 = p/T * T0/p0
TAS = a * M
EAS = a * M * sqrt(p/T * T0/p0)
EAS = a * M * sqrt(p*T0 / (T*p0))
"""
z = convert_altitude(alt, alt_units, 'ft')
p_psf = atm_pressure(z)
eas_fts = _equivalent_airspeed(mach, p_psf)
eas2 = convert_velocity(eas_fts, 'ft/s', eas_units)
return eas2
def _equivalent_airspeed(mach: float, p_psf: float) -> float:
"""helper method for atm_equivalent_airspeed"""
z0 = 0.
T0 = atm_temperature(z0)
p0 = atm_pressure(z0)
gamma = 1.4
R = 1716.
#eas = a * mach * sqrt((p * T0) / (T * p0))
# = sqrt(gamma * R * T) * mach * sqrt(T0 / p0) * sqrt(p / T)
# = sqrt(gamma * R) * mach * sqrt(T0 / p0) * sqrt(T) * sqrt(p / T)
# = sqrt(gamma * R * T0 / p0) * mach * sqrt(p)
# = k * sqrt(p)
# rho0 = p0 / (R * T0)
# k = sqrt(gamma / rho0) * mach
eas = np.sqrt(gamma * R * T0 / p0) * mach * p_psf ** 0.5
return eas
def atm_mach(alt: float, V: float, alt_units: str='ft', velocity_units: str='ft/s') -> float:
r"""
Freestream Mach Number
Parameters
----------
alt : float
altitude in alt_units
V : float
Velocity in velocity_units
alt_units : str; default='ft'
the altitude units; ft, kft, m
velocity_units : str; default='ft/s'
the velocity units; ft/s, m/s, in/s, knots
Returns
-------
mach : float
Mach Number \f$ M \f$
\f[ \large M = \frac{V}{a} \f]
"""
a = atm_speed_of_sound(alt, alt_units=alt_units, velocity_units=velocity_units)
mach = V / a
return mach
def atm_density(alt: float, R: float=1716., alt_units: str='ft', density_units: str='slug/ft^3') -> float:
r"""
Freestream Density \f$ \rho_{\infty} \f$
Parameters
----------
alt : float
altitude in feet or meters
R : float; default=1716.
gas constant for air in english units (???)
alt_units : str; default='ft'
the altitude units; ft, kft, m
density_units : str; default='slug/ft^3'
the density units; slug/ft^3, slinch/in^3, kg/m^3
Returns
-------
rho : float
density \f$ \rho \f$ in density_units
Based on the formula P=pRT
\f[ \large \rho=\frac{p}{R T} \f]
"""
z = convert_altitude(alt, alt_units, 'ft')
#z = alt * _altitude_factor(alt_units, 'ft')
p = atm_pressure(z)
T = atm_temperature(z)
rho = p / (R * T)
rho2 = convert_density(rho, 'slug/ft^3', density_units)
return rho2
def atm_kinematic_viscosity_nu(alt: float, alt_units: str='ft', visc_units: str='ft^2/s') -> float:
r"""
Freestream Kinematic Viscosity \f$ \nu_{\infty} \f$
Parameters
----------
alt : float
Altitude in alt_units
alt_units : str; default='ft'
the altitude units; ft, kft, m
visc_units : str; default='slug/ft^3'
the kinematic viscosity units; ft^2/s, m^2/s
Returns
-------
nu : float
kinematic viscosity \f$ \nu_{\infty} \f$ in visc_units
\f[ \large \nu = \frac{\mu}{\rho} \f]
.. seealso:: sutherland_viscoscity
"""
z = alt * _altitude_factor(alt_units, 'ft')
rho = atm_density(z)
mu = atm_dynamic_viscosity_mu(z)
nu = mu / rho # ft^2/s
factor = _ft2s_to_kvisc_units(alt_units, visc_units)
return nu * factor
def atm_dynamic_viscosity_mu(alt: float, alt_units: str='ft', visc_units: str='(lbf*s)/ft^2') -> float:
r"""
Freestream Dynamic Viscosity \f$ \mu_{\infty} \f$
Parameters
----------
alt : float
Altitude in alt_units
alt_units : str; default='ft'
the altitude units; ft, kft, m
visc_units : str; default='(lbf*s)/ft^2'
the viscosity units; (lbf*s)/ft^2, (N*s)/m^2, Pa*s
Returns
-------
mu : float
dynamic viscosity \f$ \mu_{\infty} \f$ in (lbf*s)/ft^2 or (N*s)/m^2 (SI)
.. seealso:: sutherland_viscoscity
"""
z = alt * _altitude_factor(alt_units, 'ft')
T = atm_temperature(z)
mu = sutherland_viscoscity(T) # (lbf*s)/ft^2
factor = _psfs_to_dvisc_units(visc_units)
return mu * factor
def atm_unit_reynolds_number2(alt: float, mach: float, alt_units: str='ft', reynolds_units: str='1/ft') -> float:
r"""
Returns the Reynolds Number per unit length.
Parameters
----------
alt : float
Altitude in alt_units
mach : float
Mach Number \f$ M \f$
alt_units : str; default='ft'
the altitude units; ft, kft, m
reynolds_units : str; default='1/ft'
the altitude units; 1/ft, 1/m, 1/in
Returns
-------
ReynoldsNumber/L : float
the Reynolds Number per unit length
\f[ \large Re_L = \frac{ \rho V}{\mu} = \frac{p M a}{\mu R T} \f]
.. note ::
this version of Reynolds number directly caculates the base quantities, so multiple
calls to atm_press and atm_temp are not made
"""
z = alt * _altitude_factor(alt_units, 'ft')
gamma = 1.4
R = 1716.
p = atm_pressure(z)
T = atm_temperature(z)
mu = sutherland_viscoscity(T)
#p = rho * R * T
#a = (gamma * R * T) ** 0.5
#
# ReL = p * a * mach / (mu * R * T)
# = p * sqrt(gamma * R * T) * mach / (mu * R * T)
# = (p * mach / mu) * sqrt(gamma * R * T) / (R * T)
# = (p * mach / mu) * sqrt(gamma / (R * T))
ReL = (p * mach / mu) * (gamma / (R * T)) ** 0.5
ReL *= _reynolds_factor('1/ft', reynolds_units)
return ReL
def atm_unit_reynolds_number(alt: float, mach: float, alt_units: str='ft', reynolds_units: str='1/ft') -> float:
r"""
Returns the Reynolds Number per unit length.
Parameters
----------
alt : float
Altitude in alt_units
mach : float
Mach Number \f$ M \f$
alt_units : str; default='ft'
the altitude units; ft, kft, m
reynolds_units : str; default='1/ft'
the altitude units; 1/ft, 1/m, 1/in
Returns
-------
ReynoldsNumber/L : float
Reynolds number per unit length in reynolds_units
\f[ \large Re = \frac{ \rho V L}{\mu} \f]
\f[ \large Re_L = \frac{ \rho V }{\mu} \f]
"""
z = alt * _altitude_factor(alt_units, 'ft')
rho = atm_density(z)
V = atm_velocity(z, mach)
mu = atm_dynamic_viscosity_mu(z)
ReL = (rho * V) / mu
ReL *= _reynolds_factor('1/ft', reynolds_units)
return ReL
def sutherland_viscoscity(T: float) -> float:
r"""
Helper function that calculates the dynamic viscosity \f$ \mu \f$ of air at
a given temperature.
Parameters
----------
T : float
Temperature T is in Rankine
Returns
-------
mu : float
dynamic viscosity \f$ \mu \f$ of air in (lbf*s)/ft^2
.. note ::
prints a warning if T>5400 deg R
Sutherland's Equation\n
From Aerodynamics for Engineers 4th Edition\n
John J. Bertin 2002\n
page 6 eq 1.5b\n
"""
if T < 225.: # Rankine
viscosity = 8.0382436E-10 * T
else:
if T > 5400.:
sys.stderr.write('WARNING: viscosity - Temperature is too large '
'(T>5400 R) T=%s\n' % T)
viscosity = 2.27E-8 * (T ** 1.5) / (T + 198.6)
return viscosity
| [
"[email protected]"
] | |
32e09174565a44e786fa360e7af4bf2209769ac7 | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2722/60618/263228.py | b160da742780d937979025c0c44bdfcdabe7989e | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 106 | py | t=int(input())
for i in t:
n=input()
if n%5==0:
print("YES")
else:
print("NO") | [
"[email protected]"
] | |
9fe0d3081bfd6bb1753c83a2b2f171503339a041 | 52b5773617a1b972a905de4d692540d26ff74926 | /.history/Nesting_20200908173521.py | 5169bca441ee68541cce697351971411928c70bf | [] | no_license | MaryanneNjeri/pythonModules | 56f54bf098ae58ea069bf33f11ae94fa8eedcabc | f4e56b1e4dda2349267af634a46f6b9df6686020 | refs/heads/master | 2022-12-16T02:59:19.896129 | 2020-09-11T12:05:22 | 2020-09-11T12:05:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 98 | py | def nesting(S):
# first
print(nesting("(()")) | [
"[email protected]"
] | |
307d7db79493210adf18a3116db90a72fbcf7642 | 1279908d488776ef1450492f0995e1bd48c99767 | /.history/app_20210728170028.py | 56fb63ebb031b38348b9cdfc6656f0a9ec0a72ab | [] | no_license | tritchlin/sqlalchemy-challenge | 249ed221daab1e148209904aa1544a924ce6a344 | 5d9288b516a1ab68bd6af16c98ca5c1170d3b927 | refs/heads/main | 2023-06-25T23:27:10.175847 | 2021-07-29T06:35:04 | 2021-07-29T06:35:04 | 388,950,398 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,024 | py | from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
# import climate_flask_data.py as querydata
app = Flask(__name__)
app.config['Hawaii']='sqlite:///hawaii.sqlite'
db=SQLAlchemy(app)
engine = create_engine("sqlite:///hawaii.sqlite")
Base = automap_base()
Base.prepare(engine, reflect=True)
measurement = base.classes.measurement
station = base.classes.station
# Create an app, being sure to pass __name__
# from climate_flask_data.py import base
# Define what to do when a user hits the index route
@app.route("/")
def welcome():
"""List all available api routes."""
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/<start><br/>"
f"/api/v1.0/<start>/<end>"
)
# Define what to do when a user hits the /about route
# @app.route("/api/v1.0/precipitation")
# def precipitation():
# return querydata.precipitation()
# # Define what to do when a user hits the /about route
# @app.route("/api/v1.0/stations")
# def about():
# print("Server received request for 'About' page...")
# return "Welcome to my 'About' page!"
# # Define what to do when a user hits the /about route
# @app.route("/api/v1.0/tobs")
# def about():
# print("Server received request for 'About' page...")
# return "Welcome to my 'About' page!"
# # Define what to do when a user hits the /about route
# @app.route("/api/v1.0/<start>")
# def about():
# print("Server received request for 'About' page...")
# return "Welcome to my 'About' page!"
# # Define what to do when a user hits the /about route
# @app.route("/api/v1.0/<start>/<end>")
# def about():
# print("Server received request for 'About' page...")
# return "Welcome to my 'About' page!"
# if __name__ == "__main__":
# app.run(debug=True)
| [
"[email protected]"
] | |
582acb3bcfdc0d636dfcd9571a7b4b463d749705 | be0f3dfbaa2fa3d8bbe59229aef3212d032e7dd1 | /Gauss_v45r10p1/Gen/DecFiles/options/23123011.py | c22ed6aed9a114cbc62b3916ee36b83d4b2a3b8e | [] | no_license | Sally27/backup_cmtuser_full | 34782102ed23c6335c48650a6eaa901137355d00 | 8924bebb935b96d438ce85b384cfc132d9af90f6 | refs/heads/master | 2020-05-21T09:27:04.370765 | 2018-12-12T14:41:07 | 2018-12-12T14:41:07 | 185,989,173 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 748 | py | # file /home/hep/ss4314/cmtuser/Gauss_v45r10p1/Gen/DecFiles/options/23123011.py generated: Wed, 25 Jan 2017 15:25:37
#
# Event Type: 23123011
#
# ASCII decay Descriptor: [D_s+ -> pi- e+ e+]cc
#
from Configurables import Generation
Generation().EventType = 23123011
Generation().SampleGenerationTool = "SignalPlain"
from Configurables import SignalPlain
Generation().addTool( SignalPlain )
Generation().SignalPlain.ProductionTool = "PythiaProduction"
from Configurables import ToolSvc
from Configurables import EvtGenDecay
ToolSvc().addTool( EvtGenDecay )
ToolSvc().EvtGenDecay.UserDecayFile = "$DECFILESROOT/dkfiles/Ds_pi-ee=DecProdCut.dec"
Generation().SignalPlain.CutTool = "DaughtersInLHCb"
Generation().SignalPlain.SignalPIDList = [ 431,-431 ]
| [
"[email protected]"
] | |
d0cfda9b9e6f2e6f19df057e89736ab28b36d573 | c1edf63a93d0a6d914256e848904c374db050ae0 | /Python/黑客攻防/破解/dictionary.py | 909018a1cd432c05322b59a1d4b38474cb25f02d | [] | no_license | clhiker/WPython | 97b53dff7e5a2b480e1bf98d1b2bf2a1742cb1cd | b21cbfe9aa4356d0fe70d5a56c8b91d41f5588a1 | refs/heads/master | 2020-03-30T03:41:50.459769 | 2018-09-28T07:36:21 | 2018-09-28T07:36:21 | 150,703,520 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 286 | py | import itertools as its
import time
def main():
a = time.time()
word = "abcdefghijklmnopqrstuvwxyz"
r = its.product(word, repeat=6)
dic = open("dictionary.txt", "a")
for i in r:
dic.write("".join(i))
b = time.time()
print(b-a)
dic.close()
main() | [
"[email protected]"
] | |
9d1d0d94f750d498a91dd81d6d464c609ac9368c | eb19f68b76ab16375a096c06bf98cf920c8e7a0c | /src/tracking1.py | ab06f2fc4b87671ddc02529d29cd626c4a85187b | [] | no_license | YerongLi/statistical-connectomes | a9869d918761b05bcd9980a0b4d36205673d582e | 7519289c2f26314d88149e878125042021cea07d | refs/heads/master | 2020-04-09T03:53:42.754095 | 2018-12-02T01:03:19 | 2018-12-02T01:03:19 | 160,001,525 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,242 | py | """
====================
Tracking Quick Start
====================
This example shows how to perform fast fiber tracking using DIPY_
[Garyfallidis12]_.
We will use Constrained Spherical Deconvolution (CSD) [Tournier07]_ for local
reconstruction and then generate deterministic streamlines using the fiber
directions (peaks) from CSD and fractional anisotropic (FA) from DTI as a
stopping criteria for the tracking.
Let's load the necessary modules.
"""
from os.path import join as pjoin
import numpy as np
from dipy.tracking.local import LocalTracking, ThresholdTissueClassifier
from dipy.tracking.utils import random_seeds_from_mask
from dipy.reconst.dti import TensorModel
from dipy.reconst.csdeconv import (ConstrainedSphericalDeconvModel,
auto_response)
from dipy.direction import peaks_from_model
from dipy.data import fetch_stanford_hardi, read_stanford_hardi, get_sphere
from dipy.segment.mask import median_otsu
from dipy.viz import actor, window
from dipy.io.image import save_nifti
from nibabel.streamlines import save as save_trk
from nibabel.streamlines import Tractogram
from dipy.tracking.streamline import Streamlines
from utils import read_data
"""
Enables/disables interactive visualization
"""
interactive = False
"""
Load one of the available datasets with 150 gradients on the sphere and 10 b0s
"""
#fetch_stanford_hardi()
#img, gtab = read_stanford_hardi()
id = 103818
folder = pjoin('/projects','ml75','data',str(id))
img, gtab = read_data(folder)
data = img.get_data()
print(gtab)
"""
Create a brain mask. This dataset is a bit difficult to segment with the
default ``median_otsu`` parameters (see :ref:`example_brain_extraction_dwi`)
therefore we use here more advanced options.
"""
maskdata, mask = median_otsu(data, 3, 1, False,
vol_idx=range(10, 50), dilate=2)
"""
For the Constrained Spherical Deconvolution we need to estimate the response
function (see :ref:`example_reconst_csd`) and create a model.
"""
response, ratio = auto_response(gtab, data, roi_radius=10, fa_thr=0.7)
csd_model = ConstrainedSphericalDeconvModel(gtab, response)
"""
Next, we use ``peaks_from_model`` to fit the data and calculated the fiber
directions in all voxels.
"""
sphere = get_sphere('symmetric724')
csd_peaks = peaks_from_model(model=csd_model,
data=data,
sphere=sphere,
mask=mask,
relative_peak_threshold=.5,
min_separation_angle=25,
parallel=True)
"""
For the tracking part, we will use the fiber directions from the ``csd_model``
but stop tracking in areas where fractional anisotropy is low (< 0.1).
To derive the FA, used here as a stopping criterion, we would need to fit a
tensor model first. Here, we fit the tensor using weighted least squares (WLS).
"""
tensor_model = TensorModel(gtab, fit_method='WLS')
tensor_fit = tensor_model.fit(data, mask)
fa = tensor_fit.fa
"""
In this simple example we can use FA to stop tracking. Here we stop tracking
when FA < 0.1.
"""
tissue_classifier = ThresholdTissueClassifier(fa, 0.1)
"""
Now, we need to set starting points for propagating each track. We call those
seeds. Using ``random_seeds_from_mask`` we can select a specific number of
seeds (``seeds_count``) in each voxel where the mask ``fa > 0.3`` is true.
"""
seeds = random_seeds_from_mask(fa > 0.3, seeds_count=1)
"""
For quality assurance we can also visualize a slice from the direction field
which we will use as the basis to perform the tracking.
"""
'''
ren = window.Renderer()
ren.add(actor.peak_slicer(csd_peaks.peak_dirs,
csd_peaks.peak_values,
colors=None))
if interactive:
window.show(ren, size=(900, 900))
else:
window.record(ren, out_path='csd_direction_field.png', size=(900, 900))
'''
"""
.. figure:: csd_direction_field.png
:align: center
**Direction Field (peaks)**
``EuDX`` [Garyfallidis12]_ is a fast algorithm that we use here to generate
streamlines. This algorithm is what is used here and the default option
when providing the output of peaks directly in LocalTracking.
"""
streamline_generator = LocalTracking(csd_peaks, tissue_classifier,
seeds, affine=np.eye(4),
step_size=0.5)
streamlines = Streamlines(streamline_generator)
"""
The total number of streamlines is shown below.
"""
print(len(streamlines))
"""
To increase the number of streamlines you can change the parameter
``seeds_count`` in ``random_seeds_from_mask``.
We can visualize the streamlines using ``actor.line`` or ``actor.streamtube``.
"""
'''
ren.clear()
ren.add(actor.line(streamlines))
if interactive:
window.show(ren, size=(900, 900))
else:
print('Saving illustration as det_streamlines.png')
window.record(ren, out_path='det_streamlines.png', size=(900, 900))
'''
"""
.. figure:: det_streamlines.png
:align: center
**Deterministic streamlines using EuDX (new framework)**
To learn more about this process you could start playing with the number of
seed points or, even better, specify seeds to be in specific regions of interest
in the brain.
Save the resulting streamlines in a Trackvis (.trk) format and FA as
Nifti (.nii.gz).
"""
save_trk(Tractogram(streamlines, affine_to_rasmm=img.affine),
'det_streamlines.trk')
save_nifti('fa_map.nii.gz', fa, img.affine)
"""
In Windows if you get a runtime error about frozen executable please start
your script by adding your code above in a ``main`` function and use::
if __name__ == '__main__':
import multiprocessing
multiprocessing.freeze_support()
main()
References
----------
.. [Garyfallidis12] Garyfallidis E., "Towards an accurate brain tractography",
PhD thesis, University of Cambridge, 2012.
.. [Tournier07] J-D. Tournier, F. Calamante and A. Connelly, "Robust
determination of the fibre orientation distribution in diffusion MRI:
Non-negativity constrained super-resolved spherical deconvolution",
Neuroimage, vol. 35, no. 4, pp. 1459-1472, 2007.
.. include:: ../links_names.inc
"""
| [
"[email protected]"
] | |
549fcc281ee7b1ff3519de8b8882f35c1e72e4de | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/otherforms/_animations.py | 02af88c871ee685813138b37592a71c92dd2f001 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 234 | py |
#calss header
class _ANIMATIONS():
def __init__(self,):
self.name = "ANIMATIONS"
self.definitions = animation
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.basic = ['animation']
| [
"[email protected]"
] | |
1f0f22bcce72ff8ae6781b02b4e85005590893ab | 15592893bd1871bfeb1cdb4741523894cf32cf67 | /python_fundamentals/bubblesort.py | accec854cbab91b213adf4927d6494e188eeb934 | [] | no_license | philmccormick23/Learning-Python | b07758d2bb310e617991a13230b257a71c3c2510 | 5a06c5155941816ce3e61d262ae5779ae2899196 | refs/heads/master | 2020-04-08T08:50:03.749946 | 2018-11-26T16:01:27 | 2018-11-26T16:01:27 | 159,195,744 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 237 | py | arr=[8,3,5,1,2,0]
def bubbleSort(arr):
for j in range(len(arr)-1):
for i in range(len(arr)-1-j):
if(arr[i]>arr[i+1]):
arr[i],arr[i+1]=arr[i+1],arr[i]
return arr
print(bubbleSort([8,3,5,1,2,0])) | [
"[email protected]"
] | |
42f89f949b1d952ff7a39e2b92955b2ee6d2e7ee | 2987124e4fc79943021596adf0b605d3b9ce5a3b | /models/05_irs.py | 4b0071b13acb48a7ff3ebcb47d54d0998693bda2 | [
"MIT"
] | permissive | abhishekarora9/eden | 4ff1fe022264fee5f972295b3d7d6662b6df3515 | be6c3e22eefd61bfd4cc54af392aed2404184e37 | refs/heads/master | 2021-05-26T20:09:33.936000 | 2011-12-27T23:23:16 | 2011-12-27T23:23:16 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 32,717 | py | # -*- coding: utf-8 -*-
""" Incident Reporting System - Model
@author: Sahana Taiwan Team
@author: Fran Boon
"""
if deployment_settings.has_module("irs"):
# Staff as component of Incident Reports
if deployment_settings.has_module("vehicle"):
link_table = "irs_ireport_vehicle_human_resource"
else:
link_table = "irs_ireport_human_resource"
s3mgr.model.add_component("hrm_human_resource",
irs_ireport=Storage(
link=link_table,
joinby="ireport_id",
key="human_resource_id",
# Dispatcher doesn't need to Add/Edit records, just Link
actuate="link",
autocomplete="name",
autodelete=False))
def ireport_tables():
""" Load the Incident Report Tables when required """
module = "irs"
# ---------------------------------------------------------------------
# List of Incident Categories
# The keys are based on the Canadian ems.incident hierarchy, with a few extra general versions added to 'other'
# The values are meant for end-users, so can be customised as-required
# NB It is important that the meaning of these entries is not changed as otherwise this hurts our ability to do synchronisation
# Entries can be hidden from user view in the controller.
# Additional sets of 'translations' can be added to the tuples.
irs_incident_type_opts = {
"animalHealth.animalDieOff": T("Animal Die Off"),
"animalHealth.animalFeed": T("Animal Feed"),
"aviation.aircraftCrash": T("Aircraft Crash"),
"aviation.aircraftHijacking": T("Aircraft Hijacking"),
"aviation.airportClosure": T("Airport Closure"),
"aviation.airspaceClosure": T("Airspace Closure"),
"aviation.noticeToAirmen": T("Notice to Airmen"),
"aviation.spaceDebris": T("Space Debris"),
"civil.demonstrations": T("Demonstrations"),
"civil.dignitaryVisit": T("Dignitary Visit"),
"civil.displacedPopulations": T("Displaced Populations"),
"civil.emergency": T("Civil Emergency"),
"civil.looting": T("Looting"),
"civil.publicEvent": T("Public Event"),
"civil.riot": T("Riot"),
"civil.volunteerRequest": T("Volunteer Request"),
"crime": T("Crime"),
"crime.bomb": T("Bomb"),
"crime.bombExplosion": T("Bomb Explosion"),
"crime.bombThreat": T("Bomb Threat"),
"crime.dangerousPerson": T("Dangerous Person"),
"crime.drugs": T("Drugs"),
"crime.homeCrime": T("Home Crime"),
"crime.illegalImmigrant": T("Illegal Immigrant"),
"crime.industrialCrime": T("Industrial Crime"),
"crime.poisoning": T("Poisoning"),
"crime.retailCrime": T("Retail Crime"),
"crime.shooting": T("Shooting"),
"crime.stowaway": T("Stowaway"),
"crime.terrorism": T("Terrorism"),
"crime.vehicleCrime": T("Vehicle Crime"),
"fire": T("Fire"),
"fire.forestFire": T("Forest Fire"),
"fire.hotSpot": T("Hot Spot"),
"fire.industryFire": T("Industry Fire"),
"fire.smoke": T("Smoke"),
"fire.urbanFire": T("Urban Fire"),
"fire.wildFire": T("Wild Fire"),
"flood": T("Flood"),
"flood.damOverflow": T("Dam Overflow"),
"flood.flashFlood": T("Flash Flood"),
"flood.highWater": T("High Water"),
"flood.overlandFlowFlood": T("Overland Flow Flood"),
"flood.tsunami": T("Tsunami"),
"geophysical.avalanche": T("Avalanche"),
"geophysical.earthquake": T("Earthquake"),
"geophysical.lahar": T("Lahar"),
"geophysical.landslide": T("Landslide"),
"geophysical.magneticStorm": T("Magnetic Storm"),
"geophysical.meteorite": T("Meteorite"),
"geophysical.pyroclasticFlow": T("Pyroclastic Flow"),
"geophysical.pyroclasticSurge": T("Pyroclastic Surge"),
"geophysical.volcanicAshCloud": T("Volcanic Ash Cloud"),
"geophysical.volcanicEvent": T("Volcanic Event"),
"hazardousMaterial": T("Hazardous Material"),
"hazardousMaterial.biologicalHazard": T("Biological Hazard"),
"hazardousMaterial.chemicalHazard": T("Chemical Hazard"),
"hazardousMaterial.explosiveHazard": T("Explosive Hazard"),
"hazardousMaterial.fallingObjectHazard": T("Falling Object Hazard"),
"hazardousMaterial.infectiousDisease": T("Infectious Disease (Hazardous Material)"),
"hazardousMaterial.poisonousGas": T("Poisonous Gas"),
"hazardousMaterial.radiologicalHazard": T("Radiological Hazard"),
"health.infectiousDisease": T("Infectious Disease"),
"health.infestation": T("Infestation"),
"ice.iceberg": T("Iceberg"),
"ice.icePressure": T("Ice Pressure"),
"ice.rapidCloseLead": T("Rapid Close Lead"),
"ice.specialIce": T("Special Ice"),
"marine.marineSecurity": T("Marine Security"),
"marine.nauticalAccident": T("Nautical Accident"),
"marine.nauticalHijacking": T("Nautical Hijacking"),
"marine.portClosure": T("Port Closure"),
"marine.specialMarine": T("Special Marine"),
"meteorological.blizzard": T("Blizzard"),
"meteorological.blowingSnow": T("Blowing Snow"),
"meteorological.drought": T("Drought"),
"meteorological.dustStorm": T("Dust Storm"),
"meteorological.fog": T("Fog"),
"meteorological.freezingDrizzle": T("Freezing Drizzle"),
"meteorological.freezingRain": T("Freezing Rain"),
"meteorological.freezingSpray": T("Freezing Spray"),
"meteorological.hail": T("Hail"),
"meteorological.hurricane": T("Hurricane"),
"meteorological.rainFall": T("Rain Fall"),
"meteorological.snowFall": T("Snow Fall"),
"meteorological.snowSquall": T("Snow Squall"),
"meteorological.squall": T("Squall"),
"meteorological.stormSurge": T("Storm Surge"),
"meteorological.thunderstorm": T("Thunderstorm"),
"meteorological.tornado": T("Tornado"),
"meteorological.tropicalStorm": T("Tropical Storm"),
"meteorological.waterspout": T("Waterspout"),
"meteorological.winterStorm": T("Winter Storm"),
"missingPerson": T("Missing Person"),
"missingPerson.amberAlert": T("Child Abduction Emergency"), # http://en.wikipedia.org/wiki/Amber_Alert
"missingPerson.missingVulnerablePerson": T("Missing Vulnerable Person"),
"missingPerson.silver": T("Missing Senior Citizen"), # http://en.wikipedia.org/wiki/Silver_Alert
"publicService.emergencySupportFacility": T("Emergency Support Facility"),
"publicService.emergencySupportService": T("Emergency Support Service"),
"publicService.schoolClosure": T("School Closure"),
"publicService.schoolLockdown": T("School Lockdown"),
"publicService.serviceOrFacility": T("Service or Facility"),
"publicService.transit": T("Transit"),
"railway.railwayAccident": T("Railway Accident"),
"railway.railwayHijacking": T("Railway Hijacking"),
"roadway.bridgeClosure": T("Bridge Closed"),
"roadway.hazardousRoadConditions": T("Hazardous Road Conditions"),
"roadway.roadwayAccident": T("Road Accident"),
"roadway.roadwayClosure": T("Road Closed"),
"roadway.roadwayDelay": T("Road Delay"),
"roadway.roadwayHijacking": T("Road Hijacking"),
"roadway.roadwayUsageCondition": T("Road Usage Condition"),
"roadway.trafficReport": T("Traffic Report"),
"temperature.arcticOutflow": T("Arctic Outflow"),
"temperature.coldWave": T("Cold Wave"),
"temperature.flashFreeze": T("Flash Freeze"),
"temperature.frost": T("Frost"),
"temperature.heatAndHumidity": T("Heat and Humidity"),
"temperature.heatWave": T("Heat Wave"),
"temperature.windChill": T("Wind Chill"),
"wind.galeWind": T("Gale Wind"),
"wind.hurricaneForceWind": T("Hurricane Force Wind"),
"wind.stormForceWind": T("Storm Force Wind"),
"wind.strongWind": T("Strong Wind"),
"other.buildingCollapsed": T("Building Collapsed"),
"other.peopleTrapped": T("People Trapped"),
"other.powerFailure": T("Power Failure"),
}
# This Table defines which Categories are visible to end-users
tablename = "irs_icategory"
table = db.define_table(tablename,
Field("code", label = T("Category"),
requires = IS_IN_SET_LAZY(lambda: \
sort_dict_by_values(irs_incident_type_opts)),
represent = lambda opt: \
irs_incident_type_opts.get(opt, opt)),
*s3_timestamp())
def irs_icategory_onvalidation(form):
"""
Incident Category Validation:
Prevent Duplicates
Done here rather than in .requires to maintain the dropdown.
"""
table = db.irs_icategory
category, error = IS_NOT_ONE_OF(db, "irs_icategory.code")(form.vars.code)
if error:
form.errors.code = error
return False
s3mgr.configure(tablename,
onvalidation=irs_icategory_onvalidation,
list_fields=[ "code" ])
# ---------------------------------------------------------------------
# Reports
# This is a report of an Incident
#
# Incident Reports can be linked to Incidents through the event_incident_report table
#
# @ToDo: If not using the Events module, we could have a 'lead incident' to track duplicates?
#
# Porto codes
#irs_incident_type_opts = {
# 1100:T("Fire"),
# 6102:T("Hazmat"),
# 8201:T("Rescue")
#}
resourcename = "ireport"
tablename = "%s_%s" % (module, resourcename)
table = db.define_table(tablename,
super_link(s3db.sit_situation),
Field("name", label = T("Short Description"),
requires = IS_NOT_EMPTY()),
Field("message", "text", label = T("Message"),
represent = lambda text: \
s3_truncate(text, length=48, nice=True)),
Field("category", label = T("Category"),
# The full set available to Admins & Imports/Exports
# (users use the subset by over-riding this in the Controller)
requires = IS_NULL_OR(IS_IN_SET_LAZY(lambda: \
sort_dict_by_values(irs_incident_type_opts))),
# Use this instead if a simpler set of Options required
#requires = IS_NULL_OR(IS_IN_SET(irs_incident_type_opts)),
represent = lambda opt: \
irs_incident_type_opts.get(opt, opt)),
# Better to use a plain text field than to clutter the PR
Field("person", label = T("Reporter Name"),
comment = (T("At/Visited Location (not virtual)"))),
#person_id(label = T("Reporter Name"),
# comment = (T("At/Visited Location (not virtual)"),
# pr_person_comment(T("Reporter Name"),
# T("The person at the location who is reporting this incident (optional)")))),
Field("contact", label = T("Contact Details")),
#organisation_id(label = T("Assign to Org.")),
Field("datetime", "datetime",
label = T("Date/Time of Alert"),
widget = S3DateTimeWidget(future=0),
requires = [IS_NOT_EMPTY(),
IS_UTC_DATETIME(allow_future=False)]),
location_id(),
human_resource_id(label=T("Incident Commander")),
Field("dispatch", "datetime",
# We don't want these visible in Create forms
# (we override in Update forms in controller)
writable = False, readable = False,
label = T("Date/Time of Dispatch"),
widget = S3DateTimeWidget(future=0),
requires = IS_EMPTY_OR(IS_UTC_DATETIME(allow_future=False))),
Field("verified", "boolean", # Ushahidi-compatibility
# We don't want these visible in Create forms
# (we override in Update forms in controller)
writable = False, readable = False,
label = T("Verified?"),
represent = lambda verified: \
(T("No"),
T("Yes"))[verified == True]),
Field("closed", "boolean",
# We don't want these visible in Create forms
# (we override in Update forms in controller)
default = False,
writable = False, readable = False,
label = T("Closed?"),
represent = lambda closed: \
(T("No"),
T("Yes"))[closed == True]),
s3_comments(),
*s3_meta_fields())
# CRUD strings
ADD_INC_REPORT = T("Add Incident Report")
LIST_INC_REPORTS = T("List Incident Reports")
s3.crud_strings[tablename] = Storage(
title_create = ADD_INC_REPORT,
title_display = T("Incident Report Details"),
title_list = LIST_INC_REPORTS,
title_update = T("Edit Incident Report"),
title_search = T("Search Incident Reports"),
subtitle_create = T("Add New Incident Report"),
subtitle_list = T("Incident Reports"),
label_list_button = LIST_INC_REPORTS,
label_create_button = ADD_INC_REPORT,
label_delete_button = T("Delete Incident Report"),
msg_record_created = T("Incident Report added"),
msg_record_modified = T("Incident Report updated"),
msg_record_deleted = T("Incident Report deleted"),
msg_list_empty = T("No Incident Reports currently registered"))
s3mgr.configure(tablename,
super_entity = s3db.sit_situation,
# Open tabs after creation
create_next = URL(args=["[id]", "update"]),
update_next = URL(args=["[id]", "update"]),
list_fields = ["id",
"name",
"category",
"location_id",
#"organisation_id",
"verified",
"message",
])
ireport_id = S3ReusableField("ireport_id", table,
requires = IS_NULL_OR(IS_ONE_OF(db, "irs_ireport.id", "%(name)s")),
represent = lambda id: (id and [db.irs_ireport[id].name] or [NONE])[0],
label = T("Incident"),
ondelete = "RESTRICT")
# ---------------------------------------------------------------------
@auth.s3_requires_membership(1) # must be Administrator
def irs_ushahidi_import(r, **attr):
"""
Import Incident Reports from Ushahidi
@ToDo: Deployment setting for Ushahidi instance URL
"""
if r.representation == "html" and \
r.name == "ireport" and not r.component and not r.id:
url = r.get_vars.get("url", "http://")
title = T("Incident Reports")
subtitle = T("Import from Ushahidi Instance")
form = FORM(TABLE(TR(
TH("URL: "),
INPUT(_type="text", _name="url", _size="100", _value=url,
requires=[IS_URL(), IS_NOT_EMPTY()]),
TH(DIV(SPAN("*", _class="req", _style="padding-right: 5px;")))),
TR(TD("Ignore Errors?: "),
TD(INPUT(_type="checkbox", _name="ignore_errors", _id="ignore_errors"))),
TR("", INPUT(_type="submit", _value=T("Import")))))
label_list_btn = s3base.S3CRUD.crud_string(r.tablename, "title_list")
list_btn = A(label_list_btn,
_href=r.url(method="", vars=None),
_class="action-btn")
rheader = DIV(P("%s: http://wiki.ushahidi.com/doku.php?id=ushahidi_api" % T("API is documented here")),
P("%s URL: http://ushahidi.my.domain/api?task=incidents&by=all&resp=xml&limit=1000" % T("Example")))
output = dict(title=title, form=form, subtitle=subtitle, list_btn=list_btn, rheader=rheader)
if form.accepts(request.vars, session):
# "Exploit" the de-duplicator hook to count import items
import_count = [0]
def count_items(job, import_count = import_count):
if job.tablename == "irs_ireport":
import_count[0] += 1
s3mgr.configure("irs_report", deduplicate=count_items)
ireports = r.resource
ushahidi = form.vars.url
ignore_errors = form.vars.get("ignore_errors", None)
stylesheet = os.path.join(request.folder, "static", "formats", "ushahidi", "import.xsl")
if os.path.exists(stylesheet) and ushahidi:
try:
success = ireports.import_xml(ushahidi,
stylesheet=stylesheet,
ignore_errors=ignore_errors)
except:
import sys
e = sys.exc_info()[1]
response.error = e
else:
if success:
count = import_count[0]
if count:
response.flash = "%s %s" % (import_count[0],
T("reports successfully imported."))
else:
response.flash = T("No reports available.")
else:
response.error = s3mgr.error
response.view = "create.html"
return output
else:
raise HTTP(501, BADMETHOD)
s3mgr.model.set_method(module, "ireport",
method="ushahidi",
action=irs_ushahidi_import)
# ---------------------------------------------------------------------
def irs_dispatch(r, **attr):
"""
Send a Dispatch notice from an Incident Report
- this will be formatted as an OpenGeoSMS
"""
if r.representation == "html" and \
r.name == "ireport" and r.id and not r.component:
s3mgr.load("msg_outbox")
msg_compose = response.s3.msg_compose
record = r.record
text = "%s %s:%s; %s" % (record.name,
T("Contact"),
record.contact,
record.message)
message = msg.prepare_opengeosms(record.location_id,
code="ST",
map="google",
text=text)
output = msg_compose(type="SMS",
recipient_type = "pr_person",
message = message,
redirect_module = "irs",
redirect_function = "ireport",
redirect_args = r.id)
# Maintain RHeader for consistency
rheader = irs_rheader(r)
title = T("Send Dispatch Update")
output.update(title=title,
rheader=rheader)
#if form.accepts(request.vars, session):
response.view = "msg/compose.html"
return output
else:
raise HTTP(501, BADMETHOD)
s3mgr.model.set_method(module, "ireport",
method="dispatch",
action=irs_dispatch)
# ---------------------------------------------------------------------
# Link Tables for iReports
# @ToDo: Make these conditional on Event not being activated?
# ---------------------------------------------------------------------
if deployment_settings.has_module("hrm"):
tablename = "irs_ireport_human_resource"
table = db.define_table(tablename,
ireport_id(),
# Simple dropdown is faster for a small team
human_resource_id(widget=None),
*s3_meta_fields())
if deployment_settings.has_module("vehicle"):
s3mgr.load("asset_asset")
asset_id = response.s3.asset_id
asset_represent = response.s3.asset_represent
tablename = "irs_ireport_vehicle"
table = db.define_table(tablename,
ireport_id(),
asset_id(label = T("Vehicle")),
Field("datetime", "datetime",
label=T("Dispatch Time"),
widget = S3DateTimeWidget(future=0),
requires = IS_EMPTY_OR(IS_UTC_DATETIME(allow_future=False)),
default = request.utcnow),
site_id,
location_id(label=T("Destination")),
Field("closed",
# @ToDo: Close all assignments when Incident closed
readable=False,
writable=False),
s3_comments(),
*s3_meta_fields())
atable = db.asset_asset
query = (atable.type == s3.asset.ASSET_TYPE_VEHICLE) & \
(atable.deleted == False) & \
((table.id == None) | \
(table.closed == True) | \
(table.deleted == True))
left = table.on(atable.id == table.asset_id)
table.asset_id.requires = IS_NULL_OR(IS_ONE_OF(db(query),
"asset_asset.id",
asset_represent,
left=left,
sort=True))
table.site_id.label = T("Fire Station")
table.site_id.readable = True
# Populated from fire_station_vehicle
#table.site_id.writable = True
def ireport_onaccept(form):
"""
Assign the appropriate vehicle & on-shift team to the incident
@ToDo: Specialist teams
@ToDo: Make more generic
"""
vars = form.vars
ireport = vars.id
category = vars.category
if category == "1100":
# Fire
types = ["VUCI", "ABSC"]
elif category == "6102":
# Hazmat
types = ["VUCI", "VCOT"]
elif category == "8201":
# Rescue
types = ["VLCI", "ABSC"]
else:
types = ["VLCI"]
# 1st unassigned vehicle
# @ToDo: Filter by Org/Base
# @ToDo: Filter by those which are under repair (asset_log)
s3mgr.load("fire_station_vehicle")
table = db.irs_ireport_vehicle
atable = db.asset_asset
vtable = db.vehicle_vehicle
for type in types:
query = (atable.type == s3.asset.ASSET_TYPE_VEHICLE) & \
(vtable.type == type) & \
(vtable.asset_id == atable.id) & \
(atable.deleted == False) & \
((table.id == None) | \
(table.closed == True) | \
(table.deleted == True))
left = table.on(atable.id == table.asset_id)
vehicle = db(query).select(atable.id,
left=left,
limitby=(0, 1)).first()
if vehicle:
s3mgr.load("vehicle_vehicle")
vehicle = vehicle.id
query = (vtable.asset_id == vehicle) & \
(db.fire_station_vehicle.vehicle_id == vtable.id) & \
(db.fire_station.id == db.fire_station_vehicle.station_id) & \
(db.org_site.id == db.fire_station.site_id)
site = db(query).select(db.org_site.id,
limitby=(0, 1)).first()
if site:
site = site.id
db.irs_ireport_vehicle.insert(ireport_id=ireport,
asset_id=vehicle,
site_id=site)
if deployment_settings.has_module("hrm"):
# Assign 1st 5 human resources on-shift
# @ToDo: Filter by Base
table = db.irs_ireport_vehicle_human_resource
htable = db.hrm_human_resource
on_shift = response.s3.fire_staff_on_duty()
query = on_shift & \
((table.id == None) | \
(table.closed == True) | \
(table.deleted == True))
left = table.on(htable.id == table.human_resource_id)
people = db(query).select(htable.id,
left=left,
limitby=(0, 5))
# @ToDo: Find Ranking person to be team leader
leader = people.first()
if leader:
leader = leader.id
query = (db.irs_ireport.id == ireport)
db(query).update(human_resource_id=leader)
for person in people:
table.insert(ireport_id=ireport,
asset_id=vehicle,
human_resource_id=person.id)
s3mgr.configure("irs_ireport",
# Porto-specific currently
#create_onaccept=ireport_onaccept,
#create_next=URL(args=["[id]", "human_resource"]),
update_next=URL(args=["[id]", "update"]))
if deployment_settings.has_module("hrm"):
tablename = "irs_ireport_vehicle_human_resource"
table = db.define_table(tablename,
ireport_id(),
# Simple dropdown is faster for a small team
human_resource_id(represent=hr_represent,
requires = IS_ONE_OF(db,
"hrm_human_resource.id",
hr_represent,
#orderby="pr_person.first_name"
),
widget=None),
asset_id(label = T("Vehicle")),
Field("closed",
# @ToDo: Close all assignments when Incident closed
readable=False,
writable=False),
*s3_meta_fields())
# ---------------------------------------------------------------------
# Pass variables back to global scope (response.s3.*)
return dict(
ireport_id = ireport_id,
irs_incident_type_opts = irs_incident_type_opts,
)
# Provide a handle to this load function
s3mgr.loader(ireport_tables,
"irs_icategory",
"irs_ireport",
# @ToDo: Make this optional when Vehicle module is active
"irs_ireport_vehicle")
else:
def ireport_id(**arguments):
""" Allow FKs to be added safely to other models in case module disabled """
return Field("ireport_id", "integer", readable=False, writable=False)
response.s3.ireport_id = ireport_id
# END =========================================================================
| [
"[email protected]"
] | |
71784b9871d44330a0d1df8c0e7409643afef6bf | 4436277af74df812490a42f33deccfcf218e25f8 | /backend/wallet/migrations/0001_initial.py | f2c922540416302dee4c799fa0921b7c911673d0 | [] | no_license | crowdbotics-apps/lunchbox-25105 | 308c49dcc77383ee8f11b25207f4b94e452f618e | 21de4ca0cbad83a09ec5e28a99ccc3dc1fc3dbeb | refs/heads/master | 2023-03-15T09:50:00.100961 | 2021-03-18T18:53:30 | 2021-03-18T18:53:30 | 349,182,205 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,258 | py | # Generated by Django 2.2.19 on 2021-03-18 18:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("task_profile", "0001_initial"),
("task", "0001_initial"),
]
operations = [
migrations.CreateModel(
name="CustomerWallet",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("balance", models.FloatField()),
("expiration_date", models.DateTimeField()),
("last_transaction", models.DateTimeField()),
(
"customer",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="customerwallet_customer",
to="task_profile.CustomerProfile",
),
),
],
),
migrations.CreateModel(
name="PaymentMethod",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("account_token", models.CharField(max_length=255)),
("payment_account", models.CharField(max_length=10)),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
(
"wallet",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="paymentmethod_wallet",
to="wallet.CustomerWallet",
),
),
],
),
migrations.CreateModel(
name="TaskerWallet",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("balance", models.FloatField(max_length=254)),
("expiration_date", models.DateTimeField()),
("last_transaction", models.DateTimeField()),
(
"tasker",
models.OneToOneField(
on_delete=django.db.models.deletion.CASCADE,
related_name="taskerwallet_tasker",
to="task_profile.TaskerProfile",
),
),
],
),
migrations.CreateModel(
name="TaskerPaymentAccount",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("account_token", models.CharField(max_length=255)),
("payment_account", models.CharField(max_length=10)),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
(
"wallet",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="taskerpaymentaccount_wallet",
to="wallet.TaskerWallet",
),
),
],
),
migrations.CreateModel(
name="PaymentTransaction",
fields=[
(
"id",
models.AutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("price", models.FloatField()),
("tip", models.FloatField()),
("tracking_id", models.CharField(max_length=50)),
("timestamp_created", models.DateTimeField(auto_now_add=True)),
(
"customer",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="paymenttransaction_customer",
to="task_profile.CustomerProfile",
),
),
(
"payment_method",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="paymenttransaction_payment_method",
to="wallet.PaymentMethod",
),
),
(
"tasker",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="paymenttransaction_tasker",
to="task_profile.TaskerProfile",
),
),
(
"transaction",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="paymenttransaction_transaction",
to="task.TaskTransaction",
),
),
],
),
]
| [
"[email protected]"
] | |
575352ef768eea3f97b304e28386e9a5188da6ef | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02258/s967893517.py | fef386565550a9bfb1823e41855b7904dda27051 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 757 | py |
n = int(input())
R = []
for i in range(n):
R.append(int(input()))
kouho = set()
diff_max = None
for (i, rt) in enumerate(R):
if i == 0:
rt_min = rt
else:
if rt < rt_min and not (diff_max is None):
kouho.add(diff_max)
diff_max = None
rt_min = rt
elif rt < rt_min and diff_max is None:
rt_min = rt
elif rt >= rt_min:
if diff_max is None:
diff_max = rt - rt_min
else:
diff_max = max(diff_max, rt - rt_min)
if not (diff_max is None):
kouho.add(diff_max)
# print(kouho)
if kouho != set():
print(max(kouho))
else:
diff_tonari = {R[i + 1] - R[i] for i in range(n - 1)}
print(max(diff_tonari)) | [
"[email protected]"
] | |
f79ea22c3b37f1ac9e6301b576168361eecb66b3 | 7bead245354e233f76fff4608938bf956abb84cf | /test/test_page_conversion_result.py | 79bca57ea61ab579fcc7be32e07b455a76551754 | [
"Apache-2.0"
] | permissive | Cloudmersive/Cloudmersive.APIClient.Python.Convert | 5ba499937b9664f37cb2700509a4ba93952e9d6c | dba2fe7257229ebdacd266531b3724552c651009 | refs/heads/master | 2021-10-28T23:12:42.698951 | 2021-10-18T03:44:49 | 2021-10-18T03:44:49 | 138,449,321 | 3 | 2 | null | null | null | null | UTF-8 | Python | false | false | 1,011 | py | # coding: utf-8
"""
convertapi
Convert API lets you effortlessly convert file formats and types. # noqa: E501
OpenAPI spec version: v1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import cloudmersive_convert_api_client
from cloudmersive_convert_api_client.models.page_conversion_result import PageConversionResult # noqa: E501
from cloudmersive_convert_api_client.rest import ApiException
class TestPageConversionResult(unittest.TestCase):
"""PageConversionResult unit test stubs"""
def setUp(self):
pass
def tearDown(self):
pass
def testPageConversionResult(self):
"""Test PageConversionResult"""
# FIXME: construct object with mandatory attributes with example values
# model = cloudmersive_convert_api_client.models.page_conversion_result.PageConversionResult() # noqa: E501
pass
if __name__ == '__main__':
unittest.main()
| [
"[email protected]"
] | |
89db78394769d2f53cdc241dbc7981412dde67f7 | 2d14aa082e33f3c9d2344ea6811a5b18ec906607 | /skdecide/discrete_optimization/rcpsp/solver/cp_solvers.py | 0e6d401ed2b4eb7947aac1cc87f569ee91c950c7 | [
"MIT"
] | permissive | walter-bd/scikit-decide | 4c0b54b7b2abdf396121cd256d1f931f0539d1bf | d4c5ae70cbe8b4c943eafa8439348291ed07dec1 | refs/heads/master | 2023-07-30T14:14:28.886267 | 2021-08-30T14:16:30 | 2021-09-03T06:46:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 36,649 | py | # Copyright (c) AIRBUS and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
from dataclasses import InitVar
from typing import Union, List
from skdecide.discrete_optimization.generic_tools.cp_tools import CPSolver, ParametersCP, CPSolverName,\
map_cp_solver_name
from skdecide.discrete_optimization.generic_tools.do_problem import ParamsObjectiveFunction, \
build_aggreg_function_and_params_objective
from skdecide.discrete_optimization.generic_tools.result_storage.result_storage import ResultStorage
from skdecide.discrete_optimization.rcpsp.rcpsp_model import RCPSPModel, RCPSPSolution, \
RCPSPModelCalendar, PartialSolution
from minizinc import Instance, Model, Solver
import json
from datetime import timedelta
import os
this_path = os.path.dirname(os.path.abspath(__file__))
files_mzn = {"single": os.path.join(this_path, "../minizinc/rcpsp_single_mode_mzn.mzn"),
"single-preemptive": os.path.join(this_path, "../minizinc/rcpsp_single_mode_mzn_preemptive.mzn"),
"multi": os.path.join(this_path, "../minizinc/rcpsp_multi_mode_mzn.mzn"),
"multi-no-bool": os.path.join(this_path, "../minizinc/rcpsp_multi_mode_mzn_no_bool.mzn"),
"multi-calendar": os.path.join(this_path, "../minizinc/rcpsp_multi_mode_mzn_calendar.mzn"),
"multi-calendar-boxes": os.path.join(this_path, "../minizinc/rcpsp_mzn_calendar_boxes.mzn"),
"modes": os.path.join(this_path, "../minizinc/mrcpsp_mode_satisfy.mzn")}
class RCPSPSolCP:
objective: int
__output_item: InitVar[str] = None
def __init__(self, objective, _output_item, **kwargs):
self.objective = objective
self.dict = kwargs
print("One solution ", self.objective)
def check(self) -> bool:
return True
class CP_RCPSP_MZN(CPSolver):
def __init__(self, rcpsp_model: RCPSPModel,
cp_solver_name: CPSolverName=CPSolverName.CHUFFED,
params_objective_function: ParamsObjectiveFunction=None, **kwargs):
self.rcpsp_model = rcpsp_model
self.instance: Instance = None
self.cp_solver_name = cp_solver_name
self.key_decision_variable = ["s"] # For now, I've put the var name of the CP model (not the rcpsp_model)
self.aggreg_sol, self.aggreg_from_dict_values, self.params_objective_function = \
build_aggreg_function_and_params_objective(self.rcpsp_model,
params_objective_function=params_objective_function)
def init_model(self, **args):
model_type = args.get("model_type", "single")
if model_type == "single-preemptive":
nb_preemptive = args.get("nb_preemptive", 2)
model = Model(files_mzn[model_type])
custom_output_type = args.get("output_type", False)
if custom_output_type:
model.output_type = RCPSPSolCP
self.custom_output_type = True
solver = Solver.lookup(map_cp_solver_name[self.cp_solver_name])
instance = Instance(solver, model)
if model_type == "single-preemptive":
instance["nb_preemptive"] = nb_preemptive
# TODO : make this as options.
instance["possibly_preemptive"] = [True for task in self.rcpsp_model.mode_details]
instance["max_preempted"] = 3
n_res = len(list(self.rcpsp_model.resources.keys()))
# print('n_res: ', n_res)
instance["n_res"] = n_res
sorted_resources = sorted(self.rcpsp_model.resources_list)
self.resources_index = sorted_resources
rc = [int(self.rcpsp_model.resources[r])
for r in sorted_resources]
# print('rc: ', rc)
instance["rc"] = rc
n_tasks = self.rcpsp_model.n_jobs + 2
# print('n_tasks: ', n_tasks)
instance["n_tasks"] = n_tasks
sorted_tasks = sorted(self.rcpsp_model.mode_details.keys())
d = [int(self.rcpsp_model.mode_details[key][1]['duration']) for key in sorted_tasks]
# print('d: ', d)
instance["d"] = d
rr = []
index = 0
for res in sorted_resources:
rr.append([])
for task in sorted_tasks:
rr[index].append(int(self.rcpsp_model.mode_details[task][1][res]))
index += 1
instance["rr"] = rr
suc = [set(self.rcpsp_model.successors[task]) for task in sorted_tasks]
instance["suc"] = suc
self.instance = instance
p_s: Union[PartialSolution, None] = args.get("partial_solution", None)
if p_s is not None:
constraint_strings = []
if p_s.start_times is not None:
for task in p_s.start_times:
string = "constraint s[" + str(task) + "] == " + str(p_s.start_times[task]) + ";\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.partial_permutation is not None:
for t1, t2 in zip(p_s.partial_permutation[:-1], p_s.partial_permutation[1:]):
string = "constraint s[" + str(t1) + "] <= s[" + str(t2) + "];\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.list_partial_order is not None:
for l in p_s.list_partial_order:
for t1, t2 in zip(l[:-1], l[1:]):
string = "constraint s[" + str(t1) + "] <= s[" + str(t2) + "];\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.start_together is not None:
for t1, t2 in p_s.start_together:
string = "constraint s[" + str(t1) + "] == s[" + str(t2) + "];\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.start_after_nunit is not None:
for t1, t2, delta in p_s.start_after_nunit:
string = "constraint s[" + str(t2) + "] >= s[" + str(t1) + "]+"+str(delta)+";\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.start_at_end_plus_offset is not None:
for t1, t2, delta in p_s.start_at_end_plus_offset:
string = "constraint s[" + str(t2) + "] >= s[" + str(t1) + "]+d["+str(t1)+"]+"+str(delta)+";\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.start_at_end is not None:
for t1, t2 in p_s.start_at_end:
string = "constraint s[" + str(t2) + "] == s[" + str(t1) + "]+d["+str(t1)+"];\n"
self.instance.add_string(string)
constraint_strings += [string]
def retrieve_solutions(self, result, parameters_cp: ParametersCP=ParametersCP.default())->ResultStorage:
intermediate_solutions = parameters_cp.intermediate_solution
best_solution = None
best_makespan = -float("inf")
list_solutions_fit = []
starts = []
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], RCPSPSolCP):
starts += [result[i].dict["s"]]
else:
starts += [result[i, "s"]]
else:
if isinstance(result, RCPSPSolCP):
starts += [result.dict["s"]]
else:
starts = [result["s"]]
for start_times in starts:
rcpsp_schedule = {}
for k in range(len(start_times)):
rcpsp_schedule[k + 1] = {'start_time': start_times[k],
'end_time': start_times[k]
+ self.rcpsp_model.mode_details[k + 1][1]['duration']}
sol = RCPSPSolution(problem=self.rcpsp_model,
rcpsp_schedule=rcpsp_schedule, rcpsp_schedule_feasible=True)
objective = self.aggreg_from_dict_values(self.rcpsp_model.evaluate(sol))
if objective > best_makespan:
best_makespan = objective
best_solution = sol.copy()
list_solutions_fit += [(sol, objective)]
result_storage = ResultStorage(list_solution_fits=list_solutions_fit,
best_solution=best_solution,
mode_optim=self.params_objective_function.sense_function,
limit_store=False)
return result_storage
def solve(self, parameters_cp: ParametersCP=ParametersCP.default(), **args): # partial_solution: PartialSolution=None, **args):
if self.instance is None:
self.init_model(**args)
timeout = parameters_cp.TimeLimit
intermediate_solutions = parameters_cp.intermediate_solution
try:
result = self.instance.solve(timeout=timedelta(seconds=timeout),
intermediate_solutions=intermediate_solutions)
except Exception as e:
print(e)
return None
verbose = args.get("verbose", False)
if verbose:
print(result.status)
print(result.statistics["solveTime"])
return self.retrieve_solutions(result, parameters_cp=parameters_cp)
class CP_MRCPSP_MZN(CPSolver):
def __init__(self,
rcpsp_model: RCPSPModel,
cp_solver_name: CPSolverName=CPSolverName.CHUFFED,
params_objective_function: ParamsObjectiveFunction=None, **kwargs):
self.rcpsp_model = rcpsp_model
self.instance = None
self.cp_solver_name = cp_solver_name
self.key_decision_variable = ["start", "mrun"] # For now, I've put the var names of the CP model (not the rcpsp_model)
self.aggreg_sol, self.aggreg_from_dict_values, self.params_objective_function = \
build_aggreg_function_and_params_objective(self.rcpsp_model,
params_objective_function=params_objective_function)
self.calendar = False
if isinstance(self.rcpsp_model, RCPSPModelCalendar):
self.calendar = True
def init_model(self, **args):
model_type = args.get("model_type", None)
if model_type is None:
model_type = "multi" if not self.calendar else "multi-calendar"
model = Model(files_mzn[model_type])
custom_output_type = args.get("output_type", False)
if custom_output_type:
model.output_type = RCPSPSolCP
self.custom_output_type = True
solver = Solver.lookup(map_cp_solver_name[self.cp_solver_name])
resources_list = list(self.rcpsp_model.resources.keys())
self.resources_index = resources_list
instance = Instance(solver, model)
n_res = len(resources_list)
# print('n_res: ', n_res)
keys = []
instance["n_res"] = n_res
keys += ["n_res"]
# rc = [val for val in self.rcpsp_model.resources.values()]
# # print('rc: ', rc)
# instance["rc"] = rc
n_tasks = self.rcpsp_model.n_jobs + 2
# print('n_tasks: ', n_tasks)
instance["n_tasks"] = n_tasks
keys += ["n_tasks"]
sorted_tasks = sorted(self.rcpsp_model.mode_details.keys())
# print('mode_details: ', self.rcpsp_model.mode_details)
n_opt = sum([len(list(self.rcpsp_model.mode_details[key].keys())) for key in sorted_tasks])
# print('n_opt: ', n_opt)
instance["n_opt"] = n_opt
keys += ["n_opt"]
modes = []
dur = []
self.modeindex_map = {}
general_counter = 1
for act in sorted_tasks:
tmp = sorted(self.rcpsp_model.mode_details[act].keys())
# tmp = [counter + x for x in tmp]
set_mode_task = set()
for i in range(len(tmp)):
original_mode_index = tmp[i]
set_mode_task.add(general_counter)
self.modeindex_map[general_counter] = {'task': act, 'original_mode_index': original_mode_index}
general_counter += 1
modes.append(set_mode_task)
dur = dur + [self.rcpsp_model.mode_details[act][key]['duration']
for key in tmp]
# print('modes: ', modes)
instance['modes'] = modes
keys += ["modes"]
# print('dur: ', dur)
instance['dur'] = dur
keys += ["dur"]
rreq = []
index = 0
for res in resources_list:
rreq.append([])
for task in sorted_tasks:
for mod in sorted(self.rcpsp_model.mode_details[task].keys()):
rreq[index].append(int(self.rcpsp_model.mode_details[task][mod][res]))
index += 1
# print('rreq: ', rreq)
instance["rreq"] = rreq
keys += ["rreq"]
if not self.calendar:
rcap = [int(self.rcpsp_model.resources[x]) for x in resources_list]
else:
rcap = [int(max(self.rcpsp_model.resources[x])) for x in resources_list]
# print('rcap: ', rcap)
instance["rcap"] = rcap
keys += ["rcap"]
# print('non_renewable_resources:', self.rcpsp_model.non_renewable_resources)
rtype = [2 if res in self.rcpsp_model.non_renewable_resources else 1
for res in resources_list]
# print('rtype: ', rtype)
instance["rtype"] = rtype
keys += ["rtype"]
succ = [set(self.rcpsp_model.successors[task]) for task in sorted_tasks]
# print('succ: ', succ)
instance["succ"] = succ
keys += ["succ"]
if self.calendar:
one_ressource = list(self.rcpsp_model.resources.keys())[0]
instance["max_time"] = len(self.rcpsp_model.resources[one_ressource])
print(instance["max_time"])
keys += ["max_time"]
ressource_capacity_time = [[int(x) for x in self.rcpsp_model.resources[res]]
for res in resources_list]
# print(instance["max_time"])
# print(len(ressource_capacity_time))
# print([len(x) for x in ressource_capacity_time])
instance["ressource_capacity_time"] = ressource_capacity_time
keys += ["ressource_capacity_time"]
# import pymzn
# pymzn.dict2dzn({key: instance[key] for key in keys},
# fout='rcpsp_.dzn')
self.instance = instance
p_s: Union[PartialSolution, None] = args.get("partial_solution", None)
if p_s is not None:
constraint_strings = []
if p_s.start_times is not None:
for task in p_s.start_times:
string = "constraint start[" + str(task) + "] == " + str(p_s.start_times[task]) + ";\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.partial_permutation is not None:
for t1, t2 in zip(p_s.partial_permutation[:-1], p_s.partial_permutation[1:]):
string = "constraint start[" + str(t1) + "] <= start[" + str(t2) + "];\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.list_partial_order is not None:
for l in p_s.list_partial_order:
for t1, t2 in zip(l[:-1], l[1:]):
string = "constraint start[" + str(t1) + "] <= start[" + str(t2) + "];\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.task_mode is not None:
for task in p_s.start_times:
indexes = [i for i in self.modeindex_map if self.modeindex_map[i]["task"] == task
and self.modeindex_map[i]["original_mode_index"] == p_s.task_mode[task]]
if len(indexes) >= 0:
string = "constraint mrun["+str(indexes[0])+"] == 1;"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.start_together is not None:
for t1, t2 in p_s.start_together:
string = "constraint start[" + str(t1) + "] == start[" + str(t2) + "];\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.start_after_nunit is not None:
for t1, t2, delta in p_s.start_after_nunit:
string = "constraint start[" + str(t2) + "] >= start[" + str(t1) + "]+"+str(delta)+";\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.start_at_end_plus_offset is not None:
for t1, t2, delta in p_s.start_at_end_plus_offset:
string = "constraint start[" + str(t2) + "] >= start[" + str(t1) + "]+adur["+str(t1)+"]+"+str(delta)+";\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.start_at_end is not None:
for t1, t2 in p_s.start_at_end:
string = "constraint start[" + str(t2) + "] == start[" + str(t1) + "]+adur["+str(t1)+"];\n"
self.instance.add_string(string)
constraint_strings += [string]
def retrieve_solutions(self, result, parameters_cp: ParametersCP=ParametersCP.default()):
intermediate_solutions = parameters_cp.intermediate_solution
best_solution = None
best_makespan = -float("inf")
list_solutions_fit = []
starts = []
mruns = []
if intermediate_solutions:
for i in range(len(result)):
if isinstance(result[i], RCPSPSolCP):
starts += [result[i].dict["start"]]
mruns += [result[i].dict["mrun"]]
else:
starts += [result[i, "start"]]
mruns += [result[i, "mrun"]]
else:
if isinstance(result, RCPSPSolCP):
starts += [result.dict["start"]]
mruns += [result.dict["mrun"]]
else:
starts = [result["start"]]
mruns = [result["mrun"]]
for start_times, mrun in zip(starts, mruns):
modes = []
for i in range(len(mrun)):
if mrun[i] and (self.modeindex_map[i + 1]['task'] != 1) and (
self.modeindex_map[i + 1]['task'] != self.rcpsp_model.n_jobs + 2):
modes.append(self.modeindex_map[i + 1]['original_mode_index'])
elif (self.modeindex_map[i + 1]['task'] == 1) or (
self.modeindex_map[i + 1]['task'] == self.rcpsp_model.n_jobs + 2):
modes.append(1)
rcpsp_schedule = {}
for i in range(len(start_times)):
rcpsp_schedule[i + 1] = {'start_time': start_times[i],
'end_time': start_times[i]
+ self.rcpsp_model.mode_details[i + 1][modes[i]]['duration']}
sol = RCPSPSolution(problem=self.rcpsp_model,
rcpsp_schedule=rcpsp_schedule,
rcpsp_modes=modes[1:-1],
rcpsp_schedule_feasible=True)
objective = self.aggreg_from_dict_values(self.rcpsp_model.evaluate(sol))
if objective > best_makespan:
best_makespan = objective
best_solution = sol.copy()
list_solutions_fit += [(sol, objective)]
result_storage = ResultStorage(list_solution_fits=list_solutions_fit,
best_solution=best_solution,
mode_optim=self.params_objective_function.sense_function,
limit_store=False)
return result_storage
def solve(self, parameters_cp: ParametersCP=ParametersCP.default(), **args):
if self.instance is None:
self.init_model(**args)
timeout = parameters_cp.TimeLimit
intermediate_solutions = parameters_cp.intermediate_solution
result = self.instance.solve(timeout=timedelta(seconds=timeout),
intermediate_solutions=intermediate_solutions)
verbose = args.get("verbose", True)
if verbose:
print(result.status)
return self.retrieve_solutions(result=result, parameters_cp=parameters_cp)
class MRCPSP_Result:
objective: int
__output_item: InitVar[str] = None
def __init__(self, objective, _output_item, **kwargs):
self.objective = objective
self.dict = kwargs
self.mode_chosen = json.loads(_output_item)
def check(self) -> bool:
return True
class CP_MRCPSP_MZN_NOBOOL(CPSolver):
def __init__(self,
rcpsp_model: RCPSPModel,
cp_solver_name: CPSolverName=CPSolverName.CHUFFED,
params_objective_function: ParamsObjectiveFunction=None, **kwargs):
self.rcpsp_model = rcpsp_model
self.instance = None
self.cp_solver_name = cp_solver_name
self.key_decision_variable = ["start", "mrun"] # For now, I've put the var names of the CP model (not the rcpsp_model)
self.aggreg_sol, self.aggreg_from_dict_values, self.params_objective_function = \
build_aggreg_function_and_params_objective(self.rcpsp_model,
params_objective_function=params_objective_function)
self.calendar = False
if isinstance(self.rcpsp_model, RCPSPModelCalendar):
self.calendar = True
def init_model(self, **args):
model = Model(files_mzn["multi-no-bool"])
model.output_type = MRCPSP_Result
solver = Solver.lookup(map_cp_solver_name[self.cp_solver_name])
resources_list = list(self.rcpsp_model.resources.keys())
instance = Instance(solver, model)
n_res = len(resources_list)
# print('n_res: ', n_res)
keys = []
instance["n_res"] = n_res
keys += ["n_res"]
# rc = [val for val in self.rcpsp_model.resources.values()]
# # print('rc: ', rc)
# instance["rc"] = rc
n_tasks = self.rcpsp_model.n_jobs + 2
# print('n_tasks: ', n_tasks)
instance["n_tasks"] = n_tasks
keys += ["n_tasks"]
sorted_tasks = sorted(self.rcpsp_model.mode_details.keys())
# print('mode_details: ', self.rcpsp_model.mode_details)
n_opt = sum([len(list(self.rcpsp_model.mode_details[key].keys())) for key in sorted_tasks])
# print('n_opt: ', n_opt)
instance["n_opt"] = n_opt
keys += ["n_opt"]
modes = []
dur = []
counter = 0
self.modeindex_map = {}
general_counter = 1
for act in sorted_tasks:
tmp = sorted(self.rcpsp_model.mode_details[act].keys())
# tmp = [counter + x for x in tmp]
set_mode_task = set()
for i in range(len(tmp)):
original_mode_index = tmp[i]
set_mode_task.add(general_counter)
self.modeindex_map[general_counter] = {'task': act, 'original_mode_index': original_mode_index}
general_counter += 1
modes.append(set_mode_task)
dur = dur + [self.rcpsp_model.mode_details[act][key]['duration']
for key in tmp]
# print('modes: ', modes)
instance['modes'] = modes
keys += ["modes"]
# print('dur: ', dur)
instance['dur'] = dur
keys += ["dur"]
rreq = []
index = 0
for res in resources_list:
rreq.append([])
for task in sorted_tasks:
for mod in sorted(self.rcpsp_model.mode_details[task].keys()):
rreq[index].append(int(self.rcpsp_model.mode_details[task][mod][res]))
index += 1
# print('rreq: ', rreq)
instance["rreq"] = rreq
keys += ["rreq"]
if not self.calendar:
rcap = [self.rcpsp_model.resources[x] for x in resources_list]
else:
rcap = [int(max(self.rcpsp_model.resources[x])) for x in resources_list]
# print('rcap: ', rcap)
instance["rcap"] = rcap
keys += ["rcap"]
# print('non_renewable_resources:', self.rcpsp_model.non_renewable_resources)
rtype = [2 if res in self.rcpsp_model.non_renewable_resources else 1
for res in resources_list]
# print('rtype: ', rtype)
instance["rtype"] = rtype
keys += ["rtype"]
succ = [set(self.rcpsp_model.successors[task]) for task in sorted_tasks]
# print('succ: ', succ)
instance["succ"] = succ
keys += ["succ"]
if self.calendar:
one_ressource = list(self.rcpsp_model.resources.keys())[0]
instance["max_time"] = len(self.rcpsp_model.resources[one_ressource])
print(instance["max_time"])
keys += ["max_time"]
ressource_capacity_time = [[int(x) for x in self.rcpsp_model.resources[res]]
for res in resources_list]
# print(instance["max_time"])
# print(len(ressource_capacity_time))
# print([len(x) for x in ressource_capacity_time])
instance["ressource_capacity_time"] = ressource_capacity_time
keys += ["ressource_capacity_time"]
# import pymzn
# pymzn.dict2dzn({key: instance[key] for key in keys},
# fout='rcpsp_.dzn')
self.instance = instance
p_s: Union[PartialSolution, None] = args.get("partial_solution", None)
if p_s is not None:
constraint_strings = []
if p_s.start_times is not None:
for task in p_s.start_times:
string = "constraint start[" + str(task) + "] == " + str(p_s.start_times[task]) + ";\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.partial_permutation is not None:
for t1, t2 in zip(p_s.partial_permutation[:-1], p_s.partial_permutation[1:]):
string = "constraint start[" + str(t1) + "] <= start[" + str(t2) + "];\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.list_partial_order is not None:
for l in p_s.list_partial_order:
for t1, t2 in zip(l[:-1], l[1:]):
string = "constraint start[" + str(t1) + "] <= start[" + str(t2) + "];\n"
self.instance.add_string(string)
constraint_strings += [string]
if p_s.task_mode is not None:
for task in p_s.start_times:
indexes = [i for i in self.modeindex_map if self.modeindex_map[i]["task"] == task
and self.modeindex_map[i]["original_mode_index"] == p_s.task_mode[task]]
if len(indexes) >= 0:
string = "constraint mrun["+str(indexes[0])+"] == 1;"
self.instance.add_string(string)
constraint_strings += [string]
def retrieve_solutions(self, result, parameters_cp: ParametersCP=ParametersCP.default()):
intermediate_solutions = parameters_cp.intermediate_solution
best_solution = None
best_makespan = -float("inf")
list_solutions_fit = []
starts = []
mruns = []
object_result: List[MRCPSP_Result] = []
if intermediate_solutions:
for i in range(len(result)):
object_result += [result[i]]
# print("Objective : ", result[i, "objective"])
else:
object_result += [result]
for res in object_result:
modes = []
for j in range(len(res.mode_chosen)):
if (self.modeindex_map[j + 1]['task'] != 1) and (self.modeindex_map[j + 1]['task'] != self.rcpsp_model.n_jobs + 2):
modes.append(self.modeindex_map[res.mode_chosen[j]]['original_mode_index'])
elif (self.modeindex_map[j + 1]['task'] == 1) or (
self.modeindex_map[j + 1]['task'] == self.rcpsp_model.n_jobs + 2):
modes.append(1)
rcpsp_schedule = {}
start_times = res.dict["start"]
for i in range(len(start_times)):
rcpsp_schedule[i + 1] = {'start_time': start_times[i],
'end_time': start_times[i]
+ self.rcpsp_model.mode_details[i + 1][modes[i]]['duration']}
sol = RCPSPSolution(problem=self.rcpsp_model,
rcpsp_schedule=rcpsp_schedule,
rcpsp_modes=modes[1:-1],
rcpsp_schedule_feasible=True)
objective = self.aggreg_from_dict_values(self.rcpsp_model.evaluate(sol))
if objective > best_makespan:
best_makespan = objective
best_solution = sol.copy()
list_solutions_fit += [(sol, objective)]
result_storage = ResultStorage(list_solution_fits=list_solutions_fit,
best_solution=best_solution,
mode_optim=self.params_objective_function.sense_function,
limit_store=False)
return result_storage
def solve(self, parameters_cp: ParametersCP=ParametersCP.default(), **args):
if self.instance is None:
self.init_model(**args)
timeout = parameters_cp.TimeLimit
intermediate_solutions = parameters_cp.intermediate_solution
result = self.instance.solve(timeout=timedelta(seconds=timeout),
intermediate_solutions=intermediate_solutions)
verbose = args.get("verbose", True)
if verbose:
print(result.status)
return self.retrieve_solutions(result=result, parameters_cp=parameters_cp)
class CP_MRCPSP_MZN_MODES:
def __init__(self, rcpsp_model: RCPSPModel,
cp_solver_name: CPSolverName=CPSolverName.CHUFFED,
params_objective_function: ParamsObjectiveFunction=None):
self.rcpsp_model = rcpsp_model
self.instance: Instance = None
self.cp_solver_name = cp_solver_name
self.key_decision_variable = ["start", "mrun"] # For now, I've put the var names of the CP model (not the rcpsp_model)
self.aggreg_sol, self.aggreg_from_dict_values, self.params_objective_function = \
build_aggreg_function_and_params_objective(self.rcpsp_model,
params_objective_function=params_objective_function)
def init_model(self, **args):
model = Model(files_mzn["modes"])
solver = Solver.lookup(map_cp_solver_name[self.cp_solver_name])
instance = Instance(solver, model)
keys = []
n_res = len(list(self.rcpsp_model.resources.keys()))
instance["n_res"] = n_res
keys += ["n_res"]
n_tasks = self.rcpsp_model.n_jobs + 2
instance["n_tasks"] = n_tasks
keys += ["n_tasks"]
sorted_tasks = sorted(self.rcpsp_model.mode_details.keys())
n_opt = sum([len(list(self.rcpsp_model.mode_details[key].keys())) for key in sorted_tasks])
instance["n_opt"] = n_opt
keys += ["n_opt"]
modes = []
counter = 0
self.modeindex_map = {}
for act in sorted_tasks:
tmp = list(self.rcpsp_model.mode_details[act].keys())
# tmp = [counter + x for x in tmp]
for i in range(len(tmp)):
original_mode_index = tmp[i]
mod_index = counter+tmp[i]
tmp[i] = mod_index
self.modeindex_map[mod_index] = {'task': act, 'original_mode_index': original_mode_index}
modes.append(set(tmp))
counter = tmp[-1]
# print('modes: ', modes)
instance['modes'] = modes
keys += ["modes"]
rreq = []
index = 0
for res in self.rcpsp_model.resources.keys():
rreq.append([])
for task in sorted_tasks:
for mod in self.rcpsp_model.mode_details[task].keys():
rreq[index].append(int(self.rcpsp_model.mode_details[task][mod][res]))
index += 1
# print('rreq: ', rreq)
instance["rreq"] = rreq
keys += ["rreq"]
rcap = [val for val in self.rcpsp_model.resources.values()]
# print('rcap: ', rcap)
if isinstance(rcap[0], list):
rcap = [int(max(r)) for r in rcap]
instance["rcap"] = rcap
keys += ["rcap"]
rtype = [2 if res in self.rcpsp_model.non_renewable_resources else 1 for res in self.rcpsp_model.resources.keys()]
instance["rtype"] = rtype
keys += ["rtype"]
# import pymzn # For debug purposes
# pymzn.dict2dzn({k: instance[k] for k in keys}, fout="debug_modes_satisfaction.dzn")
self.instance: Instance = instance
p_s: Union[PartialSolution, None] = args.get("partial_solution", None)
if p_s is not None:
constraint_strings = []
if p_s.task_mode is not None:
for task in p_s.start_times:
indexes = [i for i in self.modeindex_map if self.modeindex_map[i]["task"] == task
and self.modeindex_map[i]["original_mode_index"] == p_s.task_mode[task]]
if len(indexes) >= 0:
print("Index found : ", len(indexes))
string = "constraint mrun[" + str(indexes[0]) + "] == 1;"
self.instance.add_string(string)
constraint_strings += [string]
def retrieve_solutions(self, result, parameters_cp: ParametersCP=ParametersCP.default()):
intermediate_solutions = parameters_cp.intermediate_solution
best_solution = None
best_makespan = -float("inf")
list_solutions_fit = []
mruns = []
if intermediate_solutions:
for i in range(len(result)):
mruns += [result[i, "mrun"]]
else:
mruns += [result["mrun"]]
all_modes = []
for mrun in mruns:
modes = [1]*(self.rcpsp_model.n_jobs+2)
for i in range(len(mrun)):
if mrun[i] == 1 and (self.modeindex_map[i + 1]['task'] != 1) and (
self.modeindex_map[i + 1]['task'] != self.rcpsp_model.n_jobs + 2):
modes[self.modeindex_map[i+1]['task']-1] = self.modeindex_map[i + 1]['original_mode_index']
all_modes += [modes]
return all_modes
def solve(self, parameters_cp: ParametersCP = None, **args):
if parameters_cp is None:
parameters_cp = ParametersCP.default()
if self.instance is None:
self.init_model(**args)
timeout = parameters_cp.TimeLimit
intermediate_solutions = parameters_cp.intermediate_solution
result = self.instance.solve(timeout=timedelta(seconds=timeout),
# nr_solutions=1000,
# nr_solutions=1,
nr_solutions=parameters_cp.nr_solutions
if not parameters_cp.all_solutions else None,
all_solutions=parameters_cp.all_solutions)
#intermediate_solutions=intermediate_solutions)
verbose = args.get("verbose", False)
if verbose:
print(result.status)
return self.retrieve_solutions(result=result, parameters_cp=parameters_cp)
| [
"[email protected]"
] | |
bc7ad62bc0617a78f8aefb15b880c4de8926bd23 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/171/usersdata/269/82030/submittedfiles/decimal2bin.py | 685e2ff066c0cea09273c3191d603c291bc3306a | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 245 | py | # -*- coding: utf-8 -*-
binario=int(input('digite the fucking binario: '))
a=0
b=binario
while binario>0:
binario=binario//10
a=a+1
c=1
d=0
for i in range(0,a,1):
decimal=b//10**c
d=decimal*(2**i)+d
c=c+1
print(d)
| [
"[email protected]"
] | |
8eea73a4817b583b59e9ae72e614c0630731fafb | dcddc234eea906c63553f6495e182e44f3e8431d | /forum/migrations/0001_initial.py | 5ec4c7773023cc10c07b7d6d003e4cc6ea318831 | [
"MIT"
] | permissive | Kromey/akwriters | 53e648e1cc4c0970c843c9b426d0e7de21c9eabb | 72812b5f7dca3ad21e6e9d082298872b7fa607b9 | refs/heads/master | 2022-03-08T00:57:42.232126 | 2021-07-21T15:23:33 | 2021-07-21T15:23:33 | 28,463,802 | 0 | 0 | MIT | 2022-02-10T08:06:49 | 2014-12-24T22:41:56 | JavaScript | UTF-8 | Python | false | false | 2,238 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-01-20 01:11
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Board',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=25)),
('slug', models.SlugField(blank=True, max_length=25)),
('description', models.CharField(max_length=255)),
('parent', models.ForeignKey(blank=True, default=None, null=True, on_delete=django.db.models.deletion.CASCADE, to='forum.Board')),
],
),
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('subject', models.CharField(max_length=128)),
('body', models.TextField()),
('left', models.PositiveIntegerField(default=0)),
('right', models.PositiveIntegerField(default=0)),
],
options={
'ordering': ('left',),
},
),
migrations.CreateModel(
name='Topic',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('board', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='forum.Board')),
],
),
migrations.AddField(
model_name='post',
name='topic',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='forum.Topic'),
),
migrations.AddField(
model_name='post',
name='user',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
]
| [
"[email protected]"
] | |
daa206411acf7dd63ef2ac0a7f67334f0de62493 | 6146d080087b21e36347408eea76598f4691ed67 | /code/1112/2383.py | d2e70847a9ef9a11958d0d8c95a94edf7d85889f | [] | no_license | banggeut01/algorithm | 682c4c6e90179b8100f0272bf559dbeb1bea5a1d | 503b727134909f46e518c65f9a9aa58479a927e9 | refs/heads/master | 2020-06-27T14:07:51.927565 | 2019-12-19T03:48:30 | 2019-12-19T03:48:30 | 199,800,363 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,576 | py | # 2383.py [모의 SW 역량테스트] 점심 식사시간
import sys
sys.stdin = open('2383input.txt', 'r')
def getTime(t, l): # t: 사람-입구 거리 배열, l: 계단길이
for idx in range(len(t)):
if idx < 3:
t[idx] += l
else:
if t[idx - 3] > t[idx]:
t[idx] = t[idx - 3] + l
else:
t[idx] += l
if t: return t[-1]
else: return 0
T = int(input())
for tc in range(1, T + 1):
N = int(input())
board = [list(map(int, input().split())) for _ in range(N)]
P, S = [], [] # P: 사람 좌표(x, y), S: 계단좌표&길이(x, y, len)
MIN = 0xffffff
for i in range(N):
for j in range(N):
if board[i][j] == 1:
P.append((i, j))
elif board[i][j] > 1:
S.append((i, j, board[i][j]))
dct = [dict() for _ in range(2)]
for x in range(len(S)): # 한 계단에 대해
sr, sc, tmp = S[x]
for y in range(len(P)): # 사람-계단 거리를 구함
pr, pc = P[y]
d = abs(sr - pr) + abs(sc - pc)
dct[x][(pr, pc)] = d
for i in range(1 << len(P)):
time0, time1 = [], []
for j in range(len(P)):
if i & 1 << j:
time0.append(dct[0][P[j]] + 1)
else:
time1.append(dct[1][P[j]] + 1)
time0 = sorted(time0)
time1 = sorted(time1)
t0 = getTime(time0, S[0][2])
t1 = getTime(time1, S[1][2])
MIN = min(MIN, max(t0, t1))
print('#{} {}'.format(tc, MIN))
| [
"[email protected]"
] | |
b186151473ccd843ebb0867eb5d9584dbb5d852d | 6fcfb638fa725b6d21083ec54e3609fc1b287d9e | /python/yosinski_deep-visualization-toolbox/deep-visualization-toolbox-master/misc.py | ed1ee755e93c924c466045c1232ccace4c7d6ee6 | [] | no_license | LiuFang816/SALSTM_py_data | 6db258e51858aeff14af38898fef715b46980ac1 | d494b3041069d377d6a7a9c296a14334f2fa5acc | refs/heads/master | 2022-12-25T06:39:52.222097 | 2019-12-12T08:49:07 | 2019-12-12T08:49:07 | 227,546,525 | 10 | 7 | null | 2022-12-19T02:53:01 | 2019-12-12T07:29:39 | Python | UTF-8 | Python | false | false | 1,272 | py | #! /usr/bin/env python
import os
import time
import errno
class WithTimer:
def __init__(self, title = '', quiet = False):
self.title = title
self.quiet = quiet
def elapsed(self):
return time.time() - self.wall, time.clock() - self.proc
def enter(self):
'''Manually trigger enter'''
self.__enter__()
def __enter__(self):
self.proc = time.clock()
self.wall = time.time()
return self
def __exit__(self, *args):
if not self.quiet:
titlestr = (' ' + self.title) if self.title else ''
print 'Elapsed%s: wall: %.06f, sys: %.06f' % ((titlestr,) + self.elapsed())
def mkdir_p(path):
# From https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def combine_dicts(dicts_tuple):
'''Combines multiple dictionaries into one by adding a prefix to keys'''
ret = {}
for prefix,dictionary in dicts_tuple:
for key in dictionary.keys():
ret['%s%s' % (prefix, key)] = dictionary[key]
return ret
| [
"[email protected]"
] | |
67122d17e933488f9e88e64701632d1088a4001e | 31c9cd96667166ac4af15ce8b48753167da3084d | /sorting/bubble_sort.py | 1c21807ac98a7e18e5e4c1b990067d0c11664874 | [] | no_license | vitorponce/algorithms | a8e305e32e38bbb2f473dc07c0e93bdf6a10fde0 | 87d5f3e3110394d21844b7f3a17468e01a366e83 | refs/heads/master | 2022-06-17T04:04:18.757909 | 2020-05-04T03:03:09 | 2020-05-04T03:03:09 | 259,844,564 | 1 | 0 | null | 2020-05-04T03:04:54 | 2020-04-29T06:34:52 | Python | UTF-8 | Python | false | false | 1,717 | py |
def bubble_sort(input_list):
"""
The smallest element bubbles to the correct position
by comparing adjacent elements.
For each iteration, every element is compared with its neighbor
and swapped if they arent in the right order.
Smallest elements 'bubble' to the beginning of the list.
At the end fo the first iteration, the smallest element is in the
right position, at the end of the second iteration, the second
smallest is in the right position and so on
Complexity: O(n^2) in the worst case
- in worst case (list is sorted in descending order)
"n" elements are checked and swapped for each selected
element to get to the correct position
Stable: Yes
- logical ordering will be maintained
Memory: O(1)
- sorts in place, original list re-used so no extra space
Adaptivity: YES
- if there were no swaps on an iteration, we know the list
is already sorted, and we can break out early
Number of comparisons and swaps:
- O(n^2) comparisons and O(n^2) swaps
- more swaps than selection sort!
Discussion:
- O(n^2) == bad
- advantage over selection sort: adaptivity
"""
for i in range(len(input_list)):
swapped = False
# again, i represents the last position in list that is sorted
for j in range(len(input_list) - 1, i, -1):
if input_list[j] < input_list[j-1]:
input_list[j-1], input_list[j] = input_list[j], input_list[j-1]
swapped = True
# if no swaps, list is already in sorted state and we can break out
if not swapped:
break
return input_list
| [
"[email protected]"
] | |
71581e2aa28a19aa508f908fff09ae9da3e41017 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_connoisseur.py | f2ebfdee7349c5f0eb2d9d637ed4b4d9b3670125 | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 419 | py |
#calss header
class _CONNOISSEUR():
def __init__(self,):
self.name = "CONNOISSEUR"
self.definitions = [u'a person who knows a lot about and enjoys one of the arts, or food, drink, etc. and can judge quality and skill in that subject: ']
self.parents = []
self.childen = []
self.properties = []
self.jsondata = {}
self.specie = 'nouns'
def run(self, obj1 = [], obj2 = []):
return self.jsondata
| [
"[email protected]"
] | |
4e9f69d87e835061a181778d25e5810c1fdb12f4 | dccf1fea8d62764b8c51259671f9b61d36196d41 | /quiz/tests/test_views.py | 3206b640c985d6489348d1011b7e9a68160df405 | [
"MIT"
] | permissive | Palombredun/django_quiz | e4594852c2709a9c6c58a96cc210f3f3dc1a282b | 1565d251d54dfb54fdee83096b560876833275a2 | refs/heads/master | 2021-07-08T23:11:23.157677 | 2021-01-13T14:26:31 | 2021-01-13T14:26:31 | 224,863,683 | 0 | 0 | null | 2019-11-29T13:53:50 | 2019-11-29T13:53:50 | null | UTF-8 | Python | false | false | 3,013 | py | import datetime
import pytest
from pytest_django.asserts import assertTemplateUsed
from django.contrib.auth.models import User
from quiz.models import Category, SubCategory, Quiz, Statistic, Question, Grade
### FIXTURE ###
@pytest.fixture
def user_A(db):
return User.objects.create_user(
username="A", email="[email protected]", password="secret"
)
@pytest.fixture
def category_m(db):
return Category.objects.create(category="m")
@pytest.fixture
def sub_category_n(db, category_m):
return SubCategory.objects.create(category=category_m, sub_category="n")
@pytest.fixture
def quiz_q(db, category_m, sub_category_n, user_A):
date = datetime.datetime.now()
return Quiz.objects.create(
title="title",
description="Long description",
creator=user_A,
category=category_m,
category_name="m",
sub_category=sub_category_n,
created=date,
random_order=False,
difficulty=1,
url="title-1"
)
@pytest.fixture
def stats_s(db, quiz_q):
return Statistic.objects.create(
quiz=quiz_q,
number_participants=1,
mean=2,
easy=1,
medium=1,
difficult=1
)
@pytest.fixture
def grade_g(stats_s):
return Grade.objects.create(
statistics=stats_s,
grade=2,
number=1
)
### Tests page tutorial ###
def test_page_tutorial(client):
response = client.get("/quiz/tutorial/")
assert response.status_code == 200
### Tests page create ###
def test_access_page_create_unlogged(client):
response = client.get("/quiz/create/")
assert response.status_code == 302
def test_access_page_create_logged(client, user_A):
response = client.force_login(user_A)
response = client.get("/quiz/create/")
assert response.status_code == 200
### Test page load_sub_categories ###
def test_page_load_sub_categories(client, db):
response = client.get("quiz/ajax/load-subcategories/")
assert response.status_code == 200
### Test page quiz lists ###
def test_page_quiz_list(client, db):
response = client.get("/quiz/quiz-list/")
assert response.status_code == 200
def test_quiz_list_by_category(client, category_m):
response = client.get("/quiz/category/m/")
assert response.status_code == 200
def test_quiz_list_by_subcategory(client, sub_category_n):
response = client.get("/quiz/subcategory/n/")
assert response.status_code == 200
### Test page take ###
def test_take_quiz(client, quiz_q, user_A):
client.force_login(user_A)
url = "/quiz/take/" + quiz_q.url + "/"
response = client.get(url)
assert response.status_code == 200
### Test page statistics ###
def test_statistics(client, quiz_q, stats_s, user_A, grade_g):
q = Question.objects.create(
quiz=quiz_q,
difficulty=1
)
client.force_login(user_A)
url = "/quiz/statistics/" + quiz_q.url + "/"
response = client.get(url)
assert response.status_code == 200
| [
"baptiste.name"
] | baptiste.name |
a3c84c720bb0bc8a3ec2921c600f975aaed6f1b8 | 20b4be7df5efeb8019356659c5d054f29f450aa1 | /tools/indicators/build_indicators.py | 16a8d1caeb8619580fb4836cc6c8c4cbb50269bb | [
"Apache-2.0"
] | permissive | kumars99/TradzQAI | 75c4138e30796573d67a5f08d9674c1488feb8e4 | 1551321642b6749d9cf26caf2e822051a105b1a5 | refs/heads/master | 2020-03-29T20:14:45.562143 | 2018-09-25T16:07:21 | 2018-09-25T16:07:21 | 150,302,554 | 1 | 0 | null | 2018-09-25T17:17:54 | 2018-09-25T17:17:54 | null | UTF-8 | Python | false | false | 3,553 | py | import pandas as pd
from tools.indicators.exponential_moving_average import exponential_moving_average as ema
from tools.indicators.volatility import volatility as vol
from tools.indicators.stochastic import percent_k as K
from tools.indicators.stochastic import percent_d as D
from tools.indicators.relative_strength_index import relative_strength_index as RSI
from tools.indicators.moving_average_convergence_divergence import moving_average_convergence_divergence as macd
from tools.indicators.bollinger_bands import bandwidth as bb
class Indicators():
def __init__(self, settings=None):
self.bb_period = 20
self.rsi_period = 14
self.sd_period = 0
self.sv_period = 0
self.stoch_period = 14
self.volatility_period = 20
self.macd_long = 24
self.macd_short = 12
self.ema_periods = [20, 50, 100]
self.settings = settings
self.build_func = None
self.names = []
def add_building(self, settings=None):
if settings:
self.settings = settings
if self.settings:
self.build_func = []
for key, value in self.settings.items():
if not value:
continue
elif "RSI" == key and value:
self.names.append('RSI')
if 'default' != value:
self.rsi_period = value
self.build_func.append([RSI, 'RSI', self.rsi_period])
elif "MACD" == key and value:
self.names.append('MACD')
if 'default' != value:
self.macd_long = value[1],
self.macd_short = value[0]
self.build_func.append([macd, 'MACD', [self.macd_short, self.macd_long]])
elif "Volatility" == key and value:
self.names.append('Volatility')
if 'default' != value:
self.volatility_period = value
self.build_func.append([vol, 'Volatility', self.volatility_period])
elif "EMA" == key and value:
if 'default' != value:
for values in value:
self.names.append('EMA'+str(values))
self.build_func.append([ema, 'EMA'+str(values), values])
elif "Bollinger_bands" == key and value:
self.names.append('Bollinger_bands')
if 'default' != value:
self.bb_period = value
self.build_func.append([bb, 'Bollinger_bands', self.bb_period])
elif "Stochastic" == key and value:
self.names.append('Stochastic_D')
self.names.append('Stochastic_K')
if 'default' != value:
self.stoch_period = value
self.build_func.append([D, 'Stochastic_D', self.stoch_period])
self.build_func.append([K, 'Stochastic_K', self.stoch_period])
def build_indicators(self, data):
if not self.build_func:
raise ValueError("No indicators to build.")
indicators = pd.DataFrame(columns=self.names)
for idx in self.build_func:
print (idx[1])
if "MACD" in idx[1]:
indicators[idx[1]] = idx[0](data, idx[2][0], idx[2][1])
else:
indicators[idx[1]] = idx[0](data, idx[2])
return indicators
| [
"[email protected]"
] | |
3e78cd5beb2f40b2d302957a40cda8debb722657 | 84f8696f6f4c9f785615211fe1a746c3ac5b6996 | /fish_proc/utils/demix.py | aab6d2425221e6340e2ed4d005b33857aa250edf | [] | no_license | zqwei/fish_processing | 48a5494b92a2568bd6393685adfa465a6fe05cdb | 53251f4dc3698285873f7c58e4dd4cfaf030375a | refs/heads/master | 2021-09-21T06:51:35.874171 | 2021-08-16T19:39:34 | 2021-08-16T19:39:34 | 117,905,371 | 2 | 1 | null | 2021-08-16T19:39:34 | 2018-01-17T23:30:06 | Python | UTF-8 | Python | false | false | 9,382 | py | '''
A set of posthoc processing from demix algorithm
------------------------
Ziqiang Wei @ 2018
[email protected]
'''
from ..demix.superpixel_analysis import *
import numpy as np
def pos_sig_correction(mov, axis_):
return mov - (mov).min(axis=axis_, keepdims=True)
def recompute_C_matrix_sparse(sig, A):
from scipy.sparse import csr_matrix
from scipy.sparse.linalg import spsolve
d1, d2, T = sig.shape
sig = csr_matrix(np.reshape(sig, (d1*d2,T), order='F'))
A = csr_matrix(A)
return np.asarray(spsolve(A, sig).todense())
def recompute_C_matrix(sig, A, issparse=False):
if not issparse:
d1, d2, T = sig.shape
return np.linalg.inv(np.array(A.T.dot(A))).dot(A.T.dot(np.reshape(sig, (d1*d2,T), order='F')))
else:
return recompute_C_matrix_sparse(sig, A)
def recompute_nmf(rlt_, mov, comp_thres=0):
b = rlt_['fin_rlt']['b']
fb = rlt_['fin_rlt']['fb']
ff = rlt_['fin_rlt']['ff']
dims = mov.shape
if fb is not None:
b_ = np.matmul(fb, ff.T)+b
else:
b_ = b
mov_pos = pos_sig_correction(mov, -1)
mov_no_background = mov_pos - b_.reshape((dims[0], dims[1], len(b_)//dims[0]//dims[1]), order='F')
A = rlt_['fin_rlt']['a']
A = A[:, (A>0).sum(axis=0)>comp_thres]
C_ = recompute_C_matrix(mov_no_background, A)
mov_res = reconstruct(mov_pos, A, C_.T, b_, fb=fb, ff=ff)
mov_res_ = mov_res.mean(axis=-1, keepdims=True)
b_ = b_.reshape((dims[0], dims[1], len(b_)//dims[0]//dims[1]), order='F')
return C_, b_+mov_res_, mov_res-mov_res_
def compute_res(mov_pos, rlt_):
return reconstruct(mov_pos, rlt_['fin_rlt']['a'], rlt_['fin_rlt']['c'],
rlt_['fin_rlt']['b'], fb=rlt_['fin_rlt']['fb'], ff=rlt_['fin_rlt']['ff'])
def demix_whole_data_snr(Yd, cut_off_point=[0.95,0.9], length_cut=[15,10],
th=[2,1], pass_num=1, residual_cut = [0.6,0.6],
corr_th_fix=0.31, max_allow_neuron_size=0.3,
merge_corr_thr=0.6, merge_overlap_thr=0.6, num_plane=1,
patch_size=[100,100], std_thres=0.5, plot_en=False, TF=False,
fudge_factor=1, text=True, bg=False, max_iter=35,
max_iter_fin=50, update_after=4):
"""
This function is the demixing pipeline for whole data.
For parameters and output, please refer to demix function (demixing pipeline for low rank data).
"""
## if data has negative values then do pixel-wise minimum subtraction ##
Yd_min = Yd.min();
# threshold data using its variability
Y_amp = Yd.std(axis=-1)
if Yd_min < 0:
Yd_min_pw = Yd.min(axis=2, keepdims=True);
Yd -= Yd_min_pw;
dims = Yd.shape[:2];
T = Yd.shape[2];
superpixel_rlt = [];
## cut image into small parts to find pure superpixels ##
patch_height = patch_size[0];
patch_width = patch_size[1];
height_num = int(np.ceil(dims[0]/patch_height)); ########### if need less data to find pure superpixel, change dims[0] here #################
width_num = int(np.ceil(dims[1]/(patch_width*num_plane)));
num_patch = height_num*width_num;
patch_ref_mat = np.array(range(num_patch)).reshape(height_num, width_num, order="F");
ii = 0;
while ii < pass_num:
print("start " + str(ii+1) + " pass!");
if ii > 0:
if bg:
Yd_res = reconstruct(Yd, a, c, b, fb, ff);
else:
Yd_res = reconstruct(Yd, a, c, b);
Yt = threshold_data(Yd_res, th=th[ii]);
else:
if th[ii] >= 0:
Yt = threshold_data(Yd, th=th[ii]);
else:
Yt = Yd.copy();
Yt_ = Yt.copy()
Yt_[Y_amp<std_thres] += np.random.normal(size=Yt.shape)[Y_amp<std_thres]
start = time.time();
if num_plane > 1:
print("3d data!");
connect_mat_1, idx, comps, permute_col = find_superpixel_3d(Yt_,num_plane,cut_off_point[ii],length_cut[ii],eight_neighbours=True);
else:
print("find superpixels!")
connect_mat_1, idx, comps, permute_col = find_superpixel(Yt_,cut_off_point[ii],length_cut[ii],eight_neighbours=True);
print("time: " + str(time.time()-start));
start = time.time();
print("rank 1 svd!")
if ii > 0:
c_ini, a_ini, _, _ = spatial_temporal_ini(Yt, comps, idx, length_cut[ii], bg=False);
else:
c_ini, a_ini, ff, fb = spatial_temporal_ini(Yt, comps, idx, length_cut[ii], bg=bg);
#return ff
print("time: " + str(time.time()-start));
unique_pix = np.asarray(np.sort(np.unique(connect_mat_1)),dtype="int");
unique_pix = unique_pix[np.nonzero(unique_pix)];
#unique_pix = np.asarray(np.sort(np.unique(connect_mat_1))[1:]); #search_superpixel_in_range(connect_mat_1, permute_col, V_mat);
brightness_rank_sup = order_superpixels(permute_col, unique_pix, a_ini, c_ini);
#unique_pix = np.asarray(unique_pix);
pure_pix = [];
start = time.time();
print("find pure superpixels!")
for kk in range(num_patch):
pos = np.where(patch_ref_mat==kk);
up=pos[0][0]*patch_height;
down=min(up+patch_height, dims[0]);
left=pos[1][0]*patch_width;
right=min(left+patch_width, dims[1]);
unique_pix_temp, M = search_superpixel_in_range((connect_mat_1.reshape(dims[0],int(dims[1]/num_plane),num_plane,order="F"))[up:down,left:right], permute_col, c_ini);
pure_pix_temp = fast_sep_nmf(M, M.shape[1], residual_cut[ii]);
if len(pure_pix_temp)>0:
pure_pix = np.hstack((pure_pix, unique_pix_temp[pure_pix_temp]));
pure_pix = np.unique(pure_pix);
print("time: " + str(time.time()-start));
start = time.time();
print("prepare iteration!")
if ii > 0:
a_ini, c_ini, brightness_rank = prepare_iteration(Yd_res, connect_mat_1, permute_col, pure_pix, a_ini, c_ini);
a = np.hstack((a, a_ini));
c = np.hstack((c, c_ini));
else:
a, c, b, normalize_factor, brightness_rank = prepare_iteration(Yd, connect_mat_1, permute_col, pure_pix, a_ini, c_ini, more=True);
print("time: " + str(time.time()-start));
if plot_en:
Cnt = local_correlations_fft(Yt);
pure_superpixel_corr_compare_plot(connect_mat_1, unique_pix, pure_pix, brightness_rank_sup, brightness_rank, Cnt, text);
print("start " + str(ii+1) + " pass iteration!")
if ii == pass_num - 1:
maxiter = max_iter_fin;
else:
maxiter=max_iter;
start = time.time();
if bg:
a, c, b, fb, ff, res, corr_img_all_r, num_list = update_AC_bg_l2_Y(Yd.reshape(np.prod(dims),-1,order="F"), normalize_factor, a, c, b, ff, fb, dims,
corr_th_fix, maxiter=maxiter, tol=1e-8, update_after=update_after,
merge_corr_thr=merge_corr_thr,merge_overlap_thr=merge_overlap_thr, num_plane=num_plane, plot_en=plot_en, max_allow_neuron_size=max_allow_neuron_size);
else:
a, c, b, fb, ff, res, corr_img_all_r, num_list = update_AC_l2_Y(Yd.reshape(np.prod(dims),-1,order="F"), normalize_factor, a, c, b, dims,
corr_th_fix, maxiter=maxiter, tol=1e-8, update_after=update_after,
merge_corr_thr=merge_corr_thr,merge_overlap_thr=merge_overlap_thr, num_plane=num_plane, plot_en=plot_en, max_allow_neuron_size=max_allow_neuron_size);
print("time: " + str(time.time()-start));
superpixel_rlt.append({'connect_mat_1':connect_mat_1, 'pure_pix':pure_pix, 'unique_pix':unique_pix, 'brightness_rank':brightness_rank, 'brightness_rank_sup':brightness_rank_sup});
if pass_num > 1 and ii == 0:
rlt = {'a':a, 'c':c, 'b':b, "fb":fb, "ff":ff, 'res':res, 'corr_img_all_r':corr_img_all_r, 'num_list':num_list};
a0 = a.copy();
ii = ii+1;
c_tf = [];
start = time.time();
if TF:
sigma = noise_estimator(c.T);
sigma *= fudge_factor
for ii in range(c.shape[1]):
c_tf = np.hstack((c_tf, l1_tf(c[:,ii], sigma[ii])));
c_tf = c_tf.reshape(T,int(c_tf.shape[0]/T),order="F");
print("time: " + str(time.time()-start));
if plot_en:
if pass_num > 1:
spatial_sum_plot(a0, a, dims, num_list, text);
Yd_res = reconstruct(Yd, a, c, b);
Yd_res = threshold_data(Yd_res, th=0);
Cnt = local_correlations_fft(Yd_res);
scale = np.maximum(1, int(Cnt.shape[1]/Cnt.shape[0]));
plt.figure(figsize=(8*scale,8))
ax1 = plt.subplot(1,1,1);
show_img(ax1, Cnt);
ax1.set(title="Local mean correlation for residual")
ax1.title.set_fontsize(15)
ax1.title.set_fontweight("bold")
plt.show();
fin_rlt = {'a':a, 'c':c, 'c_tf':c_tf, 'b':b, "fb":fb, "ff":ff, 'res':res, 'corr_img_all_r':corr_img_all_r, 'num_list':num_list};
if Yd_min < 0:
Yd += Yd_min_pw;
if pass_num > 1:
return {'rlt':rlt, 'fin_rlt':fin_rlt, "superpixel_rlt":superpixel_rlt}
else:
return {'fin_rlt':fin_rlt, "superpixel_rlt":superpixel_rlt}
| [
"[email protected]"
] | |
6a77109c6aa14b0e717e99865a97ceffd8cda1c1 | 09e5ce9673590f7ca27c480da605199a6d054a63 | /modules/highscore.py | 3daff9734d8b6c7a31ec3c42d9c75b6f9f816fd8 | [] | no_license | KirillMysnik/PySnake | 781d7767cbb404033b608d15427e9e7996cc71d6 | 3fe1edc20248f20029413a31d88f673411374faf | refs/heads/master | 2021-01-13T09:46:00.622694 | 2016-09-28T14:52:14 | 2016-09-28T14:52:14 | 69,473,624 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,698 | py | from modules.delays import Delay
from modules.gui import TextLabel
from internal_events import InternalEvent
LABEL_COLOR = (255, 255, 255)
HIGHSCORE_LABEL_CAPTION = "score: {score}"
HIGHSCORE_LABEL_X = 64
HIGHSCORE_LABEL_Y = 64
TIME_LABEL_CAPTION = "elapsed: {seconds}s"
TIME_LABEL_X = 64
TIME_LABEL_Y = 100
app_ = None
highscore_label = None
time_label = None
highscore = 0
time_ = 0
time_delay = None
def update_time():
global time_, time_delay
time_ += 1
time_label.caption = TIME_LABEL_CAPTION.format(seconds=time_)
time_label.render()
time_delay = Delay(1, update_time)
@InternalEvent('load')
def on_load(app):
global app_, highscore_label, time_label
app_ = app
highscore_label = TextLabel(
HIGHSCORE_LABEL_X, HIGHSCORE_LABEL_Y,
HIGHSCORE_LABEL_CAPTION.format(score=0), 48, LABEL_COLOR,
caption_bold=True)
highscore_label.render()
time_label = TextLabel(
TIME_LABEL_X, TIME_LABEL_Y, TIME_LABEL_CAPTION.format(seconds=0),
32, LABEL_COLOR)
time_label.render()
app_.register_drawer('score', highscore_label.draw)
app_.register_drawer('score', time_label.draw)
@InternalEvent('fruit_eaten')
def on_game_start(fruit):
global highscore
highscore += 1
highscore_label.caption = HIGHSCORE_LABEL_CAPTION.format(score=highscore)
highscore_label.render()
@InternalEvent('game_start')
def on_game_end():
global highscore, time_, time_delay
highscore = 0
time_ = -1
highscore_label.caption = HIGHSCORE_LABEL_CAPTION.format(score=highscore)
highscore_label.render()
update_time()
@InternalEvent('game_end')
def on_game_end():
time_delay.cancel()
| [
"[email protected]"
] | |
fb58449531e8d4d38e17ea8628b285f48a6c86ad | 321b4ed83b6874eeb512027eaa0b17b0daf3c289 | /153/153.find-minimum-in-rotated-sorted-array.250607228.Accepted.leetcode.py | 86c48a645e1a8abbc02eb311cb58e81777442548 | [] | no_license | huangyingw/submissions | 7a610613bdb03f1223cdec5f6ccc4391149ca618 | bfac1238ecef8b03e54842b852f6fec111abedfa | refs/heads/master | 2023-07-25T09:56:46.814504 | 2023-07-16T07:38:36 | 2023-07-16T07:38:36 | 143,352,065 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 378 | py | class Solution(object):
def findMin(self, nums):
if nums[0] <= nums[-1]:
return nums[0]
left, right = 0, len(nums) - 1
while left + 1 < right:
mid = (left + right) // 2
if nums[left] >= nums[mid]:
right = mid
else:
left = mid
return min(nums[left], nums[right])
| [
"[email protected]"
] | |
f7e66124cfb611cfdde05053e6b48a4ce7dff2fd | efd30b0ba0fd4d8c9e4ababe8113ba5be08319f2 | /parkings/migrations/0015_fill_normalized_reg_nums.py | 9f8b7a05457ba264cae61e627952374292b9a03d | [
"MIT"
] | permissive | City-of-Helsinki/parkkihubi | 3f559ef047592c5321b69c52474fc23a5eae0603 | 24751065d6e6cd68b89cd2a4358d51bdfc77cae6 | refs/heads/master | 2023-07-20T12:52:43.278380 | 2023-05-10T07:46:38 | 2023-05-10T07:46:38 | 75,084,288 | 14 | 15 | MIT | 2023-07-20T12:52:08 | 2016-11-29T13:32:13 | Python | UTF-8 | Python | false | false | 838 | py | from __future__ import unicode_literals
from django.db import migrations
from django.db.models import Q
from ..models import Parking
def fill_normalized_reg_nums(apps, schema_editor):
parking_model = apps.get_model('parkings', 'Parking')
parkings_to_process = parking_model.objects.filter(
Q(normalized_reg_num=None) | Q(normalized_reg_num=''))
for parking in parkings_to_process:
parking.normalized_reg_num = Parking.normalize_reg_num(
parking.registration_number)
parking.save(update_fields=['normalized_reg_num'])
class Migration(migrations.Migration):
dependencies = [
('parkings', '0014_normalized_reg_num'),
]
operations = [
migrations.RunPython(
code=fill_normalized_reg_nums,
reverse_code=migrations.RunPython.noop),
]
| [
"[email protected]"
] | |
6c351742ccd9c3c58c9a7048ff2f0434e916f76c | 04ae1836b9bc9d73d244f91b8f7fbf1bbc58ff29 | /019/Solution.py | 77b23c403e0c7749e27a5927c92d8dbf83f175dd | [] | no_license | zhangruochi/leetcode | 6f739fde222c298bae1c68236d980bd29c33b1c6 | cefa2f08667de4d2973274de3ff29a31a7d25eda | refs/heads/master | 2022-07-16T23:40:20.458105 | 2022-06-02T18:25:35 | 2022-06-02T18:25:35 | 78,989,941 | 14 | 6 | null | null | null | null | UTF-8 | Python | false | false | 2,040 | py | """
Given a linked list, remove the n-th node from the end of list and return its head.
Example:
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Follow up:
Could you do this in one pass?
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
slow = quick = dummy
while quick:
if n >= 0:
n -= 1
quick = quick.next
else:
quick = quick.next
slow = slow.next
slow.next = slow.next.next
return dummy.next
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
count, p = 0, dummy
while p:
count += 1
p = p.next
k = count - n - 1
p = dummy
while k:
p = p.next
k -= 1
p.next = p.next.next
return dummy.next
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
m = 0
cur = head
while cur:
m += 1
cur = cur.next
n = m - n
dummy = cur = ListNode()
dummy.next = head
while n:
cur = cur.next
n-=1
cur.next = cur.next.next
return dummy.next
| [
"[email protected]"
] | |
fb785b48dbc3883bf3983cf9a771dd2f9a6bb328 | 4a44d785d19f23033ec89775c8219a2f8275a4dd | /cride/circles/admin.py | a7031ba8c50be95f1f6624a720fbf3187af1f7ce | [
"MIT"
] | permissive | mdark1001/crideApiRest | d17989dfb650eb799c44c57d87f3e0cec8fc647b | 228efec90d7f1ad8a6766b5a8085dd6bbf49fc8a | refs/heads/main | 2023-04-09T23:27:09.931730 | 2021-04-19T13:46:44 | 2021-04-19T13:46:44 | 357,706,873 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 312 | py | from django.contrib import admin
# Register your models here.
from .models import Circle
@admin.register(Circle)
class CircleAdmin(admin.ModelAdmin):
list_display = ['name', 'is_verified', 'is_public', 'rides_taken', 'rides_offered']
list_filter = ['created', 'is_verified', 'is_public','is_limited']
| [
"[email protected]"
] | |
2d8e282e4ff5217cf1139f3a412e41342844571a | 278a000f8b40476b5d1473cc1b98d5872551cab2 | /test_sphere_volume.py | cb30c89536569a7350adecec0fb65901984d43cd | [] | no_license | Kaliumerbol/kaliev_erbol_hw_2.6 | 172eb765a9cd5be8f8a9dc4f28e3fc258e5d92d9 | 5ea5fa98baf10d467a287da435f40e796c2594c3 | refs/heads/main | 2023-06-05T15:44:51.723761 | 2021-06-29T10:51:01 | 2021-06-29T10:51:01 | 381,329,097 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 981 | py | import unittest
import math
from sphere_volume import calculate_sphere_volume
pi = math.pi
class TestSphereVolume(unittest.TestCase):
def test_area(self):
self.assertAlmostEqual(calculate_sphere_volume(5), 4/3*pi*5**3)
self.assertAlmostEqual(calculate_sphere_volume(3.7), 4/3*pi*3.7**3)
self.assertAlmostEqual(calculate_sphere_volume(1), 4/3*pi)
# толком не понял как работает АсертРейсес, в нете долго копалсяя но внятного объяснения нет. что и как вылавливать не понятно, значения не описаны. Поэтому закоментил. А так все работает норм.
# self.assertRaises(ValueError, calculate_sphere, 'four')
def test_negative(self):
self.assertEqual(calculate_sphere_volume(-5), 'Радиус сферы не может быть отрицательным')
unittest.main() | [
"[email protected]"
] | |
924fcb51f482e997c837a79f2363ad5b113136aa | 03195a6f98396fd27aedc3c06d81f1553fb1d16b | /pandas/tests/series/methods/test_rename.py | 90c8f775586e6d8a3b4fbc61dfc9c8334d7b3417 | [
"BSD-3-Clause"
] | permissive | huaxz1986/pandas | a08d80d27726fe141d449835b9a09265bca5b5e0 | ba2473834fedcf571d3f8245b4b24796873f2736 | refs/heads/master | 2023-06-11T02:20:14.544220 | 2022-01-12T04:40:06 | 2022-01-12T04:40:06 | 131,370,494 | 3 | 4 | BSD-3-Clause | 2018-04-28T03:51:05 | 2018-04-28T03:51:05 | null | UTF-8 | Python | false | false | 4,450 | py | from datetime import datetime
import numpy as np
import pytest
from pandas import (
Index,
MultiIndex,
Series,
)
import pandas._testing as tm
class TestRename:
def test_rename(self, datetime_series):
ts = datetime_series
renamer = lambda x: x.strftime("%Y%m%d")
renamed = ts.rename(renamer)
assert renamed.index[0] == renamer(ts.index[0])
# dict
rename_dict = dict(zip(ts.index, renamed.index))
renamed2 = ts.rename(rename_dict)
tm.assert_series_equal(renamed, renamed2)
def test_rename_partial_dict(self):
# partial dict
ser = Series(np.arange(4), index=["a", "b", "c", "d"], dtype="int64")
renamed = ser.rename({"b": "foo", "d": "bar"})
tm.assert_index_equal(renamed.index, Index(["a", "foo", "c", "bar"]))
def test_rename_retain_index_name(self):
# index with name
renamer = Series(
np.arange(4), index=Index(["a", "b", "c", "d"], name="name"), dtype="int64"
)
renamed = renamer.rename({})
assert renamed.index.name == renamer.index.name
def test_rename_by_series(self):
ser = Series(range(5), name="foo")
renamer = Series({1: 10, 2: 20})
result = ser.rename(renamer)
expected = Series(range(5), index=[0, 10, 20, 3, 4], name="foo")
tm.assert_series_equal(result, expected)
def test_rename_set_name(self):
ser = Series(range(4), index=list("abcd"))
for name in ["foo", 123, 123.0, datetime(2001, 11, 11), ("foo",)]:
result = ser.rename(name)
assert result.name == name
tm.assert_numpy_array_equal(result.index.values, ser.index.values)
assert ser.name is None
def test_rename_set_name_inplace(self):
ser = Series(range(3), index=list("abc"))
for name in ["foo", 123, 123.0, datetime(2001, 11, 11), ("foo",)]:
ser.rename(name, inplace=True)
assert ser.name == name
exp = np.array(["a", "b", "c"], dtype=np.object_)
tm.assert_numpy_array_equal(ser.index.values, exp)
def test_rename_axis_supported(self):
# Supporting axis for compatibility, detailed in GH-18589
ser = Series(range(5))
ser.rename({}, axis=0)
ser.rename({}, axis="index")
with pytest.raises(ValueError, match="No axis named 5"):
ser.rename({}, axis=5)
def test_rename_inplace(self, datetime_series):
renamer = lambda x: x.strftime("%Y%m%d")
expected = renamer(datetime_series.index[0])
datetime_series.rename(renamer, inplace=True)
assert datetime_series.index[0] == expected
def test_rename_with_custom_indexer(self):
# GH 27814
class MyIndexer:
pass
ix = MyIndexer()
ser = Series([1, 2, 3]).rename(ix)
assert ser.name is ix
def test_rename_with_custom_indexer_inplace(self):
# GH 27814
class MyIndexer:
pass
ix = MyIndexer()
ser = Series([1, 2, 3])
ser.rename(ix, inplace=True)
assert ser.name is ix
def test_rename_callable(self):
# GH 17407
ser = Series(range(1, 6), index=Index(range(2, 7), name="IntIndex"))
result = ser.rename(str)
expected = ser.rename(lambda i: str(i))
tm.assert_series_equal(result, expected)
assert result.name == expected.name
def test_rename_none(self):
# GH 40977
ser = Series([1, 2], name="foo")
result = ser.rename(None)
expected = Series([1, 2])
tm.assert_series_equal(result, expected)
def test_rename_series_with_multiindex(self):
# issue #43659
arrays = [
["bar", "baz", "baz", "foo", "qux"],
["one", "one", "two", "two", "one"],
]
index = MultiIndex.from_arrays(arrays, names=["first", "second"])
ser = Series(np.ones(5), index=index)
result = ser.rename(index={"one": "yes"}, level="second", errors="raise")
arrays_expected = [
["bar", "baz", "baz", "foo", "qux"],
["yes", "yes", "two", "two", "yes"],
]
index_expected = MultiIndex.from_arrays(
arrays_expected, names=["first", "second"]
)
series_expected = Series(np.ones(5), index=index_expected)
tm.assert_series_equal(result, series_expected)
| [
"[email protected]"
] | |
ab3e2eb43508d9f342a4113bbe93ea6f50279af2 | 63255cf9da84b5dd6aa4454dd50385d50c43aac9 | /tencent/sort_and_search/search.py | 7ed8bafa2fc87c9642650340c00b88a538a669e8 | [
"MIT"
] | permissive | summer-vacation/AlgoExec | d37054e937b7e3cc4c0f76019cf996acb0fb5a34 | 55c6c3e7890b596b709b50cafa415b9594c03edd | refs/heads/master | 2021-07-09T12:18:51.532581 | 2020-12-20T13:46:43 | 2020-12-20T13:46:43 | 223,929,183 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,429 | py | # -*- coding: utf-8 -*-
"""
File Name: search
Author : jing
Date: 2020/3/19
https://leetcode-cn.com/explore/interview/card/tencent/224/sort-and-search/927/
搜索旋转排序数组
O(log n)
"""
class Solution:
def search(self, nums, target: int) -> int:
if nums is None or len(nums) == 0:
return -1
if target in nums:
index = nums.index(target)
return index
else:
return -1
# 二分搜索
def search2(self, nums, target: int) -> int:
if not nums:
return -1
if len(nums) == 1:
return 0 if nums[0] == target else -1
cent = len(nums) // 2
if target < nums[cent] <= nums[-1]:
return self.search(nums[:cent], target)
elif target >= nums[cent] >= nums[0]:
res = self.search(nums[cent:], target)
if res == -1:
return -1
else:
return cent + res
else:
resl = self.search(nums[:cent], target)
resr = self.search(nums[cent:], target)
if resr != -1:
return cent + resr
if resl != -1:
return resl
return -1
if __name__ == '__main__':
print(Solution().search([4,5,6,7,0,1,2], 3))
| [
"[email protected]"
] | |
2ad5fa16421f87f656519643af8a3217cfecc11c | 15f321878face2af9317363c5f6de1e5ddd9b749 | /solutions_python/Problem_145/223.py | c67f0e3c81cc4903f6cdce8da4043c6407e2bad7 | [] | no_license | dr-dos-ok/Code_Jam_Webscraper | c06fd59870842664cd79c41eb460a09553e1c80a | 26a35bf114a3aa30fc4c677ef069d95f41665cc0 | refs/heads/master | 2020-04-06T08:17:40.938460 | 2018-10-14T10:12:47 | 2018-10-14T10:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 668 | py | #!/usr/bin/env pypy
# -*- coding: utf-8 -*-
# google code jam - c.durr - 2014
# Part Elf
# https://code.google.com/codejam/contest/3004486/dashboard
#
#
from math import *
from sys import *
from fractions import *
def readint(): return int(stdin.readline())
def readarray(f): return map(f, stdin.readline().split())
def readstring(): return stdin.readline().strip()
def solve(f):
k = -1
for g in range(40):
f *= 2
if f>=1:
f-=1
if k==-1:
k = g+1
if f==0:
return k
else:
return -1
for test in range(readint()):
f = readarray(Fraction)[0]
g = solve(f)
print "Case #%i:"% (test+1), ("impossible" if g==-1 else g)
| [
"[email protected]"
] | |
385a5bafa117ea93e64ca3733a3337a00c47b93e | d24cef73100a0c5d5c275fd0f92493f86d113c62 | /SRC/tutorials/adaptive.py | a1b03746e2aa8e81ec7c3f1153c3136a05f080a9 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | rlinder1/oof3d | 813e2a8acfc89e67c3cf8fdb6af6b2b983b8b8ee | 1fb6764d9d61126bd8ad4025a2ce7487225d736e | refs/heads/master | 2021-01-23T00:40:34.642449 | 2016-09-15T20:51:19 | 2016-09-15T20:51:19 | 92,832,740 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,624 | py | # -*- python -*-
# $RCSfile: adaptive.py,v $
# $Revision: 1.14.2.6 $
# $Author: langer $
# $Date: 2014/09/27 22:34:44 $
# This software was produced by NIST, an agency of the U.S. government,
# and by statute is not subject to copyright in the United States.
# Recipients of this software assume all responsibilities associated
# with its operation, modification and maintenance. However, to
# facilitate maintenance we ask that before distributing modified
# versions of this software, you first contact the authors at
# [email protected].
from ooflib.tutorials import tutorial
TutoringItem = tutorial.TutoringItem
TutorialClass = tutorial.TutorialClass
## TODO 3.1: Rewrite this so that it uses the Refine SkeletonModifier
## instead of the AMR MeshModifier. Then re-record the GUI test for
## this tutorial.
TutorialClass(
subject = "Adaptive Mesh Refinement",
ordering = 6,
lessons = [
TutoringItem(
subject="Introduction",
comments=
"""OOF3D provides a rudimentary adaptive mesh refinement tool via
BOLD(a Posteriori) error estimation scheme that utilizes
BOLD(Superconvergent Patch Recovery) of BOLD(Zienkiewicz) and
BOLD(Zhu) -- more discussion of the subject can be found in the
OOF3D manual.
In this tutorial, the adaptive mesh refinement will be briefly
demonstrated.
BOLD(NOTE:) In version 3.0 of OOF3D, adaptive mesh refinement
only works on the default Subproblem of a Mesh. Fields and
Equations defined on other Subproblems will not be seen by the
adaptive mesh machinery.
"""),
TutoringItem(
subject="Loading a Skeleton",
comments=
"""Open a graphics window, if none has been opened yet, with
the BOLD(Graphics/New) command in the BOLD(Windows) menu.
Download the file BOLD(el_shape.mesh) from
http://www.ctcms.nist.gov/oof/oof3d/examples, or locate it within the
share/oof3d/examples directory in your OOF3D installation.
A data file can be loaded from the BOLD(File) menu in the main OOF3D
window (BOLD(File -> Load -> Data)).
Select the example file (BOLD(el_shape.mesh)) in the file selector,
and click BOLD(OK).
""",
signal = ("new who", "Skeleton")
),
TutoringItem(
subject="L-shaped Domain",
comments=
"""If you have finished the tutorial for BOLD(Non-rectangular Domain),
you should be familiar with this Mesh.
The Mesh looks rectangular but Material has been assigned only to
the BOLD(green) part of the Mesh, which simulates an effective
BOLD(L)-shaped domain.
Move on to the next slide.
""" ),
TutoringItem(
subject="Boundary Conditions",
comments="""The Mesh is ready to be solved.
The applied boundary conditions (all BOLD(Dirichlet)) are:
BOLD(1.) u_x = 0 on the BOLD(Xmin) side
BOLD(2.) u_y = 0 on the BOLD(Xmin) side
BOLD(3.) u_z = 0 on the BOLD(Xmin) side
BOLD(4.) u_x = 0 on the BOLD(Ymax) side
BOLD(5.) u_y = 0 on the BOLD(Ymax) side
BOLD(6.) u_z = 0 on the BOLD(Ymax) side
BOLD(7.) u_y = -2 on the BOLD(Xmax) side
BOLD(8.) u_z = -2 on the BOLD(Xmax) side"""
),
# TODO 3.0: Minor schizophrenia -- since the introduction of
# subproblems, the "Solve" menu item sends "subproblem changed"
# and not "mesh changed", but the adaptive mesh refinement routine
# itself sends "mesh changed".
TutoringItem(
subject="Solution",
comments=
"""Open the BOLD(Solver) page and just click BOLD(Solve).
A deformed Mesh will be displayed in the graphics window.
Note that dummy elements (BOLD(ivory) part) are BOLD(NOT) displayed
in the deformed Mesh.
For the clearer view, let us hide the Skeleton layer.
Navigate to the bottom of the graphics window and find a layer
labeled BOLD(Skeleton(skeleton)) and Uncheck the square box to
hide the layer.
Due to the shape of the domain, it is obvious that stresses are
highly concentrated in the region surrounding the corner.
It is also safe to assume that errors in this region would be higher
than in other regions.
Move on to the next slide to start the process for adaptive mesh
refinement.
""",
signal = "subproblem changed"
),
# TODO: *** Mesh Status for el_shape:skeleton:mesh ***
# Unsolvable: Subproblem 'default' is ill-posed!
# Equation 'Force_Balance' has no flux contributions
TutoringItem(
subject="Adaptive Mesh Refinement",
comments=
"""Go back to the BOLD(FEMesh) page.
Select BOLD(Adaptive Mesh Refinement).
As of now, we have only one error estimator, BOLD(Z-Z Estimator).
Select BOLD(L2 Error Norm) for error estimating BOLD(method).
Select BOLD(stress), which is the only entity,
for the BOLD(flux) parameter.
Set BOLD(threshold) to be BOLD(10).
For each element, an L2 error norm will be computed
with stresses computed from the finite element solution and their
recovered counterparts, which act as exact stresses.
If the relative error exceeds 10 percent, the element will be refined.
The next three parameters, BOLD(criterion), BOLD(degree) and, BOLD(alpha)
take care of actual refinement. Don't bother with these parameters
for this tutorial (See BOLD(skeleton) tutorial for details).
Sometimes, refinement could create badly-shaped elements. These elements
can be removed by turning on the BOLD(rationalize) option.
By default, field values are transferred to the refined mesh.
This, however, is just a
projection of the previous solution onto the refined mesh --
you need to re-solve the problem for improved solution.
Leave these options as they are for now and click BOLD(OK).
""",
signal = "mesh changed"
),
TutoringItem(
subject="Refined Mesh",
comments=
"""As expected, elements surrounding the corner have been refined.
Now, go to the BOLD(Solver) page.
BOLD(Solve) the problem again with the refined mesh.
""",
signal = "subproblem changed"
),
TutoringItem(
subject="Refine Again",
comments=
"""
Go back to the BOLD(FEMesh) page and refine the mesh again
(just click BOLD(OK)).
The corner has been refined more. For a better view, use
BOLD(ctrl)+BOLD(.) or BOLD(Settings)->BOLD(Zoom)->BOLD(In) from
the graphics window.
This process (BOLD(Refine) + BOLD(Solve)) can be repeated, until
you're satisfied.
Thanks for trying out the tutorial.
""",
signal = "mesh changed"
)
])
| [
"[email protected]"
] | |
0d66bfb2e2f61e6192594453d928317bed7f64d2 | 6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4 | /MAzBohC2PxchT3wqK_13.py | a37c09d7d848225a334c7b4bb512adb1efefa6cd | [] | no_license | daniel-reich/ubiquitous-fiesta | 26e80f0082f8589e51d359ce7953117a3da7d38c | 9af2700dbe59284f5697e612491499841a6c126f | refs/heads/master | 2023-04-05T06:40:37.328213 | 2021-04-06T20:17:44 | 2021-04-06T20:17:44 | 355,318,759 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 360 | py |
def shadow_sentence(a, b):
alist, blist = a.split(' '), b.split(' ')
if len(alist) != len(blist):
return False
j = -1
for word in alist:
j += 1
if len(word) != len(blist[j]):
return False
i = -1
for word in blist:
i += 1
for letter in word:
if letter in alist[i]:
return False
return True
| [
"[email protected]"
] | |
164b25b05085c828e869ca41bbabfa5671265b28 | 4cf3f8845d64ed31737bd7795581753c6e682922 | /.history/main_20200118153116.py | 17842057b52a9388e5ecd34d985ca161511000dd | [] | no_license | rtshkmr/hack-roll | 9bc75175eb9746b79ff0dfa9307b32cfd1417029 | 3ea480a8bf6d0067155b279740b4edc1673f406d | refs/heads/master | 2021-12-23T12:26:56.642705 | 2020-01-19T04:26:39 | 2020-01-19T04:26:39 | 234,702,684 | 1 | 0 | null | 2021-12-13T20:30:54 | 2020-01-18T08:12:52 | Python | UTF-8 | Python | false | false | 301,331 | py | from telegram.ext import Updater, CommandHandler
import requests
import re
# API call to source, get json (url is obtained):
contents = requests.get('https://random.dog/woof.json').json()
image_url = contents['url']
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_tasks():
response = requests.get('https://nowwat.herokuapp.com/api/tasks.json').json()
def extract_list(obj):
return obj.map(lambda item: item.title)
tasks = extract_list(response)
return tasks
# sending the image:
# we require:
# - the image URL
# - the recipient's ID: group/user id
def bop(bot, update):
# image url:
url = get_url()
# recipient's ID:
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def getTaskList(bot, update):
taskList = get_tasks()
chat_id = update.message.chat_id
for task in taskList:
bot.sendMessage(chat_id, task, Markdown);
def main():
updater = Updater('982938821:AAHiN0-7hIPahKJm6lWPyQ0UupOsuhP1GsQ')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop',bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main() | [
"[email protected]"
] | |
01eb27b1efe1e94dc35839dd99988ef3512c19f4 | 6584124fee86f79ce0c9402194d961395583d6c3 | /blog/migrations/0005_userprofile.py | 741df13e8b0ed00bd33880271c9c54062c148c8f | [] | no_license | janusnic/webman | fdcffb7ed2f36d0951fd18bbaa55d0626cd271e1 | 2e5eaadec64314fddc19f27d9313317f7a236b9e | refs/heads/master | 2018-12-28T18:21:00.291717 | 2015-06-05T11:49:00 | 2015-06-05T11:49:00 | 35,676,834 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 796 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('blog', '0004_auto_20150522_1108'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('website', models.URLField(blank=True)),
('picture', models.ImageField(upload_to=b'profile_images', blank=True)),
('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"[email protected]"
] | |
efb302e6899348b8a39d8588818d325e6a0f9ada | 1d1a21b37e1591c5b825299de338d18917715fec | /Mathematics/Data science/Mathmatics/02/Exercise_2_4_5.py | 4c1094e1a0624eace4209363bf4bc2727406716d | [] | no_license | brunoleej/study_git | 46279c3521f090ebf63ee0e1852aa0b6bed11b01 | 0c5c9e490140144caf1149e2e1d9fe5f68cf6294 | refs/heads/main | 2023-08-19T01:07:42.236110 | 2021-08-29T16:20:59 | 2021-08-29T16:20:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,206 | py | # 보스턴 집값 문제는 미국 보스턴내 각 지역(town)의 주택 가격을 그 지역의 범죄율이나 공기 오염도 등의 특징
# 을 사용하여 예측하는 문제다. Scikit-Learn 패키지에서 임포트할 수 있다. 보스턴 집값 문제를 선형 예측모형
# Ax = b_hat로 풀었을 때의 가중치 벡터 를 구하라. 행렬과 벡터 데이터는 다음과 같이 얻을 수 있다. 여기에서는
# 문제를 간단하게 하기 위해 입력 데이터를 범죄율(CRIM), 공기 오염도(NOX), 방의 개수(RM), 오래된 정도
# (AGE)의 4종류로 제한했고 데이터도 4개만 사용했다
import numpy as np
from sklearn.datasets import load_boston
boston = load_boston()
X = boston.data
y = boston.target
A = X[:4, [0, 4, 5, 6]] # 'CRIM', 'NOX', 'RM', 'AGE'
b = y[:4]
x, resid, rank, s = np.linalg.lstsq(A,b)
print(A)
'''
[[6.320e-03 5.380e-01 6.575e+00 6.520e+01]
[2.731e-02 4.690e-01 6.421e+00 7.890e+01]
[2.729e-02 4.690e-01 7.185e+00 6.110e+01]
[3.237e-02 4.580e-01 6.998e+00 4.580e+01]]
'''
print(x) # [-3.12710043e+02 -1.15193942e+02 1.44996465e+01 -1.13259317e-01]
print(b) # [24. 21.6 34.7 33.4]
| [
"[email protected]"
] | |
93dab5e033bf2be71722860d57e80346b770aa7b | 3b1daac7c1f72b985da899770d98e5f0e8fb835c | /Configurations/VBS/2017CR_v7/variables.py | 695bd91e5fdd8c45254bfdcdab37fb9d9235b46a | [] | no_license | freejiebao/PlotsConfigurations | 7e10aa45aa3bf742f30d1e21dc565d59d2a025d8 | cdfd3aff38d1ece9599a699997753bc8ba01b9b1 | refs/heads/master | 2020-06-18T19:22:00.561542 | 2019-09-02T12:52:28 | 2019-09-02T12:52:28 | 186,931,874 | 0 | 0 | null | 2019-05-16T01:58:07 | 2019-05-16T01:58:07 | null | UTF-8 | Python | false | false | 5,363 | py | # variables
#variables = {}
#'fold' : # 0 = not fold (default), 1 = fold underflowbin, 2 = fold overflow bin, 3 = fold underflow and overflow
# variables['events'] = { 'name': '1',
# 'range' : (1,0,2),
# 'xaxis' : 'events',
# 'fold' : 3
# }
variables['nJet'] = { 'name': 'nJet',
'range' : (6,0,6),
'xaxis' : 'njets',
'fold' : 3
}
variables['nJet_v2'] = { 'name': 'Sum$(CleanJet_pt>30)',
'range' : (4,0,4),
'xaxis' : 'njets',
'fold' : 3
}
variables['nLepton'] = {
'name': '1*(Alt$(Lepton_pt[0],0.)>20) + 1*(Alt$(Lepton_pt[1],0.)>20) + 1*(Alt$(Lepton_pt[2],0.)>20)+ 1*(Alt$(Lepton_pt[3],0.)>20) + 1*(Alt$(Lepton_pt[4],0.)>20)',
'range': (5,0,5),
'xaxis': '# leptons',
'fold': 3
}
variables['mll'] = { 'name': 'mll', # variable name
'range' : (4, 0. ,500), # variable range
'xaxis' : 'mll [GeV]', # x axis name
'fold' : 3
}
variables['mll_v3'] = { 'name': 'mll', # variable name
'range' : (12, 20. ,320), # variable range
'xaxis' : 'mll [GeV]', # x axis name
'fold' : 3
}
variables['mll_v2'] = { 'name': 'mll', # variable name
'range' : (80, 0. ,800), # variable range
'xaxis' : 'mll [GeV]', # x axis name
'fold' : 3
}
variables['mjj'] = { 'name': 'mjj',
'range': ([500,800,1200,1600,2000],), #for 500 < mjj < 1000
'xaxis': 'mjj [GeV]',
'fold': 3
}
variables['mjj_v2'] = { 'name': 'mjj',
'range': ([500,800,1200,1800,2000],), #for 500 < mjj < 1000
'xaxis': 'mjj [GeV]',
'fold': 3
}
variables['mjj_v3'] = { 'name': 'mjj',
'range': (15, 500. ,2000), #for 500 < mjj < 1000
'xaxis': 'mjj [GeV]',
'fold': 3
}
variables['mjj_v4'] = { 'name': 'mjj',
'range': (10,0 ,500), #for 500 < mjj < 1000
'xaxis': 'mjj [GeV]',
'fold': 3
}
variables['pt1'] = { 'name': 'Alt$(Lepton_pt[0],-9999.)',
'range' : (10,0.,100),
'xaxis' : 'p_{T} 1st lep',
'fold' : 3
}
variables['pt2'] = { 'name': 'Alt$(Lepton_pt[0],-9999.)',
'range' : (10,0.,150),
'xaxis' : 'p_{T} 2nd lep',
'fold' : 3
}
variables['jetpt1'] = { 'name': 'Alt$(Jet_pt[0],-9999.)',
'range' : (15,0.,200),
'xaxis' : 'p_{T} 1st jet',
'fold' : 3
}
variables['jetpt2'] = { 'name': 'Alt$(Jet_pt[1],-9999.)',
'range' : (15,0.,150),
'xaxis' : 'p_{T} 2nd jet',
'fold' : 3
}
variables['met'] = { 'name': 'MET_pt', # variable name
'range' : (10,0,200), # variable range
'xaxis' : 'pfmet [GeV]', # x axis name
'fold' : 3
}
variables['etaj1'] = { 'name': 'Alt$(Jet_eta[0],-9999.)',
'range': (10,-5,5),
'xaxis': 'etaj1',
'fold': 3
}
variables['etaj2'] = { 'name': 'Alt$(Jet_eta[1],-9999.)',
'range': (10,-5,5),
'xaxis': 'etaj2',
'fold': 3
}
variables['detajj'] = { 'name': 'detajj',
'range': (7,0.0,7.0),
'xaxis': 'detajj',
'fold': 3
}
variables['Zlep1'] = { 'name': '(Alt$(Lepton_eta[0],-9999.) - (Alt$(Jet_eta[0],-9999.)+Alt$(Jet_eta[1],-9999.))/2)/detajj',
'range': (10,-1.5,1.5),
'xaxis': 'Z^{lep}_{1}',
'fold': 3
}
variables['Zlep2'] = { 'name': '(Alt$(Lepton_eta[1],-9999.) - (Alt$(Jet_eta[0],-9999.)+Alt$(Jet_eta[1],-9999.))/2)/detajj',
'range': (10,-1.5,1.5),
'xaxis': 'Z^{lep}_{2}',
'fold': 3
}
variables['csvv2ivf_1'] = {
'name': 'Alt$(Jet_btagCSVV2[0],0.)',
'range' : (10,0,1),
'xaxis' : 'csvv2ivf 1st jet ',
'fold' : 3
}
variables['csvv2ivf_2'] = {
'name': 'Alt$(Jet_btagCSVV2[1],0.)',
'range' : (10,0,1),
'xaxis' : 'csvv2ivf 2nd jet ',
'fold' : 3
}
| [
"[email protected]"
] | |
4655a05a2e59738d661f9702526dbfdea1f20f57 | ce083128fa87ca86c65059893aa8882d088461f5 | /python/flask-webservices-labs/graphene/graphene/types/mutation.py | fe15f6a2daa5be2a7b09b6fd4419a7e2f2e88fd1 | [
"MIT"
] | permissive | marcosptf/fedora | 581a446e7f81d8ae9a260eafb92814bc486ee077 | 359db63ff1fa79696b7bc803bcfa0042bff8ab44 | refs/heads/master | 2023-04-06T14:53:40.378260 | 2023-03-26T00:47:52 | 2023-03-26T00:47:52 | 26,059,824 | 6 | 5 | null | 2022-12-08T00:43:21 | 2014-11-01T18:48:56 | null | UTF-8 | Python | false | false | 2,892 | py | from collections import OrderedDict
from ..utils.get_unbound_function import get_unbound_function
from ..utils.props import props
from .field import Field
from .objecttype import ObjectType, ObjectTypeOptions
from .utils import yank_fields_from_attrs
from ..utils.deprecated import warn_deprecation
# For static type checking with Mypy
MYPY = False
if MYPY:
from .argument import Argument # NOQA
from typing import Dict, Type, Callable # NOQA
class MutationOptions(ObjectTypeOptions):
arguments = None # type: Dict[str, Argument]
output = None # type: Type[ObjectType]
resolver = None # type: Callable
class Mutation(ObjectType):
'''
Mutation Type Definition
'''
@classmethod
def __init_subclass_with_meta__(cls, resolver=None, output=None, arguments=None,
_meta=None, **options):
if not _meta:
_meta = MutationOptions(cls)
output = output or getattr(cls, 'Output', None)
fields = {}
if not output:
# If output is defined, we don't need to get the fields
fields = OrderedDict()
for base in reversed(cls.__mro__):
fields.update(
yank_fields_from_attrs(base.__dict__, _as=Field)
)
output = cls
if not arguments:
input_class = getattr(cls, 'Arguments', None)
if not input_class:
input_class = getattr(cls, 'Input', None)
if input_class:
warn_deprecation((
"Please use {name}.Arguments instead of {name}.Input."
"Input is now only used in ClientMutationID.\n"
"Read more:"
" https://github.com/graphql-python/graphene/blob/v2.0.0/UPGRADE-v2.0.md#mutation-input"
).format(name=cls.__name__))
if input_class:
arguments = props(input_class)
else:
arguments = {}
if not resolver:
mutate = getattr(cls, 'mutate', None)
assert mutate, 'All mutations must define a mutate method in it'
resolver = get_unbound_function(mutate)
if _meta.fields:
_meta.fields.update(fields)
else:
_meta.fields = fields
_meta.output = output
_meta.resolver = resolver
_meta.arguments = arguments
super(Mutation, cls).__init_subclass_with_meta__(_meta=_meta, **options)
@classmethod
def Field(cls, name=None, description=None, deprecation_reason=None):
return Field(
cls._meta.output,
args=cls._meta.arguments,
resolver=cls._meta.resolver,
name=name,
description=description,
deprecation_reason=deprecation_reason,
)
| [
"[email protected]"
] | |
fc768d86e67ffc89d1d24ffed58e0444d7d7b40f | 01fc3bd7098dd265a78dcf23c08f427a59581dd3 | /src/prosestats/stats.py | 4988679a238bb6f0a0baadab6ab16ec4a26ccb0c | [] | no_license | rosspeckomplekt/textual-analogy-parsing | 68ba0a6e259d26059552eb8a5082c38890a43a32 | d60bdfd1d7c69bb28a16ee69c99a4f9c53044c1e | refs/heads/master | 2020-12-09T10:21:30.208376 | 2018-12-06T16:57:45 | 2018-12-06T16:57:45 | 233,275,236 | 1 | 0 | null | 2020-01-11T18:06:47 | 2020-01-11T18:06:46 | null | UTF-8 | Python | false | false | 12,237 | py | from collections import defaultdict, Counter
import numpy as np
import scipy.stats as scstats
def invert_dict(data):
ret = defaultdict(dict)
for m, dct in data.items():
for n, v in dct.items():
ret[n][m] = v
return ret
def flatten_dict(data):
ret = {}
for k, vs in data.items():
for k_, v in vs.items():
ret[k,k_] = v
return ret
def nominal_agreement(a,b):
return int(a==b)
def ordinal_agreement(a,b, V):
return 1 - abs(a - b)/(V-1)
def nominal_metric(a, b):
return a != b
def interval_metric(a, b):
return (a-b)**2
def ratio_metric(a, b):
return ((a-b)/(a+b))**2
def ordinal_metric(N_v, a, b):
a, b = min(a,b), max(a,b)
return (sum(N_v[a:b+1]) - (N_v[a] + N_v[b])/2)**2
def compute_alpha(data, metric="ordinal", V=None):
"""
Computes Krippendorff's alpha for a coding matrix V.
V implicitly represents a M x N matrix where M is the number of
coders and N is the number of instances.
In reality, to represent missing values, it is a dictionary of M
dictionaries, with each dictionary having some of N keys.
@V is the number of elements.
"""
data_ = invert_dict(data)
if V is None:
V = max({v for worker in data.values() for v in worker.values()})+1
O = np.zeros((V, V))
E = np.zeros((V, V))
for _, dct in data_.items():
if len(dct) <= 1: continue
o = np.zeros((V,V))
for m, v in dct.items():
v = int(v)
for m_, v_ in dct.items():
v_ = int(v_)
if m != m_:
o[v, v_] += 1
M_n = len(dct)
O += o/(M_n - 1)
N_v = O.sum(0)
E = (np.outer(N_v, N_v) - N_v * np.eye(V))/(sum(N_v)-1)
if metric == "nominal":
metric = nominal_metric
elif metric == "interval":
metric = lambda a, b: interval_metric(a/V, b/V)
elif metric == "ratio":
metric = ratio_metric
elif metric == "ordinal":
metric = lambda v, v_: ordinal_metric(N_v, v, v_)
else:
raise ValueError("Invalid metric " + metric)
delta = np.array([[metric(v, v_) for v in range(V)] for v_ in range(V)])
D_o = (O * delta).sum()
D_e = (E * delta).sum()
return 1 - D_o/D_e
def test_compute_alpha():
# Example from http://en.wikipedia.org/wiki/Krippendorff's_Alpha
data = {
'A': {6:2, 7:3, 8:0, 9:1, 10:0, 11:0, 12:2, 13:2, 15:2,},
'B': {1:0, 3:1, 4:0, 5:2, 6:2, 7:3, 8:2,},
'C': {3:1, 4:0, 5:2, 6:3, 7:3, 9:1, 10:0, 11:0, 12:2, 13:2, 15:3,},
}
assert np.allclose(compute_alpha(data, "nominal", 4), 0.691, 5e-3)
assert np.allclose(compute_alpha(data, "interval", 4), 0.811, 5e-3)
assert np.allclose(compute_alpha(data, "ordinal", 4), 0.807, 5e-3)
def outliers_modified_z_score(ys, threshold = 3.5):
median_y = np.median(ys)
median_absolute_deviation_y = np.median([np.abs(y - median_y) for y in ys])
modified_z_scores = [0.6745 * (y - median_y) / median_absolute_deviation_y
for y in ys]
return np.where(np.abs(modified_z_scores) > threshold)
def outliers_modified_z_score_one_sided(ys, threshold = 3.5):
median_y = np.median(ys)
median_absolute_deviation_y = np.median([np.abs(y - median_y) for y in ys])
modified_z_scores = [0.6745 * (y - median_y) / median_absolute_deviation_y
for y in ys]
return np.where(np.abs(modified_z_scores) > threshold)
def compute_pearson_rho(data):
"""
Given matrix of (task, worker_responses),
computes pairs of (worker_response - avg) for every task
and averages over all workers.
"""
data_ = invert_dict(data)
# get task means.
pearson_data = defaultdict(list)
for _, worker_responses in data_.items():
# compute pairs,
if len(worker_responses) < 2: continue
avg = np.mean(list(worker_responses.values()))
for worker, response in worker_responses.items():
pearson_data[worker].append([response, avg])
micro_data = np.array(sum(pearson_data.values(), []))
micro, _ = scstats.pearsonr(micro_data.T[0], micro_data.T[1])
macros = []
for _, vs in pearson_data.items():
if len(vs) < 3: continue
vs = np.array(vs)
rho, _ = scstats.pearsonr(vs.T[0], vs.T[1])
if not np.isnan(rho): # uh, not sure how to handle this...
macros.append(rho)
return micro #, np.mean(macros)
def test_pearson_rho():
# Example from http://en.wikipedia.org/wiki/Krippendorff's_Alpha
data = {
'A': {6:2, 7:3, 8:0, 9:1, 10:0, 11:0, 12:2, 13:2, 15:2,},
'B': {1:0, 3:1, 4:0, 5:2, 6:2, 7:3, 8:2,},
'C': {3:1, 4:0, 5:2, 6:3, 7:3, 9:1, 10:0, 11:0, 12:2, 13:2, 15:3,},
}
micro, macro = compute_pearson_rho(data)
assert np.allclose(micro, 0.947, 5e-3)
assert np.allclose(macro, 0.948, 5e-3)
def compute_tmean(data, mode="function", frac=0.1):
if mode == "worker":
ret = []
for vs in data.values():
vs = list(vs.values())
ret.append(scstats.trim_mean(vs, frac))
return np.mean(ret)
else:
data = invert_dict(data)
ret = []
for vs in data.values():
vs = list(vs.values())
ret.extend(vs)
return scstats.trim_mean(ret, frac)
def compute_mean(data, mode="function"):
if mode == "worker":
ret = []
for vs in data.values():
vs = list(vs.values())
ret.extend(vs)
return np.mean(ret)
else:
data = invert_dict(data)
ret = []
for vs in data.values():
vs = list(vs.values())
ret.append(np.mean(vs))
return np.mean(ret)
def compute_median(data):
ret = []
for vs in data.values():
vs = list(vs.values())
ret.extend(vs)
return np.median(ret)
def compute_std(data, mode="worker"):
data = invert_dict(data)
if mode == "worker":
ret = []
for vs in data.values():
vs = list(vs.values())
ret.extend((vs - np.mean(vs)).tolist())
return np.std(ret)
else:
ret = []
for vs in data.values():
vs = list(vs.values())
ret.append(np.mean(vs))
return np.std(ret)
def compute_nu(data):
return compute_std(data, "worker")/compute_std(data, "function")
def compute_mad(data, mode="worker"):
data = invert_dict(data)
if mode == "worker":
ret = []
for vs in data.values():
vs = list(vs.values())
ret.extend((vs - np.median(vs)).tolist())
return np.mean(np.abs(ret))
else:
ret = []
for vs in data.values():
vs = list(vs.values())
ret.append(np.mean(vs))
return np.mean(np.abs(ret - np.median(ret)))
def compute_agreement(data, mode="nominal", V=None):
"""
Computes simple agreement by taking pairs of data and simply computing probabilty that they agree.
@V is range of values
"""
if V is None:
V = len({v for worker in data.values() for v in worker})
if mode == "nominal":
f = nominal_agreement
elif mode == "ordinal":
f = lambda a,b: ordinal_agreement(a, b, V)
else:
raise ValueError("Invalid mode {}".format(mode))
data_ = invert_dict(data)
ret, i = 0., 0
for _, worker_responses in data_.items():
# compute pairs,
if len(worker_responses) < 2: continue
responses = sorted(worker_responses.values())
# get pairs
for j, r in enumerate(responses):
for _, r_ in enumerate(responses[j+1:]):
# compute probability
ret += (f(r,r_) - ret)/(i+1)
i += 1
return ret
def test_compute_agreement_nominal():
# Example from http://en.wikipedia.org/wiki/Krippendorff's_Alpha
data = {
'A': {6:2, 7:3, 8:0, 9:1, 10:0, 11:0, 12:2, 13:2, 15:2,},
'B': {1:0, 3:1, 4:0, 5:2, 6:2, 7:3, 8:2,},
'C': {3:1, 4:0, 5:2, 6:3, 7:3, 9:1, 10:0, 11:0, 12:2, 13:2, 15:3,},
}
agreement = compute_agreement(data, "nominal")
assert np.allclose(agreement, 0.75, 5e-3)
def test_compute_agreement_ordinal():
# Example from http://en.wikipedia.org/wiki/Krippendorff's_Alpha
data = {
'A': {6:2, 7:3, 8:0, 9:1, 10:0, 11:0, 12:2, 13:2, 15:2,},
'B': {1:0, 3:1, 4:0, 5:2, 6:2, 7:3, 8:2,},
'C': {3:1, 4:0, 5:2, 6:3, 7:3, 9:1, 10:0, 11:0, 12:2, 13:2, 15:3,},
}
agreement = compute_agreement(data, "ordinal")
assert np.allclose(agreement, 0.75, 5e-3)
def _factorize(data):
"""
Try to learn turker and task scores as a linear model.
"""
workers = sorted(data.keys())
tasks = sorted({hit for hits in data.values() for hit in hits})
n_entries = sum(len(hits) for hits in data.values())
X = np.zeros((n_entries, len(workers)+len(tasks)))
Y = np.zeros(n_entries)
i = 0
for worker, hits in data.items():
for task, value in hits.items():
X[i, workers.index(worker)] = 1
X[i, len(workers) + tasks.index(task)] = 1
Y[i] = value
i += 1
return X, Y
def compute_mean_agreement(data, mode="nominal", V=None):
if V is None:
V = len({v for worker in data.values() for v in worker})
if mode == "nominal":
f = nominal_agreement
elif mode == "ordinal":
f = lambda a,b: ordinal_agreement(a, b, V)
else:
raise ValueError("Invalid mode {}".format(mode))
data_ = invert_dict(data)
ret, i = 0., 0
for _, worker_responses in data_.items():
# compute pairs,
if len(worker_responses) < 2: continue
responses = sorted(worker_responses.values())
if mode == "nominal":
m = scstats.mode(responses)[0]
elif mode == "ordinal":
m = np.mean(responses)
# get pairs
for r in responses:
# compute probability
ret += (f(m,r) - ret)/(i+1)
i += 1
return ret
def compute_worker(data, mode="std"):
data_ = invert_dict(data)
if mode == "std":
Ms = {hit_id: np.mean(list(ws.values())) for hit_id, ws in data_.items()}
elif mode == "mad":
Ms = {hit_id: np.median(list(ws.values())) for hit_id, ws in data_.items()}
elif mode == "iaa":
Ms = {hit_id: np.median(list(ws.values())) for hit_id, ws in data_.items()}
else:
raise ValueError()
ret = {}
for worker, responses in data.items():
vs = [Ms[hit_id] - response for hit_id, response in responses.items()]
if mode == "std":
ret[worker] = np.std(vs)
elif mode == "mad":
ret[worker] = np.mean(np.abs(vs))
elif mode == "iaa":
ret[worker] = np.mean([1 if v == 0 else 0 for v in vs])
return ret
def compute_task_worker_interactions(data, alpha=0.1):
"""
Using a mixed-effects model: y = Wx + Za jk
"""
data = flatten_dict(data)
keys = sorted(data.keys())
workers, hits = zip(*keys)
workers, hits = sorted(set(workers)), sorted(set(hits))
Y = np.zeros(len(keys) + 2)
X = np.zeros((len(keys) + 2, len(workers) + len(hits))) # + len(keys)-1))
wf = [0 for _ in workers]
hf = [0 for _ in hits]
for i, (worker, hit) in enumerate(keys):
Y[i] = data[worker,hit]
wi, hi = workers.index(worker), hits.index(hit)
X[i, wi] = 1
X[i, len(workers) + hi] = 1
wf[wi] += 1
hf[hi] += 1
# constraint: proportional sum of workers = 0
Y[len(keys)], X[len(keys), :len(workers)] = 0, wf
# constraint: proportional sum of tasks = 0
Y[len(keys)+1], X[len(keys)+1, len(workers):] = 0, hf
model = Ridge(alpha=alpha)#, fit_intercept=False)
model.fit(X, Y)# - Y.mean())
mean = model.intercept_
worker_coefs = model.coef_[:len(workers)]
hit_coefs = model.coef_[len(workers):]
residuals = Y - model.predict(X)
ret = {
"mean": mean,
"worker-std": np.std(worker_coefs),
"task-std": np.std(hit_coefs),
"residual-std": np.std(residuals),
}
return ret
| [
"[email protected]"
] | |
d654571b75c42601d497f2010175e9d03db70f79 | a9f38bb28ff9bd04b151d86c653cde9f46768c7c | /easy/guessNumberHigherLower.py | 3d9a440d88b43dfb848527e6505af7060a690b0d | [] | no_license | Xynoclafe/leetcode | 02388516b10b8ee6bec6ee1b91ab5681c3254d33 | 4a80f02683e7fc14cb49c07170651ea3eeb280ac | refs/heads/master | 2020-12-01T21:05:44.656581 | 2020-02-02T09:05:32 | 2020-02-02T09:05:32 | 230,770,600 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 699 | py | # The guess API is already defined for you.
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
def binSearch(start, end):
if start == end:
start
pivot = (start + end) // 2
return pivot
start = 0
end = n
while True:
num = binSearch(start, end)
result = guess(num)
if result == 0:
return num
elif result == 1:
start = num + 1
else:
end = num - 1
| [
"[email protected]"
] | |
92e70f3375c49b5f0f371ed4cc14858df4e12007 | 2c4763aa544344a3a615f9a65d1ded7d0f59ae50 | /waflib/Node.py | 3024f5f7b3370c9e79f3ce9efc8e4d02de3fe9ca | [] | no_license | afeldman/waf | 572bf95d6b11571bbb2941ba0fe463402b1e39f3 | 4c489b38fe1520ec1bc0fa7e1521f7129c20f8b6 | refs/heads/master | 2021-05-09T18:18:16.598191 | 2019-03-05T06:33:42 | 2019-03-05T06:33:42 | 58,713,085 | 0 | 0 | null | 2016-05-13T07:34:33 | 2016-05-13T07:34:33 | null | UTF-8 | Python | false | false | 26,479 | py | #!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2005-2018 (ita)
"""
Node: filesystem structure
#. Each file/folder is represented by exactly one node.
#. Some potential class properties are stored on :py:class:`waflib.Build.BuildContext` : nodes to depend on, etc.
Unused class members can increase the `.wafpickle` file size sensibly.
#. Node objects should never be created directly, use
the methods :py:func:`Node.make_node` or :py:func:`Node.find_node` for the low-level operations
#. The methods :py:func:`Node.find_resource`, :py:func:`Node.find_dir` :py:func:`Node.find_or_declare` must be
used when a build context is present
#. Each instance of :py:class:`waflib.Context.Context` has a unique :py:class:`Node` subclass required for serialization.
(:py:class:`waflib.Node.Nod3`, see the :py:class:`waflib.Context.Context` initializer). A reference to the context
owning a node is held as *self.ctx*
"""
import os, re, sys, shutil
from waflib import Utils, Errors
exclude_regs = '''
**/*~
**/#*#
**/.#*
**/%*%
**/._*
**/*.swp
**/CVS
**/CVS/**
**/.cvsignore
**/SCCS
**/SCCS/**
**/vssver.scc
**/.svn
**/.svn/**
**/BitKeeper
**/.git
**/.git/**
**/.gitignore
**/.bzr
**/.bzrignore
**/.bzr/**
**/.hg
**/.hg/**
**/_MTN
**/_MTN/**
**/.arch-ids
**/{arch}
**/_darcs
**/_darcs/**
**/.intlcache
**/.DS_Store'''
"""
Ant patterns for files and folders to exclude while doing the
recursive traversal in :py:meth:`waflib.Node.Node.ant_glob`
"""
def ant_matcher(s, ignorecase):
reflags = re.I if ignorecase else 0
ret = []
for x in Utils.to_list(s):
x = x.replace('\\', '/').replace('//', '/')
if x.endswith('/'):
x += '**'
accu = []
for k in x.split('/'):
if k == '**':
accu.append(k)
else:
k = k.replace('.', '[.]').replace('*','.*').replace('?', '.').replace('+', '\\+')
k = '^%s$' % k
try:
exp = re.compile(k, flags=reflags)
except Exception as e:
raise Errors.WafError('Invalid pattern: %s' % k, e)
else:
accu.append(exp)
ret.append(accu)
return ret
def ant_sub_filter(name, nn):
ret = []
for lst in nn:
if not lst:
pass
elif lst[0] == '**':
ret.append(lst)
if len(lst) > 1:
if lst[1].match(name):
ret.append(lst[2:])
else:
ret.append([])
elif lst[0].match(name):
ret.append(lst[1:])
return ret
def ant_sub_matcher(name, pats):
nacc = ant_sub_filter(name, pats[0])
nrej = ant_sub_filter(name, pats[1])
if [] in nrej:
nacc = []
return [nacc, nrej]
class Node(object):
"""
This class is organized in two parts:
* The basic methods meant for filesystem access (compute paths, create folders, etc)
* The methods bound to a :py:class:`waflib.Build.BuildContext` (require ``bld.srcnode`` and ``bld.bldnode``)
"""
dict_class = dict
"""
Subclasses can provide a dict class to enable case insensitivity for example.
"""
__slots__ = ('name', 'parent', 'children', 'cache_abspath', 'cache_isdir')
def __init__(self, name, parent):
"""
.. note:: Use :py:func:`Node.make_node` or :py:func:`Node.find_node` instead of calling this constructor
"""
self.name = name
self.parent = parent
if parent:
if name in parent.children:
raise Errors.WafError('node %s exists in the parent files %r already' % (name, parent))
parent.children[name] = self
def __setstate__(self, data):
"Deserializes node information, used for persistence"
self.name = data[0]
self.parent = data[1]
if data[2] is not None:
# Issue 1480
self.children = self.dict_class(data[2])
def __getstate__(self):
"Serializes node information, used for persistence"
return (self.name, self.parent, getattr(self, 'children', None))
def __str__(self):
"""
String representation (abspath), for debugging purposes
:rtype: string
"""
return self.abspath()
def __repr__(self):
"""
String representation (abspath), for debugging purposes
:rtype: string
"""
return self.abspath()
def __copy__(self):
"""
Provided to prevent nodes from being copied
:raises: :py:class:`waflib.Errors.WafError`
"""
raise Errors.WafError('nodes are not supposed to be copied')
def read(self, flags='r', encoding='latin-1'):
"""
Reads and returns the contents of the file represented by this node, see :py:func:`waflib.Utils.readf`::
def build(bld):
bld.path.find_node('wscript').read()
:param flags: Open mode
:type flags: string
:param encoding: encoding value for Python3
:type encoding: string
:rtype: string or bytes
:return: File contents
"""
return Utils.readf(self.abspath(), flags, encoding)
def write(self, data, flags='w', encoding='latin-1'):
"""
Writes data to the file represented by this node, see :py:func:`waflib.Utils.writef`::
def build(bld):
bld.path.make_node('foo.txt').write('Hello, world!')
:param data: data to write
:type data: string
:param flags: Write mode
:type flags: string
:param encoding: encoding value for Python3
:type encoding: string
"""
Utils.writef(self.abspath(), data, flags, encoding)
def read_json(self, convert=True, encoding='utf-8'):
"""
Reads and parses the contents of this node as JSON (Python ≥ 2.6)::
def build(bld):
bld.path.find_node('abc.json').read_json()
Note that this by default automatically decodes unicode strings on Python2, unlike what the Python JSON module does.
:type convert: boolean
:param convert: Prevents decoding of unicode strings on Python2
:type encoding: string
:param encoding: The encoding of the file to read. This default to UTF8 as per the JSON standard
:rtype: object
:return: Parsed file contents
"""
import json # Python 2.6 and up
object_pairs_hook = None
if convert and sys.hexversion < 0x3000000:
try:
_type = unicode
except NameError:
_type = str
def convert(value):
if isinstance(value, list):
return [convert(element) for element in value]
elif isinstance(value, _type):
return str(value)
else:
return value
def object_pairs(pairs):
return dict((str(pair[0]), convert(pair[1])) for pair in pairs)
object_pairs_hook = object_pairs
return json.loads(self.read(encoding=encoding), object_pairs_hook=object_pairs_hook)
def write_json(self, data, pretty=True):
"""
Writes a python object as JSON to disk (Python ≥ 2.6) as UTF-8 data (JSON standard)::
def build(bld):
bld.path.find_node('xyz.json').write_json(199)
:type data: object
:param data: The data to write to disk
:type pretty: boolean
:param pretty: Determines if the JSON will be nicely space separated
"""
import json # Python 2.6 and up
indent = 2
separators = (',', ': ')
sort_keys = pretty
newline = os.linesep
if not pretty:
indent = None
separators = (',', ':')
newline = ''
output = json.dumps(data, indent=indent, separators=separators, sort_keys=sort_keys) + newline
self.write(output, encoding='utf-8')
def exists(self):
"""
Returns whether the Node is present on the filesystem
:rtype: bool
"""
return os.path.exists(self.abspath())
def isdir(self):
"""
Returns whether the Node represents a folder
:rtype: bool
"""
return os.path.isdir(self.abspath())
def chmod(self, val):
"""
Changes the file/dir permissions::
def build(bld):
bld.path.chmod(493) # 0755
"""
os.chmod(self.abspath(), val)
def delete(self, evict=True):
"""
Removes the file/folder from the filesystem (equivalent to `rm -rf`), and remove this object from the Node tree.
Do not use this object after calling this method.
"""
try:
try:
if os.path.isdir(self.abspath()):
shutil.rmtree(self.abspath())
else:
os.remove(self.abspath())
except OSError:
if os.path.exists(self.abspath()):
raise
finally:
if evict:
self.evict()
def evict(self):
"""
Removes this node from the Node tree
"""
del self.parent.children[self.name]
def suffix(self):
"""
Returns the file rightmost extension, for example `a.b.c.d → .d`
:rtype: string
"""
k = max(0, self.name.rfind('.'))
return self.name[k:]
def height(self):
"""
Returns the depth in the folder hierarchy from the filesystem root or from all the file drives
:returns: filesystem depth
:rtype: integer
"""
d = self
val = -1
while d:
d = d.parent
val += 1
return val
def listdir(self):
"""
Lists the folder contents
:returns: list of file/folder names ordered alphabetically
:rtype: list of string
"""
lst = Utils.listdir(self.abspath())
lst.sort()
return lst
def mkdir(self):
"""
Creates a folder represented by this node. Intermediate folders are created as needed.
:raises: :py:class:`waflib.Errors.WafError` when the folder is missing
"""
if self.isdir():
return
try:
self.parent.mkdir()
except OSError:
pass
if self.name:
try:
os.makedirs(self.abspath())
except OSError:
pass
if not self.isdir():
raise Errors.WafError('Could not create the directory %r' % self)
try:
self.children
except AttributeError:
self.children = self.dict_class()
def find_node(self, lst):
"""
Finds a node on the file system (files or folders), and creates the corresponding Node objects if it exists
:param lst: relative path
:type lst: string or list of string
:returns: The corresponding Node object or None if no entry was found on the filesystem
:rtype: :py:class:´waflib.Node.Node´
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
if lst and lst[0].startswith('\\\\') and not self.parent:
node = self.ctx.root.make_node(lst[0])
node.cache_isdir = True
return node.find_node(lst[1:])
cur = self
for x in lst:
if x == '..':
cur = cur.parent or cur
continue
try:
ch = cur.children
except AttributeError:
cur.children = self.dict_class()
else:
try:
cur = ch[x]
continue
except KeyError:
pass
# optimistic: create the node first then look if it was correct to do so
cur = self.__class__(x, cur)
if not cur.exists():
cur.evict()
return None
if not cur.exists():
cur.evict()
return None
return cur
def make_node(self, lst):
"""
Returns or creates a Node object corresponding to the input path without considering the filesystem.
:param lst: relative path
:type lst: string or list of string
:rtype: :py:class:´waflib.Node.Node´
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
cur = self
for x in lst:
if x == '..':
cur = cur.parent or cur
continue
try:
cur = cur.children[x]
except AttributeError:
cur.children = self.dict_class()
except KeyError:
pass
else:
continue
cur = self.__class__(x, cur)
return cur
def search_node(self, lst):
"""
Returns a Node previously defined in the data structure. The filesystem is not considered.
:param lst: relative path
:type lst: string or list of string
:rtype: :py:class:´waflib.Node.Node´ or None if there is no entry in the Node datastructure
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
cur = self
for x in lst:
if x == '..':
cur = cur.parent or cur
else:
try:
cur = cur.children[x]
except (AttributeError, KeyError):
return None
return cur
def path_from(self, node):
"""
Path of this node seen from the other::
def build(bld):
n1 = bld.path.find_node('foo/bar/xyz.txt')
n2 = bld.path.find_node('foo/stuff/')
n1.path_from(n2) # '../bar/xyz.txt'
:param node: path to use as a reference
:type node: :py:class:`waflib.Node.Node`
:returns: a relative path or an absolute one if that is better
:rtype: string
"""
c1 = self
c2 = node
c1h = c1.height()
c2h = c2.height()
lst = []
up = 0
while c1h > c2h:
lst.append(c1.name)
c1 = c1.parent
c1h -= 1
while c2h > c1h:
up += 1
c2 = c2.parent
c2h -= 1
while not c1 is c2:
lst.append(c1.name)
up += 1
c1 = c1.parent
c2 = c2.parent
if c1.parent:
lst.extend(['..'] * up)
lst.reverse()
return os.sep.join(lst) or '.'
else:
return self.abspath()
def abspath(self):
"""
Returns the absolute path. A cache is kept in the context as ``cache_node_abspath``
:rtype: string
"""
try:
return self.cache_abspath
except AttributeError:
pass
# think twice before touching this (performance + complexity + correctness)
if not self.parent:
val = os.sep
elif not self.parent.name:
val = os.sep + self.name
else:
val = self.parent.abspath() + os.sep + self.name
self.cache_abspath = val
return val
if Utils.is_win32:
def abspath(self):
try:
return self.cache_abspath
except AttributeError:
pass
if not self.parent:
val = ''
elif not self.parent.name:
val = self.name + os.sep
else:
val = self.parent.abspath().rstrip(os.sep) + os.sep + self.name
self.cache_abspath = val
return val
def is_child_of(self, node):
"""
Returns whether the object belongs to a subtree of the input node::
def build(bld):
node = bld.path.find_node('wscript')
node.is_child_of(bld.path) # True
:param node: path to use as a reference
:type node: :py:class:`waflib.Node.Node`
:rtype: bool
"""
p = self
diff = self.height() - node.height()
while diff > 0:
diff -= 1
p = p.parent
return p is node
def ant_iter(self, accept=None, maxdepth=25, pats=[], dir=False, src=True, remove=True, quiet=False):
"""
Recursive method used by :py:meth:`waflib.Node.ant_glob`.
:param accept: function used for accepting/rejecting a node, returns the patterns that can be still accepted in recursion
:type accept: function
:param maxdepth: maximum depth in the filesystem (25)
:type maxdepth: int
:param pats: list of patterns to accept and list of patterns to exclude
:type pats: tuple
:param dir: return folders too (False by default)
:type dir: bool
:param src: return files (True by default)
:type src: bool
:param remove: remove files/folders that do not exist (True by default)
:type remove: bool
:param quiet: disable build directory traversal warnings (verbose mode)
:type quiet: bool
:returns: A generator object to iterate from
:rtype: iterator
"""
dircont = self.listdir()
dircont.sort()
try:
lst = set(self.children.keys())
except AttributeError:
self.children = self.dict_class()
else:
if remove:
for x in lst - set(dircont):
self.children[x].evict()
for name in dircont:
npats = accept(name, pats)
if npats and npats[0]:
accepted = [] in npats[0]
node = self.make_node([name])
isdir = node.isdir()
if accepted:
if isdir:
if dir:
yield node
elif src:
yield node
if isdir:
node.cache_isdir = True
if maxdepth:
for k in node.ant_iter(accept=accept, maxdepth=maxdepth - 1, pats=npats, dir=dir, src=src, remove=remove, quiet=quiet):
yield k
def ant_glob(self, *k, **kw):
"""
Finds files across folders and returns Node objects:
* ``**/*`` find all files recursively
* ``**/*.class`` find all files ending by .class
* ``..`` find files having two dot characters
For example::
def configure(cfg):
# find all .cpp files
cfg.path.ant_glob('**/*.cpp')
# find particular files from the root filesystem (can be slow)
cfg.root.ant_glob('etc/*.txt')
# simple exclusion rule example
cfg.path.ant_glob('*.c*', excl=['*.c'], src=True, dir=False)
For more information about the patterns, consult http://ant.apache.org/manual/dirtasks.html
Please remember that the '..' sequence does not represent the parent directory::
def configure(cfg):
cfg.path.ant_glob('../*.h') # incorrect
cfg.path.parent.ant_glob('*.h') # correct
The Node structure is itself a filesystem cache, so certain precautions must
be taken while matching files in the build or installation phases.
Nodes objects that do have a corresponding file or folder are garbage-collected by default.
This garbage collection is usually required to prevent returning files that do not
exist anymore. Yet, this may also remove Node objects of files that are yet-to-be built.
This typically happens when trying to match files in the build directory,
but there are also cases when files are created in the source directory.
Run ``waf -v`` to display any warnings, and try consider passing ``remove=False``
when matching files in the build directory.
Since ant_glob can traverse both source and build folders, it is a best practice
to call this method only from the most specific build node::
def build(bld):
# traverses the build directory, may need ``remove=False``:
bld.path.ant_glob('project/dir/**/*.h')
# better, no accidental build directory traversal:
bld.path.find_node('project/dir').ant_glob('**/*.h') # best
In addition, files and folders are listed immediately. When matching files in the
build folders, consider passing ``generator=True`` so that the generator object
returned can defer computation to a later stage. For example::
def build(bld):
bld(rule='tar xvf ${SRC}', source='arch.tar')
bld.add_group()
gen = bld.bldnode.ant_glob("*.h", generator=True, remove=True)
# files will be listed only after the arch.tar is unpacked
bld(rule='ls ${SRC}', source=gen, name='XYZ')
:param incl: ant patterns or list of patterns to include
:type incl: string or list of strings
:param excl: ant patterns or list of patterns to exclude
:type excl: string or list of strings
:param dir: return folders too (False by default)
:type dir: bool
:param src: return files (True by default)
:type src: bool
:param maxdepth: maximum depth of recursion
:type maxdepth: int
:param ignorecase: ignore case while matching (False by default)
:type ignorecase: bool
:param generator: Whether to evaluate the Nodes lazily
:type generator: bool
:param remove: remove files/folders that do not exist (True by default)
:type remove: bool
:param quiet: disable build directory traversal warnings (verbose mode)
:type quiet: bool
:returns: The corresponding Node objects as a list or as a generator object (generator=True)
:rtype: by default, list of :py:class:`waflib.Node.Node` instances
"""
src = kw.get('src', True)
dir = kw.get('dir')
excl = kw.get('excl', exclude_regs)
incl = k and k[0] or kw.get('incl', '**')
remove = kw.get('remove', True)
maxdepth = kw.get('maxdepth', 25)
ignorecase = kw.get('ignorecase', False)
quiet = kw.get('quiet', False)
pats = (ant_matcher(incl, ignorecase), ant_matcher(excl, ignorecase))
if kw.get('generator'):
return Utils.lazy_generator(self.ant_iter, (ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet))
it = self.ant_iter(ant_sub_matcher, maxdepth, pats, dir, src, remove, quiet)
if kw.get('flat'):
# returns relative paths as a space-delimited string
# prefer Node objects whenever possible
return ' '.join(x.path_from(self) for x in it)
return list(it)
# ----------------------------------------------------------------------------
# the methods below require the source/build folders (bld.srcnode/bld.bldnode)
def is_src(self):
"""
Returns True if the node is below the source directory. Note that ``!is_src() ≠ is_bld()``
:rtype: bool
"""
cur = self
x = self.ctx.srcnode
y = self.ctx.bldnode
while cur.parent:
if cur is y:
return False
if cur is x:
return True
cur = cur.parent
return False
def is_bld(self):
"""
Returns True if the node is below the build directory. Note that ``!is_bld() ≠ is_src()``
:rtype: bool
"""
cur = self
y = self.ctx.bldnode
while cur.parent:
if cur is y:
return True
cur = cur.parent
return False
def get_src(self):
"""
Returns the corresponding Node object in the source directory (or self if already
under the source directory). Use this method only if the purpose is to create
a Node object (this is common with folders but not with files, see ticket 1937)
:rtype: :py:class:`waflib.Node.Node`
"""
cur = self
x = self.ctx.srcnode
y = self.ctx.bldnode
lst = []
while cur.parent:
if cur is y:
lst.reverse()
return x.make_node(lst)
if cur is x:
return self
lst.append(cur.name)
cur = cur.parent
return self
def get_bld(self):
"""
Return the corresponding Node object in the build directory (or self if already
under the build directory). Use this method only if the purpose is to create
a Node object (this is common with folders but not with files, see ticket 1937)
:rtype: :py:class:`waflib.Node.Node`
"""
cur = self
x = self.ctx.srcnode
y = self.ctx.bldnode
lst = []
while cur.parent:
if cur is y:
return self
if cur is x:
lst.reverse()
return self.ctx.bldnode.make_node(lst)
lst.append(cur.name)
cur = cur.parent
# the file is external to the current project, make a fake root in the current build directory
lst.reverse()
if lst and Utils.is_win32 and len(lst[0]) == 2 and lst[0].endswith(':'):
lst[0] = lst[0][0]
return self.ctx.bldnode.make_node(['__root__'] + lst)
def find_resource(self, lst):
"""
Use this method in the build phase to find source files corresponding to the relative path given.
First it looks up the Node data structure to find any declared Node object in the build directory.
If None is found, it then considers the filesystem in the source directory.
:param lst: relative path
:type lst: string or list of string
:returns: the corresponding Node object or None
:rtype: :py:class:`waflib.Node.Node`
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
node = self.get_bld().search_node(lst)
if not node:
node = self.get_src().find_node(lst)
if node and node.isdir():
return None
return node
def find_or_declare(self, lst):
"""
Use this method in the build phase to declare output files which
are meant to be written in the build directory.
This method creates the Node object and its parent folder
as needed.
:param lst: relative path
:type lst: string or list of string
"""
if isinstance(lst, str) and os.path.isabs(lst):
node = self.ctx.root.make_node(lst)
else:
node = self.get_bld().make_node(lst)
node.parent.mkdir()
return node
def find_dir(self, lst):
"""
Searches for a folder on the filesystem (see :py:meth:`waflib.Node.Node.find_node`)
:param lst: relative path
:type lst: string or list of string
:returns: The corresponding Node object or None if there is no such folder
:rtype: :py:class:`waflib.Node.Node`
"""
if isinstance(lst, str):
lst = [x for x in Utils.split_path(lst) if x and x != '.']
node = self.find_node(lst)
if node and not node.isdir():
return None
return node
# helpers for building things
def change_ext(self, ext, ext_in=None):
"""
Declares a build node with a distinct extension; this is uses :py:meth:`waflib.Node.Node.find_or_declare`
:return: A build node of the same path, but with a different extension
:rtype: :py:class:`waflib.Node.Node`
"""
name = self.name
if ext_in is None:
k = name.rfind('.')
if k >= 0:
name = name[:k] + ext
else:
name = name + ext
else:
name = name[:- len(ext_in)] + ext
return self.parent.find_or_declare([name])
def bldpath(self):
"""
Returns the relative path seen from the build directory ``src/foo.cpp``
:rtype: string
"""
return self.path_from(self.ctx.bldnode)
def srcpath(self):
"""
Returns the relative path seen from the source directory ``../src/foo.cpp``
:rtype: string
"""
return self.path_from(self.ctx.srcnode)
def relpath(self):
"""
If a file in the build directory, returns :py:meth:`waflib.Node.Node.bldpath`,
else returns :py:meth:`waflib.Node.Node.srcpath`
:rtype: string
"""
cur = self
x = self.ctx.bldnode
while cur.parent:
if cur is x:
return self.bldpath()
cur = cur.parent
return self.srcpath()
def bld_dir(self):
"""
Equivalent to self.parent.bldpath()
:rtype: string
"""
return self.parent.bldpath()
def h_file(self):
"""
See :py:func:`waflib.Utils.h_file`
:return: a hash representing the file contents
:rtype: string or bytes
"""
return Utils.h_file(self.abspath())
def get_bld_sig(self):
"""
Returns a signature (see :py:meth:`waflib.Node.Node.h_file`) for the purpose
of build dependency calculation. This method uses a per-context cache.
:return: a hash representing the object contents
:rtype: string or bytes
"""
# previous behaviour can be set by returning self.ctx.node_sigs[self] when a build node
try:
cache = self.ctx.cache_sig
except AttributeError:
cache = self.ctx.cache_sig = {}
try:
ret = cache[self]
except KeyError:
p = self.abspath()
try:
ret = cache[self] = self.h_file()
except EnvironmentError:
if self.isdir():
# allow folders as build nodes, do not use the creation time
st = os.stat(p)
ret = cache[self] = Utils.h_list([p, st.st_ino, st.st_mode])
return ret
raise
return ret
pickle_lock = Utils.threading.Lock()
"""Lock mandatory for thread-safe node serialization"""
class Nod3(Node):
"""Mandatory subclass for thread-safe node serialization"""
pass # do not remove
| [
"[email protected]"
] | |
a8972a430ffb07204980882f80982295def04f91 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p02690/s260373583.py | 683e4c44817819625608097b879fb92b1bb0fe95 | [] | no_license | Aasthaengg/IBMdataset | 7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901 | f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8 | refs/heads/main | 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 181 | py | def get(n):
for i in range(-1000,1001):
for j in range(-1000,1001):
if(i**5-j**5==n):
print(i,j)
return
n=int(input())
get(n) | [
"[email protected]"
] | |
ee3ab7b304dcfd2627a23109f9e5a4af1e9cf3b9 | 02b6f852787c0f169c298090e412de84d9fffdfa | /src/dsrlib/ui/configuration.py | 1f6bd8871dcf3223bf9723382947e5adbfa4f922 | [
"MIT"
] | permissive | ca4ti/dsremap | f5ffa0d5f15e37af23ec5bd2c326a0dfa5e6f99c | ad0929adfe5fa8499515b3a6a80e94dfd8c1c0bc | refs/heads/master | 2023-04-02T10:02:02.147173 | 2021-04-11T11:16:59 | 2021-04-11T11:16:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,439 | py | #!/usr/bin/env python3
import os
import shutil
from PyQt5 import QtCore, QtGui, QtWidgets
from dsrlib.domain import ConfigurationMixin, commands
from dsrlib.meta import Meta
from .actions import ActionWidgetBuilder
from .mixins import MainWindowMixin
from .utils import LayoutBuilder
from .uicommands import AddActionButton, DeleteActionsButton, ConvertToCustomActionButton
class ThumbnailView(MainWindowMixin, ConfigurationMixin, QtWidgets.QWidget):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setFixedWidth(170)
self.setFixedHeight(300)
self._pixmap = None
self.reload()
self.setAcceptDrops(True)
def reload(self):
filename = self.configuration().thumbnail()
if filename is None:
self._pixmap = QtGui.QIcon(':icons/image.svg').pixmap(150, 150)
else:
pixmap = QtGui.QPixmap(filename)
self._pixmap = pixmap.scaled(QtCore.QSize(150, 300), QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation)
self.update()
def paintEvent(self, event): # pylint: disable=W0613
painter = QtGui.QPainter(self)
painter.setRenderHint(painter.Antialiasing, True)
rect = QtCore.QRect(QtCore.QPoint(0, 0), self._pixmap.size())
rect.moveCenter(self.rect().center())
painter.drawPixmap(rect.topLeft(), self._pixmap)
if self.configuration().thumbnail() is None:
text = _('Drop an image here')
bbox = painter.fontMetrics().boundingRect(text)
bbox.moveCenter(rect.center())
bbox.moveTop(rect.bottom())
painter.drawText(bbox, 0, text)
def dragEnterEvent(self, event):
data = event.mimeData()
if data.hasFormat('text/uri-list'):
if len(data.urls()) != 1:
return
url = data.urls()[0]
if not url.isLocalFile():
return
filename = url.toLocalFile()
if not os.path.isfile(filename):
return
pixmap = QtGui.QPixmap(filename)
if pixmap.isNull():
return
event.setDropAction(QtCore.Qt.CopyAction)
event.accept()
def dropEvent(self, event):
src = event.mimeData().urls()[0].toLocalFile()
dst = Meta.newThumbnail(src)
shutil.copyfile(src, dst)
cmd = commands.ChangeConfigurationThumbnailCommand(configuration=self.configuration(), filename=dst)
self.history().run(cmd)
# From https://gist.github.com/hahastudio/4345418 with minor changes
class TextEdit(QtWidgets.QTextEdit):
"""
A TextEdit editor that sends editingFinished events
when the text was changed and focus is lost.
"""
editingFinished = QtCore.pyqtSignal()
receivedFocus = QtCore.pyqtSignal()
def __init__(self, parent):
super().__init__(parent)
self._changed = False
self.setTabChangesFocus(True)
self.textChanged.connect(self._handle_text_changed)
def focusInEvent(self, event):
super().focusInEvent(event)
self.receivedFocus.emit()
def focusOutEvent(self, event):
if self._changed:
self.editingFinished.emit()
super().focusOutEvent(event)
def _handle_text_changed(self): # pylint: disable=C0103
self._changed = True
def setTextChanged(self, state=True):
self._changed = state
def setHtml(self, html):
super().setHtml(html)
self._changed = False
def setPlainText(self, text):
super().setPlainText(text)
self._changed = False
class ConfigurationView(MainWindowMixin, ConfigurationMixin, QtWidgets.QWidget):
selectionChanged = QtCore.pyqtSignal()
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.actions().rowsInserted.connect(self._addRows)
self.actions().rowsRemoved.connect(self._removeRows)
self._name = QtWidgets.QLineEdit(self.configuration().name(), self)
self._name.editingFinished.connect(self._changeName)
self._thumbnail = ThumbnailView(self, configuration=self.configuration(), mainWindow=self.mainWindow())
self._description = TextEdit(self)
self._description.setAcceptRichText(False)
self._description.setPlainText(self.configuration().description())
self._description.editingFinished.connect(self._changeDescription)
# We don't actually use a QTreeView because setItemWidget is
# convenient. Not in the mood to write a custom delegate.
self._tree = QtWidgets.QTreeWidget(self)
self._tree.setHeaderHidden(True)
self._tree.itemSelectionChanged.connect(self.selectionChanged)
self._tree.setAlternatingRowColors(True)
btnAdd = AddActionButton(self, configuration=self.configuration(), mainWindow=self.mainWindow())
btnDel = DeleteActionsButton(self, configuration=self.configuration(), container=self, mainWindow=self.mainWindow())
btnConv = ConvertToCustomActionButton(self, configuration=self.configuration(), container=self, mainWindow=self.mainWindow())
bld = LayoutBuilder(self)
with bld.vbox():
with bld.hbox() as header:
header.addWidget(self._name)
header.addWidget(btnConv)
header.addWidget(btnDel)
header.addWidget(btnAdd)
with bld.hbox() as content:
content.addWidget(self._thumbnail)
with bld.vbox() as vbox:
vbox.addWidget(self._tree)
vbox.addWidget(self._description)
self.configuration().changed.connect(self._updateValues)
# In case of redo, the model may not be empty
count = len(self.actions())
if count:
self._addRows(None, 0, count - 1)
def selection(self):
return [item.data(0, QtCore.Qt.UserRole) for item in self._tree.selectedItems()]
def _addRows(self, parent, first, last): # pylint: disable=W0613
for index, action in enumerate(self.actions().items()[first:last+1]):
item = QtWidgets.QTreeWidgetItem()
item.setData(0, QtCore.Qt.UserRole, action)
self._tree.insertTopLevelItem(first + index, item)
widget = ActionWidgetBuilder(self, self.mainWindow()).visit(action)
self._tree.setItemWidget(item, 0, widget)
widget.geometryChanged.connect(item.emitDataChanged)
def _removeRows(self, parent, first, last): # pylint: disable=W0613
for _ in range(last - first + 1):
self._tree.takeTopLevelItem(first)
def _changeName(self):
name = self._name.text()
if name != self.configuration().name():
cmd = commands.ChangeConfigurationNameCommand(configuration=self.configuration(), name=name)
self.history().run(cmd)
def _changeDescription(self):
text = self._description.toPlainText()
if text != self.configuration().description():
cmd = commands.ChangeConfigurationDescriptionCommand(configuration=self.configuration(), description=text)
self.history().run(cmd)
def _updateValues(self):
self._name.setText(self.configuration().name())
self._description.setPlainText(self.configuration().description())
self._thumbnail.reload()
| [
"[email protected]"
] | |
3218938f4ff24c3363c12fa9d7ea10d14f347fda | afc8d5a9b1c2dd476ea59a7211b455732806fdfd | /Configurations/VBSjjlnu/Full2018v6s5/conf_tests_HEM/nuisances.py | 974c0373478496cf6e80d8576ac4c314386b397e | [] | no_license | latinos/PlotsConfigurations | 6d88a5ad828dde4a7f45c68765081ed182fcda21 | 02417839021e2112e740607b0fb78e09b58c930f | refs/heads/master | 2023-08-18T20:39:31.954943 | 2023-08-18T09:23:34 | 2023-08-18T09:23:34 | 39,819,875 | 10 | 63 | null | 2023-08-10T14:08:04 | 2015-07-28T07:36:50 | Python | UTF-8 | Python | false | false | 15,703 | py | # # nuisances
# #FIXME: TO BE UPDATED FOR 2018!
# # name of samples here must match keys in samples.py
mc =["DY", "top", "VV", "VVV", "VBF-V", "top", "VBS", "Wjets_LO", "Wjets_njetsLO"]
# phase_spaces_boost = []
# phase_spaces_res = []
# for d in ["all","high","low", "all_lowvtx", "all_loweta", "all_higheta"]:
# for cat in ["sig", "wjetcr", "topcr"]:
# phase_spaces_boost.append("boost_{}_dnn{}".format(cat, d))
# phase_spaces_res.append("res_{}_dnn{}".format(cat, d))
# phase_spaces_res_ele = [ ph+"_ele" for ph in phase_spaces_res]
# phase_spaces_res_mu = [ ph+"_mu" for ph in phase_spaces_res]
# phase_spaces_boost_ele = [ ph+"_ele" for ph in phase_spaces_boost]
# phase_spaces_boost_mu = [ ph+"_mu" for ph in phase_spaces_boost]
# phase_spaces_tot_ele = phase_spaces_res_ele + phase_spaces_boost_ele
# phase_spaces_tot_mu = phase_spaces_res_mu + phase_spaces_boost_mu
# phase_spaces_tot_res = phase_spaces_res_ele + phase_spaces_res_mu
# phase_spaces_tot_boost = phase_spaces_boost_ele + phase_spaces_boost_mu
# phase_spaces_dict = {"boost": phase_spaces_boost, "res": phase_spaces_res}
# phase_spaces_tot = phase_spaces_tot_ele + phase_spaces_tot_mu
# ################################ EXPERIMENTAL UNCERTAINTIES #################################
# #### Luminosity
nuisances['lumi_Uncorrelated'] = {
'name': 'lumi_13TeV_2018',
'type': 'lnN',
'samples': dict((skey, '1.015') for skey in mc if skey not in ['top', "Wjets","Wjets_HT","Wjets_LO", "Wjets_njetsLO"])
}
nuisances['lumi_XYFact'] = {
'name': 'lumi_13TeV_XYFact',
'type': 'lnN',
'samples': dict((skey, '1.02') for skey in mc if skey not in ['top',"Wjets","Wjets_HT","Wjets_LO", "Wjets_njetsLO"])
}
nuisances['lumi_LScale'] = {
'name': 'lumi_13TeV_LSCale',
'type': 'lnN',
'samples': dict((skey, '1.002') for skey in mc if skey not in ['top',"Wjets","Wjets_HT","Wjets_LO", "Wjets_njetsLO"])
}
nuisances['lumi_CurrCalib'] = {
'name': 'lumi_13TeV_CurrCalib',
'type': 'lnN',
'samples': dict((skey, '1.002') for skey in mc if skey not in ['top',"Wjets","Wjets_HT","Wjets_LO", "Wjets_njetsLO"])
}
# #### FAKES
# if Nlep == '2' :
# # already divided by central values in formulas !
# fakeW_EleUp = fakeW+'_EleUp'
# fakeW_EleDown = fakeW+'_EleDown'
# fakeW_MuUp = fakeW+'_MuUp'
# fakeW_MuDown = fakeW+'_MuDown'
# fakeW_statEleUp = fakeW+'_statEleUp'
# fakeW_statEleDown = fakeW+'_statEleDown'
# fakeW_statMuUp = fakeW+'_statMuUp'
# fakeW_statMuDown = fakeW+'_statMuDown'
# else:
# fakeW_EleUp = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lElUp / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )'
# fakeW_EleDown = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lElDown / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )'
# fakeW_MuUp = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lMuUp / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )'
# fakeW_MuDown = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lMuDown / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )'
# fakeW_statEleUp = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lstatElUp / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )'
# fakeW_statEleDown = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lstatElDown / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )'
# fakeW_statMuUp = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lstatMuUp / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )'
# fakeW_statMuDown = '( fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'lstatMuDown / fakeW_ele_'+eleWP+'_mu_'+muWP+'_'+Nlep+'l )'
nuisances['fake_syst'] = {
'name' : 'CMS_fake_syst',
'type' : 'lnN',
'samples' : {
'Fake' : '1.30',
},
}
# nuisances['fake_ele'] = {
# 'name' : 'hww_fake_ele_2018',
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : {
# 'Fake' : [ fakeW_EleUp , fakeW_EleDown ],
# },
# }
# nuisances['fake_ele_stat'] = {
# 'name' : 'hww_fake_ele_stat_2018',
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : {
# 'Fake' : [ fakeW_statEleUp , fakeW_statEleDown ],
# },
# }
# nuisances['fake_mu'] = {
# 'name' : 'hww_fake_mu_2018',
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : {
# 'Fake' : [ fakeW_MuUp , fakeW_MuDown ],
# },
# }
# nuisances['fake_mu_stat'] = {
# 'name' : 'hww_fake_mu_stat_2018',
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : {
# 'Fake' : [ fakeW_statMuUp , fakeW_statMuDown ],
# },
# }
##### Btag nuisances
for shift in ['jes', 'lf', 'hf', 'hfstats1', 'hfstats2', 'lfstats1', 'lfstats2', 'cferr1', 'cferr2']:
btag_syst = ['(btagSF%sup)/(btagSF)' % shift, '(btagSF%sdown)/(btagSF)' % shift]
btag_syst_new = ['(btagSF_new%sup)/(btagSF_new)' % shift, '(btagSF_new%sdown)/(btagSF_new)' % shift]
name = 'CMS_btag_%s' % shift
if 'stats' in shift:
name += '_2018'
nuisances['btag_shape_%s' % shift] = {
'name': name,
'kind': 'weight',
'type': 'shape',
'samples': dict((skey, btag_syst) for skey in mc if skey not in ["Wjets_njetsLO"]),
}
nuisances['btag_shape_new_%s' % shift] = {
'name': name,
'kind': 'weight',
'type': 'shape',
'samples': { "Wjets_njetsLO": btag_syst_new}
}
####### Fatjet uncertainties
fatjet_eff = ['Wtagging_SF_up/Wtagging_SF_nominal', 'Wtagging_SF_down/Wtagging_SF_nominal']
nuisances['Wtagging_eff'] = {
'name': 'CMS_eff_fatjet_2018',
'kind' : 'weight',
'type' : 'shape',
'samples': dict( (skey, fatjet_eff) for skey in mc)
}
# ##### Trigger Efficiency
trig_syst = ['((TriggerEffWeight_'+Nlep+'l_u)/(TriggerEffWeight_'+Nlep+'l))*(TriggerEffWeight_'+Nlep+'l>0.02) + (TriggerEffWeight_'+Nlep+'l<=0.02)', '(TriggerEffWeight_'+Nlep+'l_d)/(TriggerEffWeight_'+Nlep+'l)']
nuisances['trigg'] = {
'name' : 'CMS_eff_trigger_2018',
'kind' : 'weight',
'type' : 'shape',
'samples' : dict((skey, trig_syst) for skey in mc)
}
# ##### Electron Efficiency and energy scale
ele_id_syst_up = '(abs(Lepton_pdgId[0]) == 11)*(Lepton_tightElectron_'+eleWP+'_TotSF'+'_Up[0])/\
(Lepton_tightElectron_'+eleWP+'_TotSF[0]) + (abs(Lepton_pdgId[0]) == 13)'
ele_id_syst_do = '(abs(Lepton_pdgId[0]) == 11)*(Lepton_tightElectron_'+eleWP+'_TotSF'+'_Down[0])/\
(Lepton_tightElectron_'+eleWP+'_TotSF[0]) + (abs(Lepton_pdgId[0]) == 13)'
mu_id_syst_up = '(abs(Lepton_pdgId[0]) == 13)*(Lepton_tightMuon_'+muWP+'_TotSF'+'_Up[0])/\
(Lepton_tightMuon_'+muWP+'_TotSF[0]) + (abs(Lepton_pdgId[0]) == 11)'
mu_id_syst_do = '(abs(Lepton_pdgId[0]) == 13)*(Lepton_tightMuon_'+muWP+'_TotSF'+'_Down[0])/\
(Lepton_tightMuon_'+muWP+'_TotSF[0]) + (abs(Lepton_pdgId[0]) == 11)'
id_syst_ele = [ ele_id_syst_up, ele_id_syst_do ]
id_syst_mu = [ mu_id_syst_up, mu_id_syst_do ]
nuisances['eff_e'] = {
'name' : 'CMS_eff_e_2018',
'kind' : 'weight',
'type' : 'shape',
'samples' : dict((skey, id_syst_ele) for skey in mc),
}
nuisances['electronpt'] = {
'name' : 'CMS_scale_e_2018',
'kind' : 'tree',
'type' : 'shape',
'samples' : dict((skey, ['1', '1']) for skey in mc),
'folderUp' : directory_bkg +"_ElepTup",
'folderDown' : directory_bkg +"_ElepTdo"
}
# ##### Muon Efficiency and energy scale
# nuisances['eff_m'] = {
# 'name' : 'CMS_eff_m_2018',
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : dict((skey, id_syst_mu) for skey in mc)
# nuisances['muonpt'] = {
# 'name' : 'CMS_scale_m_2018',
# 'kind' : 'tree',
# 'type' : 'shape',
# 'samples' : dict((skey, ['1', '1']) for skey in mc),
# 'folderUp' : directory_bkg +"_MupTup",
# 'folderDown' : directory_bkg +"_MupTdo"
# }
##### Jet energy scale
nuisances['jes'] = {
'name' : 'CMS_scale_j_2018',
'kind' : 'tree',
'type' : 'shape',
'samples' : dict((skey, ['1', '1']) for skey in mc ),
'folderUp' : directory_bkg +"_JESup",
'folderDown' : directory_bkg +"_JESdo",
}
# nuisances['fatjet_jes'] = {
# 'name' : 'CMS_scale_fatj_2018',
# 'kind' : 'tree',
# 'type' : 'shape',
# 'samples' : dict((skey, ['1', '1']) for skey in mc),
# 'folderUp' : directory_bkg +"_fatjet_JESup",
# 'folderDown' : directory_bkg +"_fatjet_JESdo",
# }
# nuisances['fatjet_jms'] = {
# 'name' : 'CMS_mass_fatj_2018',
# 'kind' : 'tree',
# 'type' : 'shape',
# 'samples' : dict((skey, ['1', '1']) for skey in mc),
# 'folderUp' : directory_bkg +"_fatjet_JMSup",
# 'folderDown' : directory_bkg +"_fatjet_JMSdo",
# }
# ##### MET energy scale
nuisances['met'] = {
'name' : 'CMS_scale_met_2018',
'kind' : 'tree',
'type' : 'shape',
'samples' : dict((skey, ['1', '1']) for skey in mc),
'folderUp' : directory_bkg +"_METup",
'folderDown' : directory_bkg +"_METdo",
}
######################
# Theory nuisance
nuisances['QCD_scale_wjets'] = {
'name' : 'QCDscale_wjets',
'kind' : 'weight',
'type' : 'shape',
'samples' : {
"Wjets" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
"Wjets_HT" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
"Wjets_njetsLO" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
"Wjets_NLO" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
"Wjets_LO" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
}
}
nuisances['QCD_scale_top'] = {
'name' : 'QCDscale_top',
'kind' : 'weight',
'type' : 'shape',
'samples' : {
"top" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
}
}
nuisances['QCD_scale_DY'] = {
'name' : 'QCDscale_DY',
'kind' : 'weight',
'type' : 'shape',
'samples' : {
"DY_NLO" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
"DY" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
}
}
# nuisances['QCD_scale_VV'] = {
# 'name' : 'QCDscale_VV',
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : {
# "VV" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
# }
# }
nuisances['QCD_scale_VBF-V'] = {
'name' : 'QCDscale_VBF-V',
'kind' : 'weight',
'type' : 'shape',
'samples' : {
"VBF-V" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
}
}
# nuisances['QCD_scale_VBS'] = {
# 'name' : 'QCDscale_VBS',
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : {
# "VBS" : ["LHEScaleWeight[0]", "LHEScaleWeight[8]"],
# }
# }
##################################
#### Custom nuisances
# if useEmbeddedDY: del nuisances['prefire']['samples']['DY']
# #
# # PS and UE
# #
# nuisances['PS'] = {
# 'name' : 'PS',
# 'skipCMS' : 1,
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : {
# 'WW' : ['PSWeight[0]', 'PSWeight[3]'],
# },
# }
# nuisances['UE'] = {
# 'name' : 'UE',
# 'skipCMS' : 1,
# 'kind' : 'tree',
# 'type' : 'shape',
# 'samples' : {
# # 'WW' : ['1.12720771849', '1.13963144574'],
# 'ggH_hww' : ['1.00211385568', '0.994966378288'],
# 'qqH_hww' : ['1.00367895901', '0.994831373195']
# },
# 'folderUp' : treeBaseDir+'Fall2018_nAOD_v1_Full2018v2/MCl1loose2018v2__MCCorr2018__btagPerEvent__l2loose__l2tightOR2018__UEup',
# 'folderDown' : treeBaseDir+'Fall2018_nAOD_v1_Full2018v2/MCl1loose2018v2__MCCorr2018__btagPerEvent__l2loose__l2tightOR2018__UEdo',
# 'AsLnN' : '1',
# }
# nuisances['PU'] = {
# 'name' : 'CMS_PU_2018',
# 'kind' : 'weight',
# 'type' : 'shape',
# 'samples' : {
# 'DY': ['0.993259983266*(puWeightUp/puWeight)', '0.997656381501*(puWeightDown/puWeight)'],
# 'top': ['1.00331969187*(puWeightUp/puWeight)', '0.999199609528*(puWeightDown/puWeight)'],
# 'WW': ['1.0033022059*(puWeightUp/puWeight)', '0.997085330608*(puWeightDown/puWeight)'],
# 'ggH_hww': ['1.0036768006*(puWeightUp/puWeight)', '0.995996570285*(puWeightDown/puWeight)'],
# 'qqH_hww': ['1.00374694528*(puWeightUp/puWeight)', '0.995878596852*(puWeightDown/puWeight)'],
# },
# 'AsLnN' : '1',
# }
## Top pT reweighting uncertainty
# nuisances['singleTopToTTbar'] = {
# 'name': 'singleTopToTTbar',
# 'skipCMS': 1,
# 'kind': 'weight',
# 'type': 'shape',
# 'samples': {
# 'top': [
# 'isSingleTop * 1.0816 + isTTbar',
# 'isSingleTop * 0.9184 + isTTbar']
# }
# }
## Top pT reweighting uncertainty
# nuisances['TopPtRew'] = {
# 'name': 'CMS_topPtRew', # Theory uncertainty
# 'kind': 'weight',
# 'type': 'shape',
# 'samples': {'top': ["1.", "1./Top_pTrw"]},
# 'symmetrize': True
# }
#################
## Samples normalizations
# nuisances['Top_norm'] = {
# 'name' : 'CMS_Top_norm_2018',
# 'samples' : {
# 'top' : '1.00',
# },
# 'type' : 'rateParam',
# 'cuts' : phase_spaces_tot
# }
# for wjbin in Wjets_lptbins:
# for fl in ["ele", "mu"]:
# for phs in ["res", "boost"]:
# nuisances["{}_norm_{}_{}_2018".format(wjbin, fl, phs )] = {
# 'name' : 'CMS{}_norm_{}_{}_2018'.format(wjbin, fl, phs),
# 'samples' : { wjbin: '1.00' },
# 'type' : 'rateParam',
# 'cuts' : [f+"_"+fl for f in phase_spaces_dict[phs]]
# }
## Use the following if you want to apply the automatic combine MC stat nuisances.
nuisances['stat'] = {
'type' : 'auto',
'maxPoiss' : '10',
'includeSignal' : '1',
# nuisance ['maxPoiss'] = Number of threshold events for Poisson modelling
# nuisance ['includeSignal'] = Include MC stat nuisances on signal processes (1=True, 0=False)
'samples' : {}
}
for n in nuisances.values():
n['skipCMS'] = 1
#print ' '.join(nuis['name'] for nname, nuis in nuisances.iteritems() if nname not in ('lumi', 'stat'))
| [
"[email protected]"
] | |
8e48cdc36af358ce63b9cee3a6d9027cf929722e | a838d4bed14d5df5314000b41f8318c4ebe0974e | /sdk/deviceupdate/azure-iot-deviceupdate/setup.py | 3b4d52e9e304da8944d2b8b5c37ac85830a070fd | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | scbedd/azure-sdk-for-python | ee7cbd6a8725ddd4a6edfde5f40a2a589808daea | cc8bdfceb23e5ae9f78323edc2a4e66e348bb17a | refs/heads/master | 2023-09-01T08:38:56.188954 | 2021-06-17T22:52:28 | 2021-06-17T22:52:28 | 159,568,218 | 2 | 0 | MIT | 2019-08-11T21:16:01 | 2018-11-28T21:34:49 | Python | UTF-8 | Python | false | false | 2,815 | py | #!/usr/bin/env python
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#--------------------------------------------------------------------------
import re
import os.path
from io import open
from setuptools import find_packages, setup
PACKAGE_NAME = "azure-iot-deviceupdate"
PACKAGE_PPRINT_NAME = "Device Update"
# a-b-c => a/b/c
package_folder_path = PACKAGE_NAME.replace('-', '/')
# a-b-c => a.b.c
namespace_name = PACKAGE_NAME.replace('-', '.')
# azure v0.x is not compatible with this package
# azure v0.x used to have a __version__ attribute (newer versions don't)
try:
import azure
try:
ver = azure.__version__
raise Exception(
'This package is incompatible with azure=={}. '.format(ver) +
'Uninstall it with "pip uninstall azure".'
)
except AttributeError:
pass
except ImportError:
pass
# Version extraction inspired from 'requests'
with open(os.path.join(package_folder_path, '_version.py'), 'r') as fd:
version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
if not version:
raise RuntimeError('Cannot find version information')
with open('README.md', encoding='utf-8') as f:
readme = f.read()
with open('CHANGELOG.md', encoding='utf-8') as f:
changelog = f.read()
setup(
name=PACKAGE_NAME,
version=version,
description='Microsoft Azure {} Client Library for Python'.format(PACKAGE_PPRINT_NAME),
long_description=readme + "\n\n" + changelog,
long_description_content_type='text/markdown',
url='https://github.com/Azure/azure-sdk-for-python',
author='Microsoft Corporation',
author_email='[email protected]',
license='MIT License',
zip_safe=False,
classifiers=[
"Development Status :: 4 - Beta",
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Programming Language :: Python :: 3.8',
'Programming Language :: Python :: 3.9',
'License :: OSI Approved :: MIT License',
],
packages=find_packages(exclude=[
'tests',
# Exclude packages that will be covered by PEP420 or nspkg
'azure',
'azure.iot',
]),
install_requires=[
'msrest>=0.5.0',
'azure-common~=1.1',
'azure-core>=1.6.0,<2.0.0',
],
extras_require={
":python_version<'3.0'": ['azure-iot-nspkg'],
}
)
| [
"[email protected]"
] | |
8e52e5124bb4d7475be9e1aba419b63c10e1da71 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/105/usersdata/188/50874/submittedfiles/av1_3.py | 0328c1b58fec2bb6085db012bf78c1af432e4c52 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 311 | py | # -*- coding: utf-8 -*-
import math
N1=int(input('Digite o valor do número 1:'))
N2=int(input('Digite o valor do número 2:'))
N3=int(input('Digite o valor do número 3:'))
n=1
b=0
while n>0:
if(n%a)==0 and (n%b)==0 and (n%c)==0:
b=b+n
break
else:
n=n+1
print ('b')
| [
"[email protected]"
] | |
0c5b75952bd055ee2807574adfbafd0a1718e38e | ab670d6e59ebd4a0c23fa867fb77866d223163da | /Python/Problem243.py | 4e68455830c3935144068fae503f0d467fa66e99 | [] | no_license | JeromeLefebvre/ProjectEuler | 18799e85947e378e18839704c349ba770af4a128 | 3f16e5f231e341a471ffde8b0529407090920b56 | refs/heads/master | 2020-07-05T02:42:44.844607 | 2014-07-26T01:04:38 | 2014-07-26T01:04:38 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,847 | py |
'''
Problem 243
A positive fraction whose numerator is less than its denominator is called a proper fraction.
For any denominator, d, there will be d−1 proper fractions; for example, with d = 12:
1/12 , 2/12 , 3/12 , 4/12 , 5/12 , 6/12 , 7/12 , 8/12 , 9/12 , 10/12 , 11/12 .
We shall call a fraction that cannot be cancelled down a resilient fraction.
Furthermore we shall define the resilience of a denominator, R(d), to be the ratio of its proper fractions that are resilient; for example, R(12) = 4/11 .
In fact, d = 12 is the smallest denominator having a resilience R(d) < 4/10 .
Find the smallest denominator d, having a resilience R(d) < 15499/94744 .
'''
from projectEuler import primes,phiFromFactors, generateFactors,product
from itertools import combinations
import random
from math import log
def maxExponent(p,maximum):
if maximum <= 1: return 0
return int(log(maximum)/log(p))
def phiFromFactors(factors):
if factors == []: return 0
ph = 1
for p in set(factors):
ph *= p**factors.count(p) - p**(factors.count(p) - 1)
return ph
def genFactors(l = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29], maximum=10**10):
exp = {}
n = maximum
# 1 until
q = random.choice(l)
one = 1
for p in l:
try:
exp[p] = random.randint(one,maxExponent(p,n))
except:
exp[p] = 0
n //= p**exp[p]
if p == q:
one = 0
phi = product([p**exp[p] - p**(exp[p] - 1) for p in l if exp[p] > 0])
return phi, product([p**exp[p] for p in l])
genFactors(maximum=1000)
#892371480
#200560490130
#70274254050
# 10000 -> 36427776000
def problem243():
record = 2*3*5*7*11*13*17*19*23*29*31
record = 70274254050
for i in range(1,10000):
phi, n = genFactors(maximum=record)
r = phi/(n-1)
if r < 15499/94744 and n < record:
record = n
return record
if __name__ == "__main__":
print(problem243())
68916891abcABC | [
"[email protected]"
] | |
2af42a2b6608396255e292e61e930cbde59accca | 32c56293475f49c6dd1b0f1334756b5ad8763da9 | /google-cloud-sdk/lib/third_party/kubernetes/client/apis/autoscaling_v2beta1_api.py | dded44c74978be142fca5084827f341ddb1b8418 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | bopopescu/socialliteapp | b9041f17f8724ee86f2ecc6e2e45b8ff6a44b494 | 85bb264e273568b5a0408f733b403c56373e2508 | refs/heads/master | 2022-11-20T03:01:47.654498 | 2020-02-01T20:29:43 | 2020-02-01T20:29:43 | 282,403,750 | 0 | 0 | MIT | 2020-07-25T08:31:59 | 2020-07-25T08:31:59 | null | UTF-8 | Python | false | false | 95,742 | py | # coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen
https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.14.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..api_client import ApiClient
class AutoscalingV2beta1Api(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def create_namespaced_horizontal_pod_autoscaler(self, namespace, body,
**kwargs):
"""
create a HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.create_namespaced_horizontal_pod_autoscaler(namespace,
body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param V2beta1HorizontalPodAutoscaler body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.create_namespaced_horizontal_pod_autoscaler_with_http_info(
namespace, body, **kwargs)
else:
(data) = self.create_namespaced_horizontal_pod_autoscaler_with_http_info(
namespace, body, **kwargs)
return data
def create_namespaced_horizontal_pod_autoscaler_with_http_info(
self, namespace, body, **kwargs):
"""
create a HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.create_namespaced_horizontal_pod_autoscaler_with_http_info(namespace,
body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param V2beta1HorizontalPodAutoscaler body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['namespace', 'body', 'pretty', 'dry_run', 'field_manager']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method create_namespaced_horizontal_pod_autoscaler' % key)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `create_namespaced_horizontal_pod_autoscaler`'
)
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError(
'Missing the required parameter `body` when calling `create_namespaced_horizontal_pod_autoscaler`'
)
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'field_manager' in params:
query_params.append(('fieldManager', params['field_manager']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers',
'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscaler',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_collection_namespaced_horizontal_pod_autoscaler(
self, namespace, **kwargs):
"""
delete collection of HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.delete_collection_namespaced_horizontal_pod_autoscaler(namespace,
async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving
more results from the server. Since this value is server defined,
clients may only use the continue value from a previous query result
with identical query parameters (except for the value of continue) and
the server may reject a continue value it does not recognize. If the
specified continue value is no longer valid whether due to expiration
(generally five to fifteen minutes) or a configuration change on the
server, the server will respond with a 410 ResourceExpired error
together with a continue token. If the client needs a consistent list,
it must restart their list without the continue field. Otherwise, the
client may send another list request with the token received with the
410 error, the server will respond with a list starting from the next
key, but from the latest snapshot, which is inconsistent from the
previous list results - objects that are created, modified, or deleted
after the first list request will be included in the response, as long
as their keys are after the \"next key\". This field is not supported
when watch is true. Clients may start a watch from the last
resourceVersion value returned by the server and not miss any
modifications.
:param str field_selector: A selector to restrict the list of returned
objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned
objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a
list call. If more items exist, the server will set the `continue` field
on the list metadata to a value that can be used with the same initial
query to retrieve the next set of results. Setting a limit may return
fewer than the requested amount of items (up to zero items) in the event
all requested objects are filtered out and clients should only use the
presence of the continue field to determine whether more results are
available. Servers may choose not to support the limit argument and will
return all of the available results. If limit is specified and the
continue field is empty, clients may assume that no more results are
available. This field is not supported if watch is true. The server
guarantees that the objects returned when using continue will be
identical to issuing a single list call without a limit - that is, no
objects created, modified, or deleted after the first request is issued
will be included in any subsequent continued requests. This is sometimes
referred to as a consistent snapshot, and ensures that a client that is
using limit to receive smaller chunks of a very large result can ensure
they see all possible objects. If objects are updated during a chunked
list the version of the object that was present at the time the first
list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows
changes that occur after that particular version of a resource. Defaults
to changes from the beginning of history. When specified for list: - if
unset, then the result is returned from remote storage based on
quorum-read flag; - if it's 0, then we simply return what we currently
have in cache, no guarantee; - if set to non zero, then the result is at
least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits
the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and
return them as a stream of add, update, and remove notifications.
Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_collection_namespaced_horizontal_pod_autoscaler_with_http_info(
namespace, **kwargs)
else:
(data
) = self.delete_collection_namespaced_horizontal_pod_autoscaler_with_http_info(
namespace, **kwargs)
return data
def delete_collection_namespaced_horizontal_pod_autoscaler_with_http_info(
self, namespace, **kwargs):
"""
delete collection of HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.delete_collection_namespaced_horizontal_pod_autoscaler_with_http_info(namespace,
async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving
more results from the server. Since this value is server defined,
clients may only use the continue value from a previous query result
with identical query parameters (except for the value of continue) and
the server may reject a continue value it does not recognize. If the
specified continue value is no longer valid whether due to expiration
(generally five to fifteen minutes) or a configuration change on the
server, the server will respond with a 410 ResourceExpired error
together with a continue token. If the client needs a consistent list,
it must restart their list without the continue field. Otherwise, the
client may send another list request with the token received with the
410 error, the server will respond with a list starting from the next
key, but from the latest snapshot, which is inconsistent from the
previous list results - objects that are created, modified, or deleted
after the first list request will be included in the response, as long
as their keys are after the \"next key\". This field is not supported
when watch is true. Clients may start a watch from the last
resourceVersion value returned by the server and not miss any
modifications.
:param str field_selector: A selector to restrict the list of returned
objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned
objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a
list call. If more items exist, the server will set the `continue` field
on the list metadata to a value that can be used with the same initial
query to retrieve the next set of results. Setting a limit may return
fewer than the requested amount of items (up to zero items) in the event
all requested objects are filtered out and clients should only use the
presence of the continue field to determine whether more results are
available. Servers may choose not to support the limit argument and will
return all of the available results. If limit is specified and the
continue field is empty, clients may assume that no more results are
available. This field is not supported if watch is true. The server
guarantees that the objects returned when using continue will be
identical to issuing a single list call without a limit - that is, no
objects created, modified, or deleted after the first request is issued
will be included in any subsequent continued requests. This is sometimes
referred to as a consistent snapshot, and ensures that a client that is
using limit to receive smaller chunks of a very large result can ensure
they see all possible objects. If objects are updated during a chunked
list the version of the object that was present at the time the first
list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows
changes that occur after that particular version of a resource. Defaults
to changes from the beginning of history. When specified for list: - if
unset, then the result is returned from remote storage based on
quorum-read flag; - if it's 0, then we simply return what we currently
have in cache, no guarantee; - if set to non zero, then the result is at
least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits
the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and
return them as a stream of add, update, and remove notifications.
Specify resourceVersion.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
'namespace', 'pretty', '_continue', 'field_selector', 'label_selector',
'limit', 'resource_version', 'timeout_seconds', 'watch'
]
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method delete_collection_namespaced_horizontal_pod_autoscaler'
% key)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `delete_collection_namespaced_horizontal_pod_autoscaler`'
)
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers',
'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def delete_namespaced_horizontal_pod_autoscaler(self, name, namespace,
**kwargs):
"""
delete a HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.delete_namespaced_horizontal_pod_autoscaler(name,
namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param V1DeleteOptions body:
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the
object should be deleted. Value must be non-negative integer. The value
zero indicates delete immediately. If this value is nil, the default
grace period for the specified type will be used. Defaults to a per
object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the
PropagationPolicy, this field will be deprecated in 1.7. Should the
dependent objects be orphaned. If true/false, the \"orphan\" finalizer
will be added to/removed from the object's finalizers list. Either this
field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will
be performed. Either this field or OrphanDependents may be set, but not
both. The default policy is decided by the existing finalizer set in the
metadata.finalizers and the resource-specific default policy. Acceptable
values are: 'Orphan' - orphan the dependents; 'Background' - allow the
garbage collector to delete the dependents in the background;
'Foreground' - a cascading policy that deletes all dependents in the
foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.delete_namespaced_horizontal_pod_autoscaler_with_http_info(
name, namespace, **kwargs)
else:
(data) = self.delete_namespaced_horizontal_pod_autoscaler_with_http_info(
name, namespace, **kwargs)
return data
def delete_namespaced_horizontal_pod_autoscaler_with_http_info(
self, name, namespace, **kwargs):
"""
delete a HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.delete_namespaced_horizontal_pod_autoscaler_with_http_info(name,
namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param V1DeleteOptions body:
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param int grace_period_seconds: The duration in seconds before the
object should be deleted. Value must be non-negative integer. The value
zero indicates delete immediately. If this value is nil, the default
grace period for the specified type will be used. Defaults to a per
object value if not specified. zero means delete immediately.
:param bool orphan_dependents: Deprecated: please use the
PropagationPolicy, this field will be deprecated in 1.7. Should the
dependent objects be orphaned. If true/false, the \"orphan\" finalizer
will be added to/removed from the object's finalizers list. Either this
field or PropagationPolicy may be set, but not both.
:param str propagation_policy: Whether and how garbage collection will
be performed. Either this field or OrphanDependents may be set, but not
both. The default policy is decided by the existing finalizer set in the
metadata.finalizers and the resource-specific default policy. Acceptable
values are: 'Orphan' - orphan the dependents; 'Background' - allow the
garbage collector to delete the dependents in the background;
'Foreground' - a cascading policy that deletes all dependents in the
foreground.
:return: V1Status
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
'name', 'namespace', 'pretty', 'body', 'dry_run',
'grace_period_seconds', 'orphan_dependents', 'propagation_policy'
]
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method delete_namespaced_horizontal_pod_autoscaler' % key)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError(
'Missing the required parameter `name` when calling `delete_namespaced_horizontal_pod_autoscaler`'
)
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `delete_namespaced_horizontal_pod_autoscaler`'
)
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'grace_period_seconds' in params:
query_params.append(
('gracePeriodSeconds', params['grace_period_seconds']))
if 'orphan_dependents' in params:
query_params.append(('orphanDependents', params['orphan_dependents']))
if 'propagation_policy' in params:
query_params.append(('propagationPolicy', params['propagation_policy']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}',
'DELETE',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1Status',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def get_api_resources(self, **kwargs):
"""
get available resources
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_resources(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: V1APIResourceList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.get_api_resources_with_http_info(**kwargs)
else:
(data) = self.get_api_resources_with_http_info(**kwargs)
return data
def get_api_resources_with_http_info(self, **kwargs):
"""
get available resources
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.get_api_resources_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:return: V1APIResourceList
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s'"
' to method get_api_resources' % key)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/',
'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIResourceList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_horizontal_pod_autoscaler_for_all_namespaces(self, **kwargs):
"""
list or watch objects of kind HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.list_horizontal_pod_autoscaler_for_all_namespaces(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str _continue: The continue option should be set when retrieving
more results from the server. Since this value is server defined,
clients may only use the continue value from a previous query result
with identical query parameters (except for the value of continue) and
the server may reject a continue value it does not recognize. If the
specified continue value is no longer valid whether due to expiration
(generally five to fifteen minutes) or a configuration change on the
server, the server will respond with a 410 ResourceExpired error
together with a continue token. If the client needs a consistent list,
it must restart their list without the continue field. Otherwise, the
client may send another list request with the token received with the
410 error, the server will respond with a list starting from the next
key, but from the latest snapshot, which is inconsistent from the
previous list results - objects that are created, modified, or deleted
after the first list request will be included in the response, as long
as their keys are after the \"next key\". This field is not supported
when watch is true. Clients may start a watch from the last
resourceVersion value returned by the server and not miss any
modifications.
:param str field_selector: A selector to restrict the list of returned
objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned
objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a
list call. If more items exist, the server will set the `continue` field
on the list metadata to a value that can be used with the same initial
query to retrieve the next set of results. Setting a limit may return
fewer than the requested amount of items (up to zero items) in the event
all requested objects are filtered out and clients should only use the
presence of the continue field to determine whether more results are
available. Servers may choose not to support the limit argument and will
return all of the available results. If limit is specified and the
continue field is empty, clients may assume that no more results are
available. This field is not supported if watch is true. The server
guarantees that the objects returned when using continue will be
identical to issuing a single list call without a limit - that is, no
objects created, modified, or deleted after the first request is issued
will be included in any subsequent continued requests. This is sometimes
referred to as a consistent snapshot, and ensures that a client that is
using limit to receive smaller chunks of a very large result can ensure
they see all possible objects. If objects are updated during a chunked
list the version of the object that was present at the time the first
list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: When specified with a watch call, shows
changes that occur after that particular version of a resource. Defaults
to changes from the beginning of history. When specified for list: - if
unset, then the result is returned from remote storage based on
quorum-read flag; - if it's 0, then we simply return what we currently
have in cache, no guarantee; - if set to non zero, then the result is at
least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits
the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and
return them as a stream of add, update, and remove notifications.
Specify resourceVersion.
:return: V2beta1HorizontalPodAutoscalerList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info(
**kwargs)
else:
(data
) = self.list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info(
**kwargs)
return data
def list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info(
self, **kwargs):
"""
list or watch objects of kind HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.list_horizontal_pod_autoscaler_for_all_namespaces_with_http_info(async_req=True)
>>> result = thread.get()
:param async_req bool
:param str _continue: The continue option should be set when retrieving
more results from the server. Since this value is server defined,
clients may only use the continue value from a previous query result
with identical query parameters (except for the value of continue) and
the server may reject a continue value it does not recognize. If the
specified continue value is no longer valid whether due to expiration
(generally five to fifteen minutes) or a configuration change on the
server, the server will respond with a 410 ResourceExpired error
together with a continue token. If the client needs a consistent list,
it must restart their list without the continue field. Otherwise, the
client may send another list request with the token received with the
410 error, the server will respond with a list starting from the next
key, but from the latest snapshot, which is inconsistent from the
previous list results - objects that are created, modified, or deleted
after the first list request will be included in the response, as long
as their keys are after the \"next key\". This field is not supported
when watch is true. Clients may start a watch from the last
resourceVersion value returned by the server and not miss any
modifications.
:param str field_selector: A selector to restrict the list of returned
objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned
objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a
list call. If more items exist, the server will set the `continue` field
on the list metadata to a value that can be used with the same initial
query to retrieve the next set of results. Setting a limit may return
fewer than the requested amount of items (up to zero items) in the event
all requested objects are filtered out and clients should only use the
presence of the continue field to determine whether more results are
available. Servers may choose not to support the limit argument and will
return all of the available results. If limit is specified and the
continue field is empty, clients may assume that no more results are
available. This field is not supported if watch is true. The server
guarantees that the objects returned when using continue will be
identical to issuing a single list call without a limit - that is, no
objects created, modified, or deleted after the first request is issued
will be included in any subsequent continued requests. This is sometimes
referred to as a consistent snapshot, and ensures that a client that is
using limit to receive smaller chunks of a very large result can ensure
they see all possible objects. If objects are updated during a chunked
list the version of the object that was present at the time the first
list result was calculated is returned.
:param str pretty: If 'true', then the output is pretty printed.
:param str resource_version: When specified with a watch call, shows
changes that occur after that particular version of a resource. Defaults
to changes from the beginning of history. When specified for list: - if
unset, then the result is returned from remote storage based on
quorum-read flag; - if it's 0, then we simply return what we currently
have in cache, no guarantee; - if set to non zero, then the result is at
least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits
the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and
return them as a stream of add, update, and remove notifications.
Specify resourceVersion.
:return: V2beta1HorizontalPodAutoscalerList
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
'_continue', 'field_selector', 'label_selector', 'limit', 'pretty',
'resource_version', 'timeout_seconds', 'watch'
]
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method list_horizontal_pod_autoscaler_for_all_namespaces' %
key)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/horizontalpodautoscalers',
'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscalerList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def list_namespaced_horizontal_pod_autoscaler(self, namespace, **kwargs):
"""
list or watch objects of kind HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.list_namespaced_horizontal_pod_autoscaler(namespace,
async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving
more results from the server. Since this value is server defined,
clients may only use the continue value from a previous query result
with identical query parameters (except for the value of continue) and
the server may reject a continue value it does not recognize. If the
specified continue value is no longer valid whether due to expiration
(generally five to fifteen minutes) or a configuration change on the
server, the server will respond with a 410 ResourceExpired error
together with a continue token. If the client needs a consistent list,
it must restart their list without the continue field. Otherwise, the
client may send another list request with the token received with the
410 error, the server will respond with a list starting from the next
key, but from the latest snapshot, which is inconsistent from the
previous list results - objects that are created, modified, or deleted
after the first list request will be included in the response, as long
as their keys are after the \"next key\". This field is not supported
when watch is true. Clients may start a watch from the last
resourceVersion value returned by the server and not miss any
modifications.
:param str field_selector: A selector to restrict the list of returned
objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned
objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a
list call. If more items exist, the server will set the `continue` field
on the list metadata to a value that can be used with the same initial
query to retrieve the next set of results. Setting a limit may return
fewer than the requested amount of items (up to zero items) in the event
all requested objects are filtered out and clients should only use the
presence of the continue field to determine whether more results are
available. Servers may choose not to support the limit argument and will
return all of the available results. If limit is specified and the
continue field is empty, clients may assume that no more results are
available. This field is not supported if watch is true. The server
guarantees that the objects returned when using continue will be
identical to issuing a single list call without a limit - that is, no
objects created, modified, or deleted after the first request is issued
will be included in any subsequent continued requests. This is sometimes
referred to as a consistent snapshot, and ensures that a client that is
using limit to receive smaller chunks of a very large result can ensure
they see all possible objects. If objects are updated during a chunked
list the version of the object that was present at the time the first
list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows
changes that occur after that particular version of a resource. Defaults
to changes from the beginning of history. When specified for list: - if
unset, then the result is returned from remote storage based on
quorum-read flag; - if it's 0, then we simply return what we currently
have in cache, no guarantee; - if set to non zero, then the result is at
least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits
the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and
return them as a stream of add, update, and remove notifications.
Specify resourceVersion.
:return: V2beta1HorizontalPodAutoscalerList
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.list_namespaced_horizontal_pod_autoscaler_with_http_info(
namespace, **kwargs)
else:
(data) = self.list_namespaced_horizontal_pod_autoscaler_with_http_info(
namespace, **kwargs)
return data
def list_namespaced_horizontal_pod_autoscaler_with_http_info(
self, namespace, **kwargs):
"""
list or watch objects of kind HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.list_namespaced_horizontal_pod_autoscaler_with_http_info(namespace,
async_req=True)
>>> result = thread.get()
:param async_req bool
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str _continue: The continue option should be set when retrieving
more results from the server. Since this value is server defined,
clients may only use the continue value from a previous query result
with identical query parameters (except for the value of continue) and
the server may reject a continue value it does not recognize. If the
specified continue value is no longer valid whether due to expiration
(generally five to fifteen minutes) or a configuration change on the
server, the server will respond with a 410 ResourceExpired error
together with a continue token. If the client needs a consistent list,
it must restart their list without the continue field. Otherwise, the
client may send another list request with the token received with the
410 error, the server will respond with a list starting from the next
key, but from the latest snapshot, which is inconsistent from the
previous list results - objects that are created, modified, or deleted
after the first list request will be included in the response, as long
as their keys are after the \"next key\". This field is not supported
when watch is true. Clients may start a watch from the last
resourceVersion value returned by the server and not miss any
modifications.
:param str field_selector: A selector to restrict the list of returned
objects by their fields. Defaults to everything.
:param str label_selector: A selector to restrict the list of returned
objects by their labels. Defaults to everything.
:param int limit: limit is a maximum number of responses to return for a
list call. If more items exist, the server will set the `continue` field
on the list metadata to a value that can be used with the same initial
query to retrieve the next set of results. Setting a limit may return
fewer than the requested amount of items (up to zero items) in the event
all requested objects are filtered out and clients should only use the
presence of the continue field to determine whether more results are
available. Servers may choose not to support the limit argument and will
return all of the available results. If limit is specified and the
continue field is empty, clients may assume that no more results are
available. This field is not supported if watch is true. The server
guarantees that the objects returned when using continue will be
identical to issuing a single list call without a limit - that is, no
objects created, modified, or deleted after the first request is issued
will be included in any subsequent continued requests. This is sometimes
referred to as a consistent snapshot, and ensures that a client that is
using limit to receive smaller chunks of a very large result can ensure
they see all possible objects. If objects are updated during a chunked
list the version of the object that was present at the time the first
list result was calculated is returned.
:param str resource_version: When specified with a watch call, shows
changes that occur after that particular version of a resource. Defaults
to changes from the beginning of history. When specified for list: - if
unset, then the result is returned from remote storage based on
quorum-read flag; - if it's 0, then we simply return what we currently
have in cache, no guarantee; - if set to non zero, then the result is at
least as fresh as given rv.
:param int timeout_seconds: Timeout for the list/watch call. This limits
the duration of the call, regardless of any activity or inactivity.
:param bool watch: Watch for changes to the described resources and
return them as a stream of add, update, and remove notifications.
Specify resourceVersion.
:return: V2beta1HorizontalPodAutoscalerList
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
'namespace', 'pretty', '_continue', 'field_selector', 'label_selector',
'limit', 'resource_version', 'timeout_seconds', 'watch'
]
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s'"
' to method list_namespaced_horizontal_pod_autoscaler' %
key)
params[key] = val
del params['kwargs']
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `list_namespaced_horizontal_pod_autoscaler`'
)
collection_formats = {}
path_params = {}
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if '_continue' in params:
query_params.append(('continue', params['_continue']))
if 'field_selector' in params:
query_params.append(('fieldSelector', params['field_selector']))
if 'label_selector' in params:
query_params.append(('labelSelector', params['label_selector']))
if 'limit' in params:
query_params.append(('limit', params['limit']))
if 'resource_version' in params:
query_params.append(('resourceVersion', params['resource_version']))
if 'timeout_seconds' in params:
query_params.append(('timeoutSeconds', params['timeout_seconds']))
if 'watch' in params:
query_params.append(('watch', params['watch']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers',
'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscalerList',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_horizontal_pod_autoscaler(self, name, namespace, body,
**kwargs):
"""
partially update the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_horizontal_pod_autoscaler(name,
namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint. This field is
required for apply requests (application/apply-patch) but optional for
non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param bool force: Force is going to \"force\" Apply requests. It means
user will re-acquire conflicting fields owned by other people. Force
flag must be unset for non-apply patch requests.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_horizontal_pod_autoscaler_with_http_info(
name, namespace, body, **kwargs)
else:
(data) = self.patch_namespaced_horizontal_pod_autoscaler_with_http_info(
name, namespace, body, **kwargs)
return data
def patch_namespaced_horizontal_pod_autoscaler_with_http_info(
self, name, namespace, body, **kwargs):
"""
partially update the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.patch_namespaced_horizontal_pod_autoscaler_with_http_info(name,
namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint. This field is
required for apply requests (application/apply-patch) but optional for
non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param bool force: Force is going to \"force\" Apply requests. It means
user will re-acquire conflicting fields owned by other people. Force
flag must be unset for non-apply patch requests.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager',
'force'
]
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method patch_namespaced_horizontal_pod_autoscaler' % key)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError(
'Missing the required parameter `name` when calling `patch_namespaced_horizontal_pod_autoscaler`'
)
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `patch_namespaced_horizontal_pod_autoscaler`'
)
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError(
'Missing the required parameter `body` when calling `patch_namespaced_horizontal_pod_autoscaler`'
)
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'field_manager' in params:
query_params.append(('fieldManager', params['field_manager']))
if 'force' in params:
query_params.append(('force', params['force']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}',
'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscaler',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def patch_namespaced_horizontal_pod_autoscaler_status(self, name, namespace,
body, **kwargs):
"""
partially update status of the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.patch_namespaced_horizontal_pod_autoscaler_status(name,
namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint. This field is
required for apply requests (application/apply-patch) but optional for
non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param bool force: Force is going to \"force\" Apply requests. It means
user will re-acquire conflicting fields owned by other people. Force
flag must be unset for non-apply patch requests.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.patch_namespaced_horizontal_pod_autoscaler_status_with_http_info(
name, namespace, body, **kwargs)
else:
(data
) = self.patch_namespaced_horizontal_pod_autoscaler_status_with_http_info(
name, namespace, body, **kwargs)
return data
def patch_namespaced_horizontal_pod_autoscaler_status_with_http_info(
self, name, namespace, body, **kwargs):
"""
partially update status of the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.patch_namespaced_horizontal_pod_autoscaler_status_with_http_info(name,
namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param object body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint. This field is
required for apply requests (application/apply-patch) but optional for
non-apply patch types (JsonPatch, MergePatch, StrategicMergePatch).
:param bool force: Force is going to \"force\" Apply requests. It means
user will re-acquire conflicting fields owned by other people. Force
flag must be unset for non-apply patch requests.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager',
'force'
]
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method patch_namespaced_horizontal_pod_autoscaler_status' %
key)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError(
'Missing the required parameter `name` when calling `patch_namespaced_horizontal_pod_autoscaler_status`'
)
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `patch_namespaced_horizontal_pod_autoscaler_status`'
)
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError(
'Missing the required parameter `body` when calling `patch_namespaced_horizontal_pod_autoscaler_status`'
)
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'field_manager' in params:
query_params.append(('fieldManager', params['field_manager']))
if 'force' in params:
query_params.append(('force', params['force']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}/status',
'PATCH',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscaler',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_horizontal_pod_autoscaler(self, name, namespace,
**kwargs):
"""
read the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_horizontal_pod_autoscaler(name,
namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains
cluster-specific fields like 'Namespace'. Deprecated. Planned for
removal in 1.18.
:param bool export: Should this value be exported. Export strips fields
that a user can not specify. Deprecated. Planned for removal in 1.18.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_horizontal_pod_autoscaler_with_http_info(
name, namespace, **kwargs)
else:
(data) = self.read_namespaced_horizontal_pod_autoscaler_with_http_info(
name, namespace, **kwargs)
return data
def read_namespaced_horizontal_pod_autoscaler_with_http_info(
self, name, namespace, **kwargs):
"""
read the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.read_namespaced_horizontal_pod_autoscaler_with_http_info(name,
namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:param bool exact: Should the export be exact. Exact export maintains
cluster-specific fields like 'Namespace'. Deprecated. Planned for
removal in 1.18.
:param bool export: Should this value be exported. Export strips fields
that a user can not specify. Deprecated. Planned for removal in 1.18.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty', 'exact', 'export']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError("Got an unexpected keyword argument '%s'"
' to method read_namespaced_horizontal_pod_autoscaler' %
key)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError(
'Missing the required parameter `name` when calling `read_namespaced_horizontal_pod_autoscaler`'
)
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `read_namespaced_horizontal_pod_autoscaler`'
)
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'exact' in params:
query_params.append(('exact', params['exact']))
if 'export' in params:
query_params.append(('export', params['export']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}',
'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscaler',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def read_namespaced_horizontal_pod_autoscaler_status(self, name, namespace,
**kwargs):
"""
read status of the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.read_namespaced_horizontal_pod_autoscaler_status(name,
namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.read_namespaced_horizontal_pod_autoscaler_status_with_http_info(
name, namespace, **kwargs)
else:
(data
) = self.read_namespaced_horizontal_pod_autoscaler_status_with_http_info(
name, namespace, **kwargs)
return data
def read_namespaced_horizontal_pod_autoscaler_status_with_http_info(
self, name, namespace, **kwargs):
"""
read status of the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.read_namespaced_horizontal_pod_autoscaler_status_with_http_info(name,
namespace, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param str pretty: If 'true', then the output is pretty printed.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
all_params = ['name', 'namespace', 'pretty']
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method read_namespaced_horizontal_pod_autoscaler_status' % key)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError(
'Missing the required parameter `name` when calling `read_namespaced_horizontal_pod_autoscaler_status`'
)
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `read_namespaced_horizontal_pod_autoscaler_status`'
)
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}/status',
'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscaler',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_horizontal_pod_autoscaler(self, name, namespace, body,
**kwargs):
"""
replace the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_horizontal_pod_autoscaler(name,
namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param V2beta1HorizontalPodAutoscaler body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_horizontal_pod_autoscaler_with_http_info(
name, namespace, body, **kwargs)
else:
(data) = self.replace_namespaced_horizontal_pod_autoscaler_with_http_info(
name, namespace, body, **kwargs)
return data
def replace_namespaced_horizontal_pod_autoscaler_with_http_info(
self, name, namespace, body, **kwargs):
"""
replace the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.replace_namespaced_horizontal_pod_autoscaler_with_http_info(name,
namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param V2beta1HorizontalPodAutoscaler body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager'
]
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method replace_namespaced_horizontal_pod_autoscaler' % key)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError(
'Missing the required parameter `name` when calling `replace_namespaced_horizontal_pod_autoscaler`'
)
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `replace_namespaced_horizontal_pod_autoscaler`'
)
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError(
'Missing the required parameter `body` when calling `replace_namespaced_horizontal_pod_autoscaler`'
)
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'field_manager' in params:
query_params.append(('fieldManager', params['field_manager']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}',
'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscaler',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def replace_namespaced_horizontal_pod_autoscaler_status(
self, name, namespace, body, **kwargs):
"""
replace status of the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread =
api.replace_namespaced_horizontal_pod_autoscaler_status(name, namespace,
body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and
projects (required)
:param V2beta1HorizontalPodAutoscaler body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should
not be persisted. An invalid or unrecognized dryRun directive will
result in an error response and no further processing of the request.
Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the
actor or entity that is making these changes. The value must be less
than or 128 characters long, and only contain printable characters, as
defined by https://golang.org/pkg/unicode/#IsPrint.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async_req'):
return self.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info(
name, namespace, body, **kwargs)
else:
(data
) = self.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info(
name, namespace, body, **kwargs)
return data
def replace_namespaced_horizontal_pod_autoscaler_status_with_http_info(
self, name, namespace, body, **kwargs):
"""
replace status of the specified HorizontalPodAutoscaler
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namespaced_horizontal_pod_autoscaler_status_with_http_info(name, namespace, body, async_req=True)
>>> result = thread.get()
:param async_req bool
:param str name: name of the HorizontalPodAutoscaler (required)
:param str namespace: object name and auth scope, such as for teams and projects (required)
:param V2beta1HorizontalPodAutoscaler body: (required)
:param str pretty: If 'true', then the output is pretty printed.
:param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed
:param str field_manager: fieldManager is a name associated with the actor or entity that is making these changes. The value must be less than or 128 characters long, and only contain printable characters, as defined by https://golang.org/pkg/unicode/#IsPrint.
:return: V2beta1HorizontalPodAutoscaler
If the method is called asynchronously,
returns the request thread.
"""
all_params = [
'name', 'namespace', 'body', 'pretty', 'dry_run', 'field_manager'
]
all_params.append('async_req')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
' to method replace_namespaced_horizontal_pod_autoscaler_status' %
key)
params[key] = val
del params['kwargs']
# verify the required parameter 'name' is set
if ('name' not in params) or (params['name'] is None):
raise ValueError(
'Missing the required parameter `name` when calling `replace_namespaced_horizontal_pod_autoscaler_status`'
)
# verify the required parameter 'namespace' is set
if ('namespace' not in params) or (params['namespace'] is None):
raise ValueError(
'Missing the required parameter `namespace` when calling `replace_namespaced_horizontal_pod_autoscaler_status`'
)
# verify the required parameter 'body' is set
if ('body' not in params) or (params['body'] is None):
raise ValueError(
'Missing the required parameter `body` when calling `replace_namespaced_horizontal_pod_autoscaler_status`'
)
collection_formats = {}
path_params = {}
if 'name' in params:
path_params['name'] = params['name']
if 'namespace' in params:
path_params['namespace'] = params['namespace']
query_params = []
if 'pretty' in params:
query_params.append(('pretty', params['pretty']))
if 'dry_run' in params:
query_params.append(('dryRun', params['dry_run']))
if 'field_manager' in params:
query_params.append(('fieldManager', params['field_manager']))
header_params = {}
form_params = []
local_var_files = {}
body_params = None
if 'body' in params:
body_params = params['body']
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['BearerToken']
return self.api_client.call_api(
'/apis/autoscaling/v2beta1/namespaces/{namespace}/horizontalpodautoscalers/{name}/status',
'PUT',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V2beta1HorizontalPodAutoscaler',
auth_settings=auth_settings,
async_req=params.get('async_req'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
| [
"[email protected]"
] | |
06711799efc8419d428058ea3f7582f7a48c0a3e | 284713c5e6ad6681d2c6c379efc96e5c42833321 | /DB_SQLITE/04_sql_injection.py | ba90ecf3dcc02dcf9e5f32d856ff698089f5add3 | [] | no_license | alexeysorok/Udemy_Python_2019_YouRa | ddfa1f620dcac44cc53958bb88169845072db38e | 8ebd8483f7927892b346af209b4325c9ae0c7dab | refs/heads/master | 2020-09-27T03:24:08.997040 | 2019-12-07T19:04:17 | 2019-12-07T19:04:17 | 226,417,119 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,097 | py | import sqlite3
conn = sqlite3.connect('users.db')
# cursor.execute('CREATE TABLE users (user_name TEXT,'
# 'user_password TEXT)')
users = [
('jack123', 'asdasdasd'),
('kasdsa', 'asdsadasd'),
('Bio', 'asdasda')
]
# insert_query = "INSERT INTO users VALUES (?, ?);"
user_name = input('Input user name: ')
user_password = input('Input you password: ')
# select_query = f"SELECT * FROM users WHERE user_name = '{user_name}' AND " \
# f"user_password = '{user_password}'"
# правильная запись запроса
select_query = f"SELECT * FROM users WHERE user_name = ? AND user_password = ?"
cursor = conn.cursor()
cursor.execute(select_query, (user_name, user_password))
data = cursor.fetchone()
if data:
print('You are logged in!')
else:
print("Please try again")
conn.commit()
conn.close()
# Итоговая строка выполнения запроса
# SELECT * FROM users WHERE user_name = '{user_name}' AND user_password = '' OR 1=1
# инъекция по парол
# ' or 1=1--'
# -- означает коментарий | [
"alexe@W10SSD"
] | alexe@W10SSD |
376d81f18957b729df1c5d3158ad6a37aa802021 | a183a600e666b11331d9bd18bcfe1193ea328f23 | /pdt/core/migrations/0032_case_revision.py | ff8909b6297a1b81d520bff33753bd05266aae58 | [
"MIT"
] | permissive | AbdulRahmanAlHamali/pdt | abebc9cae04f4afa1fc31b87cbf4b981affdca62 | 5c32aab78e48b5249fd458d9c837596a75698968 | refs/heads/master | 2020-05-15T07:51:09.877614 | 2015-12-01T18:22:56 | 2015-12-01T18:22:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 410 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0031_auto_20150618_1116'),
]
operations = [
migrations.AddField(
model_name='case',
name='revision',
field=models.CharField(blank=True, max_length=255),
),
]
| [
"[email protected]"
] | |
c7ef589bf879fb64a6c1ba7225ee9fec2cfe12bb | ccd30f827fb3bd4231c59d05e6d61c5963019291 | /Practice/LeetCode/EverydayPrac/3.py | 603f49bc17eca59b1792306e56056465b5c878af | [] | no_license | anthony20102101/Python_practice | d6709e7768baebaa248612e0795dd3e3fa0ae6ba | 56bb1335c86feafe2d3d82efe68b207c6aa32129 | refs/heads/master | 2023-06-10T18:49:11.619624 | 2021-06-27T15:36:10 | 2021-06-27T15:36:10 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 628 | py | # 给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。
#
# 在杨辉三角中,每个数是它左上方和右上方的数的和。
#
# 示例:
# 输入: 3
# 输出: [1,3,3,1]
# 进阶:
# 你可以优化你的算法到 O(k) 空间复杂度吗?
# 优化:
# 注意到对第 i+1 行的计算仅用到了第 i 行的数据,因此可以使用滚动数组的思想优化空间复杂度。
# 利用上述公式我们可以在线性时间计算出第 n 行的所有组合数。
#
# 复杂度分析
#
# 时间复杂度:O(rowIndex)。
#
# 空间复杂度:O(1)。不考虑返回值的空间占用。
| [
"[email protected]"
] | |
04003011021ed9b70a92bbdc33e87c7af6f9ad9e | 6fa0c051f742c3f9c99ee2800cd132db5ffb28c7 | /src/account/migrations/0008_auto_20200806_2318.py | 03591749cf0b1a71c7d4f20b7e81927a0e349322 | [] | no_license | MCN10/NXTLVL | 9c37bf5782bfd8f24d0fb0431cb5885c585369b0 | 76d8818b7961e4f0362e0d5f41f48f53ce1bfdc5 | refs/heads/main | 2023-06-02T13:51:34.432668 | 2021-06-02T14:19:21 | 2021-06-02T14:19:21 | 328,625,042 | 1 | 0 | null | 2021-06-16T10:16:17 | 2021-01-11T10:19:44 | Python | UTF-8 | Python | false | false | 611 | py | # Generated by Django 3.0.8 on 2020-08-06 23:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('account', '0007_account_is_axisstaff'),
]
operations = [
migrations.AlterField(
model_name='account',
name='phone',
field=models.CharField(max_length=200, null=True, verbose_name='Phone Number'),
),
migrations.AlterField(
model_name='account',
name='username',
field=models.CharField(max_length=30, verbose_name='Full Name'),
),
]
| [
"[email protected]"
] | |
3d0e54171f99c5973fdb441873c4d1302c56d070 | 86d499787fb35024db798b0c1dbfa7a6936854e9 | /py_tools/example/TV.py | 4ec42492467c2b2392e40b3209a8fa35afb1b711 | [] | no_license | Tomtao626/python-note | afd1c82b74e2d3a488b65742547f75b49a11616e | e498e1e7398ff66a757e161a8b8c32c34c38e561 | refs/heads/main | 2023-04-28T08:47:54.525440 | 2023-04-21T17:27:25 | 2023-04-21T17:27:25 | 552,830,730 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,095 | py | class TV:
def __init__(self):
self.channel = 1 # Default channel is 1
self.volumeLevel = 1 # Default volume level is 1
self.on = False # By default TV is off
def turnOn(self):
self.on = True
def turnOff(self):
self.on = False
def getChannel(self):
return self.channel
def setChannel(self, channel):
if self.on and 1 <= self.channel <= 120:
self.channel = channel
def getVolumeLevel(self):
return self.volumeLevel
def setVolume(self, volumeLevel):
if self.on and \
1 <= self.volumeLevel <= 7:
self.volumeLevel = volumeLevel
def channelUp(self):
if self.on and self.channel < 120:
self.channel += 1
def channelDown(self):
if self.on and self.channel > 1:
self.channel -= 1
def volumeUp(self):
if self.on and self.volumeLevel < 7:
self.volumeLevel += 1
def volumeDown(self):
if self.on and self.volumeLevel > 1:
self.volumeLevel -= 1 | [
"[email protected]"
] | |
932c777e82f9b34d9552ecd5044100328cbcb95c | a140fe192fd643ce556fa34bf2f84ddbdb97f091 | /.history/class스타크래프트프로젝트전반전_20200709105346.py | 18786ac5676fbf66cb3c84a0ce24b862c00e37aa | [] | no_license | sangha0719/py-practice | 826f13cb422ef43992a69f822b9f04c2cb6d4815 | 6d71ce64bf91cc3bccee81378577d84ba9d9c121 | refs/heads/master | 2023-03-13T04:40:55.883279 | 2021-02-25T12:02:04 | 2021-02-25T12:02:04 | 342,230,484 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,135 | py | # 일반 유닛
class Unit:
def __init__(self, name, hp, speed):
self.name = name
self.hp = hp
self.speed = speed
print("{0} 유닛이 생성되었습니다.".format(name))
def move(self, location):
print("[지상 유닛 이동]")
print("{0} : {1} 방향으로 이동합니다. [속도 {2}]"
.format(self.name, location, self.speed))
def damaged(self, damage):
print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
self.hp -= damage
print("{0} : 현재 체력은 {1}입니다.".format(self.name, self.hp))
if self.hp <= 0:
print("{0} : 파괴되었습니다.".format(self.name))
# 공격 유닛
class AttackUnit(Unit):
def __init__(self, name, hp, speed, damage):
Unit.__init__(self, name, hp, speed)
self.damage = damage
def attack(self, location): # 클래스 내에서 메소드 앞에는 항상 self를 적어주어야 한다.
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]"
.format(self.name, location, self.damage))
# 마린
class Marine(AttackUnit):
def __init__(self):
AttackUnit.__init__(self, "마린", 40, 1, 5)
# 스팀팩 : 일정 시간 동안 이동 및 공격 속도를 증가, 체력 10 감소
def stimpack(self):
if self.hp > 10:
self.hp -= 10
print("{0} : 스팀팩을 사용합니다. (HP 10 감소)".format(self.name))
else:
print("{0} : 체력이 부족하여 스팀팩을 사용하지 않습니다.".format(self.name))
# 탱크
class Tank(AttackUnit):
# 시즈모드 : 탱크를 지상에 고정시켜, 더 높은 파워로 공격 가능. 이동 불가.
seize_developed = False # 시즈모드 개발 여부
def __init__(self):
AttackUnit.__init__(self, "탱크", 150, 1, 35)
self.seize_mode = False
def set_seize_mode(self):
if Tank.seize_developed == False:
return
# 현재 시즈모드가 아닐 때 -> 시즈모드
if self.seize_mode == False:
print("{0} : 시즈모드로 전환합니다.".format(self.name))
self.damage *= 2
self.seize_mode = True
# 현재 시즈모드일 때 -> 시즈모드 해제
else:
print("{0} : 시즈모드를 해제합니다.".format(self.name))
self.damaged /= 2
self.seize_mode = False
# 날 수 있는 기능을 가진 클래스
class Flyable:
def __init__(self, flying_speed):
self.flying_speed = flying_speed
def fly(self, name, location):
print("{0} : {1} 방향으로 날아갑니다. [속도 {2}]"
.format(name, location, self.flying_speed))
# 공중 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
def __init__(self, name, hp, damage, flying_speed):
AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed 0
Flyable.__init__(self, flying_speed)
def move(self, location):
print("[공중 유닛 이동]")
self.fly(self.name, location)
# 레이스
class Wraith(FlyableAttackUnit):
def __init__(self):
FlyableAttackUnit.__init__(self, "레이스", 80, 20, 5)
self.clocked = False # 클로킹 모드 (해제 상태)
def clocking(self):
if self.clocked == True: # 클로킹 모드 -> 모드 해제
print("{0} : 클로킹 모드 해제합니다.".format(self.name))
self.clocked == False
else: # 클로킹 모드 해제 -> 모드 설정
print("{0} : 클로킹 모드 설정합니다.".format(self.name))
self.clocked == True
def game_start():
print("[알림] 새로운 게임을 시작합니다.")
def game_over():
print("Player : gg")
print("[Player] 님이 게임에서 퇴장하셨습니다.")
# 실제 게임 진행
game_start()
# 마린 3기 생성
m1 = Marine()
m2 = Marine()
m3 = Marine()
# 탱크 2기 생성
t1 = Tank()
t2 = Tank()
# 레이스 1기 생성
w1 = | [
"[email protected]"
] | |
cde9e8c41184ee204fbf4f603084f018c667ea9d | 4cb81903c4d07cd85d9bb8d37eab8ab399a6e276 | /Array Sequences/Practice Problems/uniquechar.py | ac9f2e97f4e67e22a89c814f8168cfb1ea4cb2ad | [] | no_license | JitenKumar/Python-for-Algorithms--Data-Structures | 0011881c8c8558a2e21430afc1aa7d9232392b2c | 7ee8a3ef287761b00be1907c5bbad35e75c5bfd6 | refs/heads/master | 2020-03-18T22:02:47.673814 | 2018-08-05T06:07:17 | 2018-08-05T06:07:17 | 135,320,756 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 477 | py | '''
Unique Characters in String
Problem
Given a string,determine if it is compreised of all unique characters. For example, the string 'abcde' has all unique characters and should return True. The string 'aabcde' contains duplicate characters and should return false.
'''
# solution
def unique_char(string):
s = set()
for i in string:
if i in s:
return False
else:
s.add(i)
return True
print(unique_char('ABCDEFGHI')) | [
"[email protected]"
] | |
92ec87d6a1f183a10a48e5bb65076fbca52c2d3c | 55c250525bd7198ac905b1f2f86d16a44f73e03a | /Python/Lazymux/routersploit/tests/creds/routers/netcore/test_ssh_default_creds.py | 2d81b6e62845318c12ca1f5a515d18860390ca6d | [] | no_license | NateWeiler/Resources | 213d18ba86f7cc9d845741b8571b9e2c2c6be916 | bd4a8a82a3e83a381c97d19e5df42cbababfc66c | refs/heads/master | 2023-09-03T17:50:31.937137 | 2023-08-28T23:50:57 | 2023-08-28T23:50:57 | 267,368,545 | 2 | 1 | null | 2022-09-08T15:20:18 | 2020-05-27T16:18:17 | null | UTF-8 | Python | false | false | 128 | py | version https://git-lfs.github.com/spec/v1
oid sha256:029aa8eb5f4144f599d8be14416b93b3a2e19b768949e76237a74d16a341aaf0
size 634
| [
"[email protected]"
] | |
91f62217c7ebbd46b2d45992db0ba07ce6eb95da | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_197/ch36_2020_04_13_17_07_50_283710.py | 6a077ebde6ef2622e4e4f67db4cfcdf80a8088b7 | [] | no_license | gabriellaec/desoft-analise-exercicios | b77c6999424c5ce7e44086a12589a0ad43d6adca | 01940ab0897aa6005764fc220b900e4d6161d36b | refs/heads/main | 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 111 | py | def fatorial(n):
resultado=1
m=1
while m<=n:
resultado*=m
m+=1
return resultado | [
"[email protected]"
] | |
ad10934a59e725774c6d2fb2e45840eb0379946f | 9919439783a3d9ec7a4435e50e0225ea1d6f2b69 | /manage | 87e7fe63bfcd2a83db73800733b609a1a3835c72 | [] | no_license | newcontext-oss/django-rest-json-api | 19c2e5210c59d02eee88afb3061761f02f4037d6 | 107ef896397d93715d9f3eed34fcb6f14d5893b9 | refs/heads/master | 2021-01-15T20:27:51.771682 | 2017-10-02T18:41:28 | 2017-10-02T18:41:28 | 99,850,109 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 826 | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "django_rest_json_api_example.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
)
raise
execute_from_command_line(sys.argv)
| [
"[email protected]"
] | ||
922539ebe02f2df53fc16aea241cff2fb0df5b23 | 795df757ef84073c3adaf552d5f4b79fcb111bad | /i4lib/i4vec_sorted_unique.py | eea4deabcf5c5276323c987e360cb3e95fd03a39 | [] | no_license | tnakaicode/jburkardt-python | 02cb2f9ba817abf158fc93203eb17bf1cb3a5008 | 1a63f7664e47d6b81c07f2261b44f472adc4274d | refs/heads/master | 2022-05-21T04:41:37.611658 | 2022-04-09T03:31:00 | 2022-04-09T03:31:00 | 243,854,197 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,288 | py | #! /usr/bin/env python
#
def i4vec_sorted_unique ( n, a ):
#*****************************************************************************80
#
## I4VEC_SORTED_UNIQUE finds the unique elements in a sorted I4VEC.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 29 February 2016
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer N, the number of elements in A.
#
# Input, integer A(N), the sorted integer array.
#
# Output, integer N_UNIQUE, the number of unique elements in A.
#
# Output, integer A_UNIQUE[N_UNIQUE], the unique elements.
#
import numpy as np
from i4vec_sorted_unique_count import i4vec_sorted_unique_count
if ( n <= 0 ):
n_unique = 0
a_unique = np.zeros ( 0 )
return n_unique, a_unique
n_unique = i4vec_sorted_unique_count ( n, a )
a_unique = np.zeros ( n_unique, dtype = np.int32 )
k = 0
a_unique[0] = a[0];
for i in range ( 1, n ):
if ( a[i] != a_unique[k] ):
k = k + 1
a_unique[k] = a[i]
return n_unique, a_unique
def i4vec_sorted_unique_test ( ):
#*****************************************************************************80
#
## I4VEC_SORTED_UNIQUE_TEST tests I4VEC_SORTED_UNIQUE.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 29 February 2016
#
# Author:
#
# John Burkardt
#
import platform
from i4vec_print import i4vec_print
from i4vec_sort_heap_a import i4vec_sort_heap_a
from i4vec_uniform_ab import i4vec_uniform_ab
n = 20
b = 0
c = n
print ( '' )
print ( 'I4VEC_SORTED_UNIQUE_TEST' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' I4VEC_SORTED_UNIQUE finds unique entries in a sorted array.' )
seed = 123456789
a, seed = i4vec_uniform_ab ( n, b, c, seed )
a = i4vec_sort_heap_a ( n, a )
i4vec_print ( n, a, ' Input vector:' )
unique_num, a_unique = i4vec_sorted_unique ( n, a )
i4vec_print ( unique_num, a_unique, ' Unique entries:' )
#
# Terminate.
#
print ( '' )
print ( 'I4VEC_SORTED_UNIQUE_TEST' )
print ( ' Normal end of execution.' )
return
if ( __name__ == '__main__' ):
from timestamp import timestamp
timestamp ( )
i4vec_sorted_unique_test ( )
timestamp ( )
| [
"[email protected]"
] | |
827e8cc5f49718946538d832c5f3d61d6eebdca7 | 568345ee64e3e283a916af372a40b34b595d6ff3 | /utils/lldb-dotest/lldb-dotest.in | cc6ea350654a205aae889195f9e92b114c284d36 | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | enterstudio/swift-lldb | b16fb3f067da3933af0fb1024630f7066b38a7ef | af85d636d230da2460f91938b1ff734b0fb64b42 | refs/heads/stable | 2020-04-27T01:43:35.935989 | 2019-03-05T01:43:09 | 2019-03-05T01:43:09 | 173,973,645 | 2 | 0 | Apache-2.0 | 2019-03-05T15:37:31 | 2019-03-05T15:37:26 | null | UTF-8 | Python | false | false | 453 | in | #!/usr/bin/env python
import os
import subprocess
import sys
dotest_path = '@LLDB_SOURCE_DIR@/test/dotest.py'
dotest_args_str = '@LLDB_DOTEST_ARGS@'
if __name__ == '__main__':
wrapper_args = sys.argv[1:]
dotest_args = dotest_args_str.split(';')
# Build dotest.py command.
cmd = [dotest_path, '-q']
cmd.extend(dotest_args)
cmd.extend(wrapper_args)
# Invoke dotest.py and return exit code.
sys.exit(subprocess.call(cmd))
| [
"[email protected]"
] | |
a93ec77494af1405eec2e4807036d13cb21449f5 | a88e486c3be855554e8c9998766869a19a4e0635 | /coursera/knapsack/greedy.py | 9fcfd92a3a800c1f6cb2b685445bf70c2456db4b | [] | no_license | DXV-HUST-SoICT/Combinatorial-Optimization | 03559786a36f66f10742e3a0c520a3369e96a065 | 67c326635bb4245e3dd9819ea9704c37bb9635d3 | refs/heads/master | 2021-03-17T12:59:51.141027 | 2020-06-09T17:42:41 | 2020-06-09T17:42:41 | 246,992,799 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 412 | py | def greedy_by_avarage_value(items, taken, capacity):
def key(item):
return item.value / item.weight
items.sort(key=key, reverse=True)
value = 0
weight = 0
for i in range(len(items)):
item = items[i]
if weight + item.weight <= capacity:
value += item.weight
weight += item.weight
taken[item.index] = 1
return value, weight, 0 | [
"[email protected]"
] | |
0a26c1cda5fed23e78e41221fca74d55a0da585f | 1524720d6480ad0a51b6fd8ff709587455bf4c5d | /tums/trunk/source/plugins/DHCP.py | 7af3eb81f2a7ce65771d5d72723a41f35579e175 | [] | no_license | calston/tums | 2bd6d3cac5232d2ccb7e9becfc649e302a310eab | b93e3e957ff1da5b020075574942913c8822d12a | refs/heads/master | 2020-07-12T03:46:43.639800 | 2018-05-12T10:54:54 | 2018-05-12T10:54:54 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,247 | py | import config, os
from Core import Utils
class Plugin(object):
parameterHook = "--dhcp"
parameterDescription = "Reconfigure DHCP"
parameterArgs = ""
autoRun = True
configFiles = [
"/etc/dhcp/dhcpd.conf"
]
def reloadServices(self):
if config.General.get('services', {}).get('dhcp3-server', True):
os.system('/etc/init.d/dhcpd restart')
os.system('update-rc.d dhcp3-server defaults')
else:
os.system('update-rc.d -f dhcp3-server remove')
def writeConfig(self, *a):
lans = Utils.getLanNetworks(config)
extramain = config.DHCP.get('main','')
ips = Utils.getLanIPs(config)
myIp = ips[0]
rev = '.'.join([i for i in reversed(myIp.split('.')[:3])])
ifaces = []
dhcpconf = """# DHCPD config generated by TUMS Configurator
ddns-update-style interim;
default-lease-time 21600;
max-lease-time 21600;
allow booting;
allow bootp;
authoritative;
log-facility local7;
zone %(domain)s. {
primary 127.0.0.1;
}
zone %(rev)s.in-addr.arpa. {
primary 127.0.0.1;
}
option local-pac-server code 252 = text;
option option-66 code 66 = text;
option option-67 code 67 = text;
%(snomConfig)s
%(extramain)s
""" % {
'extramain': extramain,
'domain': config.Domain,
'snomConfig':"""class "snom" {
match if substring (hardware, 1, 3) = 00:04:13 ;
}""",
'rev': rev
}
n = 0
for k,v in lans.items():
myNet = v
myIp = config.EthernetDevices[k].get('ip', '/').split('/')[0]
dhcpConf = config.DHCP.get(k, {})
if not myIp:
# No IP set for this interface (is DHCP itself)
continue
if not config.EthernetDevices[k].get('dhcpserver'):
# Not set to do DHCP
continue
ifaces.append(k)
statics = ""
for ip, hostmac in config.DHCP.get('leases',{}).items():
if Utils.matchIP(myNet, ip):
# make sure the IP is in this network
host, mac = hostmac
statics += """ host %s {
fixed-address %s;
hardware ethernet %s;
}\n""" % (host, ip, mac)
myNetmask = Utils.cidr2netmask(myNet.split('/')[1])
rangeStart = dhcpConf.get('rangeStart', "100")
rangeEnd = dhcpConf.get('rangeEnd', "240")
snomRangeStart = dhcpConf.get('snomStart', "60")
snomRangeEnd = dhcpConf.get('snomEnd', "80")
snomConfigAddr = dhcpConf.get('snomConfigAddr', myIp + ':9682')
noRange = dhcpConf.get('noRange', False)
netmask = dhcpConf.get('netmask', myNetmask)
netbios = dhcpConf.get('netbios', myIp)
nameserver = dhcpConf.get('nameserver', myIp)
router = dhcpConf.get('gateway', myIp)
myNet = dhcpConf.get('network', Utils.getNetwork(config.EthernetDevices[k]['ip']))
domain = dhcpConf.get('domain', config.Domain)
if not '/' in myNet:
# AAAAAAAAAAAARGH GOD DAMN DIE IN HELL PAUL VIXIE
cdr = Utils.netmask2cidr(netmask)
myNet = "%s/%s" % (myNet, cdr)
bcast = Utils.getBroadcast(myNet)
else:
bcast = Utils.getBroadcast(myNet)
# allow custom configuration options
custom = dhcpConf.get('custom', '')
netL = '.'.join(myNet.split('.')[:3])
if not ("." in rangeStart):
rangeStart = "%s.%s" % (netL, rangeStart)
rangeEnd = "%s.%s" % (netL, rangeEnd)
if not ("." in snomRangeStart):
snomRangeStart = "%s.%s" % (netL, snomRangeStart)
snomRangeEnd = "%s.%s" % (netL, snomRangeEnd)
snomConfig = ""
if dhcpConf.get('autoProv', True):
snomConfig = """
pool {
allow members of "snom";
range dynamic-bootp %(rangeStart)s %(rangeEnd)s;
option option-66 "http://%(configURL)s";
option option-67 "snom/snom.htm";
filename "snom/snom.htm";
}""" % {
'configURL': snomConfigAddr,
'rangeStart': snomRangeStart,
'rangeEnd': snomRangeEnd,
}
defn = {
'netname': 'DHCP%s' % k.upper(),
'myIp': myIp,
'pacIp': myIp.replace('.', '-'),
'domain': domain,
'network': netL,
'networkF': myNet.split('/')[0],
'static': statics,
'custom': custom,
'netmask': netmask,
'rangeSpec': 'range dynamic-bootp %s %s;' % (rangeStart, rangeEnd),
'rangeStart': rangeStart,
'rangeEnd': rangeEnd,
'myNetbios': netbios,
'myDns': nameserver,
'myRouter': router,
'extramain': extramain,
'bcast': bcast,
'snomConfig': snomConfig,
}
"""If noRange is specified, don't provide a range in the dhcpd.conf, may be useful for custom configs"""
if noRange:
defn['generalPool'] = ""
else:
defn['generalPool'] = """
pool {
%s
%s
}""" % (
dhcpConf.get('autoProv', True) and 'deny members of "snom";' or '',
defn['rangeSpec']
)
dhcpnet = """
shared-network %(netname)s {
use-host-decl-names on;
option domain-name "%(domain)s";
option domain-name-servers %(myDns)s;
option netbios-name-servers %(myNetbios)s;
option netbios-node-type 8;
option local-pac-server "http://%(myIp)s/wpad-%(pacIp)s.pac";
option ntp-servers %(myIp)s;
option time-servers %(myIp)s;
option log-servers %(myIp)s;
option font-servers %(myIp)s;
option pop-server %(myIp)s;
option smtp-server %(myIp)s;
option x-display-manager %(myIp)s;
subnet %(networkF)s netmask %(netmask)s {
option subnet-mask %(netmask)s;
option broadcast-address %(bcast)s;
option routers %(myRouter)s;
}
%(snomConfig)s
%(generalPool)s
%(static)s
%(custom)s
}\n""" % defn
dhcpconf += dhcpnet
# Check for debianism (goes in /etc/dhcp3)
f = open('/etc/dhcp3/dhcpd.conf', 'wt')
f.write(dhcpconf)
f.close()
f = open('/etc/default/dhcp3-server', 'wt')
f.write('# On what interfaces should the DHCP server (dhcpd) serve DHCP requests?\n')
f.write('# Separate multiple interfaces with spaces, e.g. "eth0 eth1".\n')
f.write('INTERFACES="%s"\n' % ' '.join(ifaces))
f.close()
| [
"[email protected]"
] | |
de495f8070a7258d450001eb321fe83c21087cd2 | df601ac0a0dd618c75241ca050468cab5f580d3a | /kgb/calls.py | 77111f43f0829d696bd0c66e7999af9890c67e7f | [] | no_license | mitchhentges/kgb | ff90d7e6c66417ba147ab3e32518d9e4facba256 | 4c7f4361a8050e5426cb23e4a84ee64df25a6c12 | refs/heads/master | 2022-12-12T14:50:18.838424 | 2020-09-04T06:57:34 | 2020-09-04T06:57:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,232 | py | """Call tracking and checks for spiess."""
from __future__ import unicode_literals
from kgb.pycompat import iteritems, text_type
from kgb.signature import FunctionSig
class SpyCall(object):
"""Records arguments made to a spied function call.
SpyCalls are created and stored by a FunctionSpy every time it is
called. They're accessible through the FunctionSpy's ``calls`` attribute.
"""
def __init__(self, spy, args, kwargs):
"""Initialize the call.
Args:
spy (kgb.spies.FunctionSpy):
The function spy that the call was made on.
args (tuple):
A tuple of positional arguments from the spy. These correspond
to positional arguments in the function's signature.
kwargs (dict):
A dictionary of keyword arguments from the spy. These
correspond to keyword arguments in the function's signature.
"""
self.spy = spy
self.args = args
self.kwargs = kwargs
self.return_value = None
self.exception = None
def called_with(self, *args, **kwargs):
"""Return whether this call was made with the given arguments.
Not every argument and keyword argument made in the call must be
provided to this method. These can be a subset of the positional and
keyword arguments in the call, but cannot contain any arguments not
made in the call.
Args:
*args (tuple):
The positional arguments made in the call, or a subset of
those arguments (starting with the first argument).
**kwargs (dict):
The keyword arguments made in the call, or a subset of those
arguments.
Returns:
bool:
``True`` if the call's arguments match the provided arguments.
``False`` if they do not.
"""
if len(args) > len(self.args):
return False
if self.args[:len(args)] != args:
return False
pos_args = self.spy._sig.arg_names
if self.spy.func_type in (FunctionSig.TYPE_BOUND_METHOD,
FunctionSig.TYPE_UNBOUND_METHOD):
pos_args = pos_args[1:]
all_args = dict(zip(pos_args, self.args))
all_args.update(self.kwargs)
for key, value in iteritems(kwargs):
if key not in all_args or all_args[key] != value:
return False
return True
def returned(self, value):
"""Return whether this call returned the given value.
Args:
value (object):
The expected returned value from the call.
Returns:
bool:
``True`` if this call returned the given value. ``False`` if it
did not.
"""
return self.return_value == value
def raised(self, exception_cls):
"""Return whether this call raised this exception.
Args:
exception_cls (type):
The expected type of exception raised by the call.
Returns:
bool:
``True`` if this call raised the given exception type.
``False`` if it did not.
"""
return ((self.exception is None and exception_cls is None) or
type(self.exception) is exception_cls)
def raised_with_message(self, exception_cls, message):
"""Return whether this call raised this exception and message.
Args:
exception_cls (type):
The expected type of exception raised by the call.
message (unicode):
The expected message from the exception.
Returns:
bool:
``True`` if this call raised the given exception type and message.
``False`` if it did not.
"""
return (self.exception is not None and
self.raised(exception_cls) and
text_type(self.exception) == message)
def __repr__(self):
return '<SpyCall(args=%r, kwargs=%r, returned=%r, raised=%r>' % (
self.args, self.kwargs, self.return_value, self.exception)
| [
"[email protected]"
] | |
d59aaea52583e6a20a8bae86ba53ef71554cb62d | 64f39ad662546e1f92df4dd2bf7b5ac2f748d39d | /octavia_f5/common/constants.py | 0e1768c388d52b598ce6766ffe5f6d26eec24a41 | [
"Apache-2.0"
] | permissive | zongzw/python-as3 | 2b5026bec3a2e1bba24d4fae7fc90b7f1f58523a | de51773fb2877f4a0988cc655cf4624a3129fd65 | refs/heads/master | 2022-11-24T07:58:04.738669 | 2020-07-28T01:12:25 | 2020-07-28T01:12:25 | 283,049,282 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,640 | py | # Copyright 2018 SAP SE
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from octavia_lib.common.constants import *
PROJECT_ID = 'project_id'
BIGIP = 'bigip'
PREFIX_PROJECT = 'project_'
PREFIX_LISTENER = 'listener_'
PREFIX_TLS_LISTENER = 'tls_listener_'
PREFIX_TLS_POOL = 'tls_pool_'
PREFIX_CONTAINER = 'container_'
PREFIX_CERTIFICATE = 'cert_'
PREFIX_POOL = 'pool_'
PREFIX_HEALTH_MONITOR = 'hm_'
PREFIX_LOADBALANCER = 'lb_'
PREFIX_POLICY = 'l7policy_'
PREFIX_WRAPPER_POLICY = 'wrapper_policy_'
PREFIX_NETWORK = 'net_'
PREFIX_IRULE = 'irule_'
PREFIX_MEMBER = 'member_'
PREFIX_SECRET = 'secret_'
APPLICATION_TCP = 'tcp'
APPLICATION_UDP = 'udp'
APPLICATION_HTTP = 'http'
APPLICATION_HTTPS = 'https'
APPLICATION_L4 = 'l4'
APPLICATION_GENERIC = 'generic'
APPLICATION_SHARED = 'shared'
SUPPORTED_APPLICATION_TEMPLATES = (APPLICATION_TCP, APPLICATION_UDP,
APPLICATION_HTTP, APPLICATION_HTTPS,
APPLICATION_L4, APPLICATION_GENERIC,
APPLICATION_SHARED)
SERVICE_TCP = 'Service_TCP'
SERVICE_UDP = 'Service_UDP'
SERVICE_HTTP = 'Service_HTTP'
SERVICE_HTTPS = 'Service_HTTPS'
SERVICE_L4 = 'Service_L4'
SERVICE_GENERIC = 'Service_Generic'
SUPPORTED_SERVICES = (SERVICE_TCP, SERVICE_UDP, SERVICE_HTTP,
SERVICE_HTTPS, SERVICE_L4, SERVICE_GENERIC)
SERVICE_TCP_TYPES = (SERVICE_TCP, SERVICE_GENERIC, SERVICE_HTTP, SERVICE_HTTPS)
SERVICE_HTTP_TYPES = (SERVICE_HTTP, SERVICE_HTTPS)
SINGLE_USE_DH = 'singleUseDh'
STAPLER_OCSP = 'staplerOCSP'
TLS_1_0 = 'tls1_0'
TLS_1_1 = 'tls1_1'
TLS_1_2 = 'tls1_2'
TLS_1_3 = 'tls1_3'
TLS_OPTIONS_SERVER = (SINGLE_USE_DH, STAPLER_OCSP, TLS_1_0, TLS_1_1, TLS_1_2, TLS_1_3)
TLS_OPTIONS_CLIENT = (SINGLE_USE_DH, TLS_1_0, TLS_1_1, TLS_1_2, TLS_1_3)
ROLE_MASTER = 'MASTER'
ROLE_BACKUP = 'BACKUP'
SEGMENT = 'segment'
VIF_TYPE = 'f5'
ESD = 'esd'
RPC_NAMESPACE_CONTROLLER_AGENT = 'f5controller'
DEVICE_OWNER_LISTENER = 'network:' + 'f5listener'
PROFILE_L4 = 'basic'
OPEN = 'OPEN'
FULL = 'FULL'
UP = 'UP'
DOWN = 'DOWN'
DRAIN = 'DRAIN'
NO_CHECK = 'no check'
MAINT = 'MAINT'
F5_NETWORK_AGENT_TYPE = 'F5 Agent'
| [
"[email protected]"
] | |
034ac87ab3d44c8c5221b639dd2987db0f489445 | 4302fd10583ccff63ff5693bd2ae5903323cb769 | /curate/migrations/0033_auto_20190224_0315.py | 9e514c889504231d27382afd8b779b6510c0517c | [
"MIT"
] | permissive | ScienceCommons/curate_science | 1faf742c8de1e9c9180e4d8ec6a7457ad95bb705 | 4e4072e8c000df0d2e80637016f8f0e667f4df54 | refs/heads/master | 2022-02-12T19:56:51.730534 | 2022-01-25T16:44:54 | 2022-01-25T16:44:54 | 149,122,317 | 14 | 7 | MIT | 2021-03-23T17:27:05 | 2018-09-17T12:32:25 | HTML | UTF-8 | Python | false | false | 1,466 | py | # Generated by Django 2.1.7 on 2019-02-24 03:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('curate', '0032_auto_20190224_0231'),
]
operations = [
migrations.AddField(
model_name='keyfigure',
name='height',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='keyfigure',
name='thumb_height',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='keyfigure',
name='thumb_width',
field=models.PositiveIntegerField(default=0),
),
migrations.AddField(
model_name='keyfigure',
name='width',
field=models.PositiveIntegerField(default=0),
),
migrations.AlterField(
model_name='keyfigure',
name='image',
field=models.ImageField(height_field=models.PositiveIntegerField(default=0), null=True, upload_to='key_figures/', width_field=models.PositiveIntegerField(default=0)),
),
migrations.AlterField(
model_name='keyfigure',
name='thumbnail',
field=models.ImageField(height_field=models.PositiveIntegerField(default=0), null=True, upload_to='key_figure_thumbnails/', width_field=models.PositiveIntegerField(default=0)),
),
]
| [
"[email protected]"
] | |
46f088c66d64354d6e4a7ddddc6951a6a16cb979 | 7e4ee5b457ac9c85b64661eeedba0ba51b211c68 | /entities/background.py | 043381b99de005498e7cbc63c0fda1b10cbdf342 | [] | no_license | iCodeIN/Maze-Game | 180ae7dfb2ffc7b8f2868e450b186b41f3ab510a | 9956bf10f12326307eccff668cbc9cc615c0fee9 | refs/heads/master | 2022-12-03T04:00:12.270692 | 2020-08-26T23:43:45 | 2020-08-26T23:43:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 254 | py | import pygame
import os
import sys
from easy_sdl.tools import *
from easy_sdl.sprite import Sprite
from easy_sdl.sprite import keyUp, keyDown
class Background(Sprite):
def __init__(self):
super().__init__(0, 0, image=path("background.png")) | [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.